@pmate/chat-sdk 0.12.0-next.9 → 0.12.0-next.90

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 (125) hide show
  1. package/README.md +216 -83
  2. package/lib/advanced.d.ts +10 -0
  3. package/lib/advanced.js +10 -0
  4. package/lib/chat.d.ts +5 -0
  5. package/lib/chat.js +11 -0
  6. package/lib/chatContract.d.ts +158 -0
  7. package/lib/chatContract.js +1 -0
  8. package/lib/chatError.d.ts +31 -0
  9. package/lib/chatError.js +18 -0
  10. package/lib/chatTypes.d.ts +128 -0
  11. package/lib/chatTypes.js +1 -0
  12. package/lib/commands.d.ts +20 -0
  13. package/lib/commands.js +12 -0
  14. package/lib/components/ChatInputDesktop.js +5 -4
  15. package/lib/components/ChatInputMobile.js +5 -4
  16. package/lib/components/CommandMenu.d.ts +15 -0
  17. package/lib/components/CommandMenu.js +10 -0
  18. package/lib/credentials.d.ts +26 -0
  19. package/lib/credentials.js +110 -0
  20. package/lib/fileMetadata.d.ts +9 -0
  21. package/lib/fileMetadata.js +18 -0
  22. package/lib/framework.d.ts +11 -0
  23. package/lib/framework.js +12 -0
  24. package/lib/history.d.ts +4 -0
  25. package/lib/history.js +8 -0
  26. package/lib/hooks/useChatSnapshot.d.ts +4 -0
  27. package/lib/hooks/useChatSnapshot.js +9 -0
  28. package/lib/hooks/useComposerSuggestions.d.ts +50 -0
  29. package/lib/hooks/useComposerSuggestions.js +70 -0
  30. package/lib/index.d.ts +6 -0
  31. package/lib/index.js +6 -0
  32. package/lib/internal/chatEngine.d.ts +131 -0
  33. package/lib/internal/chatEngine.js +306 -0
  34. package/lib/internal/chatRegistry.d.ts +4 -0
  35. package/lib/internal/chatRegistry.js +4 -0
  36. package/lib/internal/createPublicChat.d.ts +4 -0
  37. package/lib/internal/createPublicChat.js +62 -0
  38. package/lib/messageView.d.ts +6 -0
  39. package/lib/messageView.js +103 -0
  40. package/lib/runtime/batchedReadIndex.d.ts +16 -3
  41. package/lib/runtime/batchedReadIndex.js +50 -4
  42. package/lib/runtime/cachedMessage.d.ts +12 -0
  43. package/lib/runtime/cachedMessage.js +18 -0
  44. package/lib/runtime/chatClient.d.ts +8 -1
  45. package/lib/runtime/chatClient.js +18 -6
  46. package/lib/runtime/chatError.d.ts +5 -0
  47. package/lib/runtime/chatError.js +20 -0
  48. package/lib/runtime/chatSession.d.ts +141 -13
  49. package/lib/runtime/chatSession.js +797 -48
  50. package/lib/runtime/connectivity.d.ts +4 -0
  51. package/lib/runtime/connectivity.js +8 -0
  52. package/lib/runtime/conversationDirectory.d.ts +37 -0
  53. package/lib/runtime/conversationDirectory.js +116 -0
  54. package/lib/runtime/conversationRead.d.ts +14 -0
  55. package/lib/runtime/conversationRead.js +34 -0
  56. package/lib/runtime/conversationReading.d.ts +30 -0
  57. package/lib/runtime/conversationReading.js +47 -0
  58. package/lib/runtime/createChat.d.ts +14 -7
  59. package/lib/runtime/createChat.js +67 -24
  60. package/lib/runtime/durableSender.d.ts +97 -14
  61. package/lib/runtime/durableSender.js +787 -71
  62. package/lib/runtime/groupClient.d.ts +92 -0
  63. package/lib/runtime/groupClient.js +380 -0
  64. package/lib/runtime/groupDenial.d.ts +2 -0
  65. package/lib/runtime/groupDenial.js +4 -0
  66. package/lib/runtime/groupIdentity.d.ts +4 -0
  67. package/lib/runtime/groupIdentity.js +26 -0
  68. package/lib/runtime/inboxClient.d.ts +65 -0
  69. package/lib/runtime/inboxClient.js +268 -0
  70. package/lib/runtime/inboxGroup.d.ts +4 -0
  71. package/lib/runtime/inboxGroup.js +51 -0
  72. package/lib/runtime/inboxStore.d.ts +194 -0
  73. package/lib/runtime/inboxStore.js +321 -0
  74. package/lib/runtime/inboxTransport.d.ts +6 -0
  75. package/lib/runtime/inboxTransport.js +76 -0
  76. package/lib/runtime/index.d.ts +10 -0
  77. package/lib/runtime/index.js +8 -0
  78. package/lib/runtime/indexedDbRecovery.d.ts +6 -0
  79. package/lib/runtime/indexedDbRecovery.js +42 -0
  80. package/lib/runtime/messageClient.d.ts +37 -8
  81. package/lib/runtime/messageClient.js +366 -68
  82. package/lib/runtime/messageControls.d.ts +19 -0
  83. package/lib/runtime/messageControls.js +44 -0
  84. package/lib/runtime/messageDiscussionStore.d.ts +63 -0
  85. package/lib/runtime/messageDiscussionStore.js +147 -0
  86. package/lib/runtime/messageLaunch.d.ts +44 -0
  87. package/lib/runtime/messageLaunch.js +137 -0
  88. package/lib/runtime/messageQuotes.d.ts +3 -0
  89. package/lib/runtime/messageQuotes.js +17 -0
  90. package/lib/runtime/messageReaders.d.ts +5 -1
  91. package/lib/runtime/messageReaders.js +16 -5
  92. package/lib/runtime/messageStore.d.ts +51 -2
  93. package/lib/runtime/messageStore.js +264 -14
  94. package/lib/runtime/messageThread.d.ts +9 -0
  95. package/lib/runtime/messageThread.js +17 -0
  96. package/lib/runtime/messageTimeline.d.ts +51 -0
  97. package/lib/runtime/messageTimeline.js +121 -0
  98. package/lib/runtime/outboxSchema.d.ts +5 -0
  99. package/lib/runtime/outboxSchema.js +59 -0
  100. package/lib/runtime/outgoingContent.d.ts +95 -0
  101. package/lib/runtime/outgoingContent.js +121 -0
  102. package/lib/runtime/readBatchJournal.d.ts +35 -0
  103. package/lib/runtime/readBatchJournal.js +210 -0
  104. package/lib/runtime/readCounts.d.ts +7 -1
  105. package/lib/runtime/readCounts.js +108 -21
  106. package/lib/runtime/readIndex.d.ts +74 -7
  107. package/lib/runtime/readIndex.js +488 -33
  108. package/lib/runtime/readSchema.d.ts +2 -0
  109. package/lib/runtime/readSchema.js +58 -0
  110. package/lib/runtime/readSync.d.ts +8 -0
  111. package/lib/runtime/readSync.js +125 -17
  112. package/lib/runtime/readingClient.d.ts +22 -0
  113. package/lib/runtime/readingClient.js +141 -20
  114. package/lib/runtime/readingContent.d.ts +5 -0
  115. package/lib/runtime/readingContent.js +23 -0
  116. package/lib/runtime/responseCache.d.ts +41 -5
  117. package/lib/runtime/responseCache.js +182 -44
  118. package/lib/runtime/socialReadClient.d.ts +30 -4
  119. package/lib/runtime/socialReadClient.js +34 -8
  120. package/lib/runtime/voiceUpload.d.ts +2 -0
  121. package/lib/runtime/voiceUpload.js +27 -0
  122. package/lib/snapshot.d.ts +36 -0
  123. package/lib/snapshot.js +52 -0
  124. package/lib/types/chatInput.d.ts +3 -0
  125. package/package.json +32 -2
@@ -8,6 +8,7 @@ export class BatchedReadIndex {
8
8
  queueLimit;
9
9
  queues = new Map();
10
10
  closed = false;
11
+ sourceCounts = new WeakMap();
11
12
  constructor(storage, windowMs = 16, batchSize = 128, queueLimit = 4096) {
12
13
  this.storage = storage;
13
14
  this.windowMs = windowMs;
@@ -22,7 +23,42 @@ export class BatchedReadIndex {
22
23
  throw new Error("READ_STORAGE_CLOSED");
23
24
  return this.storage.load(appId, profileId);
24
25
  }
25
- update(appId, profileId, transform) {
26
+ async loadVersioned(appId, profileId) {
27
+ await this.flush(appId, profileId);
28
+ if (this.closed)
29
+ throw new Error("READ_STORAGE_CLOSED");
30
+ return this.storage.loadVersioned ? this.storage.loadVersioned(appId, profileId) : { state: await this.storage.load(appId, profileId), versions: {} };
31
+ }
32
+ async loadVersions(appId, profileId) {
33
+ if (this.closed)
34
+ throw new Error("READ_STORAGE_CLOSED");
35
+ return this.storage.loadVersions ? this.storage.loadVersions(appId, profileId) : {};
36
+ }
37
+ async invalidateTeam(appId, profileId, teamId, version, knownThreadIds) {
38
+ if (this.closed)
39
+ throw new Error("READ_STORAGE_CLOSED");
40
+ if (!this.storage.invalidateTeam)
41
+ throw new Error("READ_SCOPE_INVALIDATION_UNAVAILABLE");
42
+ // Do not flush a blocked old HTTP transform first. The durable epoch is the
43
+ // barrier; any queued transform sees it inside its eventual transaction.
44
+ return this.storage.invalidateTeam(appId, profileId, teamId, version, knownThreadIds);
45
+ }
46
+ weight(observation) {
47
+ if (!observation)
48
+ return 1;
49
+ let counts = this.sourceCounts.get(observation.base);
50
+ if (!counts) {
51
+ counts = new Map();
52
+ for (const thread of observation.base.threads) {
53
+ counts.set(thread.id, (counts.get(thread.id) ?? 0) + 1);
54
+ if (thread.conversationId && thread.conversationId !== thread.id)
55
+ counts.set(thread.conversationId, (counts.get(thread.conversationId) ?? 0) + 1);
56
+ }
57
+ this.sourceCounts.set(observation.base, counts);
58
+ }
59
+ return observation.targets.reduce((sum, target) => sum + (counts.get(target.threadId) ?? 1), 0);
60
+ }
61
+ update(appId, profileId, transform, observation) {
26
62
  if (this.closed)
27
63
  return Promise.reject(new Error("READ_STORAGE_CLOSED"));
28
64
  const key = JSON.stringify([appId, profileId]);
@@ -33,7 +69,7 @@ export class BatchedReadIndex {
33
69
  }
34
70
  if (queue.pending.length >= this.queueLimit)
35
71
  return Promise.reject(new Error("READ_STORAGE_BACKPRESSURE"));
36
- const promise = new Promise((resolve, reject) => queue.pending.push({ transform, resolve, reject }));
72
+ const promise = new Promise((resolve, reject) => queue.pending.push({ transform, observation, weight: this.weight(observation), resolve, reject }));
37
73
  if (!queue.running && queue.timer === undefined)
38
74
  queue.timer = setTimeout(() => { queue.timer = undefined; void this.drain(key, queue); }, this.windowMs);
39
75
  return promise;
@@ -43,12 +79,22 @@ export class BatchedReadIndex {
43
79
  return queue.running;
44
80
  clearTimeout(queue.timer);
45
81
  queue.timer = undefined;
46
- const batch = queue.pending.splice(0, this.batchSize);
82
+ const batch = [];
83
+ let weight = 0;
84
+ while (queue.pending.length && batch.length < this.batchSize) {
85
+ const nextWeight = queue.pending[0].weight;
86
+ if (batch.length && weight + nextWeight > 128)
87
+ break;
88
+ weight += nextWeight;
89
+ batch.push(queue.pending.shift());
90
+ }
47
91
  if (!batch.length)
48
92
  return;
49
93
  const run = (async () => {
50
94
  try {
51
- const next = await this.storage.update(queue.appId, queue.profileId, state => batch.reduce((current, change) => change.transform(current), state));
95
+ const first = batch[0].observation;
96
+ const observation = first && batch.every(change => change.observation?.base === first.base) ? { base: first.base, targets: batch.flatMap(change => change.observation.targets) } : undefined;
97
+ const next = await this.storage.update(queue.appId, queue.profileId, (state, versions) => batch.reduce((current, change) => change.transform(current, versions), state), observation);
52
98
  batch.forEach(change => change.resolve(next));
53
99
  }
54
100
  catch (error) {
@@ -0,0 +1,12 @@
1
+ import type { ChatReaderSocialMessage } from "./readerClient.js";
2
+ import type { ChatRuntimeMessage } from "./protocol.js";
3
+ export type CachedChatMessage = ChatReaderSocialMessage & {
4
+ id: string;
5
+ timestamp: number;
6
+ readPolicy?: "visible" | "explicit";
7
+ };
8
+ export declare function decodeCachedChatMessage(message: ChatRuntimeMessage, scope: {
9
+ appId: string;
10
+ profileId: string;
11
+ teamId: string;
12
+ }): CachedChatMessage | undefined;
@@ -0,0 +1,18 @@
1
+ import { chatTeamId } from "./teamScope.js";
2
+ import { dmThreadId, groupThreadId } from "./thread.js";
3
+ export function decodeCachedChatMessage(message, scope) {
4
+ if (message.opcode !== 1 || !message.body || typeof message.body !== "object")
5
+ return;
6
+ const body = message.body;
7
+ const invitation = body.kind === "contact" && ["friendRequest", "requestFriend"].includes(String(body.action));
8
+ if ((!invitation && body.kind !== "message") || (invitation ? body.payload?.appId : body.content?.appId) !== scope.appId || chatTeamId(body) !== scope.teamId)
9
+ return;
10
+ const threadKind = invitation ? "dm" : body.threadKind;
11
+ if (threadKind !== "dm" && threadKind !== "group")
12
+ return;
13
+ if (threadKind === "dm" && message.from !== scope.profileId && message.to !== scope.profileId)
14
+ return;
15
+ const threadId = threadKind === "dm" ? dmThreadId(scope.appId, message.from, message.to, scope.teamId) : groupThreadId(scope.appId, message.to, scope.teamId);
16
+ return { appId: scope.appId, teamId: scope.teamId, threadId, threadKind, messageId: message.hash, id: message.hash,
17
+ timestamp: message.t, serverCreatedAt: message.t, clientCreatedAt: message.t, from: message.from, to: message.to, body: message.body, recipients: message.recipients };
18
+ }
@@ -16,6 +16,7 @@ export type ChatClientOptions = {
16
16
  onNotification?: OnlineNotificationHandler;
17
17
  profileId?: string;
18
18
  botKey?: PmateBotKeyFile | string | unknown;
19
+ getToken?: () => Promise<string>;
19
20
  session?: BotLoginSession;
20
21
  hubUrl?: string;
21
22
  authBaseUrl?: string;
@@ -62,6 +63,7 @@ export declare class ChatClient {
62
63
  profileId: string | undefined;
63
64
  accountId: string | undefined;
64
65
  teamId: string | undefined;
66
+ clientInstanceId: string;
65
67
  };
66
68
  watchConnection(handler: (state: ChatConnectionState) => void): () => void;
67
69
  private setConnection;
@@ -107,7 +109,7 @@ export declare class ChatClient {
107
109
  teamId?: string;
108
110
  }): Promise<ChatRuntimeMessage>;
109
111
  createGroup(input: {
110
- groupId: string;
112
+ groupId?: string;
111
113
  teamId?: string;
112
114
  members: string[];
113
115
  title?: string;
@@ -121,6 +123,11 @@ export declare class ChatClient {
121
123
  title?: string;
122
124
  avatar?: string;
123
125
  }): Promise<ChatRuntimeMessage>;
126
+ dissolveGroup(input: {
127
+ groupId: string;
128
+ teamId?: string;
129
+ expectedRevision: string;
130
+ }): Promise<ChatRuntimeMessage>;
124
131
  sendGroup(input: {
125
132
  groupId: string;
126
133
  teamId?: string;
@@ -1,3 +1,4 @@
1
+ import { createUniqueGroup } from "./groupIdentity.js";
1
2
  import { withChatTeam } from "./teamScope.js";
2
3
  import { OnlineReachReceiver } from "./reach.js";
3
4
  import { OnlineNotificationReceiver } from "./notification.js";
@@ -123,7 +124,7 @@ export class ChatClient {
123
124
  /** Non-secret identity used to validate a shared browser transport. */
124
125
  identityScope() {
125
126
  const identity = this.session?.identity ?? this.session?.session?.identity;
126
- return { appId: this.options.appId, profileId: this.profileIdValue ?? this.options.profileId, accountId: identity?.accountId, teamId: this.options.teamId };
127
+ return { appId: this.options.appId, profileId: this.profileIdValue ?? this.options.profileId, accountId: identity?.accountId, teamId: this.options.teamId, clientInstanceId: this.instanceId };
127
128
  }
128
129
  watchConnection(handler) {
129
130
  this.connectionHandlers.add(handler);
@@ -161,7 +162,7 @@ export class ChatClient {
161
162
  catch (error) {
162
163
  if (generation !== this.generation)
163
164
  return;
164
- if (error instanceof ChatAckError) {
165
+ if (error instanceof ChatAckError || ["authentication-required", "access-denied"].includes(error?.code ?? "")) {
165
166
  this.close();
166
167
  this.setConnection("authentication_required");
167
168
  }
@@ -232,18 +233,18 @@ export class ChatClient {
232
233
  });
233
234
  }
234
235
  async createGroup(input) {
235
- return this.sendChat(input.groupId, {
236
+ return createUniqueGroup(input.groupId, groupId => this.sendChat(groupId, {
236
237
  kind: "group",
237
238
  threadKind: "group",
238
239
  action: "groupCreate",
239
240
  payload: {
240
241
  appId: this.options.appId,
241
- groupId: input.groupId,
242
+ groupId,
242
243
  ...(input.teamId !== undefined ? { teamId: input.teamId } : {}),
243
244
  members: input.members,
244
245
  title: input.title,
245
246
  },
246
- }, input.members);
247
+ }, input.members));
247
248
  }
248
249
  async updateGroup(input) {
249
250
  return this.sendChat(input.groupId, {
@@ -252,6 +253,12 @@ export class ChatClient {
252
253
  addMembers: input.addMembers ?? [], removeMembers: input.removeMembers ?? [], ...(input.title !== undefined ? { title: input.title } : {}), ...(input.avatar !== undefined ? { avatar: input.avatar } : {}) },
253
254
  });
254
255
  }
256
+ async dissolveGroup(input) {
257
+ return this.sendChat(input.groupId, {
258
+ kind: "group", threadKind: "group", action: "groupDissolve",
259
+ payload: { appId: this.options.appId, groupId: input.groupId, ...(input.teamId !== undefined ? { teamId: input.teamId } : {}), expectedRevision: input.expectedRevision },
260
+ });
261
+ }
255
262
  async sendGroup(input) {
256
263
  return this.sendChat(input.groupId, {
257
264
  kind: "message",
@@ -295,7 +302,12 @@ export class ChatClient {
295
302
  });
296
303
  }
297
304
  async sendAuth() {
298
- const token = this.session?.token;
305
+ const generation = this.generation;
306
+ const token = this.options.getToken ? await this.options.getToken() : this.session?.token;
307
+ if (generation !== this.generation)
308
+ throw new Error("ChatClient closed");
309
+ if (this.session && token)
310
+ this.session = { ...this.session, token };
299
311
  if (!token) {
300
312
  throw new Error("Missing PMate session token");
301
313
  }
@@ -0,0 +1,5 @@
1
+ import { ChatError } from "../chatError.js";
2
+ export { ChatError, type ChatErrorCode } from "../chatError.js";
3
+ export declare function asChatError(error: unknown): ChatError;
4
+ /** Keep a conversation denial distinct from loss of Team authority. */
5
+ export declare function threadChatError(error: unknown, threadId: string): ChatError;
@@ -0,0 +1,20 @@
1
+ import { ChatError } from "../chatError.js";
2
+ export { ChatError } from "../chatError.js";
3
+ export function asChatError(error) {
4
+ if (error instanceof ChatError)
5
+ return error;
6
+ const value = error;
7
+ const status = value?.status, message = value?.message ?? String(error);
8
+ const code = status === 401 ? "authentication-required" : status === 403 || /ACCESS_REVOKED|ACCESS_DENIED|SCOPE_CHANGED/.test(message) ? "access-denied"
9
+ : /CLOSED/.test(message) ? "closed"
10
+ : status === 409 || /REVISION_CONFLICT|PROJECTION_CHANGED/.test(message) ? "conflict"
11
+ : /BACKPRESSURE|TOO_LARGE/.test(message) ? "busy"
12
+ : status === 400 || /INVALID_|CONVERSATION_MISMATCH|CONVERSATION_UNKNOWN|NOT_OWNED/.test(message) ? "invalid-input"
13
+ : /QuotaExceeded|DatabaseClosed|UnknownError|AbortError/.test(value?.name ?? "") || /STORAGE_|DATABASE_|CACHE_WRITE/.test(message) ? "storage-unavailable" : "unavailable";
14
+ return new ChatError(code, message, { cause: error, status, threadId: value?.threadId, diagnostic: value?.diagnostic });
15
+ }
16
+ /** Keep a conversation denial distinct from loss of Team authority. */
17
+ export function threadChatError(error, threadId) {
18
+ const failure = asChatError(error);
19
+ return failure.code === "access-denied" ? new ChatError(failure.code, failure.message, { cause: failure, status: failure.status, threadId }) : failure;
20
+ }
@@ -1,61 +1,132 @@
1
+ import { type MessageThreadScope } from "./messageThread.js";
2
+ import { type ConversationTarget } from "./conversationDirectory.js";
3
+ import { type ChatGroup } from "./groupClient.js";
4
+ import type { SocialGroup } from "./socialReadClient.js";
5
+ import { type ChatConversation, type OutgoingContent } from "./outgoingContent.js";
6
+ import { type TimelineItem } from "./messageTimeline.js";
7
+ import { type ReadingCandidate, type MessageReadingState } from "./conversationReading.js";
8
+ import type { ConversationReadMessage } from "./conversationRead.js";
9
+ import { type ReadCountsResult } from "./readCounts.js";
10
+ import type { OnlineReachEvent } from "./reach.js";
1
11
  import { type MessageReadersQuery } from "./messageReaders.js";
2
12
  import { type MessageClientOptions, type MessageSnapshot } from "./messageClient.js";
3
- import { DurableChatSender } from "./durableSender.js";
4
- import { type ReadingClientOptions } from "./readingClient.js";
13
+ import { DurableChatSender, type SendMessageInput, type DurableSenderOptions, type VoiceAttachmentLease } from "./durableSender.js";
14
+ import { ReadingClient, type ReadingClientOptions } from "./readingClient.js";
5
15
  import { ChatClient, type ChatClientOptions, type ChatConnectionState } from "./chatClient.js";
6
16
  import { unreadInConversation } from "./readIndex.js";
7
17
  import type { StoredMessage } from "./messageStore.js";
8
- import type { ChatBody, ChatRuntimeMessage } from "./protocol.js";
18
+ import type { ChatRuntimeMessage } from "./protocol.js";
19
+ import type { InboxClient } from "./inboxClient.js";
9
20
  export type ChatSessionOptions<T extends StoredMessage> = {
21
+ inbox?: InboxClient;
22
+ discussion?: MessageThreadScope;
23
+ messageThreads?: (threadId: string, roots: readonly string[], signal?: AbortSignal) => Promise<{
24
+ items: import("./socialReadClient.js").MessageThreadSummary[];
25
+ revision: number;
26
+ }>;
27
+ onDispose?: () => void;
10
28
  messages: MessageClientOptions<T>;
11
29
  connection: ChatClientOptions;
12
30
  sharedConnection?: ChatClient;
31
+ activeThreadId?: string;
32
+ uploadVoice?: DurableSenderOptions["uploadVoice"];
33
+ reconcileOutgoing?: DurableSenderOptions["reconcile"];
34
+ loadGroup?: (groupId: string, signal: AbortSignal) => Promise<SocialGroup>;
13
35
  reading: ReadingClientOptions;
14
36
  decode: (message: ChatRuntimeMessage) => T | undefined;
37
+ readingCandidate?: (message: T) => ReadingCandidate | undefined;
15
38
  onError: (error: unknown) => void;
16
39
  };
17
40
  export type ChatThreadSnapshot<T> = {
18
41
  messages: readonly T[];
42
+ timeline: readonly TimelineItem<T>[];
19
43
  outgoing: ReturnType<DurableChatSender["snapshot"]>;
20
44
  hasEarlier: boolean;
21
45
  resetVersion: number;
22
46
  complete: boolean;
23
- unread: ReturnType<typeof unreadInConversation>;
47
+ group?: ChatGroup;
48
+ readCounts?: ReadCountsResult;
49
+ unread: ReturnType<typeof unreadInConversation> | undefined;
50
+ messageReading: Readonly<Record<string, MessageReadingState>>;
24
51
  };
25
52
  export type ChatSummarySnapshot<T> = {
26
53
  threads: readonly {
27
54
  threadId: string;
28
55
  lastMessage?: T;
56
+ lastItem?: TimelineItem<T>;
57
+ group?: ChatGroup;
29
58
  unread: ChatThreadSnapshot<T>["unread"];
30
59
  outgoingCount: number;
31
60
  }[];
32
- unreadMessageCount: number;
33
- badgeCount: number;
61
+ unreadMessageCount: number | undefined;
62
+ badgeCount: number | undefined;
34
63
  connection: ChatConnectionState;
35
64
  };
36
65
  /** Owns all browser message clients. Hosts subscribe to stable thread snapshots. */
37
66
  export declare class ChatSession<T extends StoredMessage> {
38
67
  private options;
68
+ private conversations;
39
69
  private messages;
40
70
  private connection;
41
71
  private reading;
42
72
  private readers;
73
+ private groups?;
74
+ private counts?;
75
+ private countsReceiver?;
76
+ private countsThread?;
77
+ private countSnapshots;
78
+ private countClosings;
79
+ private countTasks;
80
+ private controlTails;
81
+ private acceptedControls;
82
+ private controlCount;
83
+ private controlBytes;
43
84
  private sender;
44
85
  private listeners;
45
86
  private snapshots;
87
+ private timelineDecoded;
88
+ private decodeTimeline;
46
89
  private historyEdges;
47
90
  private earlierReads;
48
91
  private off;
49
92
  private globalListeners;
50
93
  private globalSnapshot?;
94
+ private closedThread;
95
+ private closedSummary;
51
96
  private connectionState;
52
97
  private catchUp;
98
+ private readingAllowed;
99
+ private readingListeners;
100
+ private acceptedReading;
101
+ private readingAccess?;
53
102
  private readingStarted;
103
+ private readingStarting?;
104
+ private withdrawn;
105
+ private revoking?;
54
106
  private closed;
55
107
  private starting?;
108
+ private initializing?;
56
109
  private closing?;
57
110
  constructor(options: ChatSessionOptions<T>);
111
+ private scheduleCatchUp;
58
112
  start(): Promise<void>;
113
+ /** Initializes local state and background reading sync without opening a
114
+ * second transport when the host already owns calls/presence. */
115
+ initialize(): Promise<void>;
116
+ private startReading;
117
+ /** One-time migration only: never establishes trusted history coverage. */
118
+ importLegacyMessages(threadId: string, messages: T[]): Promise<void>;
119
+ getReadingSnapshot(): import("./readIndex.js").ReadIndexState | undefined;
120
+ subscribeReading(listener: () => void): () => void;
121
+ private setReadingAllowed;
122
+ private readingAuthority;
123
+ private authorizeReading;
124
+ private readingOperation;
125
+ refreshReading(): void;
126
+ synchronizeReading(cursor?: string, profileId?: string): Promise<import("./readIndex.js").ReadIndexState>;
127
+ /** Explicit text-history acknowledgement; unheard audio stays unread. */
128
+ markRead(threadId: string, messages?: readonly ConversationReadMessage[]): Promise<import("./readIndex.js").ReadIndexState>;
129
+ updateReading(transform: Parameters<ReadingClient["update"]>[0]): Promise<import("./readIndex.js").ReadIndexState>;
59
130
  private assertOpen;
60
131
  getMessages(threadId: string, options?: {
61
132
  limit?: number;
@@ -67,24 +138,81 @@ export declare class ChatSession<T extends StoredMessage> {
67
138
  all?: boolean;
68
139
  refresh?: boolean;
69
140
  }): Promise<MessageSnapshot<T>>;
141
+ private confirmMessages;
70
142
  private rememberHistoryEdge;
71
143
  private readEarlier;
72
144
  private readAll;
73
- sendMessage(threadId: string, input: {
74
- to: string;
75
- body: ChatBody;
76
- recipients?: string[];
145
+ /** Reads trusted local group metadata immediately; SDK refreshes it in the background. */
146
+ getGroup(thread: ChatConversation | string, options?: {
147
+ refresh?: boolean;
148
+ }): Promise<ChatGroup>;
149
+ createGroup(thread: ChatConversation, content: {
150
+ title: string;
151
+ members: readonly string[];
152
+ }): Promise<ChatGroup>;
153
+ updateGroup(target: ChatConversation | string, changes: {
154
+ expectedRevision?: string;
155
+ addMembers?: readonly string[];
156
+ removeMembers?: readonly string[];
157
+ title?: string;
158
+ avatar?: string;
159
+ }): Promise<ChatGroup>;
160
+ dissolveGroup(target: ChatConversation | string, options?: {
161
+ expectedRevision?: string;
162
+ }): Promise<ChatGroup>;
163
+ sendMessage(threadId: string, input: OutgoingContent, options?: {
164
+ waitFor?: "accepted" | "delivered";
165
+ }): Promise<ChatRuntimeMessage>;
166
+ sendMessage(thread: ChatConversation, input: OutgoingContent, options?: {
167
+ waitFor?: "accepted" | "delivered";
168
+ }): Promise<ChatRuntimeMessage>;
169
+ sendMessage(threadId: string, input: SendMessageInput, options?: {
170
+ waitFor?: "accepted" | "delivered";
77
171
  }): Promise<ChatRuntimeMessage>;
172
+ sharedTransport(): ChatClient;
173
+ getMessageThreads(threadId: string, roots: readonly string[], signal?: AbortSignal): Promise<{
174
+ items: import("./socialReadClient.js").MessageThreadSummary[];
175
+ revision: number;
176
+ }>;
177
+ private sendWire;
178
+ getConversation(target: ConversationTarget): Promise<string>;
179
+ private sendContent;
180
+ private resolveConversation;
181
+ /** Validated target identity survives content redaction; no roster is exposed. */
182
+ getConversationTarget(threadId: string): ChatConversation | undefined;
183
+ private sendControl;
78
184
  getReaders(threadId: string, messageId: string, page?: Omit<MessageReadersQuery, "threadId" | "messageId">, signal?: AbortSignal): Promise<import("./messageReaders.js").MessageReadersPage>;
185
+ /** Resolve voice media uniformly; pending local bytes are loaded only on demand. */
186
+ getVoiceAttachment(threadId: string, messageId: string): Promise<VoiceAttachmentLease>;
79
187
  retryMessage(messageId: string): Promise<ChatRuntimeMessage>;
80
- observeMessages(threadId: string, ids: string[], event: "visible" | "played"): Promise<import("./readIndex.js").ReadIndexState>;
188
+ observeMessages(threadId: string, ids: string[], event: "visible" | "played"): ReturnType<ReadingClient["recordVisible"]>;
189
+ observeMessages(threadId: string | undefined, ids: string[], event: "receipts", clientInstanceId?: string): Promise<void>;
190
+ /** Bridge transports can delegate social events without maintaining clients. */
191
+ handleReach(event: OnlineReachEvent): Promise<"handled" | undefined>;
192
+ private wakeCounts;
193
+ private publishCountSnapshot;
194
+ private publishCounts;
195
+ private watchCounts;
81
196
  getSnapshot(): ChatSummarySnapshot<T>;
82
197
  getSnapshot(threadId: string): ChatThreadSnapshot<T>;
83
- subscribe(listener: () => void): () => void;
84
- subscribe(threadId: string, listener: () => void): () => void;
198
+ private buildThreadSnapshot;
199
+ /** Delivers the current stable snapshot immediately, then only meaningful changes. */
200
+ subscribe(listener: (snapshot: ChatSummarySnapshot<T>) => void): () => void;
201
+ subscribe(threadId: string, listener: (snapshot: ChatThreadSnapshot<T>) => void, fields?: readonly (keyof ChatThreadSnapshot<T>)[]): () => void;
202
+ /** Change-only bridge for useSyncExternalStore and other framework adapters. */
203
+ subscribeChanges(listener: () => void): () => void;
204
+ subscribeChanges(threadId: string, listener: () => void, fields?: readonly (keyof ChatThreadSnapshot<T>)[]): () => void;
85
205
  private publishAll;
86
206
  private buildGlobal;
87
207
  private publishGlobal;
88
208
  private publish;
209
+ conversationFailure(error: unknown, threadId: string): Promise<import("./chatError.js").ChatError>;
210
+ /** Withdraw one conversation without retiring sibling conversations. */
211
+ revokeThread(threadId: string): Promise<void>;
212
+ /** Permanently retire this identity/team session. UI withdrawal is immediate;
213
+ * completion means all durable stores have crossed the same authority epoch. */
214
+ revokeAccess(): Promise<void>;
215
+ get active(): boolean;
89
216
  close(): Promise<void>;
217
+ private dispose;
90
218
  }