@pmate/chat-sdk 0.12.0-next.95 → 0.13.0-profile.0
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/lib/framework.d.ts +2 -0
- package/lib/framework.js +2 -0
- package/lib/messageView.d.ts +5 -0
- package/lib/messageView.js +2 -2
- package/lib/profile.d.ts +14 -0
- package/lib/profile.js +10 -0
- package/lib/profileWorker.d.ts +1 -0
- package/lib/profileWorker.js +3 -0
- package/lib/runtime/inboxClient.d.ts +3 -1
- package/lib/runtime/inboxClient.js +19 -1
- package/lib/runtime/profileChat.d.ts +135 -0
- package/lib/runtime/profileChat.js +299 -0
- package/lib/runtime/profileCommitQueue.d.ts +38 -0
- package/lib/runtime/profileCommitQueue.js +101 -0
- package/lib/runtime/profileCoordinator.d.ts +46 -0
- package/lib/runtime/profileCoordinator.js +135 -0
- package/lib/runtime/profileDatabase.d.ts +42 -0
- package/lib/runtime/profileDatabase.js +164 -0
- package/lib/runtime/profileGenerationBuilder.d.ts +18 -0
- package/lib/runtime/profileGenerationBuilder.js +112 -0
- package/lib/runtime/profileInboxFeed.d.ts +38 -0
- package/lib/runtime/profileInboxFeed.js +240 -0
- package/lib/runtime/profileMemoryStore.d.ts +113 -0
- package/lib/runtime/profileMemoryStore.js +259 -0
- package/lib/runtime/profileOutboxDispatcher.d.ts +31 -0
- package/lib/runtime/profileOutboxDispatcher.js +106 -0
- package/lib/runtime/profileOwner.d.ts +57 -0
- package/lib/runtime/profileOwner.js +202 -0
- package/lib/runtime/profileProjection.d.ts +77 -0
- package/lib/runtime/profileProjection.js +625 -0
- package/lib/runtime/profileReadingIndex.d.ts +17 -0
- package/lib/runtime/profileReadingIndex.js +99 -0
- package/lib/runtime/profileReplica.d.ts +59 -0
- package/lib/runtime/profileReplica.js +236 -0
- package/lib/runtime/profileStoreTypes.d.ts +163 -0
- package/lib/runtime/profileStoreTypes.js +1 -0
- package/lib/runtime/profileWindows.d.ts +38 -0
- package/lib/runtime/profileWindows.js +175 -0
- package/lib/runtime/profileWorkerHost.d.ts +33 -0
- package/lib/runtime/profileWorkerHost.js +156 -0
- package/package.json +11 -1
package/lib/framework.d.ts
CHANGED
|
@@ -7,5 +7,7 @@ export interface ChatStore {
|
|
|
7
7
|
subscribeChanges(listener: () => void): () => void;
|
|
8
8
|
subscribeChanges(threadId: string, listener: () => void, fields?: readonly (keyof ChatThreadSnapshot)[]): () => void;
|
|
9
9
|
}
|
|
10
|
+
/** SDK backends register their prepared, synchronous view without a legacy engine. */
|
|
11
|
+
export declare function registerChatStore(chat: Chat, store: ChatStore): void;
|
|
10
12
|
/** Synchronous memory reads are for external-store integrations, not cache selection. */
|
|
11
13
|
export declare function getChatStore(chat: Chat): ChatStore;
|
package/lib/framework.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { chatEngine } from "./internal/chatRegistry.js";
|
|
2
2
|
const stores = new WeakMap();
|
|
3
|
+
/** SDK backends register their prepared, synchronous view without a legacy engine. */
|
|
4
|
+
export function registerChatStore(chat, store) { stores.set(chat, store); }
|
|
3
5
|
/** Synchronous memory reads are for external-store integrations, not cache selection. */
|
|
4
6
|
export function getChatStore(chat) {
|
|
5
7
|
let store = stores.get(chat);
|
package/lib/messageView.d.ts
CHANGED
|
@@ -2,5 +2,10 @@ import type { TimelineItem } from "./runtime/messageTimeline.js";
|
|
|
2
2
|
import type { CachedChatMessage } from "./runtime/cachedMessage.js";
|
|
3
3
|
import type { ChatMessage } from "./chatTypes.js";
|
|
4
4
|
export type { ChatMessage } from "./chatTypes.js";
|
|
5
|
+
type Mutable<T> = {
|
|
6
|
+
-readonly [K in keyof T]: T[K];
|
|
7
|
+
};
|
|
8
|
+
type Content = Mutable<Pick<ChatMessage, "kind" | "text" | "file" | "image" | "voice" | "quote" | "attachment" | "richContent" | "mentions" | "recipientCount" | "system" | "senderName" | "senderAvatar" | "timeLabel">>;
|
|
9
|
+
export declare function projectMessageContent(message: CachedChatMessage): Content;
|
|
5
10
|
/** Decode a body once; reading and delivery projections reuse its normalized content. */
|
|
6
11
|
export declare function createMessagePresenter(): (item: TimelineItem<CachedChatMessage>) => ChatMessage;
|
package/lib/messageView.js
CHANGED
|
@@ -24,7 +24,7 @@ function legacyDuration(value) {
|
|
|
24
24
|
const [minutes, seconds] = value.split(":").map(Number);
|
|
25
25
|
return (minutes * 60 + seconds) * 1000;
|
|
26
26
|
}
|
|
27
|
-
function
|
|
27
|
+
export function projectMessageContent(message) {
|
|
28
28
|
const body = object(message.body), outer = object(body.content);
|
|
29
29
|
const envelope = body.kind === "quote" && outer.content !== undefined ? outer : body;
|
|
30
30
|
const payload = object(envelope.content);
|
|
@@ -93,7 +93,7 @@ export function createMessagePresenter() {
|
|
|
93
93
|
return previous;
|
|
94
94
|
let value = { kind: "system", text: "" };
|
|
95
95
|
if (!item.recalled && item.message) {
|
|
96
|
-
value = bodies.get(item.message) ??
|
|
96
|
+
value = bodies.get(item.message) ?? projectMessageContent(item.message);
|
|
97
97
|
bodies.set(item.message, value);
|
|
98
98
|
}
|
|
99
99
|
const result = { id: item.id, threadId: item.threadId, ...(item.threadRootId === undefined ? {} : { threadRootId: item.threadRootId }), timestamp: item.timestamp, from: item.from, mine: item.mine, status: item.status, recalled: item.recalled, unread: item.unread, attentionEligible: item.attentionEligible, reading: item.reading, reactions: item.reactions, ...value };
|
package/lib/profile.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export { ProfileDatabase, profileDatabaseName } from "./runtime/profileDatabase.js";
|
|
2
|
+
export { ProfileOwner } from "./runtime/profileOwner.js";
|
|
3
|
+
export { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION, PROFILE_PROJECTION_VERSION } from "./runtime/profileMemoryStore.js";
|
|
4
|
+
export { ProfileReplica, serveProfileOwner } from "./runtime/profileReplica.js";
|
|
5
|
+
export { connectProfileWorker, installProfileWorker, profileChannelName } from "./runtime/profileWorkerHost.js";
|
|
6
|
+
export { profileDiscussionId } from "./runtime/profileProjection.js";
|
|
7
|
+
export { ProfileCoordinator } from "./runtime/profileCoordinator.js";
|
|
8
|
+
export { ProfileInboxFeed } from "./runtime/profileInboxFeed.js";
|
|
9
|
+
export { ProfileOutboxDispatcher } from "./runtime/profileOutboxDispatcher.js";
|
|
10
|
+
export { createProfileChat, getProfileChatRuntime } from "./runtime/profileChat.js";
|
|
11
|
+
export type { ProfileChatHost } from "./runtime/profileChat.js";
|
|
12
|
+
export type { ProfileWorkerConfiguration } from "./runtime/profileWorkerHost.js";
|
|
13
|
+
export type { ProfileSnapshot, ProfileDelta } from "./runtime/profileMemoryStore.js";
|
|
14
|
+
export type { ProfileIdentity, ProfileThread, ProfileWindow, ProfileMessage, ProfileOutboxCommand } from "./runtime/profileStoreTypes.js";
|
package/lib/profile.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { ProfileDatabase, profileDatabaseName } from "./runtime/profileDatabase.js";
|
|
2
|
+
export { ProfileOwner } from "./runtime/profileOwner.js";
|
|
3
|
+
export { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION, PROFILE_PROJECTION_VERSION } from "./runtime/profileMemoryStore.js";
|
|
4
|
+
export { ProfileReplica, serveProfileOwner } from "./runtime/profileReplica.js";
|
|
5
|
+
export { connectProfileWorker, installProfileWorker, profileChannelName } from "./runtime/profileWorkerHost.js";
|
|
6
|
+
export { profileDiscussionId } from "./runtime/profileProjection.js";
|
|
7
|
+
export { ProfileCoordinator } from "./runtime/profileCoordinator.js";
|
|
8
|
+
export { ProfileInboxFeed } from "./runtime/profileInboxFeed.js";
|
|
9
|
+
export { ProfileOutboxDispatcher } from "./runtime/profileOutboxDispatcher.js";
|
|
10
|
+
export { createProfileChat, getProfileChatRuntime } from "./runtime/profileChat.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -16,7 +16,8 @@ export type InboxClientOptions = InboxScope & {
|
|
|
16
16
|
onError?: (error: unknown) => void;
|
|
17
17
|
onProgress?: (progress: InboxProgress) => void;
|
|
18
18
|
onChange?: (threads: readonly string[]) => void;
|
|
19
|
-
live?: boolean;
|
|
19
|
+
live?: boolean; /** Consume shared committed storage without owning network synchronization. */
|
|
20
|
+
replica?: boolean;
|
|
20
21
|
};
|
|
21
22
|
/** Push full facts normally; range catch-up repairs gaps and silent push loss.
|
|
22
23
|
* One persisted lease owns live/check traffic across tabs and team sessions. */
|
|
@@ -64,6 +65,7 @@ export declare class InboxClient {
|
|
|
64
65
|
readyForDisplay(): boolean;
|
|
65
66
|
offlineMode(): boolean;
|
|
66
67
|
allowOffline(): Promise<void>;
|
|
68
|
+
private restoreReplica;
|
|
67
69
|
private initialize;
|
|
68
70
|
synchronize(): Promise<void>;
|
|
69
71
|
private catchUp;
|
|
@@ -37,8 +37,11 @@ export class InboxClient {
|
|
|
37
37
|
if (typeof BroadcastChannel !== "undefined" && typeof window !== "undefined") {
|
|
38
38
|
this.channel = new BroadcastChannel(`pmate-inbox:${this.store.owner}`);
|
|
39
39
|
this.channel.onmessage = event => {
|
|
40
|
-
if (Array.isArray(event.data?.threads))
|
|
40
|
+
if (Array.isArray(event.data?.threads)) {
|
|
41
|
+
if (this.options.replica)
|
|
42
|
+
void this.restoreReplica().catch(error => this.failed(error));
|
|
41
43
|
this.notify(event.data.threads, false);
|
|
44
|
+
}
|
|
42
45
|
if (Array.isArray(event.data?.events)) {
|
|
43
46
|
const events = event.data.events;
|
|
44
47
|
void this.queueReceipts(() => {
|
|
@@ -129,7 +132,20 @@ export class InboxClient {
|
|
|
129
132
|
this.enterOffline();
|
|
130
133
|
this.publish({ ...this.progress, stage: "offline", percent: 100 });
|
|
131
134
|
}
|
|
135
|
+
async restoreReplica() {
|
|
136
|
+
const cursor = await this.store.cursor();
|
|
137
|
+
if (!cursor?.initialized)
|
|
138
|
+
return;
|
|
139
|
+
if (!this.receiptsHydrated)
|
|
140
|
+
await this.hydrateReceipts();
|
|
141
|
+
this.initializedOnce = true;
|
|
142
|
+
this.publish({ stage: "ready", percent: 100, processed: "0", total: "0" });
|
|
143
|
+
}
|
|
132
144
|
async initialize() {
|
|
145
|
+
if (this.options.replica) {
|
|
146
|
+
await this.restoreReplica();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
133
149
|
if (this.options.live === false) {
|
|
134
150
|
if (!this.offlineAllowed)
|
|
135
151
|
await this.synchronize();
|
|
@@ -161,6 +177,8 @@ export class InboxClient {
|
|
|
161
177
|
synchronize() {
|
|
162
178
|
if (this.closed)
|
|
163
179
|
return Promise.reject(new Error("INBOX_CLIENT_CLOSED"));
|
|
180
|
+
if (this.options.replica)
|
|
181
|
+
return this.restoreReplica();
|
|
164
182
|
return this.running ??= this.catchUp().catch(error => { this.failed(error); throw error; }).finally(() => { this.running = undefined; });
|
|
165
183
|
}
|
|
166
184
|
async catchUp() {
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { Chat, OutgoingContent, ReadersQuery, SendOptions, SentMessage, GroupChanges } from "../chatContract.js";
|
|
2
|
+
import type { ChatGroup, ChatSnapshot, ChatThreadSnapshot, ReadOptions } from "../chatTypes.js";
|
|
3
|
+
import type { ProfileMemoryStore } from "./profileMemoryStore.js";
|
|
4
|
+
import { type ProfileOperation } from "./profileProjection.js";
|
|
5
|
+
import type { ProfileIdentity } from "./profileStoreTypes.js";
|
|
6
|
+
import { type ChatRuntimeMessage } from "./protocol.js";
|
|
7
|
+
export type ProfileChatHost = {
|
|
8
|
+
identity: ProfileIdentity;
|
|
9
|
+
memory: ProfileMemoryStore;
|
|
10
|
+
start(): Promise<void>;
|
|
11
|
+
submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
|
|
12
|
+
synchronize(): Promise<void>;
|
|
13
|
+
waitForCommand(id: string): Promise<void>;
|
|
14
|
+
voiceAttachment(id: string): Promise<Blob | null>;
|
|
15
|
+
};
|
|
16
|
+
export declare function getProfileChatRuntime(chat: Chat): ProfileChat;
|
|
17
|
+
export declare function createProfileChat(host: ProfileChatHost, teamId: string): Chat;
|
|
18
|
+
/** Product-facing Chat adapter over prepared Profile views. No legacy Session,
|
|
19
|
+
* second outbox, reading persistence or per-team message database is created. */
|
|
20
|
+
export declare class ProfileChat implements Chat {
|
|
21
|
+
readonly host: ProfileChatHost;
|
|
22
|
+
readonly teamId: string;
|
|
23
|
+
private discussion?;
|
|
24
|
+
private views;
|
|
25
|
+
private limits;
|
|
26
|
+
private listening;
|
|
27
|
+
private listListeners;
|
|
28
|
+
private offs;
|
|
29
|
+
private offList;
|
|
30
|
+
private closed;
|
|
31
|
+
private summary;
|
|
32
|
+
constructor(host: ProfileChatHost, teamId: string, discussion?: {
|
|
33
|
+
parentId: string;
|
|
34
|
+
rootId: string;
|
|
35
|
+
} | undefined);
|
|
36
|
+
private assertOpen;
|
|
37
|
+
private key;
|
|
38
|
+
private thread;
|
|
39
|
+
private parent;
|
|
40
|
+
private group;
|
|
41
|
+
private empty;
|
|
42
|
+
private snapshot;
|
|
43
|
+
private prepare;
|
|
44
|
+
private prepareSummary;
|
|
45
|
+
start(): Promise<void>;
|
|
46
|
+
initialize(): Promise<void>;
|
|
47
|
+
close(): Promise<void>;
|
|
48
|
+
resolveThreadId(target: {
|
|
49
|
+
peerId: string;
|
|
50
|
+
groupId?: never;
|
|
51
|
+
} | {
|
|
52
|
+
groupId: string;
|
|
53
|
+
peerId?: never;
|
|
54
|
+
}, options?: ReadOptions): Promise<string>;
|
|
55
|
+
getThread(id: string, options?: ReadOptions): Promise<ChatThreadSnapshot>;
|
|
56
|
+
loadEarlier(id: string, options?: ReadOptions): Promise<ChatThreadSnapshot>;
|
|
57
|
+
refreshThread(id: string, options?: ReadOptions): Promise<ChatThreadSnapshot>;
|
|
58
|
+
subscribeThread(id: string, listener: (snapshot: ChatThreadSnapshot) => void, _options?: {}): () => void;
|
|
59
|
+
subscribeChat(listener: (snapshot: ChatSnapshot) => void, _options?: {}): () => void;
|
|
60
|
+
openMessageThread(threadId: string, rootId: string): Chat;
|
|
61
|
+
getMessageThreads(id: string, roots: readonly string[], options?: ReadOptions): Promise<{
|
|
62
|
+
revision: number;
|
|
63
|
+
items: {
|
|
64
|
+
rootMessageId: string;
|
|
65
|
+
replyCount: number;
|
|
66
|
+
unreadCount: number;
|
|
67
|
+
lastReplyId: string | null;
|
|
68
|
+
lastReplyAt: number | null;
|
|
69
|
+
participantProfileIds: string[];
|
|
70
|
+
ownerAgentId: string | undefined;
|
|
71
|
+
}[];
|
|
72
|
+
}>;
|
|
73
|
+
sendPrepared(threadId: string, wire: ChatRuntimeMessage, options?: SendOptions, voiceBlob?: Blob): Promise<ChatRuntimeMessage>;
|
|
74
|
+
sendMessage(id: string, content: OutgoingContent, options?: SendOptions): Promise<SentMessage>;
|
|
75
|
+
retryMessage(messageId: string): Promise<{
|
|
76
|
+
id: string;
|
|
77
|
+
timestamp: number;
|
|
78
|
+
}>;
|
|
79
|
+
observeMessages(id: string, ids: string[], event: "visible" | "played"): Promise<void>;
|
|
80
|
+
markRead(id: string): Promise<void>;
|
|
81
|
+
getReaders(id: string, messageId: string, options?: ReadersQuery & ReadOptions): Promise<{
|
|
82
|
+
appId: string;
|
|
83
|
+
threadId: string;
|
|
84
|
+
messageId: string;
|
|
85
|
+
revision: number;
|
|
86
|
+
total: number;
|
|
87
|
+
profileIds: string[];
|
|
88
|
+
nextAfter: string | null;
|
|
89
|
+
resetRequired: boolean;
|
|
90
|
+
}>;
|
|
91
|
+
watchReaders(_id: string | undefined, _ids: string[], _receiver?: string): Promise<void>;
|
|
92
|
+
getVoiceAttachment(id: string, messageId: string, options?: ReadOptions): Promise<{
|
|
93
|
+
url: string;
|
|
94
|
+
release: () => void;
|
|
95
|
+
}>;
|
|
96
|
+
getGroup(id: string, options?: ReadOptions): Promise<ChatGroup>;
|
|
97
|
+
refreshGroup(id: string, options?: ReadOptions): Promise<ChatGroup>;
|
|
98
|
+
private waitGroup;
|
|
99
|
+
createGroup(input: {
|
|
100
|
+
groupId?: string;
|
|
101
|
+
title: string;
|
|
102
|
+
members: readonly string[];
|
|
103
|
+
}): Promise<{
|
|
104
|
+
threadId: string;
|
|
105
|
+
groupId: string;
|
|
106
|
+
teamId: string;
|
|
107
|
+
ownerId: string;
|
|
108
|
+
revision: string;
|
|
109
|
+
status: "active";
|
|
110
|
+
title: string;
|
|
111
|
+
avatar?: string;
|
|
112
|
+
memberIds: readonly string[];
|
|
113
|
+
} | {
|
|
114
|
+
threadId: string;
|
|
115
|
+
groupId: string;
|
|
116
|
+
teamId: string;
|
|
117
|
+
ownerId: string;
|
|
118
|
+
revision: string;
|
|
119
|
+
status: "dissolved";
|
|
120
|
+
dissolvedBy?: string;
|
|
121
|
+
dissolvedAt?: number;
|
|
122
|
+
}>;
|
|
123
|
+
private sendControl;
|
|
124
|
+
updateGroup(id: string, changes: GroupChanges): Promise<ChatGroup>;
|
|
125
|
+
dissolveGroup(id: string, options?: {
|
|
126
|
+
expectedRevision?: string;
|
|
127
|
+
}): Promise<ChatGroup>;
|
|
128
|
+
synchronizeReading(): Promise<void>;
|
|
129
|
+
revokeThread(id: string): Promise<void>;
|
|
130
|
+
revokeAccess(): Promise<void>;
|
|
131
|
+
firstUnread(id: string): string | undefined;
|
|
132
|
+
sharedTransport(): {
|
|
133
|
+
sendPrepared: (wire: ChatRuntimeMessage) => Promise<ChatRuntimeMessage>;
|
|
134
|
+
};
|
|
135
|
+
}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { ChatError } from "../chatError.js";
|
|
2
|
+
import { registerChatStore } from "../framework.js";
|
|
3
|
+
import { profileDiscussionId } from "./profileProjection.js";
|
|
4
|
+
import { createRuntimeMsg } from "./protocol.js";
|
|
5
|
+
import { outgoingContent } from "./outgoingContent.js";
|
|
6
|
+
import { dmThreadId, groupThreadId } from "./thread.js";
|
|
7
|
+
import { createUniqueGroup } from "./groupIdentity.js";
|
|
8
|
+
const sessions = new WeakMap();
|
|
9
|
+
export function getProfileChatRuntime(chat) {
|
|
10
|
+
const session = sessions.get(chat);
|
|
11
|
+
if (!session)
|
|
12
|
+
throw Error("UNKNOWN_PROFILE_CHAT");
|
|
13
|
+
return session;
|
|
14
|
+
}
|
|
15
|
+
export function createProfileChat(host, teamId) { return new ProfileChat(host, teamId); }
|
|
16
|
+
/** Product-facing Chat adapter over prepared Profile views. No legacy Session,
|
|
17
|
+
* second outbox, reading persistence or per-team message database is created. */
|
|
18
|
+
export class ProfileChat {
|
|
19
|
+
host;
|
|
20
|
+
teamId;
|
|
21
|
+
discussion;
|
|
22
|
+
views = new Map();
|
|
23
|
+
limits = new Map();
|
|
24
|
+
listening = new Map();
|
|
25
|
+
listListeners = new Set();
|
|
26
|
+
offs = new Map();
|
|
27
|
+
offList;
|
|
28
|
+
closed = false;
|
|
29
|
+
summary = { threads: [], unreadMessageCount: undefined, badgeCount: undefined, connection: "connecting" };
|
|
30
|
+
constructor(host, teamId, discussion) {
|
|
31
|
+
this.host = host;
|
|
32
|
+
this.teamId = teamId;
|
|
33
|
+
this.discussion = discussion;
|
|
34
|
+
sessions.set(this, this);
|
|
35
|
+
const subscribeChanges = ((target, listener) => typeof target === "string"
|
|
36
|
+
? this.subscribeThread(target, () => listener()) : this.subscribeChat(() => target()));
|
|
37
|
+
registerChatStore(this, { getSnapshot: ((id) => id === undefined ? this.summary : this.snapshot(id)),
|
|
38
|
+
subscribeThread: (id, listener) => this.subscribeThread(id, () => listener()), subscribeChanges });
|
|
39
|
+
this.offList = host.memory.subscribeThreadList(() => this.prepareSummary());
|
|
40
|
+
this.prepareSummary();
|
|
41
|
+
}
|
|
42
|
+
assertOpen() { if (this.closed)
|
|
43
|
+
throw new ChatError("closed", "Chat session closed"); }
|
|
44
|
+
key(id) { return this.discussion ? profileDiscussionId(this.discussion.parentId, this.discussion.rootId) : id; }
|
|
45
|
+
thread(id) { return this.host.memory.getThread(this.key(id)); }
|
|
46
|
+
parent(id) { return this.host.memory.getThread(this.discussion?.parentId ?? id); }
|
|
47
|
+
group(thread) {
|
|
48
|
+
const group = thread?.group;
|
|
49
|
+
if (!group)
|
|
50
|
+
return;
|
|
51
|
+
const base = { groupId: group.groupId, teamId: group.teamId ?? this.teamId, ownerId: group.ownerId, revision: group.revision };
|
|
52
|
+
return group.status === "dissolved" ? { ...base, status: "dissolved", dissolvedBy: group.dissolvedBy, dissolvedAt: group.dissolvedAt }
|
|
53
|
+
: { ...base, status: "active", title: group.title ?? "", avatar: group.avatar ?? undefined, memberIds: group.members ?? [] };
|
|
54
|
+
}
|
|
55
|
+
empty(id) {
|
|
56
|
+
return { threadId: id, messages: [], hasEarlier: false, unread: undefined, group: undefined, readCounts: undefined, status: "pending", ready: false };
|
|
57
|
+
}
|
|
58
|
+
snapshot(id) {
|
|
59
|
+
let view = this.views.get(id);
|
|
60
|
+
if (!view) {
|
|
61
|
+
view = this.empty(id);
|
|
62
|
+
this.views.set(id, view);
|
|
63
|
+
}
|
|
64
|
+
return view;
|
|
65
|
+
}
|
|
66
|
+
prepare(id) {
|
|
67
|
+
const memory = this.host.memory, thread = this.thread(id), parent = this.parent(id);
|
|
68
|
+
if (memory.getStatus().phase !== "ready" || !thread && !(this.discussion && parent?.status === "ready"))
|
|
69
|
+
return this.snapshot(id);
|
|
70
|
+
if (thread?.status === "unavailable" || parent?.status === "unavailable") {
|
|
71
|
+
const error = new ChatError("access-denied", "Conversation unavailable", { threadId: id, status: 403 });
|
|
72
|
+
const view = { ...this.empty(id), status: "error", ready: false, error };
|
|
73
|
+
this.views.set(id, view);
|
|
74
|
+
return view;
|
|
75
|
+
}
|
|
76
|
+
const count = Math.min(this.limits.get(id) ?? 128, thread?.messageCount ?? 0);
|
|
77
|
+
// Compatibility API accumulates requested pages; readPage remains the
|
|
78
|
+
// bounded API for page components and never materializes the whole thread.
|
|
79
|
+
const pages = [];
|
|
80
|
+
let anchor;
|
|
81
|
+
for (let remaining = count; remaining > 0; remaining -= 1000) {
|
|
82
|
+
const page = memory.readPresentedPage(this.key(id), anchor, Math.min(remaining, 1000));
|
|
83
|
+
pages.unshift(page);
|
|
84
|
+
anchor = page[0]?.id;
|
|
85
|
+
}
|
|
86
|
+
const messages = pages.length === 1 ? pages[0] : pages.flat();
|
|
87
|
+
const group = this.group(parent);
|
|
88
|
+
const counts = {};
|
|
89
|
+
for (const message of messages) {
|
|
90
|
+
const raw = memory.getMessage(message.id);
|
|
91
|
+
if (raw?.receiptStatus === "ready")
|
|
92
|
+
counts[message.id] = raw.readBy.length;
|
|
93
|
+
}
|
|
94
|
+
const previous = this.views.get(id);
|
|
95
|
+
const view = { threadId: id, messages, hasEarlier: count < (thread?.messageCount ?? 0),
|
|
96
|
+
conversation: parent ? { kind: parent.kind === "dm" ? "dm" : "group", targetId: parent.internal?.targetId ?? "" } : undefined,
|
|
97
|
+
unread: thread?.unreadCount === null ? undefined : { unreadMessageCount: thread?.unreadCount ?? 0, unreadMentionCount: thread?.mentionCount ?? 0,
|
|
98
|
+
badgeCount: thread?.kind === "dm" ? thread.unreadCount ?? 0 : thread?.mentionCount ?? 0 },
|
|
99
|
+
group, readCounts: { appId: this.host.identity.appId, threadId: id, revision: memory.getStatus().revision ?? 0, counts }, status: "ready", ready: true };
|
|
100
|
+
if (previous?.messages === view.messages && previous.unread?.unreadMessageCount === view.unread?.unreadMessageCount &&
|
|
101
|
+
previous.unread?.unreadMentionCount === view.unread?.unreadMentionCount && previous.group?.revision === view.group?.revision && previous.readCounts?.revision === view.readCounts?.revision)
|
|
102
|
+
return previous;
|
|
103
|
+
this.views.set(id, view);
|
|
104
|
+
return view;
|
|
105
|
+
}
|
|
106
|
+
prepareSummary() {
|
|
107
|
+
const rows = this.host.memory.getThreadList().filter(thread => thread.teamId === this.teamId && thread.status !== "unavailable");
|
|
108
|
+
this.summary = { threads: rows.map(thread => ({ threadId: thread.threadId, lastMessage: thread.lastMessageId ? this.host.memory.getPresentedMessage(thread.lastMessageId) : undefined,
|
|
109
|
+
group: this.group(thread), unread: thread.unreadCount === null ? undefined : { unreadMessageCount: thread.unreadCount, unreadMentionCount: thread.mentionCount ?? 0,
|
|
110
|
+
badgeCount: thread.kind === "dm" ? thread.unreadCount : thread.mentionCount ?? 0 }, outgoingCount: 0 })),
|
|
111
|
+
unreadMessageCount: rows.some(thread => thread.unreadCount === null) ? undefined : rows.reduce((sum, thread) => sum + thread.unreadCount, 0),
|
|
112
|
+
badgeCount: rows.some(thread => thread.unreadCount === null) ? undefined : rows.reduce((sum, thread) => sum + (thread.kind === "dm" ? thread.unreadCount : thread.mentionCount ?? 0), 0),
|
|
113
|
+
connection: this.host.memory.getStatus().phase === "ready" ? "connected" : "connecting" };
|
|
114
|
+
for (const listener of this.listListeners)
|
|
115
|
+
listener(this.summary);
|
|
116
|
+
}
|
|
117
|
+
async start() { this.assertOpen(); await this.host.start(); this.prepareSummary(); }
|
|
118
|
+
initialize() { return this.start(); }
|
|
119
|
+
async close() { if (this.closed)
|
|
120
|
+
return; this.closed = true; this.offList(); for (const off of this.offs.values())
|
|
121
|
+
off(); this.offs.clear(); this.listening.clear(); this.listListeners.clear(); }
|
|
122
|
+
async resolveThreadId(target, options = {}) {
|
|
123
|
+
this.assertOpen();
|
|
124
|
+
options.signal?.throwIfAborted();
|
|
125
|
+
await this.host.start();
|
|
126
|
+
const kind = target.groupId !== undefined ? "group" : "dm", targetId = target.groupId ?? target.peerId;
|
|
127
|
+
if (this.discussion)
|
|
128
|
+
return this.discussion.parentId;
|
|
129
|
+
const existing = this.host.memory.getThreadList().find(thread => thread.teamId === this.teamId && thread.kind === kind && thread.internal?.targetId === targetId);
|
|
130
|
+
const id = existing?.threadId ?? (kind === "group" ? groupThreadId(this.host.identity.appId, targetId, this.teamId) : dmThreadId(this.host.identity.appId, this.host.identity.profileId, targetId, this.teamId));
|
|
131
|
+
if (!existing)
|
|
132
|
+
await this.host.submit({ type: "register", threadId: id, kind, targetId, teamId: this.teamId }, true);
|
|
133
|
+
this.prepare(id);
|
|
134
|
+
return id;
|
|
135
|
+
}
|
|
136
|
+
async getThread(id, options = {}) { this.assertOpen(); options.signal?.throwIfAborted(); return this.prepare(id); }
|
|
137
|
+
async loadEarlier(id, options = {}) { options.signal?.throwIfAborted(); this.limits.set(id, (this.limits.get(id) ?? 128) + 128); return this.getThread(id, options); }
|
|
138
|
+
async refreshThread(id, options = {}) { options.signal?.throwIfAborted(); await this.host.synchronize(); return this.getThread(id, options); }
|
|
139
|
+
subscribeThread(id, listener, _options = {}) {
|
|
140
|
+
this.assertOpen();
|
|
141
|
+
let listeners = this.listening.get(id);
|
|
142
|
+
if (!listeners) {
|
|
143
|
+
listeners = new Set();
|
|
144
|
+
this.listening.set(id, listeners);
|
|
145
|
+
const update = () => { const value = this.prepare(id); for (const current of this.listening.get(id) ?? [])
|
|
146
|
+
current(value); };
|
|
147
|
+
const off = this.host.memory.subscribeThread(this.key(id), update);
|
|
148
|
+
const parentOff = this.discussion ? this.host.memory.subscribeThread(this.discussion.parentId, update) : undefined;
|
|
149
|
+
this.offs.set(id, () => { off(); parentOff?.(); });
|
|
150
|
+
}
|
|
151
|
+
listeners.add(listener);
|
|
152
|
+
listener(this.prepare(id));
|
|
153
|
+
return () => { listeners.delete(listener); if (!listeners.size) {
|
|
154
|
+
this.offs.get(id)?.();
|
|
155
|
+
this.offs.delete(id);
|
|
156
|
+
this.listening.delete(id);
|
|
157
|
+
} };
|
|
158
|
+
}
|
|
159
|
+
subscribeChat(listener, _options = {}) { this.listListeners.add(listener); listener(this.summary); return () => { this.listListeners.delete(listener); }; }
|
|
160
|
+
openMessageThread(threadId, rootId) {
|
|
161
|
+
this.assertOpen();
|
|
162
|
+
if (this.discussion)
|
|
163
|
+
throw new ChatError("invalid-input", "Nested discussions are not supported");
|
|
164
|
+
return new ProfileChat(this.host, this.teamId, { parentId: threadId, rootId });
|
|
165
|
+
}
|
|
166
|
+
async getMessageThreads(id, roots, options = {}) {
|
|
167
|
+
options.signal?.throwIfAborted();
|
|
168
|
+
return { revision: this.host.memory.getStatus().revision ?? 0, items: roots.map(root => {
|
|
169
|
+
const thread = this.host.memory.getThread(profileDiscussionId(id, root));
|
|
170
|
+
return { rootMessageId: root, replyCount: thread?.messageCount ?? 0, unreadCount: thread?.unreadCount ?? 0,
|
|
171
|
+
lastReplyId: thread?.lastMessageId ?? null, lastReplyAt: thread?.lastActivityAt ?? null, participantProfileIds: thread?.participantProfileIds ?? [], ownerAgentId: thread?.ownerAgentId };
|
|
172
|
+
}) };
|
|
173
|
+
}
|
|
174
|
+
async sendPrepared(threadId, wire, options = {}, voiceBlob) {
|
|
175
|
+
this.assertOpen();
|
|
176
|
+
await this.host.submit({ type: "send", threadId: this.key(threadId), parentThreadId: this.discussion?.parentId, message: wire, command: {
|
|
177
|
+
commandId: wire.hash, messageId: wire.hash, kind: "message", threadId: this.key(threadId), createdAt: wire.t,
|
|
178
|
+
payload: voiceBlob ? { message: wire, voiceBlob } : wire, state: "pending", attempts: 0,
|
|
179
|
+
} }, true);
|
|
180
|
+
if (options.waitFor === "delivered")
|
|
181
|
+
await this.host.waitForCommand(wire.hash);
|
|
182
|
+
return wire;
|
|
183
|
+
}
|
|
184
|
+
async sendMessage(id, content, options = {}) {
|
|
185
|
+
const parent = this.parent(id);
|
|
186
|
+
if (!parent?.internal?.targetId)
|
|
187
|
+
throw new ChatError("unavailable", "Conversation is not prepared");
|
|
188
|
+
const kind = parent.kind === "dm" ? "dm" : "group", identity = this.host.identity;
|
|
189
|
+
const expectedId = kind === "group" ? groupThreadId(identity.appId, parent.internal.targetId, this.teamId) : dmThreadId(identity.appId, identity.profileId, parent.internal.targetId, this.teamId);
|
|
190
|
+
const input = outgoingContent({ ...identity, teamId: this.teamId }, { id: expectedId, kind, targetId: parent.internal.targetId, teamId: this.teamId, memberIds: parent.group?.members }, { ...content, ...(this.discussion ? { threadRootId: this.discussion.rootId } : {}) });
|
|
191
|
+
const wire = createRuntimeMsg(identity.profileId, input.to, 1, input.body);
|
|
192
|
+
wire.recipients = input.recipients;
|
|
193
|
+
await this.sendPrepared(id, wire, options, input.voiceBlob);
|
|
194
|
+
return { id: wire.hash, timestamp: wire.t };
|
|
195
|
+
}
|
|
196
|
+
async retryMessage(messageId) {
|
|
197
|
+
const message = this.host.memory.getMessage(messageId);
|
|
198
|
+
if (!message)
|
|
199
|
+
throw new ChatError("invalid-input", "Message not found");
|
|
200
|
+
await this.host.submit({ type: "commandResult", commandId: messageId, state: "pending" }, true);
|
|
201
|
+
return { id: messageId, timestamp: message.orderKey[0] };
|
|
202
|
+
}
|
|
203
|
+
observeMessages(id, ids, event) {
|
|
204
|
+
return this.host.submit({ type: "observe", threadId: this.key(id), messageIds: ids, policy: event, commandId: crypto.randomUUID(), createdAt: Date.now() }, event === "played");
|
|
205
|
+
}
|
|
206
|
+
async markRead(id) {
|
|
207
|
+
const thread = this.thread(id);
|
|
208
|
+
if (!thread)
|
|
209
|
+
return;
|
|
210
|
+
// Explicit media and discussion cards are excluded by the owner reducer.
|
|
211
|
+
const ids = [];
|
|
212
|
+
let anchor;
|
|
213
|
+
for (;;) {
|
|
214
|
+
const page = this.host.memory.readPage(this.key(id), anchor, 1000);
|
|
215
|
+
ids.push(...page.map(row => row.messageId));
|
|
216
|
+
if (page.length < 1000)
|
|
217
|
+
break;
|
|
218
|
+
anchor = page[0].messageId;
|
|
219
|
+
}
|
|
220
|
+
await this.observeMessages(id, ids, "visible");
|
|
221
|
+
}
|
|
222
|
+
async getReaders(id, messageId, options = {}) {
|
|
223
|
+
options.signal?.throwIfAborted();
|
|
224
|
+
const message = this.host.memory.getMessage(messageId);
|
|
225
|
+
if (!message || message.threadId !== this.key(id))
|
|
226
|
+
throw new ChatError("invalid-input", "Message not found");
|
|
227
|
+
if (message.receiptStatus !== "ready")
|
|
228
|
+
throw new ChatError("unavailable", "Reading receipts are not prepared");
|
|
229
|
+
const readers = message.readBy.filter(profile => !options.afterProfileId || profile > options.afterProfileId).slice(0, 100);
|
|
230
|
+
return { appId: this.host.identity.appId, threadId: id, messageId, revision: message.revision, total: message.readBy.length,
|
|
231
|
+
profileIds: readers, nextAfter: readers.length === 100 ? readers.at(-1) : null, resetRequired: options.revision !== undefined && options.revision !== message.revision };
|
|
232
|
+
}
|
|
233
|
+
async watchReaders(_id, _ids, _receiver) { }
|
|
234
|
+
async getVoiceAttachment(id, messageId, options = {}) {
|
|
235
|
+
options.signal?.throwIfAborted();
|
|
236
|
+
const message = this.host.memory.getMessage(messageId);
|
|
237
|
+
if (!message || message.threadId !== this.key(id))
|
|
238
|
+
throw new ChatError("invalid-input", "Message not found");
|
|
239
|
+
const url = this.host.memory.getPresentedMessage(messageId)?.voice?.url;
|
|
240
|
+
if (url)
|
|
241
|
+
return { url, release: () => { } };
|
|
242
|
+
const blob = await this.host.voiceAttachment(messageId);
|
|
243
|
+
if (!blob)
|
|
244
|
+
throw new ChatError("unavailable", "Voice attachment unavailable");
|
|
245
|
+
const objectUrl = URL.createObjectURL(blob);
|
|
246
|
+
return { url: objectUrl, release: () => URL.revokeObjectURL(objectUrl) };
|
|
247
|
+
}
|
|
248
|
+
async getGroup(id, options = {}) { options.signal?.throwIfAborted(); const group = this.group(this.parent(id)); if (!group)
|
|
249
|
+
throw new ChatError("unavailable", "Group is not prepared"); return group; }
|
|
250
|
+
async refreshGroup(id, options = {}) { await this.host.synchronize(); return this.getGroup(id, options); }
|
|
251
|
+
async waitGroup(id, previous) {
|
|
252
|
+
const get = () => { const group = this.group(this.parent(id)); return group && group.revision !== previous ? group : undefined; };
|
|
253
|
+
const current = get();
|
|
254
|
+
if (current)
|
|
255
|
+
return current;
|
|
256
|
+
return new Promise((resolve, reject) => {
|
|
257
|
+
const timer = setTimeout(() => { off(); reject(new ChatError("unavailable", "Waiting for group confirmation")); }, 30000);
|
|
258
|
+
const off = this.host.memory.subscribeThread(id, () => { const group = get(); if (group) {
|
|
259
|
+
clearTimeout(timer);
|
|
260
|
+
off();
|
|
261
|
+
resolve(group);
|
|
262
|
+
} });
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
async createGroup(input) {
|
|
266
|
+
return createUniqueGroup(input.groupId, async (groupId) => {
|
|
267
|
+
const id = await this.resolveThreadId({ groupId });
|
|
268
|
+
await this.sendControl(id, { groupCreate: { title: input.title, members: input.members } });
|
|
269
|
+
return { ...await this.waitGroup(id), threadId: id };
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
async sendControl(id, content) {
|
|
273
|
+
const parent = this.parent(id), identity = this.host.identity;
|
|
274
|
+
if (!parent?.internal?.targetId)
|
|
275
|
+
throw new ChatError("unavailable", "Conversation is not prepared");
|
|
276
|
+
const input = outgoingContent({ ...identity, teamId: this.teamId }, { id: groupThreadId(identity.appId, parent.internal.targetId, this.teamId), kind: "group", targetId: parent.internal.targetId, teamId: this.teamId, memberIds: parent.group?.members }, content);
|
|
277
|
+
const wire = createRuntimeMsg(identity.profileId, input.to, 1, input.body);
|
|
278
|
+
wire.recipients = input.recipients;
|
|
279
|
+
await this.sendPrepared(id, wire, { waitFor: "delivered" });
|
|
280
|
+
await this.host.synchronize();
|
|
281
|
+
}
|
|
282
|
+
async updateGroup(id, changes) { const previous = await this.getGroup(id); await this.sendControl(id, { groupUpdate: { ...changes, expectedRevision: changes.expectedRevision ?? previous.revision } }); return this.waitGroup(id, previous.revision); }
|
|
283
|
+
async dissolveGroup(id, options = {}) { const previous = await this.getGroup(id); await this.sendControl(id, { groupDissolve: { expectedRevision: options.expectedRevision ?? previous.revision } }); return this.waitGroup(id, previous.revision); }
|
|
284
|
+
synchronizeReading() { return this.host.synchronize(); }
|
|
285
|
+
revokeThread(id) { return this.host.submit({ type: "revoke", threadId: this.key(id) }, true); }
|
|
286
|
+
async revokeAccess() { for (const thread of this.host.memory.getThreadList())
|
|
287
|
+
if (thread.teamId === this.teamId)
|
|
288
|
+
await this.revokeThread(thread.threadId); }
|
|
289
|
+
firstUnread(id) { return this.thread(id)?.firstUnreadMessageId; }
|
|
290
|
+
sharedTransport() {
|
|
291
|
+
return { sendPrepared: (wire) => {
|
|
292
|
+
const content = wire.body;
|
|
293
|
+
const thread = this.host.memory.getThreadList().find(row => row.teamId === this.teamId && row.internal?.targetId === (content.content?.groupId ?? content.payload?.groupId ?? wire.to));
|
|
294
|
+
if (!thread)
|
|
295
|
+
return Promise.reject(new ChatError("unavailable", "Conversation is not prepared"));
|
|
296
|
+
return this.sendPrepared(thread.threadId, wire, { waitFor: "delivered" });
|
|
297
|
+
} };
|
|
298
|
+
}
|
|
299
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export type ProfileCommitQueueOptions<T> = {
|
|
2
|
+
commit: (events: readonly T[]) => Promise<void>;
|
|
3
|
+
windowMs?: number;
|
|
4
|
+
maxEvents?: number;
|
|
5
|
+
maxBytes?: number;
|
|
6
|
+
capacityEvents?: number;
|
|
7
|
+
capacityBytes?: number;
|
|
8
|
+
retryMs?: number;
|
|
9
|
+
onError?: (error: unknown) => void;
|
|
10
|
+
};
|
|
11
|
+
/** A fixed acceptance window with one durable commit in flight. Failed batches
|
|
12
|
+
* stay at the head: later commands cannot pass a failed Inbox cursor update. */
|
|
13
|
+
export declare class ProfileCommitQueue<T> {
|
|
14
|
+
private entries;
|
|
15
|
+
private bytes;
|
|
16
|
+
private timer?;
|
|
17
|
+
private running?;
|
|
18
|
+
private closed;
|
|
19
|
+
private retryAt;
|
|
20
|
+
private urgent;
|
|
21
|
+
private retryBatch?;
|
|
22
|
+
private options;
|
|
23
|
+
constructor(options: ProfileCommitQueueOptions<T>);
|
|
24
|
+
get pending(): {
|
|
25
|
+
events: number;
|
|
26
|
+
bytes: number;
|
|
27
|
+
};
|
|
28
|
+
/** Admission is synchronous; callers pause their source on backpressure.
|
|
29
|
+
* A single oversized event is admitted only into an otherwise empty queue. */
|
|
30
|
+
enqueue(event: T, bytes: number, immediate?: boolean, barrier?: boolean): Promise<void>;
|
|
31
|
+
/** Expedite accepted commands without bypassing a failed batch's retry delay. */
|
|
32
|
+
flush(): void;
|
|
33
|
+
private schedule;
|
|
34
|
+
private run;
|
|
35
|
+
/** Never silently discard accepted non-durable commands. The owner must drain
|
|
36
|
+
* before closing; an interrupted process recovers remote inputs by cursor. */
|
|
37
|
+
close(): void;
|
|
38
|
+
}
|