@myclaw163/clawclaw-cli 0.7.5 → 0.7.7

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 (62) hide show
  1. package/docs/desktop-event-push.md +154 -0
  2. package/docs/runtime/README.md +1 -0
  3. package/docs/runtime/official-perception-modules.md +346 -0
  4. package/package.json +2 -1
  5. package/src/commands/game/index.test.ts +167 -1
  6. package/src/commands/game/index.ts +125 -36
  7. package/src/lib/game-client.test.ts +15 -0
  8. package/src/lib/game-client.ts +4 -0
  9. package/src/lib/participation-status.ts +113 -0
  10. package/src/lib/service-status.test.ts +56 -0
  11. package/src/lib/service-status.ts +111 -0
  12. package/src/pipeline/event-format.test.ts +30 -0
  13. package/src/pipeline/event-format.ts +26 -1
  14. package/src/pipeline/event-hints.test.ts +18 -3
  15. package/src/pipeline/event-hints.ts +11 -0
  16. package/src/pipeline/game-sync-event-normalization.test.ts +58 -1
  17. package/src/pipeline/game-sync-event-normalization.ts +51 -0
  18. package/src/runtime/clawclaw/agent-event-policy.test.ts +4 -0
  19. package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
  20. package/src/runtime/clawclaw/owner.ts +62 -3
  21. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +189 -0
  22. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +532 -0
  23. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +363 -0
  24. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +236 -0
  25. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +411 -0
  26. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  27. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +166 -0
  28. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +194 -0
  29. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +262 -0
  30. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +28 -0
  31. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +49 -0
  32. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +77 -259
  33. package/src/runtime/clawclaw/plugins/perception/contracts.ts +4 -0
  34. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +6 -0
  35. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +6 -0
  36. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +6 -0
  37. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +6 -0
  38. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +6 -0
  39. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +6 -0
  40. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +6 -0
  41. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +11 -0
  42. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +8 -0
  43. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +12 -0
  44. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +37 -1
  45. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +5 -0
  46. package/src/runtime/clawclaw/plugins/source/room-transport.ts +2 -1
  47. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +201 -1
  48. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +113 -24
  49. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  50. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +6 -0
  51. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +4 -0
  52. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +4 -0
  53. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +36 -0
  54. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +13 -0
  55. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +22 -0
  56. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +46 -16
  57. package/src/runtime/clawclaw-event-catalog.test.ts +2 -0
  58. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  59. package/src/sdk/perception-plugin/index.ts +14 -0
  60. package/src/sdk/resource-metadata.test.ts +40 -0
  61. package/src/sdk/resource-metadata.ts +63 -0
  62. package/src/sdk/strategy-plugin/index.ts +14 -0
@@ -0,0 +1,194 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import type { CanonicalEvent } from '../../../framework/events/index.js';
3
+ import {
4
+ MailboxEventBatchPump,
5
+ type MailboxEventBatchAcceptance,
6
+ type MailboxEventBatchSink,
7
+ type MailboxEventBatchSource,
8
+ } from './mailbox-event-batch-delivery.js';
9
+
10
+ function canonicalEvent(
11
+ eventId: string,
12
+ commitSeq: number,
13
+ deliveryClass: CanonicalEvent['deliveryClass'] = 'monitor_and_events',
14
+ ): CanonicalEvent {
15
+ return {
16
+ commitSeq,
17
+ epochSeq: commitSeq,
18
+ eventId,
19
+ sessionId: 'session-1',
20
+ segmentId: 'game-1',
21
+ type: 'speech',
22
+ producer: 'backend_push',
23
+ deliveryClass,
24
+ occurredAt: '2026-08-04T00:00:00.000Z',
25
+ receivedAt: '2026-08-04T00:00:00.000Z',
26
+ payload: { text: eventId },
27
+ sourceId: 'test',
28
+ replayed: false,
29
+ };
30
+ }
31
+
32
+ function prepared(deliveryToken: string, readyEpochSeq = 2) {
33
+ return {
34
+ deliveryToken,
35
+ readyEpochSeq,
36
+ batch: {
37
+ state: { phase: 'wandering' },
38
+ events: [{ type: 'speech', text: deliveryToken }],
39
+ },
40
+ };
41
+ }
42
+
43
+ afterEach(() => vi.useRealTimers());
44
+
45
+ describe('MailboxEventBatchPump', () => {
46
+ it('honors the coordinator retry boundary and waits for Host acceptance before ACK', async () => {
47
+ vi.useFakeTimers();
48
+ vi.setSystemTime(new Date('2026-08-04T00:00:00.000Z'));
49
+ let accept: ((value: MailboxEventBatchAcceptance) => void) | undefined;
50
+ const source: MailboxEventBatchSource = {
51
+ prepare: vi.fn()
52
+ .mockReturnValueOnce({
53
+ batch: { state: null, events: [] },
54
+ readyEpochSeq: 1,
55
+ nextAttemptAtMs: Date.now() + 220,
56
+ })
57
+ .mockReturnValueOnce(prepared('delivery-1')),
58
+ renew: vi.fn(() => true),
59
+ ack: vi.fn(() => true),
60
+ release: vi.fn(() => true),
61
+ };
62
+ const sink: MailboxEventBatchSink = {
63
+ deliver: vi.fn(() => new Promise<MailboxEventBatchAcceptance>((resolve) => {
64
+ accept = resolve;
65
+ })),
66
+ close: vi.fn(async () => {}),
67
+ };
68
+ const pump = new MailboxEventBatchPump({ source, sink });
69
+
70
+ pump.observeEvents([canonicalEvent('event-1', 1)]);
71
+ await Promise.resolve();
72
+ expect(source.prepare).toHaveBeenCalledOnce();
73
+ await vi.advanceTimersByTimeAsync(219);
74
+ expect(sink.deliver).not.toHaveBeenCalled();
75
+
76
+ pump.observeEvents([canonicalEvent('event-2', 2, 'events_only')]);
77
+ await vi.advanceTimersByTimeAsync(1);
78
+ expect(source.prepare).toHaveBeenCalledTimes(2);
79
+ expect(sink.deliver).toHaveBeenCalledWith({
80
+ deliveryId: 'delivery-1',
81
+ batch: prepared('delivery-1').batch,
82
+ }, expect.any(AbortSignal));
83
+ expect(source.ack).not.toHaveBeenCalled();
84
+
85
+ accept?.({
86
+ acceptedAt: '2026-08-04T00:00:00.220Z',
87
+ receiptId: 'wake-1',
88
+ });
89
+ await vi.runAllTimersAsync();
90
+ expect(source.ack).toHaveBeenCalledWith('delivery-1');
91
+ expect(source.release).not.toHaveBeenCalled();
92
+ await pump.stop();
93
+ });
94
+
95
+ it('keeps one prepared delivery across retry without observing internal-only state', async () => {
96
+ vi.useFakeTimers();
97
+ vi.setSystemTime(new Date('2026-08-04T00:00:00.000Z'));
98
+ const source: MailboxEventBatchSource = {
99
+ prepare: vi.fn(() => prepared('delivery-1', 1)),
100
+ renew: vi.fn(() => true),
101
+ ack: vi.fn(() => true),
102
+ release: vi.fn(() => true),
103
+ };
104
+ const deliver = vi.fn<MailboxEventBatchSink['deliver']>()
105
+ .mockRejectedValueOnce(new Error('desktop_disconnected'))
106
+ .mockResolvedValueOnce({ acceptedAt: '2026-08-04T00:00:00.470Z' });
107
+ const sink: MailboxEventBatchSink = {
108
+ deliver,
109
+ close: vi.fn(async () => {}),
110
+ };
111
+ const pump = new MailboxEventBatchPump({ source, sink });
112
+
113
+ pump.observeEvents([canonicalEvent('internal-1', 1, 'internal_only')]);
114
+ await vi.advanceTimersByTimeAsync(500);
115
+ expect(source.prepare).not.toHaveBeenCalled();
116
+
117
+ pump.observeEvents([canonicalEvent('visible-1', 1)]);
118
+ await Promise.resolve();
119
+ await Promise.resolve();
120
+ expect(source.release).not.toHaveBeenCalled();
121
+ expect(source.ack).not.toHaveBeenCalled();
122
+
123
+ await vi.advanceTimersByTimeAsync(250);
124
+ await Promise.resolve();
125
+ expect(source.prepare).toHaveBeenCalledOnce();
126
+ expect(source.renew).toHaveBeenCalledWith('delivery-1');
127
+ expect(source.ack).toHaveBeenCalledWith('delivery-1');
128
+ expect(deliver.mock.calls.map(([envelope]) => envelope.deliveryId))
129
+ .toEqual(['delivery-1', 'delivery-1']);
130
+ await pump.stop();
131
+ expect(sink.close).toHaveBeenCalledOnce();
132
+ });
133
+
134
+ it('does not make Runtime lifecycle flush wait for Host acknowledgement', async () => {
135
+ const source: MailboxEventBatchSource = {
136
+ prepare: vi.fn(() => prepared('delivery-1')),
137
+ renew: vi.fn(() => true),
138
+ ack: vi.fn(() => true),
139
+ release: vi.fn(() => true),
140
+ };
141
+ const sink: MailboxEventBatchSink = {
142
+ deliver: vi.fn((_envelope, signal) => new Promise<MailboxEventBatchAcceptance>(
143
+ (_resolve, reject) => {
144
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
145
+ },
146
+ )),
147
+ close: vi.fn(async () => {}),
148
+ };
149
+ const pump = new MailboxEventBatchPump({ source, sink });
150
+
151
+ pump.observeEvents([canonicalEvent('event-1', 1)]);
152
+ await Promise.resolve();
153
+ await expect(pump.flush()).resolves.toBeUndefined();
154
+ expect(sink.deliver).toHaveBeenCalledOnce();
155
+ expect(source.ack).not.toHaveBeenCalled();
156
+
157
+ await pump.stop();
158
+ expect(source.release).toHaveBeenCalledWith('delivery-1');
159
+ });
160
+
161
+ it('retries Mailbox ACK without redelivering after the Host already accepted', async () => {
162
+ vi.useFakeTimers();
163
+ vi.setSystemTime(new Date('2026-08-04T00:00:00.000Z'));
164
+ const source: MailboxEventBatchSource = {
165
+ prepare: vi.fn(() => prepared('delivery-1')),
166
+ renew: vi.fn(() => true),
167
+ ack: vi.fn()
168
+ .mockReturnValueOnce(false)
169
+ .mockReturnValueOnce(true),
170
+ release: vi.fn(() => true),
171
+ };
172
+ const sink: MailboxEventBatchSink = {
173
+ deliver: vi.fn(async () => ({
174
+ acceptedAt: '2026-08-04T00:00:00.000Z',
175
+ receiptId: 'wake-1',
176
+ })),
177
+ close: vi.fn(async () => {}),
178
+ };
179
+ const pump = new MailboxEventBatchPump({ source, sink });
180
+
181
+ pump.observeEvents([canonicalEvent('event-1', 1)]);
182
+ await Promise.resolve();
183
+ await Promise.resolve();
184
+ expect(sink.deliver).toHaveBeenCalledOnce();
185
+ expect(source.ack).toHaveBeenCalledOnce();
186
+
187
+ await vi.advanceTimersByTimeAsync(250);
188
+ expect(source.renew).toHaveBeenCalledWith('delivery-1');
189
+ expect(source.ack).toHaveBeenCalledTimes(2);
190
+ expect(sink.deliver).toHaveBeenCalledOnce();
191
+ expect(source.release).not.toHaveBeenCalled();
192
+ await pump.stop();
193
+ });
194
+ });
@@ -0,0 +1,262 @@
1
+ import type { CanonicalEvent } from '../../../framework/events/index.js';
2
+ import type {
3
+ AgentMailboxBatch,
4
+ PreparedAgentMailboxBatch,
5
+ } from './agent-mailbox-coordinator.js';
6
+
7
+ const DEFAULT_RETRY_BASE_MS = 250;
8
+ const DEFAULT_RETRY_MAX_MS = 5_000;
9
+
10
+ export interface MailboxEventBatchSource {
11
+ prepare(): PreparedAgentMailboxBatch;
12
+ renew(deliveryToken: string): boolean;
13
+ ack(deliveryToken: string): boolean;
14
+ release(deliveryToken: string): boolean;
15
+ }
16
+
17
+ export interface MailboxEventBatchEnvelope {
18
+ /** Stable for this durable preparation and required on the application ACK. */
19
+ deliveryId: string;
20
+ batch: AgentMailboxBatch;
21
+ }
22
+
23
+ export interface MailboxEventBatchAcceptance {
24
+ acceptedAt: string;
25
+ receiptId?: string;
26
+ }
27
+
28
+ /** A transport adapter only hands a prepared batch to a Host input queue. */
29
+ export interface MailboxEventBatchSink {
30
+ deliver(
31
+ envelope: MailboxEventBatchEnvelope,
32
+ signal: AbortSignal,
33
+ ): Promise<MailboxEventBatchAcceptance>;
34
+ close(): Promise<void>;
35
+ }
36
+
37
+ export interface MailboxEventBatchPumpOptions {
38
+ source: MailboxEventBatchSource;
39
+ sink: MailboxEventBatchSink;
40
+ now?: () => number;
41
+ diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
42
+ }
43
+
44
+ interface PreparedPumpDelivery {
45
+ deliveryToken: string;
46
+ batch: AgentMailboxBatch;
47
+ readyEpochSeq: number;
48
+ generation: number;
49
+ acceptance?: MailboxEventBatchAcceptance;
50
+ }
51
+
52
+ function errorMessage(error: unknown): string {
53
+ return error instanceof Error ? error.message : String(error);
54
+ }
55
+
56
+ function retryDelay(attempt: number): number {
57
+ const exponent = Math.max(0, Math.min(8, attempt - 1));
58
+ return Math.min(DEFAULT_RETRY_MAX_MS, DEFAULT_RETRY_BASE_MS * (2 ** exponent));
59
+ }
60
+
61
+ /**
62
+ * Coordinates the durable Mailbox detail lane with the Host sink selected for
63
+ * this Owner. Desktop IPC and Channels are sibling adapters over this boundary;
64
+ * the pump knows neither their wire formats nor Monitor presentation.
65
+ */
66
+ export class MailboxEventBatchPump {
67
+ private readonly source: MailboxEventBatchSource;
68
+ private readonly sink: MailboxEventBatchSink;
69
+ private readonly now: () => number;
70
+ private readonly diagnostic?: MailboxEventBatchPumpOptions['diagnostic'];
71
+
72
+ private stopped = false;
73
+ private pending = false;
74
+ private generation = 0;
75
+ private retryAttempt = 0;
76
+ private timer: ReturnType<typeof setTimeout> | undefined;
77
+ private timerAtMs: number | undefined;
78
+ private pumpRequested = false;
79
+ private pumpPromise: Promise<void> | undefined;
80
+ private activeAbort: AbortController | undefined;
81
+ private preparedDelivery: PreparedPumpDelivery | undefined;
82
+
83
+ constructor(options: MailboxEventBatchPumpOptions) {
84
+ this.source = options.source;
85
+ this.sink = options.sink;
86
+ this.now = options.now ?? Date.now;
87
+ this.diagnostic = options.diagnostic;
88
+ }
89
+
90
+ /** Called by the Mailbox Plugin after committed Agent-visible Events appear. */
91
+ observeEvents(events: readonly CanonicalEvent[]): void {
92
+ if (this.stopped) return;
93
+ const visible = events.filter((event) => event.deliveryClass !== 'internal_only');
94
+ if (visible.length === 0) return;
95
+ this.pending = true;
96
+ this.generation += 1;
97
+ this.clearTimer();
98
+ this.requestPump();
99
+ }
100
+
101
+ /** Shortens a persisted retry after the Host transport reconnects. */
102
+ retryNow(): void {
103
+ if (this.stopped || !this.pending || this.retryAttempt === 0) return;
104
+ this.clearTimer();
105
+ this.scheduleAt(this.now());
106
+ }
107
+
108
+ /** Kicks delivery without making Runtime lifecycle flush wait for Host ACK. */
109
+ async flush(): Promise<void> {
110
+ if (this.stopped) {
111
+ return;
112
+ }
113
+ this.pending = true;
114
+ this.generation += 1;
115
+ this.clearTimer();
116
+ this.requestPump();
117
+ }
118
+
119
+ /** Waits only for the currently runnable delivery attempt at an Owner boundary. */
120
+ async drain(): Promise<void> {
121
+ await this.flush();
122
+ while (this.pumpPromise) await this.pumpPromise;
123
+ }
124
+
125
+ async stop(): Promise<void> {
126
+ if (this.stopped) {
127
+ await this.pumpPromise;
128
+ return;
129
+ }
130
+ this.stopped = true;
131
+ this.pending = false;
132
+ this.pumpRequested = false;
133
+ this.clearTimer();
134
+ this.activeAbort?.abort(new Error('mailbox_event_batch_pump_stopped'));
135
+ await this.pumpPromise;
136
+ this.releasePreparedDelivery();
137
+ await this.sink.close();
138
+ }
139
+
140
+ private requestPump(): void {
141
+ if (this.stopped) return;
142
+ this.pumpRequested = true;
143
+ if (this.pumpPromise) return;
144
+ this.pumpPromise = this.pump()
145
+ .catch((error) => {
146
+ this.diagnostic?.('runtime.mailbox.event_batch_pump_failed', {
147
+ error: errorMessage(error),
148
+ });
149
+ })
150
+ .finally(() => {
151
+ this.pumpPromise = undefined;
152
+ if (this.pumpRequested && !this.stopped) this.requestPump();
153
+ });
154
+ }
155
+
156
+ private async pump(): Promise<void> {
157
+ this.pumpRequested = false;
158
+ if (!this.pending || this.stopped) return;
159
+
160
+ try {
161
+ let prepared = this.preparedDelivery;
162
+ if (prepared) {
163
+ if (!this.source.renew(prepared.deliveryToken)) {
164
+ this.releasePreparedDelivery();
165
+ throw new Error('mailbox_event_batch_lease_lost');
166
+ }
167
+ } else {
168
+ const selected = this.source.prepare();
169
+ const deliveryToken = selected.deliveryToken;
170
+ if (!deliveryToken || selected.batch.events.length === 0) {
171
+ if (deliveryToken) this.source.release(deliveryToken);
172
+ if (selected.nextAttemptAtMs !== undefined) {
173
+ this.scheduleAt(selected.nextAttemptAtMs);
174
+ return;
175
+ }
176
+ if (!this.pumpRequested) {
177
+ this.pending = false;
178
+ this.retryAttempt = 0;
179
+ } else {
180
+ this.scheduleAt(this.now());
181
+ }
182
+ return;
183
+ }
184
+ prepared = {
185
+ deliveryToken,
186
+ batch: selected.batch,
187
+ readyEpochSeq: selected.readyEpochSeq,
188
+ generation: this.generation,
189
+ };
190
+ this.preparedDelivery = prepared;
191
+ }
192
+
193
+ if (!prepared.acceptance) {
194
+ const controller = new AbortController();
195
+ this.activeAbort = controller;
196
+ prepared.acceptance = await this.sink.deliver({
197
+ deliveryId: prepared.deliveryToken,
198
+ batch: prepared.batch,
199
+ }, controller.signal);
200
+ this.activeAbort = undefined;
201
+ }
202
+ if (!this.source.ack(prepared.deliveryToken)) {
203
+ throw new Error('mailbox_event_batch_ack_lost');
204
+ }
205
+ this.preparedDelivery = undefined;
206
+ this.diagnostic?.('runtime.mailbox.event_batch_accepted', {
207
+ delivery_id: prepared.deliveryToken,
208
+ event_count: prepared.batch.events.length,
209
+ ready_epoch_seq: prepared.readyEpochSeq,
210
+ accepted_at: prepared.acceptance.acceptedAt,
211
+ ...(prepared.acceptance.receiptId ? { receipt_id: prepared.acceptance.receiptId } : {}),
212
+ });
213
+ this.retryAttempt = 0;
214
+ if (this.generation === prepared.generation) {
215
+ this.pending = false;
216
+ } else {
217
+ this.scheduleAt(this.now());
218
+ }
219
+ } catch (error) {
220
+ this.activeAbort = undefined;
221
+ if (this.stopped) {
222
+ this.releasePreparedDelivery();
223
+ return;
224
+ }
225
+ this.pending = true;
226
+ this.retryAttempt += 1;
227
+ const delayMs = retryDelay(this.retryAttempt);
228
+ this.diagnostic?.('runtime.mailbox.event_batch_retry', {
229
+ attempt: this.retryAttempt,
230
+ retry_in_ms: delayMs,
231
+ error: errorMessage(error),
232
+ });
233
+ this.scheduleAt(this.now() + delayMs);
234
+ }
235
+ }
236
+
237
+ private scheduleAt(atMs: number): void {
238
+ if (this.stopped) return;
239
+ if (this.timer && this.timerAtMs !== undefined && this.timerAtMs <= atMs) return;
240
+ this.clearTimer();
241
+ this.timerAtMs = atMs;
242
+ const timer = setTimeout(() => {
243
+ this.timer = undefined;
244
+ this.timerAtMs = undefined;
245
+ this.requestPump();
246
+ }, Math.max(0, atMs - this.now()));
247
+ timer.unref?.();
248
+ this.timer = timer;
249
+ }
250
+
251
+ private clearTimer(): void {
252
+ if (this.timer) clearTimeout(this.timer);
253
+ this.timer = undefined;
254
+ this.timerAtMs = undefined;
255
+ }
256
+
257
+ private releasePreparedDelivery(): void {
258
+ const prepared = this.preparedDelivery;
259
+ this.preparedDelivery = undefined;
260
+ if (prepared) this.source.release(prepared.deliveryToken);
261
+ }
262
+ }
@@ -5,15 +5,42 @@ import type {
5
5
  RuntimeEpochPluginInput,
6
6
  RuntimeEpochPluginResult,
7
7
  } from '../../../framework/plugins/index.js';
8
+ import type { CanonicalEvent } from '../../../framework/events/index.js';
8
9
 
9
10
  export const CLAWCLAW_MAILBOX_PLUGIN_ID = 'clawclaw.mailbox';
10
11
 
11
12
  /** Delivery I/O runs independently from epoch cadence. */
12
13
  export interface ClawclawMailboxDriver {
14
+ observeEvents?(events: readonly CanonicalEvent[]): void;
13
15
  flush(): Promise<void>;
14
16
  stop(): Promise<void>;
15
17
  }
16
18
 
19
+ /** Keeps the Mailbox Plugin single-owner while composing independent adapters. */
20
+ export class CompositeClawclawMailboxDriver implements ClawclawMailboxDriver {
21
+ constructor(private readonly drivers: readonly ClawclawMailboxDriver[]) {}
22
+
23
+ observeEvents(events: readonly CanonicalEvent[]): void {
24
+ for (const driver of this.drivers) driver.observeEvents?.(events);
25
+ }
26
+
27
+ async flush(): Promise<void> {
28
+ for (const driver of this.drivers) await driver.flush();
29
+ }
30
+
31
+ async stop(): Promise<void> {
32
+ let firstError: unknown;
33
+ for (const driver of [...this.drivers].reverse()) {
34
+ try {
35
+ await driver.stop();
36
+ } catch (error) {
37
+ firstError ??= error;
38
+ }
39
+ }
40
+ if (firstError) throw firstError;
41
+ }
42
+ }
43
+
17
44
  export interface ClawclawMailboxPluginOptions {
18
45
  after?: readonly string[];
19
46
  timeoutMs?: number;
@@ -50,6 +77,7 @@ export class ClawclawMailboxPlugin implements RuntimeEpochPlugin<Record<string,
50
77
  input: RuntimeEpochPluginInput<Record<string, any>>,
51
78
  ): Promise<RuntimeEpochPluginResult> {
52
79
  const eventCursor = input.pendingEvents.at(-1)?.commitSeq;
80
+ if (eventCursor !== undefined) this.driver?.observeEvents?.(input.pendingEvents);
53
81
  return {
54
82
  outcome: eventCursor === undefined ? 'noop' : 'processed',
55
83
  ...(eventCursor === undefined ? { reason: 'no_pending_events' } : {}),
@@ -477,6 +477,55 @@ describe('ClawClaw Mailbox Event query', () => {
477
477
  expect(repository.delivery(task.eventId, 'local-agent')?.detailState).toBe('not_applicable');
478
478
  });
479
479
 
480
+ it('uses one enriched task_completed for Monitor and ccl events while task_assigned stays internal', async () => {
481
+ const { repository, ingress, service, setReady } = fixture();
482
+ const completed = await publish(ingress, {
483
+ eventId: 'task-completed-1',
484
+ type: 'task_completed',
485
+ segmentId: 'room-1',
486
+ epochSeq: 1,
487
+ payload: {
488
+ tick: 42,
489
+ task_name: '擦拭酒瓶',
490
+ newly_assigned_task: {
491
+ name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456, is_fake_shrimp: false,
492
+ },
493
+ },
494
+ });
495
+ const assigned = await publish(ingress, {
496
+ eventId: 'task-assigned-1',
497
+ type: 'task_assigned',
498
+ segmentId: 'room-1',
499
+ epochSeq: 1,
500
+ payload: { tick: 42, task_name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456 },
501
+ });
502
+ setReady(readyView('room-1', 1, assigned.commitSeq, { phase: 'wandering', tick: 42 }));
503
+
504
+ expect(service.prepareMonitor(true)).toBe(1);
505
+ const broker = new MailboxRelayBroker(repository, 'short');
506
+ const claim = broker.handle({
507
+ type: 'mailbox_claim',
508
+ relay_id: 'relay-task-completed',
509
+ mode: 'short',
510
+ });
511
+ const payloads = claim?.claim?.items.map((item: any) => item.payload) ?? [];
512
+ expect(service.composeMonitor(payloads)).toMatchObject({
513
+ events: ['task_completed'],
514
+ messages: [expect.stringContaining('任务完成:擦拭酒瓶;新分配任务:消毒淋浴器(制氧舱)')],
515
+ });
516
+
517
+ expect(service.prepareEvents().output.events).toEqual([{
518
+ type: 'task_completed',
519
+ tick: 42,
520
+ task_name: '擦拭酒瓶',
521
+ newly_assigned_task: {
522
+ name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456, is_fake_shrimp: false,
523
+ },
524
+ }]);
525
+ expect(repository.delivery(assigned.eventId, 'local-agent')?.detailState).toBe('not_applicable');
526
+ expect(repository.delivery(completed.eventId, 'local-agent')?.detailState).not.toBe('not_applicable');
527
+ });
528
+
480
529
  it('adds the latest structured Strategy status only to ccl events State', async () => {
481
530
  const { ingress, service, setReady } = fixture();
482
531
  const event = await publish(ingress, {