@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.
Files changed (41) 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/inboxClient.d.ts +3 -1
  10. package/lib/runtime/inboxClient.js +19 -1
  11. package/lib/runtime/profileChat.d.ts +135 -0
  12. package/lib/runtime/profileChat.js +299 -0
  13. package/lib/runtime/profileCommitQueue.d.ts +38 -0
  14. package/lib/runtime/profileCommitQueue.js +101 -0
  15. package/lib/runtime/profileCoordinator.d.ts +46 -0
  16. package/lib/runtime/profileCoordinator.js +135 -0
  17. package/lib/runtime/profileDatabase.d.ts +42 -0
  18. package/lib/runtime/profileDatabase.js +164 -0
  19. package/lib/runtime/profileGenerationBuilder.d.ts +18 -0
  20. package/lib/runtime/profileGenerationBuilder.js +112 -0
  21. package/lib/runtime/profileInboxFeed.d.ts +38 -0
  22. package/lib/runtime/profileInboxFeed.js +240 -0
  23. package/lib/runtime/profileMemoryStore.d.ts +113 -0
  24. package/lib/runtime/profileMemoryStore.js +259 -0
  25. package/lib/runtime/profileOutboxDispatcher.d.ts +31 -0
  26. package/lib/runtime/profileOutboxDispatcher.js +106 -0
  27. package/lib/runtime/profileOwner.d.ts +57 -0
  28. package/lib/runtime/profileOwner.js +202 -0
  29. package/lib/runtime/profileProjection.d.ts +77 -0
  30. package/lib/runtime/profileProjection.js +625 -0
  31. package/lib/runtime/profileReadingIndex.d.ts +17 -0
  32. package/lib/runtime/profileReadingIndex.js +99 -0
  33. package/lib/runtime/profileReplica.d.ts +59 -0
  34. package/lib/runtime/profileReplica.js +236 -0
  35. package/lib/runtime/profileStoreTypes.d.ts +163 -0
  36. package/lib/runtime/profileStoreTypes.js +1 -0
  37. package/lib/runtime/profileWindows.d.ts +38 -0
  38. package/lib/runtime/profileWindows.js +175 -0
  39. package/lib/runtime/profileWorkerHost.d.ts +33 -0
  40. package/lib/runtime/profileWorkerHost.js +156 -0
  41. package/package.json +11 -1
@@ -0,0 +1,99 @@
1
+ import { compareProfileOrder } from "./profileWindows.js";
2
+ const empty = () => ({ unread: 0, mentions: 0 });
3
+ function combine(a, b) {
4
+ return { unread: a.unread + b.unread, mentions: a.mentions + b.mentions,
5
+ first: !a.first ? b.first : !b.first ? a.first : compareProfileOrder(a.first.orderKey, b.first.orderKey) <= 0 ? a.first : b.first };
6
+ }
7
+ function aggregate(node) {
8
+ const own = { unread: 1, mentions: node.mention ? 1 : 0, first: node.ref };
9
+ return { ...node,
10
+ visible: combine(combine(node.left?.visible ?? empty(), node.explicit ? empty() : own), node.right?.visible ?? empty()),
11
+ exceptions: combine(combine(node.left?.exceptions ?? empty(), node.explicit ? own : empty()), node.right?.exceptions ?? empty()) };
12
+ }
13
+ function compare(seq, id, node) { return seq - node.seq || (id < node.id ? -1 : id > node.id ? 1 : 0); }
14
+ function priority(id) {
15
+ let result = 2166136261;
16
+ for (let i = 0; i < id.length; i++)
17
+ result = Math.imul(result ^ id.charCodeAt(i), 16777619);
18
+ return result >>> 0;
19
+ }
20
+ function merge(left, right) {
21
+ if (!left)
22
+ return right;
23
+ if (!right)
24
+ return left;
25
+ return left.priority < right.priority ? aggregate({ ...left, right: merge(left.right, right) }) : aggregate({ ...right, left: merge(left, right.left) });
26
+ }
27
+ function remove(root, seq, id) {
28
+ if (!root)
29
+ return;
30
+ const order = compare(seq, id, root);
31
+ if (!order)
32
+ return merge(root.left, root.right);
33
+ return aggregate(order < 0 ? { ...root, left: remove(root.left, seq, id) } : { ...root, right: remove(root.right, seq, id) });
34
+ }
35
+ function insert(root, node) {
36
+ if (!root)
37
+ return aggregate(node);
38
+ const order = compare(node.seq, node.id, root);
39
+ if (!order)
40
+ return aggregate({ ...node, left: root.left, right: root.right });
41
+ if (order < 0) {
42
+ const left = insert(root.left, node), next = aggregate({ ...root, left });
43
+ return left.priority < root.priority ? aggregate({ ...left, right: aggregate({ ...next, left: left.right }) }) : next;
44
+ }
45
+ const right = insert(root.right, node), next = aggregate({ ...root, right });
46
+ return right.priority < root.priority ? aggregate({ ...right, left: aggregate({ ...next, right: right.left }) }) : next;
47
+ }
48
+ /** Return visible unread facts after a cursor using subtree aggregates. */
49
+ function after(root, seq) {
50
+ if (!root)
51
+ return empty();
52
+ if (root.seq <= seq)
53
+ return after(root.right, seq);
54
+ const own = root.explicit ? empty() : { unread: 1, mentions: root.mention ? 1 : 0, first: root.ref };
55
+ return combine(combine(after(root.left, seq), own), root.right?.visible ?? empty());
56
+ }
57
+ function between(root, low, high, result) {
58
+ if (!root)
59
+ return;
60
+ if (root.seq > low)
61
+ between(root.left, low, high, result);
62
+ if (root.seq > low && root.seq <= high && !root.explicit)
63
+ result.push(root.ref);
64
+ if (root.seq <= high)
65
+ between(root.right, low, high, result);
66
+ }
67
+ /** Persistent per-source range trees. Cursor advances aggregate whole ranges;
68
+ * they neither scan history nor rewrite a read flag on each Message. */
69
+ export class ProfileReadingIndex {
70
+ sources = new Map();
71
+ fork() { const draft = new ProfileReadingIndex(); draft.sources = new Map(this.sources); return draft; }
72
+ remove(message) {
73
+ const root = this.sources.get(message.sourceThreadId);
74
+ this.sources.set(message.sourceThreadId, remove(root, message.sourceSeq ?? 0, message.messageId));
75
+ }
76
+ upsert(message, profileId, source) {
77
+ this.remove(message);
78
+ if (message.from === profileId || message.recalled || message.readPolicy === "discussion" ||
79
+ message.explicitReadingFacts.some(fact => fact.profileId === profileId) ||
80
+ source?.explicitReadMessageIds.includes(message.messageId) || source?.pendingExplicitReadMessageIds?.includes(message.messageId) || source?.preservedReadMessageIds.includes(message.messageId))
81
+ return;
82
+ const node = { seq: message.sourceSeq ?? 0, id: message.messageId, priority: priority(message.messageId),
83
+ ref: { messageId: message.messageId, orderKey: message.orderKey }, explicit: message.readPolicy === "explicit" || !message.sourceSeq,
84
+ mention: message.mention ?? false, visible: empty(), exceptions: empty() };
85
+ this.sources.set(message.sourceThreadId, insert(this.sources.get(message.sourceThreadId), node));
86
+ }
87
+ summary(positions) {
88
+ const cursors = new Map(positions.map(source => [source.sourceThreadId, Math.max(source.readThroughSeq, source.pendingReadThroughSeq ?? 0)]));
89
+ let total = empty();
90
+ for (const [source, root] of this.sources)
91
+ total = combine(total, combine(after(root, cursors.get(source) ?? 0), root?.exceptions ?? empty()));
92
+ return total;
93
+ }
94
+ visibleBetween(sourceId, low, high) {
95
+ const result = [];
96
+ between(this.sources.get(sourceId), low, high, result);
97
+ return result;
98
+ }
99
+ }
@@ -0,0 +1,59 @@
1
+ import { ProfileMemoryStore, type ProfileDelta } from "./profileMemoryStore.js";
2
+ import type { ProfileOperation } from "./profileProjection.js";
3
+ import type { ProfileOwner } from "./profileOwner.js";
4
+ export type ProfileMessagePort = {
5
+ postMessage(message: unknown): void;
6
+ addEventListener(type: "message", listener: (event: MessageEvent) => void): void;
7
+ removeEventListener(type: "message", listener: (event: MessageEvent) => void): void;
8
+ start?(): void;
9
+ };
10
+ /** A bounded, volatile history: no extra persistence or full-team snapshot write.
11
+ * A producer restart intentionally falls back to a prepared snapshot. */
12
+ export declare class ProfileDeltaJournal {
13
+ private maxEntries;
14
+ private maxBytes;
15
+ private rows;
16
+ private bytes;
17
+ constructor(maxEntries?: number, maxBytes?: number);
18
+ append(delta: ProfileDelta): void;
19
+ since(generation: string | undefined, revision: number | undefined, current: {
20
+ activeGeneration: string;
21
+ commitRevision: number;
22
+ }): ProfileDelta[] | undefined;
23
+ }
24
+ /** Same adapter accepts a Dedicated Worker's message port or BroadcastChannel. */
25
+ export declare function serveProfileOwner(owner: ProfileOwner, port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void): () => void;
26
+ /** UI/WebView replica. Reads and subscriptions use memory; only commands and
27
+ * revision repair cross the message boundary. Normal deltas never read disk. */
28
+ export declare class ProfileReplica {
29
+ private port;
30
+ private scope;
31
+ private onError;
32
+ private timeoutMs;
33
+ readonly memory: ProfileMemoryStore;
34
+ private clientId;
35
+ private requests;
36
+ private repairing?;
37
+ private closed;
38
+ private buffered;
39
+ private timer?;
40
+ private lastError?;
41
+ constructor(port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void, timeoutMs?: number, profileId?: string);
42
+ private receive;
43
+ private fail;
44
+ private request;
45
+ start(poll?: boolean): Promise<void>;
46
+ check(): Promise<void>;
47
+ repair(): Promise<void>;
48
+ submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
49
+ synchronize(): Promise<void>;
50
+ waitForCommand(commandId: string): Promise<void>;
51
+ voiceAttachment(messageId: string): Promise<Blob | null>;
52
+ getStatus(): {
53
+ error: Error | undefined;
54
+ phase: "ready" | "restoring";
55
+ generation: string | undefined;
56
+ revision: number | undefined;
57
+ };
58
+ close(): void;
59
+ }
@@ -0,0 +1,236 @@
1
+ import { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION } from "./profileMemoryStore.js";
2
+ /** A bounded, volatile history: no extra persistence or full-team snapshot write.
3
+ * A producer restart intentionally falls back to a prepared snapshot. */
4
+ export class ProfileDeltaJournal {
5
+ maxEntries;
6
+ maxBytes;
7
+ rows = [];
8
+ bytes = 0;
9
+ constructor(maxEntries = 256, maxBytes = 8 * 1024 * 1024) {
10
+ this.maxEntries = maxEntries;
11
+ this.maxBytes = maxBytes;
12
+ }
13
+ append(delta) {
14
+ if (this.rows.length && (this.rows.at(-1).delta.generation !== delta.generation || this.rows.at(-1).delta.toRevision !== delta.fromRevision)) {
15
+ this.rows = [];
16
+ this.bytes = 0;
17
+ }
18
+ const bytes = new TextEncoder().encode(JSON.stringify(delta)).byteLength;
19
+ this.rows.push({ delta, bytes });
20
+ this.bytes += bytes;
21
+ while (this.rows.length && (this.rows.length > this.maxEntries || this.bytes > this.maxBytes))
22
+ this.bytes -= this.rows.shift().bytes;
23
+ }
24
+ since(generation, revision, current) {
25
+ if (generation !== current.activeGeneration || revision === undefined || revision > current.commitRevision)
26
+ return;
27
+ if (revision === current.commitRevision)
28
+ return [];
29
+ const start = this.rows.findIndex(row => row.delta.fromRevision === revision && row.delta.generation === generation);
30
+ if (start < 0 || this.rows.at(-1)?.delta.toRevision !== current.commitRevision)
31
+ return;
32
+ return this.rows.slice(start).map(row => row.delta);
33
+ }
34
+ }
35
+ /** Same adapter accepts a Dedicated Worker's message port or BroadcastChannel. */
36
+ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
37
+ const journal = new ProfileDeltaJournal();
38
+ const send = (response) => port.postMessage({ ...response, profileProtocol: PROFILE_PROTOCOL_VERSION, scope });
39
+ const off = owner.subscribeCommitted(delta => {
40
+ journal.append(delta);
41
+ send({ clientId: "*", delta });
42
+ });
43
+ let active = true;
44
+ const controller = new AbortController();
45
+ const listener = (event) => {
46
+ const request = event.data;
47
+ if (!request || request.scope !== scope || !request.requestId || !request.action)
48
+ return;
49
+ void (async () => {
50
+ if (request.profileProtocol !== PROFILE_PROTOCOL_VERSION)
51
+ throw Error("PROFILE_PROTOCOL_INCOMPATIBLE");
52
+ if (!owner.active)
53
+ throw Error("PROFILE_OWNER_UNAVAILABLE");
54
+ let result;
55
+ if (request.action === "catchUp") {
56
+ const deltas = journal.since(request.generation, request.revision, owner.current);
57
+ result = deltas ? { deltas } : { snapshot: owner.snapshot() };
58
+ }
59
+ else if (request.action === "status")
60
+ result = { generation: owner.current.activeGeneration, revision: owner.current.commitRevision };
61
+ else if (request.action === "synchronize") {
62
+ await owner.synchronize();
63
+ result = null;
64
+ }
65
+ else if (request.action === "waitCommand") {
66
+ if (typeof request.commandId !== "string" || !request.commandId)
67
+ throw Error("INVALID_PROFILE_COMMAND");
68
+ await owner.waitForCommand(request.commandId, controller.signal);
69
+ result = null;
70
+ }
71
+ else if (request.action === "voiceAttachment") {
72
+ const command = owner.commands().find(row => row.messageId === request.commandId);
73
+ const blob = command?.payload?.voiceBlob;
74
+ result = blob instanceof Blob ? blob : null;
75
+ }
76
+ else if (request.action === "operation") {
77
+ if (!request.operation || !Number.isSafeInteger(request.bytes) || request.bytes < 0)
78
+ throw Error("INVALID_PROFILE_OPERATION");
79
+ await owner.enqueue(request.operation, request.bytes, request.immediate);
80
+ result = null;
81
+ }
82
+ else
83
+ throw Error("INVALID_PROFILE_REQUEST");
84
+ if (active)
85
+ send({ clientId: request.clientId, requestId: request.requestId, result });
86
+ })().catch(error => {
87
+ if (!active)
88
+ return;
89
+ try {
90
+ send({ clientId: request.clientId, requestId: request.requestId, error: error instanceof Error ? error.message : "PROFILE_REQUEST_FAILED" });
91
+ }
92
+ catch (failure) {
93
+ onError(failure);
94
+ }
95
+ });
96
+ };
97
+ port.addEventListener("message", listener);
98
+ port.start?.();
99
+ return () => { active = false; controller.abort(); off(); port.removeEventListener("message", listener); };
100
+ }
101
+ /** UI/WebView replica. Reads and subscriptions use memory; only commands and
102
+ * revision repair cross the message boundary. Normal deltas never read disk. */
103
+ export class ProfileReplica {
104
+ port;
105
+ scope;
106
+ onError;
107
+ timeoutMs;
108
+ memory;
109
+ clientId = crypto.randomUUID();
110
+ requests = new Map();
111
+ repairing;
112
+ closed = false;
113
+ buffered = [];
114
+ timer;
115
+ lastError;
116
+ constructor(port, scope, onError = () => { }, timeoutMs = 30000, profileId = "") {
117
+ this.port = port;
118
+ this.scope = scope;
119
+ this.onError = onError;
120
+ this.timeoutMs = timeoutMs;
121
+ this.memory = new ProfileMemoryStore(onError, profileId);
122
+ port.addEventListener("message", this.receive);
123
+ port.start?.();
124
+ }
125
+ receive = (event) => {
126
+ const response = event.data;
127
+ if (!response || response.scope !== this.scope || ![this.clientId, "*"].includes(response.clientId))
128
+ return;
129
+ if (response.profileProtocol !== PROFILE_PROTOCOL_VERSION) {
130
+ this.fail(Error("PROFILE_PROTOCOL_INCOMPATIBLE"));
131
+ return;
132
+ }
133
+ if (response.requestId) {
134
+ const request = this.requests.get(response.requestId);
135
+ if (!request)
136
+ return;
137
+ this.requests.delete(response.requestId);
138
+ clearTimeout(request.timer);
139
+ if (response.error)
140
+ request.reject(Error(response.error));
141
+ else
142
+ request.resolve(response.result);
143
+ }
144
+ if (response.delta) {
145
+ if (this.repairing || this.memory.getStatus().phase === "restoring") {
146
+ this.buffered.push(response.delta);
147
+ if (!this.repairing)
148
+ void this.repair().catch(failure => this.fail(failure));
149
+ }
150
+ else {
151
+ try {
152
+ this.memory.apply(response.delta);
153
+ }
154
+ catch (error) {
155
+ this.buffered.push(response.delta);
156
+ void this.repair().catch(failure => this.fail(failure));
157
+ }
158
+ }
159
+ if (this.buffered.length > 256)
160
+ this.buffered = this.buffered.slice(-256);
161
+ }
162
+ };
163
+ fail(error) { this.lastError = error instanceof Error ? error : Error("PROFILE_REPLICA_FAILED"); try {
164
+ this.onError(this.lastError);
165
+ }
166
+ catch { } }
167
+ request(action, fields = {}) {
168
+ if (this.closed)
169
+ return Promise.reject(Error("PROFILE_REPLICA_CLOSED"));
170
+ const requestId = crypto.randomUUID();
171
+ return new Promise((resolve, reject) => {
172
+ const timeout = action === "status" || action === "catchUp" ? this.timeoutMs : Math.max(this.timeoutMs, 30000);
173
+ const timer = setTimeout(() => { this.requests.delete(requestId); reject(Error("PROFILE_OWNER_TIMEOUT")); }, timeout);
174
+ this.requests.set(requestId, { resolve, reject, timer });
175
+ try {
176
+ this.port.postMessage({ ...fields, profileProtocol: PROFILE_PROTOCOL_VERSION, scope: this.scope, clientId: this.clientId, requestId, action });
177
+ }
178
+ catch (error) {
179
+ clearTimeout(timer);
180
+ this.requests.delete(requestId);
181
+ reject(error);
182
+ }
183
+ });
184
+ }
185
+ async start(poll = true) {
186
+ await this.repair();
187
+ if (poll && !this.timer)
188
+ this.timer = setInterval(() => { void this.check().catch(error => this.fail(error)); }, 10000);
189
+ }
190
+ async check() {
191
+ const remote = await this.request("status"), local = this.memory.getStatus();
192
+ if (remote.generation !== local.generation || remote.revision !== local.revision)
193
+ await this.repair();
194
+ }
195
+ repair() {
196
+ if (this.repairing)
197
+ return this.repairing;
198
+ const task = Promise.resolve().then(async () => {
199
+ const local = this.memory.getStatus();
200
+ const result = await this.request("catchUp", { generation: local.generation, revision: local.revision });
201
+ if ("snapshot" in result)
202
+ this.memory.restore(result.snapshot);
203
+ else
204
+ for (const delta of result.deltas)
205
+ this.memory.apply(delta);
206
+ const buffered = this.buffered;
207
+ this.buffered = [];
208
+ for (const delta of buffered)
209
+ this.memory.apply(delta);
210
+ this.lastError = undefined;
211
+ });
212
+ this.repairing = task;
213
+ void task.finally(() => { if (this.repairing === task)
214
+ this.repairing = undefined; }).catch(() => { });
215
+ return task;
216
+ }
217
+ submit(operation, immediate = false) {
218
+ const payload = "type" in operation && operation.type === "send" ? operation.command.payload : undefined;
219
+ const binaryBytes = payload?.voiceBlob instanceof Blob ? payload.voiceBlob.size : 0;
220
+ return this.request("operation", { operation, bytes: new TextEncoder().encode(JSON.stringify(operation)).byteLength + binaryBytes, immediate });
221
+ }
222
+ synchronize() { return this.request("synchronize"); }
223
+ waitForCommand(commandId) { return this.request("waitCommand", { commandId }); }
224
+ voiceAttachment(messageId) { return this.request("voiceAttachment", { commandId: messageId }); }
225
+ getStatus() { return { ...this.memory.getStatus(), error: this.lastError }; }
226
+ close() {
227
+ this.closed = true;
228
+ clearInterval(this.timer);
229
+ this.port.removeEventListener("message", this.receive);
230
+ for (const request of this.requests.values()) {
231
+ clearTimeout(request.timer);
232
+ request.reject(Error("PROFILE_REPLICA_CLOSED"));
233
+ }
234
+ this.requests.clear();
235
+ }
236
+ }
@@ -0,0 +1,163 @@
1
+ import type { InboxScope } from "./inboxStore.js";
2
+ import type { projectMessageContent } from "../messageView.js";
3
+ export type ProfileIdentity = InboxScope;
4
+ export type ProfileOrderKey = [number, string, number, string];
5
+ export type ProfileReadingStatus = "unknown" | "unread" | "read";
6
+ export type ProfileReadingSource = {
7
+ sourceThreadId: string;
8
+ readThroughSeq: number;
9
+ explicitReadMessageIds: string[];
10
+ preservedReadMessageIds: string[];
11
+ confirmedRevision?: string;
12
+ pendingReadThroughSeq?: number;
13
+ pendingExplicitReadMessageIds?: string[];
14
+ };
15
+ export type ProfileThread = {
16
+ generation: string;
17
+ threadId: string;
18
+ kind: "group" | "dm" | "discussion";
19
+ parentThreadId?: string;
20
+ rootMessageId?: string;
21
+ teamId?: string;
22
+ title: string;
23
+ group?: import("./socialReadClient.js").SocialGroup;
24
+ avatar?: string;
25
+ lastMessageId?: string;
26
+ lastActivityAt: number;
27
+ messageCount: number;
28
+ windowCount: number;
29
+ pendingWindowId?: string;
30
+ participantProfileIds?: string[];
31
+ ownerAgentId?: string;
32
+ readingStatus: ProfileReadingStatus;
33
+ unreadCount: number | null;
34
+ mentionCount: number | null;
35
+ firstUnreadMessageId?: string;
36
+ readingSources: ProfileReadingSource[];
37
+ coverage: {
38
+ complete: boolean;
39
+ windowStart: number;
40
+ };
41
+ status: "building" | "ready" | "unavailable";
42
+ revision: number;
43
+ internal?: {
44
+ targetId?: string;
45
+ groupControls?: Record<string, unknown>;
46
+ organizationRevisions?: Record<string, number>;
47
+ assignments?: Record<string, string>;
48
+ pendingControls?: Record<string, unknown[]>;
49
+ messageRoots?: Record<string, string>;
50
+ pendingReceipts?: Record<string, string[]>;
51
+ participantCounts?: Record<string, number>;
52
+ };
53
+ };
54
+ export type ProfileMessageRef = {
55
+ messageId: string;
56
+ orderKey: ProfileOrderKey;
57
+ };
58
+ export type ProfileWindow = {
59
+ generation: string;
60
+ threadId: string;
61
+ windowId: string;
62
+ sequence: number;
63
+ status: "pending" | "sealed";
64
+ firstOrderKey?: ProfileOrderKey;
65
+ lastOrderKey?: ProfileOrderKey;
66
+ refs: ProfileMessageRef[];
67
+ count: number;
68
+ readingIndex: {
69
+ messageId: string;
70
+ sourceThreadId: string;
71
+ sourceSeq?: number;
72
+ policy: "visible" | "explicit" | "discussion";
73
+ mention: boolean;
74
+ }[];
75
+ revision: number;
76
+ };
77
+ export type ProfileMessage = {
78
+ generation: string;
79
+ messageId: string;
80
+ sourceThreadId: string;
81
+ sourceSeq?: number;
82
+ threadId: string;
83
+ orderKey: ProfileOrderKey;
84
+ from: string;
85
+ recipients?: string[];
86
+ readPolicy?: "visible" | "explicit" | "discussion";
87
+ mention?: boolean;
88
+ discussionThreadId?: string;
89
+ content: unknown;
90
+ presentation?: ReturnType<typeof projectMessageContent>;
91
+ attachmentRefs: unknown[];
92
+ reactions: {
93
+ emojiId: string;
94
+ profileIds: string[];
95
+ }[];
96
+ sendStatus?: "sending" | "failed" | "sent";
97
+ recalled?: boolean;
98
+ readBy: string[];
99
+ receiptStatus: "unknown" | "ready";
100
+ explicitReadingFacts: {
101
+ profileId: string;
102
+ kind: "played" | "preserved";
103
+ revision?: string;
104
+ }[];
105
+ controlVersions: Record<string, string | number>;
106
+ revision: number;
107
+ };
108
+ export type ProfileCurrentState = {
109
+ key: "current";
110
+ epoch: string;
111
+ committedSeq: string;
112
+ activeGeneration: string;
113
+ projectionVersion: number;
114
+ commitRevision: number;
115
+ receiptsReady?: boolean;
116
+ };
117
+ export type ProfileWriterLease = {
118
+ key: "lease";
119
+ ownerId: string;
120
+ fence: number;
121
+ expiresAt: number;
122
+ };
123
+ export type ProfileGenerationState = {
124
+ key: `build:${string}`;
125
+ generation: string;
126
+ status: "building" | "validated" | "active" | "retired";
127
+ epoch: string;
128
+ committedSeq: string;
129
+ projectionVersion: number;
130
+ sourceRevision: number;
131
+ progress?: string;
132
+ buildRevision?: number;
133
+ throughSeq?: string;
134
+ windowStart?: number;
135
+ receiptsReady?: boolean;
136
+ };
137
+ export type ProfileStateRecord = ProfileCurrentState | ProfileWriterLease | ProfileGenerationState;
138
+ export type ProfileOutboxCommand = {
139
+ commandId: string;
140
+ kind: "message" | "reading" | "played";
141
+ threadId: string;
142
+ messageId?: string;
143
+ createdAt: number;
144
+ payload: unknown;
145
+ state: "pending" | "sending" | "failed" | "confirmed";
146
+ attempts: number;
147
+ };
148
+ export type ProfileWriteBatch = {
149
+ ownerId: string;
150
+ fence: number;
151
+ expectedRevision: number;
152
+ generation: string;
153
+ epoch: string;
154
+ committedSeq: string;
155
+ receiptsReady?: boolean;
156
+ threads?: ProfileThread[];
157
+ windows?: ProfileWindow[];
158
+ messages?: ProfileMessage[];
159
+ outbox?: ProfileOutboxCommand[];
160
+ deleteMessages?: string[];
161
+ deleteWindows?: [string, string][];
162
+ deleteOutbox?: string[];
163
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ import type { ProfileMessageRef, ProfileOrderKey, ProfileWindow } from "./profileStoreTypes.js";
2
+ export declare function compareProfileOrder(a: ProfileOrderKey, b: ProfileOrderKey): number;
3
+ export type ProfileWindowChange = {
4
+ windows: ProfileWindow[];
5
+ windowCount: number;
6
+ pendingWindowId?: string;
7
+ };
8
+ /** A directory contains references to immutable blocks. Blocks seal at 128
9
+ * ordinary appends; historical inserts and moves never split or merge them. */
10
+ export declare class ProfileWindowDirectory {
11
+ readonly generation: string;
12
+ readonly threadId: string;
13
+ private windows;
14
+ private byMessage;
15
+ private baseLookup?;
16
+ private removed;
17
+ private offsets;
18
+ private size;
19
+ constructor(generation: string, threadId: string, windows?: readonly ProfileWindow[]);
20
+ get count(): number;
21
+ get blocks(): readonly ProfileWindow[];
22
+ /** A transaction draft shares immutable blocks and the committed ID directory.
23
+ * Only IDs in replaced blocks enter the overlay; no whole-thread Map copy. */
24
+ fork(): ProfileWindowDirectory;
25
+ private lookup;
26
+ /** Returns changes only. Call accept after the corresponding durable commit. */
27
+ insert(ref: ProfileMessageRef, options: {
28
+ historical?: boolean;
29
+ revision: number;
30
+ newWindowId: () => string;
31
+ }): ProfileWindowChange;
32
+ remove(messageId: string, revision: number): ProfileWindowChange;
33
+ private result;
34
+ accept(change: ProfileWindowChange): void;
35
+ private reindex;
36
+ /** Exclusive message anchor; no storage, sort, or reading work on this path. */
37
+ readPage(anchor: string | undefined, limit: number, direction?: "older" | "newer"): readonly ProfileMessageRef[];
38
+ }