@pmate/chat-sdk 0.14.0-seq.1 → 0.14.0-seq.3

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.
@@ -322,7 +322,7 @@ export class ChatClient {
322
322
  }, ChatMsgKind.DM);
323
323
  await this.sendAndWaitForAck(auth);
324
324
  }
325
- async sendAndWaitForAck(msg) {
325
+ async sendAndWaitForAck(msg, recoverAuth = true) {
326
326
  const client = this.requireClient();
327
327
  if (msg.opcode !== ChatMsgOp.AUTH && this.connection !== "connected") {
328
328
  throw new Error(this.connection === "authentication_required" ? "登录已失效,请重新登录" : "聊天连接正在恢复,请稍后重试");
@@ -345,7 +345,22 @@ export class ChatClient {
345
345
  pending.reject(error instanceof Error ? error : new Error("Send failed"));
346
346
  }
347
347
  }
348
- return ack;
348
+ try {
349
+ return await ack;
350
+ }
351
+ catch (error) {
352
+ // This ACK explicitly guarantees that Hub rejected the write before
353
+ // processing it. Re-authenticate, then retry the exact envelope once.
354
+ // Disconnects/timeouts have uncertain delivery and must not be replayed here.
355
+ if (!recoverAuth || msg.opcode === ChatMsgOp.AUTH || !(error instanceof ChatAckError)
356
+ || error.code !== "CHAT_CONNECTION_AUTH_REQUIRED" || this.client !== client
357
+ || this.connection === "closed" || this.connection === "authentication_required")
358
+ throw error;
359
+ if (this.connection === "connected")
360
+ client.close(false);
361
+ await this.waitUntilReady();
362
+ return this.sendAndWaitForAck(msg, false);
363
+ }
349
364
  }
350
365
  handleIncoming(message) {
351
366
  if (message.opcode === ChatMsgOp.NOTIFICATION) {
@@ -369,7 +384,7 @@ export class ChatClient {
369
384
  pending.resolve(ack);
370
385
  }
371
386
  else {
372
- pending.reject(new ChatAckError(ack.message || ack.code || "Ack failed"));
387
+ pending.reject(new ChatAckError(ack.message || ack.code || "Ack failed", ack.code));
373
388
  }
374
389
  }
375
390
  return;
@@ -469,6 +484,11 @@ export class ChatClient {
469
484
  }
470
485
  }
471
486
  class ChatAckError extends Error {
487
+ code;
488
+ constructor(message, code) {
489
+ super(message);
490
+ this.code = code;
491
+ }
472
492
  }
473
493
  export function createChatClient(options) {
474
494
  return new ChatClient(options);
@@ -109,7 +109,7 @@ export declare class ProfileChat implements Chat {
109
109
  private loadGroup;
110
110
  private refreshChangedGroups;
111
111
  refreshGroup(id: string, options?: ReadOptions): Promise<ChatGroup>;
112
- private waitGroup;
112
+ private confirmGroup;
113
113
  createGroup(input: {
114
114
  groupId?: string;
115
115
  title: string;
@@ -410,32 +410,59 @@ export class ProfileChat {
410
410
  await pending.catch(() => { });
411
411
  return this.getGroup(id, options);
412
412
  }
413
- async waitGroup(id, previous) {
414
- // Delivered commands have an accepted index cursor; the API is the authority.
415
- const group = await this.refreshGroup(id);
416
- if (previous !== undefined && group.revision === previous)
417
- throw new ChatError("unavailable", "Waiting for group confirmation");
418
- return group;
413
+ async confirmGroup(id, matches) {
414
+ for (const delay of [0, 150, 400]) {
415
+ if (delay)
416
+ await new Promise(resolve => setTimeout(resolve, delay));
417
+ this.assertAccessible(id);
418
+ try {
419
+ const group = await this.refreshGroup(id);
420
+ if (matches(group))
421
+ return group;
422
+ }
423
+ catch (error) {
424
+ if (!(error instanceof SocialReadError) || ![404, 503].includes(error.status))
425
+ throw error;
426
+ }
427
+ }
428
+ throw new ChatError("unavailable", "Waiting for group confirmation");
419
429
  }
420
430
  async createGroup(input) {
421
431
  return createUniqueGroup(input.groupId, async (groupId) => {
422
- const id = await this.resolveThreadId({ groupId });
423
- await this.sendControl(id, { groupCreate: { title: input.title, members: input.members } });
424
- return { ...await this.waitGroup(id), threadId: id };
432
+ const threadId = await this.resolveThreadId({ groupId });
433
+ const group = await this.sendControl(threadId, { groupCreate: { title: input.title, members: input.members } });
434
+ return { ...group, threadId };
425
435
  });
426
436
  }
427
- async sendControl(id, content) {
437
+ async sendControl(id, content, previous) {
428
438
  const parent = this.parent(id), identity = this.host.identity;
429
439
  if (!parent?.internal?.targetId)
430
440
  throw new ChatError("unavailable", "Conversation is not prepared");
431
441
  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);
432
442
  const wire = createRuntimeMsg(identity.profileId, input.to, 1, input.body);
433
443
  wire.recipients = input.recipients;
434
- await this.sendPrepared(id, wire, { waitFor: "delivered" });
435
- await this.host.synchronize();
444
+ try {
445
+ await this.sendPrepared(id, wire, { waitFor: "delivered" });
446
+ }
447
+ catch (error) {
448
+ // An interrupted acknowledgement can leave the group change committed.
449
+ const group = await this.confirmGroup(id, current => current.revision === wire.hash).catch(() => undefined);
450
+ if (!group)
451
+ throw error;
452
+ await this.host.submit({ type: "commandResult", commandId: wire.hash, state: "confirmed" }, true).catch(() => { });
453
+ return group;
454
+ }
455
+ // Group metadata is authoritative independently of the Inbox catch-up.
456
+ return this.confirmGroup(id, group => group.revision !== previous);
457
+ }
458
+ async updateGroup(id, changes) {
459
+ const previous = await this.getGroup(id);
460
+ return this.sendControl(id, { groupUpdate: { ...changes, expectedRevision: changes.expectedRevision ?? previous.revision } }, previous.revision);
461
+ }
462
+ async dissolveGroup(id, options = {}) {
463
+ const previous = await this.getGroup(id);
464
+ return this.sendControl(id, { groupDissolve: { expectedRevision: options.expectedRevision ?? previous.revision } }, previous.revision);
436
465
  }
437
- 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); }
438
- 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); }
439
466
  synchronizeReading() { return this.host.synchronize(); }
440
467
  revokeAccess() { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: false }, true); }
441
468
  /** Call only after a fresh authoritative Team membership check succeeds. */
@@ -22,6 +22,26 @@ export type MessageThreadSummary = {
22
22
  lastReplyAt: number | null;
23
23
  participantProfileIds: string[];
24
24
  };
25
+ export type TeamTask = {
26
+ id: string;
27
+ teamId: string;
28
+ discussionId: string;
29
+ threadId: string;
30
+ title: string;
31
+ description: string;
32
+ kind: "standard" | "flow";
33
+ status: "todo" | "inProgress" | "done";
34
+ assigneeId: string | null;
35
+ revision: number;
36
+ createdBy: string;
37
+ createdAt: number;
38
+ updatedBy: string;
39
+ updatedAt: number;
40
+ };
41
+ export type TeamTaskPage = {
42
+ tasks: TeamTask[];
43
+ nextAfterId: string | null;
44
+ };
25
45
  export type SocialGroup = {
26
46
  appId: string;
27
47
  groupId: string;
@@ -74,6 +94,7 @@ export declare class SocialReadClient {
74
94
  threadRootId?: string;
75
95
  mainOnly?: boolean;
76
96
  }, signal?: AbortSignal): Promise<SocialMessagePage>;
97
+ private validateMessagePage;
77
98
  messageThreads(input: {
78
99
  threadId: string;
79
100
  teamId?: string;
@@ -84,6 +105,22 @@ export declare class SocialReadClient {
84
105
  revision: number;
85
106
  items: MessageThreadSummary[];
86
107
  }>;
108
+ teamTasks(input: {
109
+ teamId: string;
110
+ afterId?: string;
111
+ limit?: number;
112
+ }, signal?: AbortSignal): Promise<TeamTaskPage>;
113
+ teamTask(input: {
114
+ teamId: string;
115
+ id: string;
116
+ }, signal?: AbortSignal): Promise<TeamTask>;
117
+ taskMessagePage(input: {
118
+ teamId: string;
119
+ taskId: string;
120
+ limit?: number;
121
+ before?: string;
122
+ after?: string;
123
+ }, signal?: AbortSignal): Promise<SocialMessagePage>;
87
124
  group(input: {
88
125
  groupId: string;
89
126
  teamId?: string;
@@ -92,6 +129,7 @@ export declare class SocialReadClient {
92
129
  peerId: string;
93
130
  teamId?: string;
94
131
  }): Promise<SocialRelationship | null>;
132
+ private requireMerryTaskTeam;
95
133
  private teamQuery;
96
134
  private requireTeam;
97
135
  private list;
@@ -1,4 +1,20 @@
1
1
  import { messageThreadRoot, validMessageThreadRoot } from "./messageThread.js";
2
+ import { groupThreadId, isValidChatTeamId } from "./thread.js";
3
+ const taskId = (value) => typeof value === "string" && /^(?:iss|tsk)_[a-f0-9]{64}$/.test(value);
4
+ function teamTask(value, teamId) {
5
+ if (!value || typeof value !== "object")
6
+ return false;
7
+ const row = value;
8
+ return row.teamId === teamId && taskId(row.id) && row.discussionId === row.id &&
9
+ row.threadId === groupThreadId("pmate:merry", row.discussionId, teamId) &&
10
+ typeof row.title === "string" && typeof row.description === "string" &&
11
+ (row.kind === "standard" || row.kind === "flow") &&
12
+ (row.status === "todo" || row.status === "inProgress" || row.status === "done") &&
13
+ (row.assigneeId === null || typeof row.assigneeId === "string") &&
14
+ typeof row.revision === "number" && Number.isSafeInteger(row.revision) && row.revision > 0 &&
15
+ typeof row.createdBy === "string" && Number.isSafeInteger(row.createdAt) &&
16
+ typeof row.updatedBy === "string" && Number.isSafeInteger(row.updatedAt);
17
+ }
2
18
  export class SocialReadError extends Error {
3
19
  status;
4
20
  constructor(status, message) {
@@ -36,6 +52,16 @@ export class SocialReadClient {
36
52
  throw new SocialReadError(400, "INVALID_MESSAGE_LOOKUP");
37
53
  const value = await this.request("messages", { threadId: input.threadId, ...this.teamQuery(input.teamId), limit: String(limit),
38
54
  ...(input.threadRootId === undefined ? {} : { threadRootId: input.threadRootId }), ...(input.mainOnly === undefined ? {} : { mainOnly: String(input.mainOnly) }), ...(input.before === undefined ? {} : { before: input.before }), ...(input.after === undefined ? {} : { after: input.after }), ...(input.messageId === undefined ? {} : { messageId: input.messageId }) }, signal);
55
+ this.validateMessagePage(value, input, limit);
56
+ if (value.messages.some(row => {
57
+ const root = messageThreadRoot(row.body);
58
+ const content = row.body?.content;
59
+ return input.mainOnly && root !== undefined || input.threadRootId !== undefined && root !== input.threadRootId && !content?.reaction && !content?.recall;
60
+ }))
61
+ throw new SocialReadError(502, "INVALID_MESSAGE_THREAD_PAGE_RESPONSE");
62
+ return value;
63
+ }
64
+ validateMessagePage(value, input, limit) {
39
65
  const cursor = (token) => typeof token === "string" && /^mp1:\d+:[0-9a-f]{64}$/.test(token);
40
66
  if (!value || !Array.isArray(value.messages) || value.messages.length > limit || !cursor(value.checkpoint)
41
67
  || (value.nextBefore !== null && !cursor(value.nextBefore)) || typeof value.hasMoreChanges !== "boolean" || typeof value.resetRequired !== "boolean"
@@ -44,13 +70,6 @@ export class SocialReadClient {
44
70
  throw new SocialReadError(502, "INVALID_MESSAGE_PAGE_RESPONSE");
45
71
  if (input.messageId !== undefined && (value.messages.some(row => row.messageId !== input.messageId) || value.nextBefore !== null || value.hasMoreChanges || value.resetRequired))
46
72
  throw new SocialReadError(502, "INVALID_MESSAGE_LOOKUP_RESPONSE");
47
- if (value.messages.some(row => {
48
- const root = messageThreadRoot(row.body);
49
- const content = row.body?.content;
50
- return input.mainOnly && root !== undefined || input.threadRootId !== undefined && root !== input.threadRootId && !content?.reaction && !content?.recall;
51
- }))
52
- throw new SocialReadError(502, "INVALID_MESSAGE_THREAD_PAGE_RESPONSE");
53
- return value;
54
73
  }
55
74
  async messageThreads(input, signal) {
56
75
  this.requireTeam(input.teamId);
@@ -66,6 +85,56 @@ export class SocialReadClient {
66
85
  throw new SocialReadError(502, "INVALID_MESSAGE_THREAD_SUMMARY_RESPONSE");
67
86
  return value;
68
87
  }
88
+ async teamTasks(input, signal) {
89
+ this.requireMerryTaskTeam(input.teamId);
90
+ const limit = input.limit ?? 50;
91
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 ||
92
+ (input.afterId !== undefined && !taskId(input.afterId))) {
93
+ throw new SocialReadError(400, "INVALID_TASK_QUERY");
94
+ }
95
+ const page = await this.request("v2/tasks", {
96
+ teamId: input.teamId,
97
+ limit: String(limit),
98
+ ...(input.afterId === undefined ? {} : { afterId: input.afterId }),
99
+ }, signal);
100
+ if (!page || !Array.isArray(page.tasks) || page.tasks.length > limit ||
101
+ page.tasks.some((row, index) => {
102
+ const prior = index === 0 ? input.afterId : page.tasks[index - 1]?.id;
103
+ return !teamTask(row, input.teamId) || (prior !== undefined && row.id <= prior);
104
+ }) || (page.nextAfterId !== null && (!taskId(page.nextAfterId) ||
105
+ page.tasks.length !== limit || page.tasks.at(-1)?.id !== page.nextAfterId))) {
106
+ throw new SocialReadError(502, "INVALID_TASK_PAGE_RESPONSE");
107
+ }
108
+ return page;
109
+ }
110
+ async teamTask(input, signal) {
111
+ this.requireMerryTaskTeam(input.teamId);
112
+ if (!taskId(input.id))
113
+ throw new SocialReadError(400, "INVALID_TASK_ID");
114
+ const data = await this.request("v2/tasks", { teamId: input.teamId, id: input.id }, signal);
115
+ if (!teamTask(data?.task, input.teamId) || data.task.id !== input.id) {
116
+ throw new SocialReadError(502, "INVALID_TASK_RESPONSE");
117
+ }
118
+ return data.task;
119
+ }
120
+ async taskMessagePage(input, signal) {
121
+ const { teamId, taskId: id, before, after, limit = 50 } = input;
122
+ this.requireMerryTaskTeam(teamId);
123
+ if (!taskId(id))
124
+ throw new SocialReadError(400, "INVALID_TASK_ID");
125
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500 || (before !== undefined && after !== undefined)) {
126
+ throw new SocialReadError(400, "INVALID_MESSAGE_PAGE");
127
+ }
128
+ const page = await this.request("v2/tasks/messages", {
129
+ taskId: id, teamId, limit: String(limit),
130
+ ...(before === undefined ? {} : { before }), ...(after === undefined ? {} : { after }),
131
+ }, signal);
132
+ this.validateMessagePage(page, { teamId, threadId: groupThreadId("pmate:merry", id, teamId) }, limit);
133
+ if (page.messages.some(row => row.threadKind !== "group" || row.to !== id)) {
134
+ throw new SocialReadError(502, "INVALID_TASK_MESSAGE_PAGE_RESPONSE");
135
+ }
136
+ return page;
137
+ }
69
138
  group(input, signal) {
70
139
  return this.request("group", { groupId: input.groupId, ...this.teamQuery(input.teamId) }, signal);
71
140
  }
@@ -73,6 +142,11 @@ export class SocialReadClient {
73
142
  this.requireTeam(input.teamId);
74
143
  return this.request("relationship", { peerId: input.peerId, ...this.teamQuery(input.teamId) });
75
144
  }
145
+ requireMerryTaskTeam(teamId) {
146
+ if (this.options.appId !== "pmate:merry" || !isValidChatTeamId(teamId)) {
147
+ throw new SocialReadError(400, "MERRY_TASK_TEAM_REQUIRED");
148
+ }
149
+ }
76
150
  teamQuery(teamId) {
77
151
  return teamId === undefined ? {} : { teamId };
78
152
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.14.0-seq.1",
3
+ "version": "0.14.0-seq.3",
4
4
  "description": "Local-first chat SDK, message subscriptions, reading state, and shared chat UI primitives",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",