@pmate/chat-sdk 0.12.0-next.96 → 0.13.0-profile.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.
Files changed (39) hide show
  1. package/lib/framework.d.ts +2 -0
  2. package/lib/framework.js +2 -0
  3. package/lib/messageView.d.ts +5 -0
  4. package/lib/messageView.js +2 -2
  5. package/lib/profile.d.ts +14 -0
  6. package/lib/profile.js +10 -0
  7. package/lib/profileWorker.d.ts +1 -0
  8. package/lib/profileWorker.js +3 -0
  9. package/lib/runtime/profileChat.d.ts +138 -0
  10. package/lib/runtime/profileChat.js +324 -0
  11. package/lib/runtime/profileCommitQueue.d.ts +38 -0
  12. package/lib/runtime/profileCommitQueue.js +101 -0
  13. package/lib/runtime/profileCoordinator.d.ts +46 -0
  14. package/lib/runtime/profileCoordinator.js +135 -0
  15. package/lib/runtime/profileDatabase.d.ts +42 -0
  16. package/lib/runtime/profileDatabase.js +164 -0
  17. package/lib/runtime/profileGenerationBuilder.d.ts +18 -0
  18. package/lib/runtime/profileGenerationBuilder.js +112 -0
  19. package/lib/runtime/profileInboxFeed.d.ts +38 -0
  20. package/lib/runtime/profileInboxFeed.js +240 -0
  21. package/lib/runtime/profileMemoryStore.d.ts +115 -0
  22. package/lib/runtime/profileMemoryStore.js +265 -0
  23. package/lib/runtime/profileOutboxDispatcher.d.ts +31 -0
  24. package/lib/runtime/profileOutboxDispatcher.js +106 -0
  25. package/lib/runtime/profileOwner.d.ts +57 -0
  26. package/lib/runtime/profileOwner.js +202 -0
  27. package/lib/runtime/profileProjection.d.ts +77 -0
  28. package/lib/runtime/profileProjection.js +625 -0
  29. package/lib/runtime/profileReadingIndex.d.ts +17 -0
  30. package/lib/runtime/profileReadingIndex.js +99 -0
  31. package/lib/runtime/profileReplica.d.ts +59 -0
  32. package/lib/runtime/profileReplica.js +236 -0
  33. package/lib/runtime/profileStoreTypes.d.ts +163 -0
  34. package/lib/runtime/profileStoreTypes.js +1 -0
  35. package/lib/runtime/profileWindows.d.ts +38 -0
  36. package/lib/runtime/profileWindows.js +175 -0
  37. package/lib/runtime/profileWorkerHost.d.ts +33 -0
  38. package/lib/runtime/profileWorkerHost.js +156 -0
  39. package/package.json +11 -1
@@ -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);
@@ -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;
@@ -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 content(message) {
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) ?? content(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 };
@@ -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, handleProfileChatReach, revokeProfileChatAccess } 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, handleProfileChatReach, revokeProfileChatAccess } from "./runtime/profileChat.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import { installProfileWorker } from "./runtime/profileWorkerHost.js";
2
+ // Worker-only entry point. Consumers instantiate this module with new Worker().
3
+ installProfileWorker(globalThis);
@@ -0,0 +1,138 @@
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
+ import type { OnlineReachEvent } from "./reach.js";
8
+ export type ProfileChatHost = {
9
+ identity: ProfileIdentity;
10
+ memory: ProfileMemoryStore;
11
+ start(): Promise<void>;
12
+ submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
13
+ synchronize(): Promise<void>;
14
+ waitForCommand(id: string): Promise<void>;
15
+ voiceAttachment(id: string): Promise<Blob | null>;
16
+ };
17
+ export declare function getProfileChatRuntime(chat: Chat): ProfileChat;
18
+ export declare function createProfileChat(host: ProfileChatHost, teamId: string): Chat;
19
+ export declare function handleProfileChatReach(chat: Chat, event: OnlineReachEvent): "handled" | undefined;
20
+ export declare function revokeProfileChatAccess(chat: Chat): Promise<void>;
21
+ /** Product-facing Chat adapter over prepared Profile views. No legacy Session,
22
+ * second outbox, reading persistence or per-team message database is created. */
23
+ export declare class ProfileChat implements Chat {
24
+ readonly host: ProfileChatHost;
25
+ readonly teamId: string;
26
+ private discussion?;
27
+ private views;
28
+ private limits;
29
+ private listening;
30
+ private listListeners;
31
+ private offs;
32
+ private offList;
33
+ private closed;
34
+ private summary;
35
+ constructor(host: ProfileChatHost, teamId: string, discussion?: {
36
+ parentId: string;
37
+ rootId: string;
38
+ } | undefined);
39
+ private assertOpen;
40
+ private key;
41
+ private thread;
42
+ private parent;
43
+ private group;
44
+ private empty;
45
+ private snapshot;
46
+ private prepare;
47
+ private prepareSummary;
48
+ start(): Promise<void>;
49
+ initialize(): Promise<void>;
50
+ close(): Promise<void>;
51
+ resolveThreadId(target: {
52
+ peerId: string;
53
+ groupId?: never;
54
+ } | {
55
+ groupId: string;
56
+ peerId?: never;
57
+ }, options?: ReadOptions): Promise<string>;
58
+ getThread(id: string, options?: ReadOptions): Promise<ChatThreadSnapshot>;
59
+ loadEarlier(id: string, options?: ReadOptions): Promise<ChatThreadSnapshot>;
60
+ refreshThread(id: string, options?: ReadOptions): Promise<ChatThreadSnapshot>;
61
+ subscribeThread(id: string, listener: (snapshot: ChatThreadSnapshot) => void, _options?: {}): () => void;
62
+ subscribeChat(listener: (snapshot: ChatSnapshot) => void, _options?: {}): () => void;
63
+ openMessageThread(threadId: string, rootId: string): Chat;
64
+ getMessageThreads(id: string, roots: readonly string[], options?: ReadOptions): Promise<{
65
+ revision: number;
66
+ items: {
67
+ rootMessageId: string;
68
+ replyCount: number;
69
+ unreadCount: number;
70
+ lastReplyId: string | null;
71
+ lastReplyAt: number | null;
72
+ participantProfileIds: string[];
73
+ ownerAgentId: string | undefined;
74
+ }[];
75
+ }>;
76
+ sendPrepared(threadId: string, wire: ChatRuntimeMessage, options?: SendOptions, voiceBlob?: Blob): Promise<ChatRuntimeMessage>;
77
+ sendMessage(id: string, content: OutgoingContent, options?: SendOptions): Promise<SentMessage>;
78
+ retryMessage(messageId: string): Promise<{
79
+ id: string;
80
+ timestamp: number;
81
+ }>;
82
+ observeMessages(id: string, ids: string[], event: "visible" | "played"): Promise<void>;
83
+ markRead(id: string): Promise<void>;
84
+ getReaders(id: string, messageId: string, options?: ReadersQuery & ReadOptions): Promise<{
85
+ appId: string;
86
+ threadId: string;
87
+ messageId: string;
88
+ revision: number;
89
+ total: number;
90
+ profileIds: string[];
91
+ nextAfter: string | null;
92
+ resetRequired: boolean;
93
+ }>;
94
+ watchReaders(_id: string | undefined, _ids: string[], _receiver?: string): Promise<void>;
95
+ getVoiceAttachment(id: string, messageId: string, options?: ReadOptions): Promise<{
96
+ url: string;
97
+ release: () => void;
98
+ }>;
99
+ getGroup(id: string, options?: ReadOptions): Promise<ChatGroup>;
100
+ refreshGroup(id: string, options?: ReadOptions): Promise<ChatGroup>;
101
+ private waitGroup;
102
+ createGroup(input: {
103
+ groupId?: string;
104
+ title: string;
105
+ members: readonly string[];
106
+ }): Promise<{
107
+ threadId: string;
108
+ groupId: string;
109
+ teamId: string;
110
+ ownerId: string;
111
+ revision: string;
112
+ status: "active";
113
+ title: string;
114
+ avatar?: string;
115
+ memberIds: readonly string[];
116
+ } | {
117
+ threadId: string;
118
+ groupId: string;
119
+ teamId: string;
120
+ ownerId: string;
121
+ revision: string;
122
+ status: "dissolved";
123
+ dissolvedBy?: string;
124
+ dissolvedAt?: number;
125
+ }>;
126
+ private sendControl;
127
+ updateGroup(id: string, changes: GroupChanges): Promise<ChatGroup>;
128
+ dissolveGroup(id: string, options?: {
129
+ expectedRevision?: string;
130
+ }): Promise<ChatGroup>;
131
+ synchronizeReading(): Promise<void>;
132
+ revokeThread(id: string): Promise<void>;
133
+ revokeAccess(): Promise<void>;
134
+ firstUnread(id: string): string | undefined;
135
+ sharedTransport(): {
136
+ sendPrepared: (wire: ChatRuntimeMessage) => Promise<ChatRuntimeMessage>;
137
+ };
138
+ }
@@ -0,0 +1,324 @@
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
+ import { messageThreadRoot } from "./messageThread.js";
9
+ const sessions = new WeakMap();
10
+ export function getProfileChatRuntime(chat) {
11
+ const session = sessions.get(chat);
12
+ if (!session)
13
+ throw Error("UNKNOWN_PROFILE_CHAT");
14
+ return session;
15
+ }
16
+ export function createProfileChat(host, teamId) { return new ProfileChat(host, teamId); }
17
+ export function handleProfileChatReach(chat, event) {
18
+ if (!["social.readCountsChanged", "social.readStateChanged"].includes(event.eventType))
19
+ return;
20
+ const { identity } = getProfileChatRuntime(chat).host;
21
+ if (event.appId !== identity.appId)
22
+ throw Error("UNEXPECTED_READING_APPLICATION");
23
+ if (event.eventType === "social.readStateChanged" && event.payload.profileId !== identity.profileId)
24
+ throw Error("Reading reach identity mismatch");
25
+ // Inbox owns the ordered receipt stream. Reach is only a hint and must not
26
+ // create another reading store or apply facts outside that stream.
27
+ return "handled";
28
+ }
29
+ export function revokeProfileChatAccess(chat) { return getProfileChatRuntime(chat).revokeAccess(); }
30
+ /** Product-facing Chat adapter over prepared Profile views. No legacy Session,
31
+ * second outbox, reading persistence or per-team message database is created. */
32
+ export class ProfileChat {
33
+ host;
34
+ teamId;
35
+ discussion;
36
+ views = new Map();
37
+ limits = new Map();
38
+ listening = new Map();
39
+ listListeners = new Set();
40
+ offs = new Map();
41
+ offList;
42
+ closed = false;
43
+ summary = { threads: [], unreadMessageCount: undefined, badgeCount: undefined, connection: "connecting" };
44
+ constructor(host, teamId, discussion) {
45
+ this.host = host;
46
+ this.teamId = teamId;
47
+ this.discussion = discussion;
48
+ sessions.set(this, this);
49
+ const subscribeChanges = ((target, listener) => typeof target === "string"
50
+ ? this.subscribeThread(target, () => listener()) : this.subscribeChat(() => target()));
51
+ registerChatStore(this, { getSnapshot: ((id) => id === undefined ? this.summary : this.snapshot(id)),
52
+ subscribeThread: (id, listener) => this.subscribeThread(id, () => listener()), subscribeChanges });
53
+ this.offList = host.memory.subscribeThreadList(() => this.prepareSummary());
54
+ this.prepareSummary();
55
+ }
56
+ assertOpen() { if (this.closed)
57
+ throw new ChatError("closed", "Chat session closed"); }
58
+ key(id) { return this.discussion ? profileDiscussionId(this.discussion.parentId, this.discussion.rootId) : id; }
59
+ thread(id) { return this.host.memory.getThread(this.key(id)); }
60
+ parent(id) { return this.host.memory.getThread(this.discussion?.parentId ?? id); }
61
+ group(thread) {
62
+ const group = thread?.group;
63
+ if (!group)
64
+ return;
65
+ const base = { groupId: group.groupId, teamId: group.teamId ?? this.teamId, ownerId: group.ownerId, revision: group.revision };
66
+ return group.status === "dissolved" ? { ...base, status: "dissolved", dissolvedBy: group.dissolvedBy, dissolvedAt: group.dissolvedAt }
67
+ : { ...base, status: "active", title: group.title ?? "", avatar: group.avatar ?? undefined, memberIds: group.members ?? [] };
68
+ }
69
+ empty(id) {
70
+ return { threadId: id, messages: [], hasEarlier: false, unread: undefined, group: undefined, readCounts: undefined, status: "pending", ready: false };
71
+ }
72
+ snapshot(id) {
73
+ let view = this.views.get(id);
74
+ if (!view) {
75
+ view = this.empty(id);
76
+ this.views.set(id, view);
77
+ }
78
+ return view;
79
+ }
80
+ prepare(id) {
81
+ const memory = this.host.memory, thread = this.thread(id), parent = this.parent(id);
82
+ if (memory.getStatus().phase !== "ready" || !thread && !(this.discussion && parent?.status === "ready"))
83
+ return this.snapshot(id);
84
+ if (thread?.status === "unavailable" || parent?.status === "unavailable") {
85
+ const error = new ChatError("access-denied", "Conversation unavailable", { threadId: id, status: 403 });
86
+ const view = { ...this.empty(id), status: "error", ready: false, error };
87
+ this.views.set(id, view);
88
+ return view;
89
+ }
90
+ const count = Math.min(this.limits.get(id) ?? 128, thread?.messageCount ?? 0);
91
+ // Compatibility API accumulates requested pages; readPage remains the
92
+ // bounded API for page components and never materializes the whole thread.
93
+ const pages = [];
94
+ let anchor;
95
+ for (let remaining = count; remaining > 0; remaining -= 1000) {
96
+ const page = memory.readPresentedPage(this.key(id), anchor, Math.min(remaining, 1000));
97
+ pages.unshift(page);
98
+ anchor = page[0]?.id;
99
+ }
100
+ const messages = pages.length === 1 ? pages[0] : pages.flat();
101
+ const group = this.group(parent);
102
+ const counts = {};
103
+ for (const message of messages) {
104
+ const raw = memory.getMessage(message.id);
105
+ if (raw?.receiptStatus === "ready")
106
+ counts[message.id] = raw.readBy.length;
107
+ }
108
+ const previous = this.views.get(id);
109
+ const view = { threadId: id, messages, hasEarlier: count < (thread?.messageCount ?? 0),
110
+ conversation: parent ? { kind: parent.kind === "dm" ? "dm" : "group", targetId: parent.internal?.targetId ?? "" } : undefined,
111
+ unread: thread?.unreadCount === null ? undefined : { unreadMessageCount: thread?.unreadCount ?? 0, unreadMentionCount: thread?.mentionCount ?? 0,
112
+ badgeCount: thread?.kind === "dm" ? thread.unreadCount ?? 0 : thread?.mentionCount ?? 0 },
113
+ group, readCounts: { appId: this.host.identity.appId, threadId: id, revision: memory.getStatus().revision ?? 0, counts }, status: "ready", ready: true };
114
+ if (previous?.messages === view.messages && previous.unread?.unreadMessageCount === view.unread?.unreadMessageCount &&
115
+ previous.unread?.unreadMentionCount === view.unread?.unreadMentionCount && previous.group?.revision === view.group?.revision && previous.readCounts?.revision === view.readCounts?.revision)
116
+ return previous;
117
+ this.views.set(id, view);
118
+ return view;
119
+ }
120
+ prepareSummary() {
121
+ const rows = this.host.memory.getThreadList().filter(thread => thread.teamId === this.teamId && thread.status !== "unavailable");
122
+ this.summary = { threads: rows.map(thread => ({ threadId: thread.threadId, lastMessage: thread.lastMessageId ? this.host.memory.getPresentedMessage(thread.lastMessageId) : undefined,
123
+ group: this.group(thread), unread: thread.unreadCount === null ? undefined : { unreadMessageCount: thread.unreadCount, unreadMentionCount: thread.mentionCount ?? 0,
124
+ badgeCount: thread.kind === "dm" ? thread.unreadCount : thread.mentionCount ?? 0 }, outgoingCount: 0 })),
125
+ unreadMessageCount: rows.some(thread => thread.unreadCount === null) ? undefined : rows.reduce((sum, thread) => sum + thread.unreadCount, 0),
126
+ badgeCount: rows.some(thread => thread.unreadCount === null) ? undefined : rows.reduce((sum, thread) => sum + (thread.kind === "dm" ? thread.unreadCount : thread.mentionCount ?? 0), 0),
127
+ connection: this.host.memory.getStatus().phase === "ready" ? "connected" : "connecting" };
128
+ for (const listener of this.listListeners)
129
+ listener(this.summary);
130
+ }
131
+ async start() { this.assertOpen(); await this.host.start(); this.prepareSummary(); }
132
+ initialize() { return this.start(); }
133
+ async close() { if (this.closed)
134
+ return; this.closed = true; this.offList(); for (const off of this.offs.values())
135
+ off(); this.offs.clear(); this.listening.clear(); this.listListeners.clear(); }
136
+ async resolveThreadId(target, options = {}) {
137
+ this.assertOpen();
138
+ options.signal?.throwIfAborted();
139
+ await this.host.start();
140
+ const kind = target.groupId !== undefined ? "group" : "dm", targetId = target.groupId ?? target.peerId;
141
+ if (this.discussion)
142
+ return this.discussion.parentId;
143
+ const existing = this.host.memory.getThreadList().find(thread => thread.teamId === this.teamId && thread.kind === kind && thread.internal?.targetId === targetId);
144
+ 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));
145
+ if (!existing)
146
+ await this.host.submit({ type: "register", threadId: id, kind, targetId, teamId: this.teamId }, true);
147
+ this.prepare(id);
148
+ return id;
149
+ }
150
+ async getThread(id, options = {}) { this.assertOpen(); options.signal?.throwIfAborted(); return this.prepare(id); }
151
+ async loadEarlier(id, options = {}) {
152
+ this.assertOpen();
153
+ options.signal?.throwIfAborted();
154
+ this.limits.set(id, (this.limits.get(id) ?? 128) + 128);
155
+ const previous = this.views.get(id), value = this.prepare(id);
156
+ if (previous !== value)
157
+ for (const listener of this.listening.get(id) ?? [])
158
+ listener(value);
159
+ return value;
160
+ }
161
+ async refreshThread(id, options = {}) { options.signal?.throwIfAborted(); await this.host.synchronize(); return this.getThread(id, options); }
162
+ subscribeThread(id, listener, _options = {}) {
163
+ this.assertOpen();
164
+ let listeners = this.listening.get(id);
165
+ if (!listeners) {
166
+ listeners = new Set();
167
+ this.listening.set(id, listeners);
168
+ const update = () => { const value = this.prepare(id); for (const current of this.listening.get(id) ?? [])
169
+ current(value); };
170
+ const off = this.host.memory.subscribeThread(this.key(id), update);
171
+ const parentOff = this.discussion ? this.host.memory.subscribeThread(this.discussion.parentId, update) : undefined;
172
+ this.offs.set(id, () => { off(); parentOff?.(); });
173
+ }
174
+ listeners.add(listener);
175
+ listener(this.prepare(id));
176
+ return () => { listeners.delete(listener); if (!listeners.size) {
177
+ this.offs.get(id)?.();
178
+ this.offs.delete(id);
179
+ this.listening.delete(id);
180
+ } };
181
+ }
182
+ subscribeChat(listener, _options = {}) { this.listListeners.add(listener); listener(this.summary); return () => { this.listListeners.delete(listener); }; }
183
+ openMessageThread(threadId, rootId) {
184
+ this.assertOpen();
185
+ if (this.discussion)
186
+ throw new ChatError("invalid-input", "Nested discussions are not supported");
187
+ return new ProfileChat(this.host, this.teamId, { parentId: threadId, rootId });
188
+ }
189
+ async getMessageThreads(id, roots, options = {}) {
190
+ options.signal?.throwIfAborted();
191
+ return { revision: this.host.memory.getStatus().revision ?? 0, items: roots.map(root => {
192
+ const thread = this.host.memory.getThread(profileDiscussionId(id, root));
193
+ return { rootMessageId: root, replyCount: thread?.messageCount ?? 0, unreadCount: thread?.unreadCount ?? 0,
194
+ lastReplyId: thread?.lastMessageId ?? null, lastReplyAt: thread?.lastActivityAt ?? null, participantProfileIds: thread?.participantProfileIds ?? [], ownerAgentId: thread?.ownerAgentId };
195
+ }) };
196
+ }
197
+ async sendPrepared(threadId, wire, options = {}, voiceBlob) {
198
+ this.assertOpen();
199
+ const root = messageThreadRoot(wire.body);
200
+ const destination = this.discussion ? this.key(threadId) : root ? profileDiscussionId(threadId, root) : threadId;
201
+ await this.host.submit({ type: "send", threadId: destination, parentThreadId: this.discussion?.parentId ?? (root ? threadId : undefined), message: wire, command: {
202
+ commandId: wire.hash, messageId: wire.hash, kind: "message", threadId: destination, createdAt: wire.t,
203
+ payload: voiceBlob ? { message: wire, voiceBlob } : wire, state: "pending", attempts: 0,
204
+ } }, true);
205
+ if (options.waitFor === "delivered")
206
+ await this.host.waitForCommand(wire.hash);
207
+ return wire;
208
+ }
209
+ async sendMessage(id, content, options = {}) {
210
+ const parent = this.parent(id);
211
+ if (!parent?.internal?.targetId)
212
+ throw new ChatError("unavailable", "Conversation is not prepared");
213
+ const kind = parent.kind === "dm" ? "dm" : "group", identity = this.host.identity;
214
+ const expectedId = kind === "group" ? groupThreadId(identity.appId, parent.internal.targetId, this.teamId) : dmThreadId(identity.appId, identity.profileId, parent.internal.targetId, this.teamId);
215
+ 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 } : {}) });
216
+ const wire = createRuntimeMsg(identity.profileId, input.to, 1, input.body);
217
+ wire.recipients = input.recipients;
218
+ await this.sendPrepared(id, wire, options, input.voiceBlob);
219
+ return { id: wire.hash, timestamp: wire.t };
220
+ }
221
+ async retryMessage(messageId) {
222
+ const message = this.host.memory.getMessage(messageId);
223
+ if (!message)
224
+ throw new ChatError("invalid-input", "Message not found");
225
+ await this.host.submit({ type: "commandResult", commandId: messageId, state: "pending" }, true);
226
+ return { id: messageId, timestamp: message.orderKey[0] };
227
+ }
228
+ observeMessages(id, ids, event) {
229
+ return this.host.submit({ type: "observe", threadId: this.key(id), messageIds: ids, policy: event, commandId: crypto.randomUUID(), createdAt: Date.now() }, event === "played");
230
+ }
231
+ async markRead(id) {
232
+ const thread = this.thread(id);
233
+ if (!thread)
234
+ return;
235
+ // Explicit media and discussion cards are excluded by the owner reducer.
236
+ const ids = [];
237
+ let anchor;
238
+ for (;;) {
239
+ const page = this.host.memory.readPage(this.key(id), anchor, 1000);
240
+ ids.push(...page.map(row => row.messageId));
241
+ if (page.length < 1000)
242
+ break;
243
+ anchor = page[0].messageId;
244
+ }
245
+ await this.observeMessages(id, ids, "visible");
246
+ }
247
+ async getReaders(id, messageId, options = {}) {
248
+ options.signal?.throwIfAborted();
249
+ const message = this.host.memory.getMessage(messageId);
250
+ if (!message || message.threadId !== this.key(id))
251
+ throw new ChatError("invalid-input", "Message not found");
252
+ if (message.receiptStatus !== "ready")
253
+ throw new ChatError("unavailable", "Reading receipts are not prepared");
254
+ const readers = message.readBy.filter(profile => !options.afterProfileId || profile > options.afterProfileId).slice(0, 100);
255
+ return { appId: this.host.identity.appId, threadId: id, messageId, revision: message.revision, total: message.readBy.length,
256
+ profileIds: readers, nextAfter: readers.length === 100 ? readers.at(-1) : null, resetRequired: options.revision !== undefined && options.revision !== message.revision };
257
+ }
258
+ async watchReaders(_id, _ids, _receiver) { }
259
+ async getVoiceAttachment(id, messageId, options = {}) {
260
+ options.signal?.throwIfAborted();
261
+ const message = this.host.memory.getMessage(messageId);
262
+ if (!message || message.threadId !== this.key(id))
263
+ throw new ChatError("invalid-input", "Message not found");
264
+ const url = this.host.memory.getPresentedMessage(messageId)?.voice?.url;
265
+ if (url)
266
+ return { url, release: () => { } };
267
+ const blob = await this.host.voiceAttachment(messageId);
268
+ if (!blob)
269
+ throw new ChatError("unavailable", "Voice attachment unavailable");
270
+ const objectUrl = URL.createObjectURL(blob);
271
+ return { url: objectUrl, release: () => URL.revokeObjectURL(objectUrl) };
272
+ }
273
+ async getGroup(id, options = {}) { options.signal?.throwIfAborted(); const group = this.group(this.parent(id)); if (!group)
274
+ throw new ChatError("unavailable", "Group is not prepared"); return group; }
275
+ async refreshGroup(id, options = {}) { await this.host.synchronize(); return this.getGroup(id, options); }
276
+ async waitGroup(id, previous) {
277
+ const get = () => { const group = this.group(this.parent(id)); return group && group.revision !== previous ? group : undefined; };
278
+ const current = get();
279
+ if (current)
280
+ return current;
281
+ return new Promise((resolve, reject) => {
282
+ const timer = setTimeout(() => { off(); reject(new ChatError("unavailable", "Waiting for group confirmation")); }, 30000);
283
+ const off = this.host.memory.subscribeThread(id, () => { const group = get(); if (group) {
284
+ clearTimeout(timer);
285
+ off();
286
+ resolve(group);
287
+ } });
288
+ });
289
+ }
290
+ async createGroup(input) {
291
+ return createUniqueGroup(input.groupId, async (groupId) => {
292
+ const id = await this.resolveThreadId({ groupId });
293
+ await this.sendControl(id, { groupCreate: { title: input.title, members: input.members } });
294
+ return { ...await this.waitGroup(id), threadId: id };
295
+ });
296
+ }
297
+ async sendControl(id, content) {
298
+ const parent = this.parent(id), identity = this.host.identity;
299
+ if (!parent?.internal?.targetId)
300
+ throw new ChatError("unavailable", "Conversation is not prepared");
301
+ 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);
302
+ const wire = createRuntimeMsg(identity.profileId, input.to, 1, input.body);
303
+ wire.recipients = input.recipients;
304
+ await this.sendPrepared(id, wire, { waitFor: "delivered" });
305
+ await this.host.synchronize();
306
+ }
307
+ 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); }
308
+ 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); }
309
+ synchronizeReading() { return this.host.synchronize(); }
310
+ revokeThread(id) { return this.host.submit({ type: "revoke", threadId: this.key(id) }, true); }
311
+ async revokeAccess() { for (const thread of this.host.memory.getThreadList())
312
+ if (thread.teamId === this.teamId)
313
+ await this.revokeThread(thread.threadId); }
314
+ firstUnread(id) { return this.thread(id)?.firstUnreadMessageId; }
315
+ sharedTransport() {
316
+ return { sendPrepared: (wire) => {
317
+ const content = wire.body;
318
+ const thread = this.host.memory.getThreadList().find(row => row.teamId === this.teamId && row.internal?.targetId === (content.content?.groupId ?? content.payload?.groupId ?? wire.to));
319
+ if (!thread)
320
+ return Promise.reject(new ChatError("unavailable", "Conversation is not prepared"));
321
+ return this.sendPrepared(thread.threadId, wire, { waitFor: "delivered" });
322
+ } };
323
+ }
324
+ }
@@ -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
+ }