@myclaw163/clawclaw-cli 0.7.4 → 0.7.6

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 (35) hide show
  1. package/docs/desktop-event-push.md +120 -0
  2. package/docs/runtime/events-and-state.md +1 -1
  3. package/package.json +3 -1
  4. package/skills/clawclaw/SKILL.md +9 -9
  5. package/skills/clawclaw/references/GAME-MECHANICS.md +2 -2
  6. package/src/assets/clawclaw-spatial-model.txt +142 -0
  7. package/src/commands/game/index.test.ts +167 -1
  8. package/src/commands/game/index.ts +124 -35
  9. package/src/commands/game-map.test.ts +8 -4
  10. package/src/lib/game-client.test.ts +15 -0
  11. package/src/lib/game-client.ts +4 -0
  12. package/src/lib/game-context.ts +6 -6
  13. package/src/lib/participation-status.ts +113 -0
  14. package/src/pipeline/canonical-event-presentation.test.ts +5 -4
  15. package/src/pipeline/event-format.test.ts +17 -0
  16. package/src/pipeline/event-format.ts +15 -1
  17. package/src/pipeline/game-sync-event-normalization.test.ts +58 -1
  18. package/src/pipeline/game-sync-event-normalization.ts +51 -0
  19. package/src/runtime/clawclaw/owner.ts +56 -3
  20. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +189 -0
  21. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +532 -0
  22. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +339 -0
  23. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +207 -0
  24. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +372 -0
  25. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  26. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +166 -0
  27. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +194 -0
  28. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +262 -0
  29. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +28 -0
  30. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +49 -0
  31. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +77 -259
  32. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +5 -0
  33. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +52 -0
  34. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +4 -3
  35. package/src/assets/clawclaw-ascii-map.txt +0 -40
@@ -44,11 +44,18 @@ import {
44
44
  type ParentProcessWatchHandle,
45
45
  } from '../parent-process-watch.js';
46
46
  import { BufferedRawWsLog, ownerRawWsLogPath } from '../raw-ws-log.js';
47
+ import { presentCanonicalEventForCclEvents } from '../../pipeline/canonical-event-presentation.js';
48
+ import { compactStateForEvents } from '../../pipeline/event-format.js';
47
49
  import { createClawclawRuntime } from './runtime.js';
48
50
  import { assembleClawclawPlugins } from './plugins/assembly.js';
49
51
  import {
50
52
  ClawclawMailboxPlugin,
51
53
  ClawclawMailboxService,
54
+ CompositeClawclawMailboxDriver,
55
+ DesktopEventSocketSink,
56
+ AgentMailboxCoordinator,
57
+ MailboxEventBatchPump,
58
+ type DesktopEventSocketConfig,
52
59
  } from './plugins/mailbox/index.js';
53
60
  import {
54
61
  resolveDefaultClawclawStrategies,
@@ -72,6 +79,8 @@ export interface ClawclawOwnerOptions {
72
79
  forceExistingRuntime?: boolean;
73
80
  epochPlugins?: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
74
81
  notificationHost?: ClawclawOwnerNotificationHost;
82
+ /** Desktop Host adapter for this run; Channels can be wired as a sibling adapter later. */
83
+ desktopEvents?: DesktopEventSocketConfig;
75
84
  }
76
85
 
77
86
  export interface ClawclawOwnerRuntimeStart {
@@ -466,6 +475,8 @@ export async function runClawclawOwner(
466
475
  let source: ClawclawSourcePlugin | undefined;
467
476
  let mailbox: ClawclawMailboxPlugin | undefined;
468
477
  let mailboxService: ClawclawMailboxService | undefined;
478
+ let agentMailbox: AgentMailboxCoordinator | undefined;
479
+ let desktopEventPump: MailboxEventBatchPump | undefined;
469
480
  let mailboxBroker: MailboxRelayBroker | undefined;
470
481
  let ownerControl: OwnerControlServer | undefined;
471
482
  let runtimePointer: OwnerRuntimePointer | undefined;
@@ -535,12 +546,51 @@ export async function runClawclawOwner(
535
546
  throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
536
547
  }
537
548
  const mailboxRepository = runtime.repository;
549
+ agentMailbox = new AgentMailboxCoordinator({
550
+ repository: mailboxRepository,
551
+ readyView: () => runtime!.readReadyView(0, 1),
552
+ presentEvent: presentCanonicalEventForCclEvents,
553
+ compactState: compactStateForEvents,
554
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
555
+ });
538
556
  mailboxService = new ClawclawMailboxService({
539
557
  repository: mailboxRepository,
540
558
  readyView: () => runtime!.readReadyView(0, 1),
559
+ agentMailbox,
560
+ monitorEnabled: !options.desktopEvents,
541
561
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
542
562
  });
543
- mailbox.attachDriver(mailboxService);
563
+ if (options.desktopEvents) {
564
+ const desktopSink = new DesktopEventSocketSink({
565
+ ...options.desktopEvents,
566
+ onConnected: () => desktopEventPump?.retryNow(),
567
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
568
+ });
569
+ desktopEventPump = new MailboxEventBatchPump({
570
+ source: {
571
+ prepare: () => agentMailbox!.prepareEvents({
572
+ deliveryVia: 'mailbox_full',
573
+ ownerIdPrefix: 'desktop_ipc',
574
+ }),
575
+ renew: (deliveryToken) => agentMailbox!.renew(deliveryToken),
576
+ ack: (deliveryToken) => agentMailbox!.ack(deliveryToken),
577
+ release: (deliveryToken) => agentMailbox!.release(deliveryToken),
578
+ },
579
+ sink: desktopSink,
580
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
581
+ });
582
+ mailbox.attachDriver(new CompositeClawclawMailboxDriver([
583
+ mailboxService,
584
+ agentMailbox,
585
+ desktopEventPump,
586
+ ]));
587
+ desktopSink.start();
588
+ } else {
589
+ mailbox.attachDriver(new CompositeClawclawMailboxDriver([
590
+ mailboxService,
591
+ agentMailbox,
592
+ ]));
593
+ }
544
594
  const ownerSource = new ClawclawSourcePlugin({
545
595
  client,
546
596
  profile: options.profile,
@@ -601,7 +651,7 @@ export async function runClawclawOwner(
601
651
  });
602
652
  return eventsQueryBarrier;
603
653
  };
604
- if (options.notificationHost) {
654
+ if (options.notificationHost && !options.desktopEvents) {
605
655
  mailboxBroker = new MailboxRelayBroker(
606
656
  mailboxRepository,
607
657
  'short',
@@ -898,11 +948,14 @@ export async function runClawclawOwner(
898
948
  process.on('SIGINT', onSignal);
899
949
  process.on('SIGTERM', onSignal);
900
950
  await runtime.startSourcePlugin(ownerSource);
951
+ await desktopEventPump?.flush();
901
952
  if (localStopRequested) await ownerSource.submitIntent({ kind: 'stop' });
902
- options.notificationHost?.markMailboxReady();
953
+ if (!options.desktopEvents) options.notificationHost?.markMailboxReady();
903
954
  const completion = await source.waitForCompletion();
904
955
  await runtime.flush();
905
956
  await mailboxService.flush();
957
+ await agentMailbox.flush();
958
+ await desktopEventPump?.drain();
906
959
  if (mailboxBroker && !(await waitForMailboxDrain(mailboxBroker))) {
907
960
  runtime.diagnostic('runtime.shutdown.mailbox_drain_incomplete', {
908
961
  timeout_ms: MAILBOX_DRAIN_TIMEOUT_MS,
@@ -0,0 +1,189 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
3
+ import {
4
+ EventIngress,
5
+ MemoryEventRepository,
6
+ type CanonicalEvent,
7
+ } from '../../../framework/events/index.js';
8
+ import type { RuntimeReadyView } from '../../../framework/runtime.js';
9
+ import {
10
+ AGENT_MAILBOX_COALESCE_MS,
11
+ AgentMailboxCoordinator,
12
+ } from './agent-mailbox-coordinator.js';
13
+
14
+ const START_MS = Date.parse('2026-08-04T00:00:00.000Z');
15
+
16
+ function readyView(epochSeq: number, eventWatermark: number): RuntimeReadyView {
17
+ const scope = {
18
+ adapterId: 'clawclaw',
19
+ accountId: 'account-1',
20
+ sessionId: 'session-1',
21
+ segmentId: 'segment-1',
22
+ segmentSeq: 1,
23
+ };
24
+ return {
25
+ scope,
26
+ state: {
27
+ state: { phase: 'wandering', tick: epochSeq },
28
+ stateStatus: {
29
+ status: 'fresh',
30
+ semantics: 'latest_received',
31
+ source: 'owner_memory',
32
+ scope,
33
+ connectionId: 'connection-1',
34
+ connectionState: 'connected',
35
+ receivedAtMs: START_MS,
36
+ ageMs: 0,
37
+ backendTick: epochSeq,
38
+ reason: null,
39
+ },
40
+ },
41
+ pluginStates: {},
42
+ pluginOutcomes: {},
43
+ events: [],
44
+ throughCommitSeq: eventWatermark,
45
+ frameSeq: epochSeq,
46
+ eventWatermark,
47
+ epochSeq,
48
+ hasMore: false,
49
+ };
50
+ }
51
+
52
+ function fixture() {
53
+ const repository = new MemoryEventRepository();
54
+ repository.saveSession({
55
+ sessionId: 'session-1',
56
+ adapterId: 'clawclaw',
57
+ accountId: 'account-1',
58
+ status: 'open',
59
+ isCurrent: true,
60
+ openedAt: new Date(START_MS).toISOString(),
61
+ });
62
+ repository.saveSegment({
63
+ segmentId: 'segment-1',
64
+ sessionId: 'session-1',
65
+ sequence: 1,
66
+ kind: 'game',
67
+ status: 'open',
68
+ isCurrent: true,
69
+ openedAt: new Date(START_MS).toISOString(),
70
+ });
71
+ const ingress = new EventIngress(repository, createClawclawEventCatalog());
72
+ let nowMs = START_MS;
73
+ let ready = readyView(1, 0);
74
+ const coordinator = new AgentMailboxCoordinator({
75
+ repository,
76
+ readyView: () => structuredClone(ready),
77
+ presentEvent: (event) => ({
78
+ type: event.type,
79
+ ...(typeof event.payload.text === 'string' ? { text: event.payload.text } : {}),
80
+ }),
81
+ compactState: (state) => state
82
+ ? { phase: state.phase, tick: state.tick }
83
+ : null,
84
+ now: () => nowMs,
85
+ });
86
+ return {
87
+ repository,
88
+ ingress,
89
+ coordinator,
90
+ advance: (milliseconds: number) => { nowMs += milliseconds; },
91
+ setReady: (epochSeq: number, watermark: number) => {
92
+ ready = readyView(epochSeq, watermark);
93
+ },
94
+ };
95
+ }
96
+
97
+ async function publish(
98
+ ingress: EventIngress,
99
+ eventId: string,
100
+ type: string,
101
+ epochSeq: number,
102
+ payload: Record<string, unknown> = {},
103
+ ): Promise<CanonicalEvent> {
104
+ return (await ingress.publish({
105
+ eventId,
106
+ epochSeq,
107
+ type,
108
+ producer: 'backend_push',
109
+ sessionId: 'session-1',
110
+ segmentId: 'segment-1',
111
+ payload,
112
+ source: { sourceId: 'game-ws', eventId: `remote:${eventId}` },
113
+ })).event;
114
+ }
115
+
116
+ describe('AgentMailboxCoordinator', () => {
117
+ it('uses one fixed coalescing window without extending it for later Events', async () => {
118
+ const { ingress, coordinator, advance, setReady } = fixture();
119
+ const first = await publish(ingress, 'speech-1', 'speech', 1, { text: 'first' });
120
+ coordinator.observeEvents([first]);
121
+ setReady(1, first.commitSeq);
122
+
123
+ advance(100);
124
+ const second = await publish(ingress, 'speech-2', 'speech', 2, { text: 'second' });
125
+ coordinator.observeEvents([second]);
126
+ setReady(2, second.commitSeq);
127
+
128
+ advance(AGENT_MAILBOX_COALESCE_MS - 101);
129
+ const waiting = coordinator.prepareEvents();
130
+ expect(waiting.deliveryToken).toBeUndefined();
131
+ expect(waiting.nextAttemptAtMs).toBe(START_MS + AGENT_MAILBOX_COALESCE_MS);
132
+
133
+ advance(1);
134
+ const prepared = coordinator.prepareEvents();
135
+ expect(prepared.deliveryToken).toBeTypeOf('string');
136
+ expect(prepared.batch.events).toEqual([
137
+ { type: 'speech', text: 'second' },
138
+ { type: 'speech', text: 'first' },
139
+ ]);
140
+ expect(coordinator.ack(prepared.deliveryToken!)).toBe(true);
141
+ });
142
+
143
+ it('excludes internal facts and preserves Agent payloads larger than 64 KiB', async () => {
144
+ const { repository, ingress, coordinator, advance, setReady } = fixture();
145
+ const internal = await publish(ingress, 'task-1', 'task_assigned', 1, {
146
+ task_name: 'wires',
147
+ });
148
+ const text = `BEGIN-${'x'.repeat(64 * 1024)}-END`;
149
+ const visible = await publish(ingress, 'speech-long', 'speech', 1, { text });
150
+ coordinator.observeEvents([internal, visible]);
151
+ setReady(1, visible.commitSeq);
152
+ advance(AGENT_MAILBOX_COALESCE_MS);
153
+
154
+ const prepared = coordinator.prepareEvents();
155
+ expect(prepared.batch.events).toEqual([{ type: 'speech', text }]);
156
+ expect(Buffer.byteLength(JSON.stringify(prepared.batch), 'utf8')).toBeGreaterThan(64 * 1024);
157
+ expect(repository.delivery(internal.eventId, 'local-agent')?.detailState)
158
+ .toBe('not_applicable');
159
+ expect(coordinator.ack(prepared.deliveryToken!)).toBe(true);
160
+ });
161
+
162
+ it('owns one details lease and only advances delivery after ACK', async () => {
163
+ const { repository, ingress, coordinator, advance, setReady } = fixture();
164
+ const event = await publish(ingress, 'speech-1', 'speech', 1, { text: 'lease me' });
165
+ coordinator.observeEvents([event]);
166
+ setReady(1, event.commitSeq);
167
+ advance(AGENT_MAILBOX_COALESCE_MS);
168
+
169
+ const first = coordinator.prepareEvents();
170
+ expect(first.deliveryToken).toBeTypeOf('string');
171
+ expect(coordinator.renew(first.deliveryToken!)).toBe(true);
172
+ expect(() => coordinator.prepareEvents()).toThrow('agent_mailbox_delivery_busy');
173
+ expect(repository.delivery(event.eventId, 'local-agent')?.detailState).toBe('pending');
174
+ expect(repository.acquireLease({
175
+ consumerId: 'local-agent',
176
+ channel: 'details',
177
+ ownerId: 'competing-adapter',
178
+ ttlMs: 1_000,
179
+ nowMs: START_MS + AGENT_MAILBOX_COALESCE_MS,
180
+ })).toBeNull();
181
+
182
+ expect(coordinator.release(first.deliveryToken!)).toBe(true);
183
+ expect(repository.delivery(event.eventId, 'local-agent')?.detailState).toBe('pending');
184
+
185
+ const retried = coordinator.prepareEvents();
186
+ expect(coordinator.ack(retried.deliveryToken!)).toBe(true);
187
+ expect(repository.delivery(event.eventId, 'local-agent')?.detailState).toBe('delivered');
188
+ });
189
+ });