@alexsun-top/opencode-chat-room 0.1.1 → 0.1.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.
@@ -1,7 +1,7 @@
1
1
  // ponytail: central-server mode client. All room state lives on the central
2
- // server (CHAT_ROOM_SERVER_URL); this machine self-pushes queue notifications
3
- // to its own embedded server (localhost is always reachable from the same
4
- // process, so no cross-host serverUrl or firewall setup is needed).
2
+ // server (CHAT_ROOM_SERVER_URL); this machine pushes queue notifications to
3
+ // sessions owned by this OpenCode process before using an HTTP fallback.
4
+ import { OpencodeClient } from "@opencode-ai/sdk/v2";
5
5
  import RoomService, {
6
6
  type Message,
7
7
  type Participant,
@@ -10,16 +10,72 @@ import RoomService, {
10
10
  import os from "node:os";
11
11
  import {
12
12
  authHeader,
13
+ formatServeWakePrompt,
13
14
  formatNotificationLines,
14
15
  formatRoom,
15
16
  identity,
16
17
  NOTIFY_INSTRUCTION,
17
- SERVE_WAKE_PROMPT,
18
18
  timeOf,
19
19
  } from "./store";
20
+ import {
21
+ admissionMatches,
22
+ clearPendingAdmission,
23
+ getOrCreatePendingAdmission,
24
+ markPendingAdmissionAdmitted,
25
+ pendingAdmission,
26
+ rejectPendingAdmission,
27
+ type QueueBody,
28
+ type QueueItem,
29
+ type PendingAdmission,
30
+ } from "./queue";
31
+ export { queueAdmissionId } from "./queue";
20
32
 
21
33
  type Json = Record<string, unknown>;
22
34
 
35
+ const LOCAL_SERVER_URL = "http://localhost:4096";
36
+
37
+ export type PushResult = "delivered" | "unreachable" | "rejected";
38
+
39
+ export type QueueTransport = {
40
+ client?: OpencodeClient;
41
+ serverUrl?: string;
42
+ directory?: string;
43
+ };
44
+
45
+ type QueueTransportInput = {
46
+ client?: unknown;
47
+ directory?: string;
48
+ serverUrl?: URL | string;
49
+ };
50
+
51
+ // Compatibility bridge for OpenCode 1.18.16. The plugin exposes the embedded
52
+ // transport through a private field; HTTP remains the compatibility fallback.
53
+ export function createQueueTransport(
54
+ input: QueueTransportInput = {},
55
+ ): QueueTransport {
56
+ const raw =
57
+ input.client && typeof input.client === "object"
58
+ ? (input.client as { _client?: unknown })._client
59
+ : undefined;
60
+ let client: OpencodeClient | undefined;
61
+ if (raw !== undefined && raw !== null) {
62
+ try {
63
+ type ClientArgs = NonNullable<ConstructorParameters<typeof OpencodeClient>[0]>;
64
+ client = new OpencodeClient({
65
+ client: raw as NonNullable<ClientArgs["client"]>,
66
+ });
67
+ } catch {
68
+ client = undefined;
69
+ }
70
+ }
71
+ const serverUrl = String(input.serverUrl ?? "").trim();
72
+ return {
73
+ client,
74
+ serverUrl: serverUrl || LOCAL_SERVER_URL,
75
+ directory: input.directory,
76
+ };
77
+ }
78
+
23
79
  function toRoom(r: Json): Room {
24
80
  const participants = new Map<string, Participant>();
25
81
  if (Array.isArray(r.participants)) {
@@ -45,7 +101,7 @@ function svcOf(room: Json): RoomService {
45
101
  return svc;
46
102
  }
47
103
 
48
- type CenterOpts = { center: string; token: string };
104
+ type CenterOpts = { center: string; token: string; directory?: string };
49
105
 
50
106
  async function request(
51
107
  opts: CenterOpts,
@@ -74,6 +130,17 @@ async function request(
74
130
  return data;
75
131
  }
76
132
 
133
+ async function markQueued(
134
+ opts: CenterOpts,
135
+ roomId: string,
136
+ sessionID: string,
137
+ ts: number,
138
+ ): Promise<boolean> {
139
+ return request(opts, "/queued", "POST", { roomId, sessionID, ts })
140
+ .then(() => true)
141
+ .catch(() => false);
142
+ }
143
+
77
144
  export async function centerAction(
78
145
  opts: CenterOpts,
79
146
  args: {
@@ -110,6 +177,7 @@ export async function centerAction(
110
177
  sessionID,
111
178
  // ponytail: ora-1 #2 — 记录归属主机,跨机 @-wake 只由所属机器唤醒
112
179
  host: os.hostname(),
180
+ directory: opts.directory,
113
181
  });
114
182
  return formatRoom(svcOf(room), toRoom(room));
115
183
  }
@@ -128,6 +196,7 @@ export async function centerAction(
128
196
  participantName: me,
129
197
  // ponytail: ora-1 #2 — 记录归属主机,跨机 @-wake 只由所属机器唤醒
130
198
  host: os.hostname(),
199
+ directory: opts.directory,
131
200
  },
132
201
  );
133
202
  return formatRoom(svcOf(room), toRoom(room));
@@ -195,14 +264,17 @@ export async function centerAction(
195
264
  const lines = items.map(
196
265
  (it) => `[${timeOf(it.createdAt)}] ${it.senderId}: ${it.text}`,
197
266
  );
198
- // ponytail: F7 — advance the watermark after the result is delivered
199
- // (fire-and-forget); a failure only repeats the messages, never loses
267
+ // ponytail: F7 — serialize the acknowledgment before returning so a
268
+ // following action cannot race the read watermark update. A failure only
269
+ // repeats the messages, never loses them.
200
270
  const maxTs = items.reduce((mx, it) => Math.max(mx, it.createdAt), 0);
201
- void request(opts, "/read", "POST", {
271
+ await request(opts, "/read", "POST", {
202
272
  roomId: args.roomId,
203
273
  sessionID,
204
274
  ts: maxTs,
205
- }).catch(() => {});
275
+ })
276
+ .then(() => clearPendingAdmission(sessionID, args.roomId!, maxTs))
277
+ .catch(() => {});
206
278
  return lines.join("\n");
207
279
  }
208
280
  default:
@@ -210,136 +282,280 @@ export async function centerAction(
210
282
  }
211
283
  }
212
284
 
213
- type InboxItem = {
285
+ type InboxItem = QueueItem & {
214
286
  roomId: string;
215
287
  roomName: string;
216
- senderId: string;
217
- text: string;
218
- createdAt: number;
219
288
  };
220
289
 
221
- // ponytail: overlapping hook+tool triggers must not double-deliver;
222
- // per-session so a slow check for one session can't starve another
290
+ function isRecord(value: unknown): value is Json {
291
+ return typeof value === "object" && value !== null;
292
+ }
293
+
294
+ function queueBody(admissionID: string, text: string): QueueBody {
295
+ return {
296
+ id: admissionID,
297
+ prompt: { text },
298
+ delivery: "queue",
299
+ resume: true,
300
+ };
301
+ }
302
+
303
+ function statusOf(value: unknown): number | undefined {
304
+ if (!isRecord(value)) {
305
+ return undefined;
306
+ }
307
+ if (typeof value.status === "number") {
308
+ return value.status;
309
+ }
310
+ if (isRecord(value.response) && typeof value.response.status === "number") {
311
+ return value.response.status;
312
+ }
313
+ if (isRecord(value.cause) && typeof value.cause.status === "number") {
314
+ return value.cause.status;
315
+ }
316
+ return undefined;
317
+ }
318
+
319
+ function httpHeaders(transport: QueueTransport): Record<string, string> {
320
+ const auth = authHeader();
321
+ return {
322
+ "Content-Type": "application/json",
323
+ ...(auth ? { Authorization: auth } : {}),
324
+ ...(transport.directory
325
+ ? { "x-opencode-directory": encodeURIComponent(transport.directory) }
326
+ : {}),
327
+ };
328
+ }
329
+
330
+ async function sendQueueInProcess(
331
+ client: OpencodeClient,
332
+ sessionID: string,
333
+ body: QueueBody,
334
+ ): Promise<PushResult> {
335
+ let result: unknown;
336
+ try {
337
+ result = await client.v2.session.prompt(
338
+ { sessionID, ...body },
339
+ { responseStyle: "fields", signal: AbortSignal.timeout(10_000) },
340
+ );
341
+ } catch (error) {
342
+ const status = statusOf(error);
343
+ return status === undefined || status === 404
344
+ ? "unreachable"
345
+ : "rejected";
346
+ }
347
+ if (!isRecord(result)) {
348
+ return "unreachable";
349
+ }
350
+ if (!isRecord(result.response)) {
351
+ if (admissionMatches(result, body, sessionID)) {
352
+ return "delivered";
353
+ }
354
+ return "unreachable";
355
+ }
356
+ const status = result.response.status;
357
+ if (typeof status !== "number") {
358
+ return "unreachable";
359
+ }
360
+ if (status === 404) {
361
+ return "unreachable";
362
+ }
363
+ if (status < 200 || status >= 300) {
364
+ return "rejected";
365
+ }
366
+ return admissionMatches(result.data, body, sessionID)
367
+ ? "delivered"
368
+ : "rejected";
369
+ }
370
+
371
+ async function sendQueueHttp(
372
+ transport: QueueTransport,
373
+ sessionID: string,
374
+ body: QueueBody,
375
+ ): Promise<PushResult> {
376
+ const base = (transport.serverUrl || LOCAL_SERVER_URL).replace(/\/+$/, "");
377
+ let response: Response;
378
+ try {
379
+ response = await fetch(
380
+ `${base}/api/session/${encodeURIComponent(sessionID)}/prompt`,
381
+ {
382
+ method: "POST",
383
+ headers: httpHeaders(transport),
384
+ body: JSON.stringify(body),
385
+ signal: AbortSignal.timeout(10_000),
386
+ },
387
+ );
388
+ } catch {
389
+ return "unreachable";
390
+ }
391
+ const data = await response.json().catch(() => undefined);
392
+ if (response.status === 404) {
393
+ return "unreachable";
394
+ }
395
+ if (!response.ok) {
396
+ return "rejected";
397
+ }
398
+ return admissionMatches(data, body, sessionID) ? "delivered" : "rejected";
399
+ }
400
+
401
+ export async function sendQueue(
402
+ transport: QueueTransport,
403
+ sessionID: string,
404
+ text: string,
405
+ admissionID: string,
406
+ ): Promise<PushResult> {
407
+ const body = queueBody(admissionID, text);
408
+ if (transport.client) {
409
+ const result = await sendQueueInProcess(transport.client, sessionID, body);
410
+ if (result !== "unreachable") {
411
+ return result;
412
+ }
413
+ }
414
+ return sendQueueHttp(transport, sessionID, body);
415
+ }
416
+
417
+ // Overlapping hook and tool triggers must not double-deliver; keep the lock
418
+ // per session so a slow check cannot starve another session.
223
419
  const inboxChecks = new Set<string>();
420
+ const sessionPushes = new Map<string, Promise<void>>();
421
+
422
+ function serializeSessionPush(
423
+ sessionID: string,
424
+ task: () => Promise<void>,
425
+ ): Promise<void> {
426
+ const previous = sessionPushes.get(sessionID) ?? Promise.resolve();
427
+ const run = previous.catch(() => {}).then(task);
428
+ let current: Promise<void>;
429
+ current = run.finally(() => {
430
+ if (sessionPushes.get(sessionID) === current) {
431
+ sessionPushes.delete(sessionID);
432
+ }
433
+ });
434
+ sessionPushes.set(sessionID, current);
435
+ return current;
436
+ }
224
437
 
225
- // ponytail: central mode has no cross-host push; each session pulls its inbox
226
- // on every hook/tool call and self-pushes queue notifications (localhost).
227
- // Items are grouped by room: a room's watermark advances only when every item
228
- // in that room was pushed successfully, so a failed push is retried next time.
229
438
  export async function checkCenterInbox(
230
439
  opts: CenterOpts,
231
440
  sessionID: string,
232
- selfServerUrl: string,
441
+ transport: QueueTransport,
233
442
  ): Promise<void> {
234
443
  if (inboxChecks.has(sessionID)) {
235
444
  return;
236
445
  }
237
446
  inboxChecks.add(sessionID);
238
447
  try {
239
- const result = (await request(
240
- opts,
241
- `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1`,
242
- "GET",
243
- )) as unknown as { member: boolean; items: InboxItem[] };
244
- const items = Array.isArray(result.items) ? result.items : [];
245
- if (items.length > 0) {
246
- await pushItemsToSession(opts, sessionID, items, selfServerUrl);
247
- }
448
+ await serializeSessionPush(sessionID, async () => {
449
+ const result = (await request(
450
+ opts,
451
+ `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1`,
452
+ "GET",
453
+ )) as unknown as {
454
+ member: boolean;
455
+ items: InboxItem[];
456
+ queuedTs?: Record<string, number>;
457
+ };
458
+ const queuedTs = result.queuedTs ?? {};
459
+ const items = (Array.isArray(result.items) ? result.items : []).filter(
460
+ (item) => item.createdAt > (queuedTs[item.roomId] ?? 0),
461
+ );
462
+ if (items.length > 0) {
463
+ await pushItemsToSession(opts, sessionID, items, transport, queuedTs);
464
+ }
465
+ });
248
466
  } catch {
249
467
  // best-effort: next check retries
250
468
  } finally {
251
469
  inboxChecks.delete(sessionID);
252
470
  }
253
471
  }
254
- // ponytail: push a batch of inbox items to one session (grouped per room —
255
- // a room's watermark advances only when every item in it was pushed
256
- // successfully, so a failed push is retried next time).
257
- // Result: "delivered" = all 2xx; "unreachable" = connection refused or 404
258
- // (the session's process is very likely gone — the only case worth spawning
259
- // a replacement process for); "rejected" = server alive but refused (401/5xx
260
- // — do NOT spawn, the session may live in another window).
261
- export type PushResult = "delivered" | "unreachable" | "rejected";
262
472
 
263
- // ponytail: in-process push dedupe — the 30s wake sweep and the per-hook
264
- // inbox check must not deliver the same items twice; capped pushes (which
265
- // deliberately don't advance the watermark) would otherwise re-notify every
266
- // sweep forever (orc-1 #4)
267
- const lastPushed = new Map<string, number>();
473
+ // Items are grouped by room. Queue admission advances only the durable queued
474
+ // cursor; poll remains the only path that advances the read cursor.
268
475
 
269
476
  export async function pushItemsToSession(
270
477
  opts: CenterOpts,
271
478
  sessionID: string,
272
479
  items: InboxItem[],
273
- selfServerUrl: string,
480
+ transport: QueueTransport,
481
+ queuedTs: Readonly<Record<string, number>> = {},
274
482
  ): Promise<PushResult> {
275
483
  if (items.length === 0) {
276
484
  return "delivered";
277
485
  }
278
486
  const byRoom = new Map<string, InboxItem[]>();
279
487
  for (const it of items) {
488
+ if (it.createdAt <= (queuedTs[it.roomId] ?? 0)) {
489
+ continue;
490
+ }
280
491
  const list = byRoom.get(it.roomId) ?? [];
281
492
  list.push(it);
282
493
  byRoom.set(it.roomId, list);
283
494
  }
284
- const auth = authHeader();
285
- const base = selfServerUrl.replace(/\/+$/, "");
286
495
  let worst: PushResult = "delivered";
287
496
  for (const [roomId, roomItems] of byRoom) {
288
497
  const maxTs = roomItems.reduce(
289
498
  (mx, it) => Math.max(mx, it.createdAt),
290
499
  0,
291
500
  );
292
- const key = `${sessionID}|${roomId}`;
293
- if (maxTs <= (lastPushed.get(key) ?? 0)) {
294
- continue; // already pushed this content
295
- }
296
- if (lastPushed.size > 1000) {
297
- lastPushed.clear(); // ponytail: cap——防长驻进程无限增长
501
+ const existing = pendingAdmission(sessionID, roomId);
502
+ const deltaItems =
503
+ existing?.state === "admitted" && maxTs > existing.maxTs
504
+ ? roomItems.filter((item) => item.createdAt > existing.maxTs)
505
+ : roomItems;
506
+ if (
507
+ existing?.state === "admitted" &&
508
+ (maxTs <= existing.maxTs || deltaItems.length === 0)
509
+ ) {
510
+ if (existing.maxTs > 0) {
511
+ const queued = await markQueued(
512
+ opts,
513
+ roomId,
514
+ sessionID,
515
+ existing.maxTs,
516
+ );
517
+ if (queued) {
518
+ clearPendingAdmission(sessionID, roomId, existing.maxTs);
519
+ }
520
+ }
521
+ continue;
298
522
  }
299
- const { lines, capped } = formatNotificationLines(roomItems);
300
- const prompt = `<notification>\nNew messages in room ${roomItems[0]!.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
301
- // ponytail: network errors (e.g. connection refused — the session's
302
- // process has exited) count as push failure, NOT as a crash: a rejected
303
- // fetch here would abort the whole wake sweep and skip every other
304
- // session, and the @-wake spawn would never run
305
- let res: Response;
306
- try {
307
- res = await fetch(`${base}/api/session/${sessionID}/prompt`, {
308
- method: "POST",
309
- headers: {
310
- "Content-Type": "application/json",
311
- ...(auth ? { Authorization: auth } : {}),
312
- },
313
- body: JSON.stringify({ prompt, delivery: "queue" }),
314
- });
315
- } catch {
316
- worst = "unreachable";
523
+ const deltaMaxTs = deltaItems.reduce(
524
+ (mx, it) => Math.max(mx, it.createdAt),
525
+ 0,
526
+ );
527
+ const { lines, capped } = formatNotificationLines(deltaItems);
528
+ const prompt = `<notification>\nNew messages in room ${deltaItems[0]!.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
529
+ const admission = getOrCreatePendingAdmission(
530
+ sessionID,
531
+ roomId,
532
+ deltaItems,
533
+ prompt,
534
+ deltaMaxTs,
535
+ capped,
536
+ );
537
+ const result = await sendQueue(
538
+ transport,
539
+ sessionID,
540
+ admission.prompt,
541
+ admission.id,
542
+ );
543
+ if (result !== "delivered") {
544
+ if (result === "rejected") {
545
+ rejectPendingAdmission(sessionID, roomId, admission.id);
546
+ }
547
+ if (result === "rejected" || worst === "delivered") {
548
+ worst = result;
549
+ }
317
550
  continue;
318
551
  }
319
- // ponytail: a capped push must not advance the watermark — the
320
- // folded-out messages would become permanently unreadable; the
321
- // uncapped poll/inbox path remains the lossless catch-up
322
- if (res.ok) {
323
- if (capped) {
324
- lastPushed.set(key, maxTs);
325
- } else {
326
- // orc-3 #6——/read 失败时不得记 lastPushed:水位未推进,下次 sweep
327
- // 重推(否则推送成功但水位未动 → 推送路径对该批消息永久静默)
328
- const advanced = await request(opts, "/read", "POST", {
329
- roomId,
330
- sessionID,
331
- ts: maxTs,
332
- })
333
- .then(() => true)
334
- .catch(() => false);
335
- if (advanced) lastPushed.set(key, maxTs);
552
+ markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
553
+ void request(opts, "/active", "POST", { sessionID }).catch(() => {});
554
+ if (admission.maxTs > 0) {
555
+ const queued = await markQueued(opts, roomId, sessionID, admission.maxTs);
556
+ if (queued) {
557
+ clearPendingAdmission(sessionID, roomId, admission.maxTs);
336
558
  }
337
- } else if (res.status === 404 || res.status === 400) {
338
- // 404 / 400 (Invalid session ID): 本进程/本 server 不持有该 session
339
- // ——已退出或从未在本机运行 → 视为 unreachable,可由 serve 唤起
340
- worst = "unreachable";
341
- } else {
342
- worst = "rejected";
343
559
  }
344
560
  }
345
561
  return worst;
@@ -352,16 +568,15 @@ export async function pushItemsToSession(
352
568
  // knowledge, this is purely client-side.
353
569
  let wakeChecking = false;
354
570
 
355
- // ponytail: 纯进程内唤醒(去 spawn)——已退出进程的 session 不再拉起新
356
- // 进程。若部署者配置了 CHAT_ROOM_WAKE_SERVE_URL(常驻 opencode serve),
357
- // 对被 @ 的已退出 session 通过 serve 的 /session/:id/message 进程内唤起;
358
- // serve 未配置/不可达 → 不唤醒(未读由水位保留,session 下次运行时 poll
359
- // 自动拿到)
571
+ // No process is spawned here. A configured opencode serve is only a fallback
572
+ // for mentioned sessions that cannot be admitted by the current process.
360
573
  async function wakeViaServe(
361
574
  serveUrl: string,
362
575
  sessionID: string,
576
+ roomId: string,
363
577
  opts: CenterOpts,
364
- prompt = SERVE_WAKE_PROMPT,
578
+ transport: QueueTransport,
579
+ admission: PendingAdmission,
365
580
  ): Promise<boolean> {
366
581
  // ponytail: 与多窗口插件共用服务器原子去重,避免重复唤起同一 session
367
582
  try {
@@ -380,26 +595,30 @@ async function wakeViaServe(
380
595
  } catch {
381
596
  return false;
382
597
  }
383
- try {
384
- const res = await fetch(
385
- `${serveUrl.replace(/\/+$/, "")}/session/${sessionID}/message`,
386
- {
387
- method: "POST",
388
- headers: { "Content-Type": "application/json" },
389
- body: JSON.stringify({ parts: [{ type: "text", text: prompt }] }),
390
- signal: AbortSignal.timeout(10_000),
391
- },
392
- );
393
- return res.ok;
394
- } catch {
395
- // serve 未启动/不可达——按用户要求不唤醒(无 spawn、无重试)
396
- return false;
598
+ const result = await sendQueue(
599
+ { ...transport, client: undefined, serverUrl: serveUrl },
600
+ sessionID,
601
+ admission.prompt,
602
+ admission.id,
603
+ );
604
+ if (result === "delivered") {
605
+ void request(opts, "/active", "POST", { sessionID }).catch(() => {});
606
+ markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
607
+ if (admission.maxTs > 0) {
608
+ const queued = await markQueued(opts, roomId, sessionID, admission.maxTs);
609
+ if (queued) {
610
+ clearPendingAdmission(sessionID, roomId, admission.maxTs);
611
+ }
612
+ }
613
+ } else if (result === "rejected") {
614
+ rejectPendingAdmission(sessionID, roomId, admission.id);
397
615
  }
616
+ return result === "delivered";
398
617
  }
399
618
 
400
619
  export async function wakeSessions(
401
620
  opts: CenterOpts,
402
- selfServerUrl: string,
621
+ transport: QueueTransport,
403
622
  serveUrl = "",
404
623
  ): Promise<void> {
405
624
  if (wakeChecking) {
@@ -429,7 +648,13 @@ export async function wakeSessions(
429
648
  "GET",
430
649
  )) as unknown as Record<
431
650
  string,
432
- { name: string; lastReadTs?: number; host?: string }
651
+ {
652
+ name: string;
653
+ lastReadTs?: number;
654
+ lastQueuedTs?: number;
655
+ host?: string;
656
+ directory?: string;
657
+ }
433
658
  >;
434
659
  if (!reg || typeof reg !== "object") {
435
660
  continue;
@@ -441,21 +666,44 @@ export async function wakeSessions(
441
666
  continue;
442
667
  }
443
668
  // ponytail: orc-2 #6——跨 host 条目由各自机器上的插件负责,本机
444
- // 扫描+推送只会 404(lastPushed 只在 res.ok 时设置,永不去重)
669
+ // 扫描+推送只会 404;队列游标由中心服务器持久化
445
670
  if (entry.host !== os.hostname()) {
446
671
  continue;
447
672
  }
448
673
  // quick skip: nothing newer than this session's watermark
449
- if (latest <= (entry.lastReadTs ?? 0)) {
674
+ if (
675
+ latest <=
676
+ Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0)
677
+ ) {
450
678
  continue;
451
679
  }
452
- const result = (await request(
453
- opts,
454
- `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1&timeout=0`,
455
- "GET",
456
- )) as unknown as { member: boolean; items: InboxItem[] };
457
- const items = Array.isArray(result.items) ? result.items : [];
458
- if (items.length > 0) {
680
+ await serializeSessionPush(sessionID, async () => {
681
+ const result = (await request(
682
+ opts,
683
+ `/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(roomId)}&excludeSelf=1&timeout=0`,
684
+ "GET",
685
+ )) as unknown as {
686
+ member: boolean;
687
+ items: InboxItem[];
688
+ queuedTs?: Record<string, number>;
689
+ };
690
+ const queuedTs = Math.max(
691
+ entry.lastQueuedTs ?? 0,
692
+ result.queuedTs?.[roomId] ?? 0,
693
+ );
694
+ const items = Array.isArray(result.items)
695
+ ? result.items.filter(
696
+ (item) =>
697
+ item.roomId === roomId && item.createdAt > queuedTs,
698
+ )
699
+ : [];
700
+ if (items.length === 0) {
701
+ return;
702
+ }
703
+ const targetTransport = {
704
+ ...transport,
705
+ directory: entry.directory ?? transport.directory,
706
+ };
459
707
  // ponytail: ora-1 #2 — @-wake 只由 session 归属主机执行;web 条目
460
708
  // (host 为空)与异机条目绝不 spawn(否则错机 spawn 一个不存在
461
709
  // 的 session,且 5 分钟 claim 窗口会挡住真正正确的那台机器)
@@ -463,17 +711,11 @@ export async function wakeSessions(
463
711
  opts,
464
712
  sessionID,
465
713
  items,
466
- selfServerUrl,
714
+ targetTransport,
715
+ result.queuedTs,
467
716
  );
468
- if (pushed === "delivered") {
469
- // ponytail: 进程内自推成功 = 该 session 真实活跃——上报服务器,
470
- // 避免服务器 serve 双唤起
471
- void request(opts, "/active", "POST", { sessionID }).catch(
472
- () => {},
473
- );
474
- }
475
717
  // 被 @ 的已退出 session:serve 配置了才唤起(进程内,零 spawn)。
476
- // 唤起成功即推进水位——消息已进入该 session 的对话(不丢),
718
+ // 唤起成功即推进队列游标——消息已进入该 session 的对话(不丢),
477
719
  // 避免同一未读反复唤起导致循环回复。
478
720
  // 仅唤起本机 opencode session(host === 本机主机名)——web 条目
479
721
  // 与 curl 模拟成员(host 空)没有可恢复的 opencode 会话
@@ -490,32 +732,50 @@ export async function wakeSessions(
490
732
  );
491
733
  });
492
734
  if (mentioned) {
493
- // ponytail: orc-2 #1——唤起 prompt 必须带未读消息内容(镜像
494
- // 服务器路径),否则 agent poll 时已无未读(水位已推进),
495
- // @ 内容永远不达;水位推进到 maxTs 因此是安全的
496
- const content = items
497
- .map((it) => `[${it.senderId}]: ${it.text}`)
498
- .join("\n");
499
- const woke = await wakeViaServe(
735
+ const currentMaxTs = items.reduce(
736
+ (mx, it) => Math.max(mx, it.createdAt),
737
+ 0,
738
+ );
739
+ const existing = pendingAdmission(sessionID, roomId);
740
+ const deltaItems =
741
+ existing?.state === "admitted" &&
742
+ currentMaxTs > existing.maxTs
743
+ ? items.filter((item) => item.createdAt > existing.maxTs)
744
+ : items;
745
+ if (
746
+ existing?.state === "admitted" &&
747
+ (currentMaxTs <= existing.maxTs || deltaItems.length === 0)
748
+ ) {
749
+ return;
750
+ }
751
+ const { lines, capped } = formatNotificationLines(deltaItems);
752
+ const prompt = formatServeWakePrompt(
753
+ deltaItems[0]!.roomName,
754
+ lines,
755
+ );
756
+ const maxTs = deltaItems.reduce(
757
+ (mx, it) => Math.max(mx, it.createdAt),
758
+ 0,
759
+ );
760
+ const admission = getOrCreatePendingAdmission(
761
+ sessionID,
762
+ roomId,
763
+ deltaItems,
764
+ prompt,
765
+ maxTs,
766
+ capped,
767
+ );
768
+ await wakeViaServe(
500
769
  serveUrl,
501
770
  sessionID,
771
+ roomId,
502
772
  opts,
503
- `${SERVE_WAKE_PROMPT}\n\n未读消息:\n${content}`,
773
+ targetTransport,
774
+ admission,
504
775
  );
505
- if (woke) {
506
- const maxTs = items.reduce(
507
- (mx, it) => Math.max(mx, it.createdAt),
508
- 0,
509
- );
510
- await request(opts, "/read", "POST", {
511
- roomId,
512
- sessionID,
513
- ts: maxTs,
514
- }).catch(() => {});
515
- }
516
776
  }
517
777
  }
518
- }
778
+ });
519
779
  }
520
780
  } catch {
521
781
  // ponytail: orc-3 #4——单房间错误(registry/inbox 请求失败)只跳过