@myclaw163/clawclaw-cli 0.6.95 → 0.6.100
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.
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +26 -10
- package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +17 -5
- package/skills/clawclaw/references/STREAM.md +15 -12
- package/src/commands/account.test.ts +20 -0
- package/src/commands/account.ts +16 -0
- package/src/commands/do.test.ts +27 -1
- package/src/commands/do.ts +61 -0
- package/src/commands/events.test.ts +21 -3
- package/src/commands/events.ts +8 -2
- package/src/commands/game-start-plan.test.ts +158 -0
- package/src/commands/game.ts +670 -64
- package/src/commands/history-player.test.ts +3 -0
- package/src/commands/knowledge.ts +41 -4
- package/src/commands/strategy.ts +11 -0
- package/src/commands/watch.test.ts +272 -0
- package/src/commands/watch.ts +185 -25
- package/src/lib/game-client.ts +34 -0
- package/src/lib/room.test.ts +74 -0
- package/src/lib/room.ts +129 -0
- package/src/lib/server-registry.test.ts +54 -0
- package/src/lib/server-registry.ts +35 -2
- package/src/perception/player-history-store.test.ts +92 -2
- package/src/perception/player-history-store.ts +68 -0
- package/src/pipeline/event-format.test.ts +61 -1
- package/src/pipeline/event-format.ts +88 -0
- package/src/pipeline/event-hints.ts +10 -1
- package/src/runtime/event-daemon.test.ts +43 -0
- package/src/runtime/event-daemon.ts +8 -4
- package/src/runtime/room-lobby-runtime.test.ts +95 -0
- package/src/runtime/room-lobby-runtime.ts +367 -0
- package/src/sdk/index.ts +8 -3
- package/src/strategies/avoid-lone.ts +2 -0
- package/src/strategies/avoid-players.ts +2 -0
- package/src/strategies/corpse-patrol.ts +2 -0
- package/src/strategies/crab-sabotage.ts +2 -0
- package/src/strategies/find-player.ts +2 -0
- package/src/strategies/hide.ts +2 -0
- package/src/strategies/kill-frenzy.ts +2 -0
- package/src/strategies/kill-lone.ts +2 -0
- package/src/strategies/kill-target.ts +2 -0
- package/src/strategies/knowledge-contract.ts +85 -0
- package/src/strategies/lone-kill-task.ts +2 -0
- package/src/strategies/move-room.ts +2 -0
- package/src/strategies/paradise-fish.ts +2 -0
- package/src/strategies/patrol.ts +2 -0
- package/src/strategies/report-patrol.ts +2 -0
- package/src/strategies/shrimp-memory.ts +2 -0
- package/src/strategies/social-task.ts +2 -0
- package/src/strategies/task-kill-report.ts +2 -0
- package/src/strategies/task-only.ts +2 -0
- package/src/strategies/task-report.ts +2 -0
- package/src/strategies/types.ts +37 -1
- package/src/strategies/warrior-memory.ts +2 -0
package/src/commands/watch.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { hubReminder, readCachedGamesPlayed } from '../lib/hub-reminder.js';
|
|
|
12
12
|
import { sendOwnerControlRequest } from '../runtime/owner-control.js';
|
|
13
13
|
|
|
14
14
|
export const POLL_INTERVAL_MS = 220;
|
|
15
|
-
const HEARTBEAT_INTERVAL_MS =
|
|
15
|
+
const HEARTBEAT_INTERVAL_MS = 30_000;
|
|
16
16
|
const RUNTIME_WAIT_MS = 30_000;
|
|
17
17
|
|
|
18
18
|
export class WatchNotReadyError extends Error {
|
|
@@ -85,6 +85,24 @@ export const MONITOR_EVENT_CONFIG: Record<string, MonitorEventConfig> = {
|
|
|
85
85
|
robot_speak_rule: { priority: 50 },
|
|
86
86
|
// #endregion
|
|
87
87
|
|
|
88
|
+
// Room-mode lobby events
|
|
89
|
+
'room.snapshot': { priority: 50 },
|
|
90
|
+
'room.member_joined': { priority: 50 },
|
|
91
|
+
'room.member_left': { priority: 50 },
|
|
92
|
+
'room.owner_changed': { priority: 50 },
|
|
93
|
+
'room.full': { priority: 60 },
|
|
94
|
+
'room.chat': { priority: 50 },
|
|
95
|
+
'room.game_starting': { priority: 80 },
|
|
96
|
+
'room.game_started': { priority: 90 },
|
|
97
|
+
'room.game_start_failed': { priority: 80 },
|
|
98
|
+
'room.game_finished': { priority: 80 },
|
|
99
|
+
'room.cooldown': { priority: 60 },
|
|
100
|
+
'room.self_left': { priority: 80 },
|
|
101
|
+
room_self_left: { priority: 80 },
|
|
102
|
+
room_ready_to_start: { priority: 90 },
|
|
103
|
+
room_returning_to_lobby: { priority: 60 },
|
|
104
|
+
room_ping_timeout: { priority: 60 },
|
|
105
|
+
|
|
88
106
|
// Strategy → agent real-time briefing (the automation explaining a decisive
|
|
89
107
|
// autonomous move, e.g. self-reporting its own kill). Ranked above ambient
|
|
90
108
|
// wander events so it leads the events[] list.
|
|
@@ -114,6 +132,19 @@ export interface GameEvent {
|
|
|
114
132
|
export function eventKey(evt: GameEvent): string {
|
|
115
133
|
const type = evt.type ?? '?';
|
|
116
134
|
const tick = evt.tick ?? 0;
|
|
135
|
+
const roomDiscriminator = typeof type === 'string' && (type.startsWith('room.') || type.startsWith('room_'))
|
|
136
|
+
? [
|
|
137
|
+
evt.room_code,
|
|
138
|
+
evt.status,
|
|
139
|
+
evt.agent_id,
|
|
140
|
+
evt.name,
|
|
141
|
+
evt.seat,
|
|
142
|
+
evt.content,
|
|
143
|
+
evt.reason,
|
|
144
|
+
Array.isArray(evt.members) ? evt.members.length : evt.member_count,
|
|
145
|
+
evt.ts,
|
|
146
|
+
]
|
|
147
|
+
: [];
|
|
117
148
|
const parts = [
|
|
118
149
|
evt.actor_name,
|
|
119
150
|
evt.spotted_name,
|
|
@@ -122,6 +153,7 @@ export function eventKey(evt: GameEvent): string {
|
|
|
122
153
|
evt.target_name,
|
|
123
154
|
evt.corpse_name,
|
|
124
155
|
evt.task_name,
|
|
156
|
+
...roomDiscriminator,
|
|
125
157
|
].filter(Boolean);
|
|
126
158
|
const disc = parts.length > 0 ? parts.join('|') : '';
|
|
127
159
|
return `${type}@${tick}#${disc}`;
|
|
@@ -146,6 +178,11 @@ interface RouteRule {
|
|
|
146
178
|
nextStep: string;
|
|
147
179
|
}
|
|
148
180
|
|
|
181
|
+
interface RouteContext {
|
|
182
|
+
summary?: any | null;
|
|
183
|
+
events?: Array<Record<string, any>>;
|
|
184
|
+
}
|
|
185
|
+
|
|
149
186
|
const ROUTING_RULES: RouteRule[] = [
|
|
150
187
|
{ reason: 'speech_your_turn', match: (t) => t.includes('speech_your_turn'), nextStep: 'It is YOUR turn to speak. Submit `ccl do -s "<draft>"` immediately. Server skips you after 45s.' },
|
|
151
188
|
{ reason: 'role_assigned', match: (t) => t.includes('role_assigned'), nextStep: 'Tell user your role, faction, win condition, and first plan.' },
|
|
@@ -154,13 +191,30 @@ const ROUTING_RULES: RouteRule[] = [
|
|
|
154
191
|
{ reason: 'match_start', match: (t) => t.includes('match_start'), nextStep: 'Matchmaking queue entered. The game runtime is live and the stream is attached. Chat with the user while waiting for allocation.' },
|
|
155
192
|
{ reason: 'match_waiting', match: (t) => t.includes('match_waiting'), nextStep: 'Still in queue (see `events[].waited_secs`). Keep chatting with the user; no tactical action required.' },
|
|
156
193
|
{ reason: 'match_timeout', match: (t) => t.includes('match_timeout'), nextStep: `Cumulative wait reached ${Math.round(DEFAULT_MATCH_TIMEOUT_MS / 60_000)} min (see \`events[].waited_secs\`). The stream will exit — discuss with the user: launch a fresh \`ccl game start\` to retry, or call it a session.` },
|
|
194
|
+
{ reason: 'room_ready_to_start', match: (t) => t.includes('room_ready_to_start') || t.includes('room.full'), nextStep: 'Room is full. Ask the user whether to start now before running `ccl game start-room`.' },
|
|
195
|
+
{ reason: 'room_game_started', match: (t) => t.includes('room.game_started'), nextStep: 'Room match is starting. Stay attached; the runtime will switch to the GameServer stream.' },
|
|
196
|
+
{ reason: 'room_game_finished', match: (t) => t.includes('room.game_finished'), nextStep: '上一轮房间对局已结束;如果你提前回房间等待,现在告知用户上局已结束,并继续留在房间。' },
|
|
197
|
+
{ reason: 'room_self_left', match: (t) => t.includes('room.self_left') || t.includes('room_self_left'), nextStep: 'The user left the room from the web page, or the current CLI quit command has left the room. Stop the room flow and do not create or join another room unless the user asks.' },
|
|
157
198
|
{ reason: 'game_over', match: (t) => t.includes('game_over'), nextStep: 'Game ended. The current ccl game start process is exiting automatically. Review the result with the user; start another match only if the user asks.' },
|
|
158
199
|
{ reason: 'strategy_alert', match: (t) => t.includes('strategy_alert'), nextStep: 'Your automation just made a decisive autonomous move and is briefing you (read events[].message). Lock your story to it before you next speak or vote — e.g. if it reported a corpse that is likely your own kill, present yourself as the proactive reporter, steer suspicion onto the bystanders, and do NOT confess.' },
|
|
159
200
|
];
|
|
160
201
|
|
|
161
202
|
const DEFAULT_NEXT_STEP = 'React to summary fields. No relaunch needed — the stream stays attached.';
|
|
203
|
+
const ROOM_GAME_OVER_NEXT_STEP = 'This room match round has ended. Wait for the room stream to resume; do not start normal matchmaking.';
|
|
204
|
+
|
|
205
|
+
function hasRoomGameContext(ctx?: RouteContext): boolean {
|
|
206
|
+
if (!ctx) return false;
|
|
207
|
+
if (ctx.summary?.game?.mode === 'room' || ctx.summary?.game_mode === 'room') return true;
|
|
208
|
+
return (ctx.events ?? []).some((event) => event.game_mode === 'room');
|
|
209
|
+
}
|
|
162
210
|
|
|
163
|
-
function routeTriggers(triggers: string[]): { exitReason: string; nextStep: string } {
|
|
211
|
+
function routeTriggers(triggers: string[], ctx?: RouteContext): { exitReason: string; nextStep: string } {
|
|
212
|
+
if (triggers.includes('game_over') && hasRoomGameContext(ctx)) {
|
|
213
|
+
return {
|
|
214
|
+
exitReason: 'game_over',
|
|
215
|
+
nextStep: ROOM_GAME_OVER_NEXT_STEP,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
164
218
|
const rule = ROUTING_RULES.find((r) => r.match(triggers));
|
|
165
219
|
return {
|
|
166
220
|
exitReason: rule?.reason ?? triggers[0],
|
|
@@ -168,12 +222,12 @@ function routeTriggers(triggers: string[]): { exitReason: string; nextStep: stri
|
|
|
168
222
|
};
|
|
169
223
|
}
|
|
170
224
|
|
|
171
|
-
export function nextStepFor(reason: string): string {
|
|
172
|
-
return routeTriggers([reason]).nextStep;
|
|
225
|
+
export function nextStepFor(reason: string, ctx?: RouteContext): string {
|
|
226
|
+
return routeTriggers([reason], ctx).nextStep;
|
|
173
227
|
}
|
|
174
228
|
|
|
175
|
-
export function nextStepForTriggers(triggers: string[]): string {
|
|
176
|
-
return routeTriggers(triggers).nextStep;
|
|
229
|
+
export function nextStepForTriggers(triggers: string[], ctx?: RouteContext): string {
|
|
230
|
+
return routeTriggers(triggers, ctx).nextStep;
|
|
177
231
|
}
|
|
178
232
|
|
|
179
233
|
export function sortEventsForMonitor(events: GameEvent[]): GameEvent[] {
|
|
@@ -230,6 +284,9 @@ export function summarizeFeed(feed: any): any | null {
|
|
|
230
284
|
meeting: feed.meeting,
|
|
231
285
|
};
|
|
232
286
|
if (feed.automation) summary.automation = feed.automation;
|
|
287
|
+
if (typeof feed.phase === 'string' && feed.phase.startsWith('room_')) {
|
|
288
|
+
summary.room = feed.room;
|
|
289
|
+
}
|
|
233
290
|
return summary;
|
|
234
291
|
}
|
|
235
292
|
|
|
@@ -279,6 +336,30 @@ export function compactSummaryForMonitor(summary: any | null, triggers: string[]
|
|
|
279
336
|
});
|
|
280
337
|
}
|
|
281
338
|
|
|
339
|
+
function roomHeartbeatMessage(summary: any | null): string | null {
|
|
340
|
+
if (!summary || typeof summary.phase !== 'string' || !summary.phase.startsWith('room_')) return null;
|
|
341
|
+
const room = summary.room ?? {};
|
|
342
|
+
const label = typeof room.room_code === 'string' && room.room_code.length > 0
|
|
343
|
+
? `房间 ${room.room_code}`
|
|
344
|
+
: '房间';
|
|
345
|
+
const count = typeof room.member_count === 'number'
|
|
346
|
+
? room.member_count
|
|
347
|
+
: Array.isArray(room.members)
|
|
348
|
+
? room.members.length
|
|
349
|
+
: undefined;
|
|
350
|
+
const countText = count === undefined ? '?/10' : `${count}/10`;
|
|
351
|
+
if (room.status === 'playing' || summary.phase === 'room_playing') {
|
|
352
|
+
return `${label} 上一轮对局仍在进行,正在等待其他玩家结束。`;
|
|
353
|
+
}
|
|
354
|
+
if (room.status === 'starting' || summary.phase === 'room_starting') {
|
|
355
|
+
return `${label} 对局正在开始,继续等待。`;
|
|
356
|
+
}
|
|
357
|
+
if (count !== undefined && count >= 10) {
|
|
358
|
+
return `${label} 当前 ${countText} 人,等待房主操作。`;
|
|
359
|
+
}
|
|
360
|
+
return `${label} 当前 ${countText} 人,正在等待更多玩家加入。`;
|
|
361
|
+
}
|
|
362
|
+
|
|
282
363
|
export interface RunStreamingOptions {
|
|
283
364
|
feedPath: string;
|
|
284
365
|
sessionPath: string | null;
|
|
@@ -313,6 +394,13 @@ export interface RunStreamingOptions {
|
|
|
313
394
|
* `initial_payload`.
|
|
314
395
|
*/
|
|
315
396
|
emitGameStart?: boolean;
|
|
397
|
+
/**
|
|
398
|
+
* On intentional stream handoff, drain already-written events once more before
|
|
399
|
+
* returning so the next WS stage does not inherit them as backlog.
|
|
400
|
+
*/
|
|
401
|
+
finalDrainOnAbort?: boolean | (() => boolean);
|
|
402
|
+
/** Max ms to wait for final written events during a handoff. Default 500ms. */
|
|
403
|
+
finalDrainTimeoutMs?: number;
|
|
316
404
|
/**
|
|
317
405
|
* When set, attached to the `game_over` emission (as a `hub_reminder` field
|
|
318
406
|
* and appended to `next_step`) so the agent sees the nudge in the same beat it
|
|
@@ -423,7 +511,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
|
|
|
423
511
|
|
|
424
512
|
const buildOut = (
|
|
425
513
|
triggers: string[],
|
|
426
|
-
|
|
514
|
+
nextStep: string,
|
|
427
515
|
events: GameEvent[] = [],
|
|
428
516
|
): any => {
|
|
429
517
|
const rawSummary = opts.readSummary?.() ?? readFeedSummary(opts.feedPath);
|
|
@@ -442,11 +530,16 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
|
|
|
442
530
|
if (sumCaller && e.caller && sumCaller !== e.caller) return e;
|
|
443
531
|
return { ...e, speech_order: so };
|
|
444
532
|
};
|
|
533
|
+
const heartbeatMessage = triggers.length === 1 && triggers[0] === 'heartbeat'
|
|
534
|
+
? roomHeartbeatMessage(summary)
|
|
535
|
+
: null;
|
|
445
536
|
const sourceEvents: GameEvent[] = events.length > 0
|
|
446
537
|
? sortEventsForMonitor(events).map(enrichMeetingBriefing)
|
|
447
|
-
:
|
|
538
|
+
: heartbeatMessage
|
|
539
|
+
? [{ type: 'heartbeat', message: heartbeatMessage }]
|
|
540
|
+
: triggers.map((type) => ({ type }));
|
|
448
541
|
const gameMode = sourceEvents.find(
|
|
449
|
-
(event) => event.game_mode === 'match' || event.game_mode === 'competition',
|
|
542
|
+
(event) => event.game_mode === 'match' || event.game_mode === 'competition' || event.game_mode === 'room',
|
|
450
543
|
)?.game_mode;
|
|
451
544
|
const context = {
|
|
452
545
|
summary,
|
|
@@ -458,6 +551,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
|
|
|
458
551
|
...(gameMode ? { game_mode: gameMode } : {}),
|
|
459
552
|
messages: sourceEvents.map((event) => formatEventMessage(event, context)),
|
|
460
553
|
state: shortStateText(summary),
|
|
554
|
+
...(nextStep === ROOM_GAME_OVER_NEXT_STEP ? { next_step: nextStep } : {}),
|
|
461
555
|
};
|
|
462
556
|
};
|
|
463
557
|
|
|
@@ -466,14 +560,90 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
|
|
|
466
560
|
triggeredEvents: GameEvent[],
|
|
467
561
|
): void => {
|
|
468
562
|
if (triggers.length === 0) return;
|
|
469
|
-
const
|
|
470
|
-
const
|
|
563
|
+
const routeEvents = triggeredEvents.slice(-10);
|
|
564
|
+
const rawSummary = opts.readSummary?.() ?? readFeedSummary(opts.feedPath);
|
|
565
|
+
const { nextStep } = routeTriggers(triggers, { summary: rawSummary, events: routeEvents });
|
|
566
|
+
const out = buildOut(triggers, nextStep, routeEvents);
|
|
471
567
|
if (opts.hubReminder && triggers.includes('game_over')) {
|
|
472
568
|
out.hub_reminder = opts.hubReminder;
|
|
473
569
|
}
|
|
474
570
|
emit(out);
|
|
475
571
|
};
|
|
476
572
|
|
|
573
|
+
const collectNotableEvents = (
|
|
574
|
+
events: GameEvent[],
|
|
575
|
+
triggers: string[],
|
|
576
|
+
triggeredEvents: GameEvent[],
|
|
577
|
+
): void => {
|
|
578
|
+
for (const evt of events) {
|
|
579
|
+
const cls = classifyEvent(evt, youName);
|
|
580
|
+
if (!cls.notable) continue;
|
|
581
|
+
const key = eventKey(evt);
|
|
582
|
+
if (seenKeys.has(key)) continue;
|
|
583
|
+
seenKeys.add(key);
|
|
584
|
+
triggeredEvents.push(evt);
|
|
585
|
+
if (evt.type && !triggers.includes(evt.type)) {
|
|
586
|
+
triggers.push(evt.type);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
|
|
591
|
+
const shouldFinalDrainOnAbort = (): boolean => {
|
|
592
|
+
if (typeof opts.finalDrainOnAbort === 'function') return opts.finalDrainOnAbort();
|
|
593
|
+
return opts.finalDrainOnAbort === true;
|
|
594
|
+
};
|
|
595
|
+
|
|
596
|
+
const waitForNextPoll = async (): Promise<void> => {
|
|
597
|
+
await new Promise<void>((resolve) => {
|
|
598
|
+
if (opts.signal?.aborted) {
|
|
599
|
+
resolve();
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
let done = false;
|
|
603
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
604
|
+
const finish = (): void => {
|
|
605
|
+
if (done) return;
|
|
606
|
+
done = true;
|
|
607
|
+
if (timer) clearTimeout(timer);
|
|
608
|
+
opts.signal?.removeEventListener('abort', finish);
|
|
609
|
+
resolve();
|
|
610
|
+
};
|
|
611
|
+
timer = setTimeout(finish, interval);
|
|
612
|
+
opts.signal?.addEventListener('abort', finish, { once: true });
|
|
613
|
+
});
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
const flushDelayBuffer = (triggers: string[], triggeredEvents: GameEvent[]): void => {
|
|
617
|
+
for (const t of delayBuffer.triggers) {
|
|
618
|
+
if (!triggers.includes(t)) triggers.push(t);
|
|
619
|
+
}
|
|
620
|
+
triggeredEvents.push(...delayBuffer.events);
|
|
621
|
+
delayBuffer.triggers.clear();
|
|
622
|
+
delayBuffer.events.length = 0;
|
|
623
|
+
delayActive = false;
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
const finalDrain = async (): Promise<void> => {
|
|
627
|
+
if (!shouldFinalDrainOnAbort()) return;
|
|
628
|
+
const deadline = Date.now() + (opts.finalDrainTimeoutMs ?? 500);
|
|
629
|
+
while (Date.now() <= deadline) {
|
|
630
|
+
refreshSessionPath();
|
|
631
|
+
const triggers: string[] = [];
|
|
632
|
+
const triggeredEvents: GameEvent[] = [];
|
|
633
|
+
if (delayBuffer.triggers.size > 0 || delayBuffer.events.length > 0) {
|
|
634
|
+
flushDelayBuffer(triggers, triggeredEvents);
|
|
635
|
+
}
|
|
636
|
+
collectNotableEvents(drainNewEvents(), triggers, triggeredEvents);
|
|
637
|
+
if (triggers.length > 0) {
|
|
638
|
+
fireTrigger(triggers, triggeredEvents);
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
const remaining = deadline - Date.now();
|
|
642
|
+
if (remaining <= 0) break;
|
|
643
|
+
await new Promise((r) => setTimeout(r, Math.min(20, remaining)));
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
|
|
477
647
|
// Always emit an attached first beat when there is a pre-attach backlog OR
|
|
478
648
|
// the caller explicitly requests one.
|
|
479
649
|
if (caughtUpEvents.length > 0 || opts.emitGameStart) {
|
|
@@ -503,18 +673,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
|
|
|
503
673
|
const triggers: string[] = [];
|
|
504
674
|
const triggeredEvents: GameEvent[] = [];
|
|
505
675
|
|
|
506
|
-
|
|
507
|
-
for (const evt of newEvents) {
|
|
508
|
-
const cls = classifyEvent(evt, youName);
|
|
509
|
-
if (!cls.notable) continue;
|
|
510
|
-
const key = eventKey(evt);
|
|
511
|
-
if (seenKeys.has(key)) continue;
|
|
512
|
-
seenKeys.add(key);
|
|
513
|
-
triggeredEvents.push(evt);
|
|
514
|
-
if (evt.type && !triggers.includes(evt.type)) {
|
|
515
|
-
triggers.push(evt.type);
|
|
516
|
-
}
|
|
517
|
-
}
|
|
676
|
+
collectNotableEvents(drainNewEvents(), triggers, triggeredEvents);
|
|
518
677
|
|
|
519
678
|
// ── Delay buffer: merge rapid-fire wandering-phase events ──
|
|
520
679
|
// Only active during wandering; meeting-phase events (my_turn, speech, etc.)
|
|
@@ -555,7 +714,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
|
|
|
555
714
|
|
|
556
715
|
if (triggers.length > 0) {
|
|
557
716
|
fireTrigger(triggers, triggeredEvents);
|
|
558
|
-
if (triggers.includes('game_over') || triggers.includes('user_left_game')) return;
|
|
717
|
+
if (triggers.includes('game_over') || triggers.includes('user_left_game') || triggers.includes('room.self_left') || triggers.includes('room_self_left')) return;
|
|
559
718
|
} else if (!delayActive && heartbeatInterval > 0 && Date.now() - lastEmitMs >= heartbeatInterval) {
|
|
560
719
|
// Idle keepalive — prevents downstream adapters from interpreting a quiet
|
|
561
720
|
// wandering/transit period as a hung subprocess and killing it on their
|
|
@@ -567,8 +726,9 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
|
|
|
567
726
|
}
|
|
568
727
|
|
|
569
728
|
if (opts.signal?.aborted) break;
|
|
570
|
-
await
|
|
729
|
+
await waitForNextPoll();
|
|
571
730
|
}
|
|
731
|
+
if (opts.signal?.aborted) await finalDrain();
|
|
572
732
|
}
|
|
573
733
|
|
|
574
734
|
export interface SnapshotOnceOptions {
|
package/src/lib/game-client.ts
CHANGED
|
@@ -225,6 +225,40 @@ export class GameClient {
|
|
|
225
225
|
return this.http.post('/api/v1/game/leave');
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
+
// ─── Room API (→ lobby) ───
|
|
229
|
+
|
|
230
|
+
async createRoom(): Promise<any> {
|
|
231
|
+
return this.http.post('/api/v1/room/create');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async joinRoom(roomCode: string): Promise<any> {
|
|
235
|
+
return this.http.post('/api/v1/room/join', { room_code: roomCode });
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async leaveRoom(): Promise<any> {
|
|
239
|
+
return this.http.post('/api/v1/room/leave');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async startRoom(): Promise<any> {
|
|
243
|
+
return this.http.post('/api/v1/room/start');
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async chatRoom(content: string): Promise<any> {
|
|
247
|
+
return this.http.post('/api/v1/room/chat', { content });
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
get lobbyAgentWsUrl(): string {
|
|
251
|
+
return this.registry.lobbyAgentWsUrl;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
setRoomGameServer(gameServerName: string): void {
|
|
255
|
+
this.registry.setGatewayGameServerName(gameServerName);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
setGameServerUrl(url: string): void {
|
|
259
|
+
this.registry.setGameServerUrl(url);
|
|
260
|
+
}
|
|
261
|
+
|
|
228
262
|
async getRoleInfo(): Promise<any> {
|
|
229
263
|
return this.http.get('/api/v1/game/role_info');
|
|
230
264
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
hasRoomQueueContext,
|
|
4
|
+
isCurrentAgentRoomOwner,
|
|
5
|
+
isInRoomQueueStatus,
|
|
6
|
+
isRoomAllocatedQueueStatus,
|
|
7
|
+
isRoomReadyToStart,
|
|
8
|
+
memberCount,
|
|
9
|
+
queueMode,
|
|
10
|
+
queueRoomCode,
|
|
11
|
+
queueStatus,
|
|
12
|
+
} from './room.js';
|
|
13
|
+
|
|
14
|
+
const members = Array.from({ length: 10 }, (_, index) => ({
|
|
15
|
+
seat: index + 1,
|
|
16
|
+
name: `player-${index + 1}`,
|
|
17
|
+
is_owner: index === 0,
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
describe('room helpers', () => {
|
|
21
|
+
it('reads in-room queue status and room code from wrapped responses', () => {
|
|
22
|
+
const response = { data: { status: 'in_room', room_code: '123456' } };
|
|
23
|
+
|
|
24
|
+
expect(queueStatus(response)).toBe('in_room');
|
|
25
|
+
expect(queueRoomCode(response)).toBe('123456');
|
|
26
|
+
expect(isInRoomQueueStatus(response)).toBe(true);
|
|
27
|
+
expect(hasRoomQueueContext(response)).toBe(true);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('recognizes allocated room games as room context', () => {
|
|
31
|
+
const response = { data: { status: 'allocated', mode: 'room', game_server_name: 'room-gs' } };
|
|
32
|
+
|
|
33
|
+
expect(queueStatus(response)).toBe('allocated');
|
|
34
|
+
expect(queueMode(response)).toBe('room');
|
|
35
|
+
expect(isRoomAllocatedQueueStatus(response)).toBe(true);
|
|
36
|
+
expect(hasRoomQueueContext(response)).toBe(true);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('does not treat normal allocations as room context', () => {
|
|
40
|
+
const response = { data: { status: 'allocated', mode: 'match' } };
|
|
41
|
+
|
|
42
|
+
expect(isRoomAllocatedQueueStatus(response)).toBe(false);
|
|
43
|
+
expect(hasRoomQueueContext(response)).toBe(false);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('detects owner status by the current seat', () => {
|
|
47
|
+
expect(isCurrentAgentRoomOwner({
|
|
48
|
+
my_seat: 1,
|
|
49
|
+
members,
|
|
50
|
+
})).toBe(true);
|
|
51
|
+
|
|
52
|
+
expect(isCurrentAgentRoomOwner({
|
|
53
|
+
my_seat: 2,
|
|
54
|
+
members,
|
|
55
|
+
})).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('requires owner, waiting status, full room, and no cooldown before manual start', () => {
|
|
59
|
+
const ready = {
|
|
60
|
+
room_type: 'casual',
|
|
61
|
+
status: 'waiting',
|
|
62
|
+
my_seat: 1,
|
|
63
|
+
members,
|
|
64
|
+
cooldown_seconds: 0,
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
expect(memberCount(ready)).toBe(10);
|
|
68
|
+
expect(isRoomReadyToStart(ready)).toBe(true);
|
|
69
|
+
expect(isRoomReadyToStart({ ...ready, cooldown_seconds: 5 })).toBe(false);
|
|
70
|
+
expect(isRoomReadyToStart({ ...ready, status: 'starting' })).toBe(false);
|
|
71
|
+
expect(isRoomReadyToStart({ ...ready, my_seat: 2 })).toBe(false);
|
|
72
|
+
expect(isRoomReadyToStart({ ...ready, members: members.slice(0, 9) })).toBe(false);
|
|
73
|
+
});
|
|
74
|
+
});
|
package/src/lib/room.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { ApiError } from './http-transport.js';
|
|
2
|
+
|
|
3
|
+
export interface RoomMember {
|
|
4
|
+
seat?: number;
|
|
5
|
+
agent_id?: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
is_owner?: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface RoomSnapshot {
|
|
11
|
+
room_code?: string;
|
|
12
|
+
room_type?: string;
|
|
13
|
+
status?: string;
|
|
14
|
+
my_seat?: number;
|
|
15
|
+
seat?: number;
|
|
16
|
+
members?: RoomMember[];
|
|
17
|
+
cooldown_seconds?: number;
|
|
18
|
+
deadline?: number;
|
|
19
|
+
game_id?: string;
|
|
20
|
+
game_server_name?: string;
|
|
21
|
+
ws_url?: string;
|
|
22
|
+
[key: string]: any;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function unwrapData(value: any): any {
|
|
26
|
+
return value?.data ?? value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function queueStatus(value: any): string | undefined {
|
|
30
|
+
return unwrapData(value)?.status;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function queueMode(value: any): string | undefined {
|
|
34
|
+
const data = unwrapData(value);
|
|
35
|
+
const mode = data?.mode ?? data?.game?.mode ?? data?.allocation?.mode;
|
|
36
|
+
return typeof mode === 'string' ? mode : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function queueRoomCode(value: any): string | undefined {
|
|
40
|
+
const data = unwrapData(value);
|
|
41
|
+
return typeof data?.room_code === 'string' ? data.room_code : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isInRoomQueueStatus(value: any): boolean {
|
|
45
|
+
return queueStatus(value) === 'in_room' && !!queueRoomCode(value);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function isRoomAllocatedQueueStatus(value: any): boolean {
|
|
49
|
+
return queueStatus(value) === 'allocated' && queueMode(value) === 'room';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function hasRoomQueueContext(value: any): boolean {
|
|
53
|
+
return isInRoomQueueStatus(value) || isRoomAllocatedQueueStatus(value);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function normalizeRoomSnapshot(value: any): RoomSnapshot {
|
|
57
|
+
const data = unwrapData(value);
|
|
58
|
+
return data && typeof data === 'object' ? { ...data } : {};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function memberCount(snapshot: RoomSnapshot | null | undefined): number {
|
|
62
|
+
return Array.isArray(snapshot?.members) ? snapshot.members.length : 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function isCurrentAgentRoomOwner(snapshot: RoomSnapshot | null | undefined): boolean {
|
|
66
|
+
if (!snapshot) return false;
|
|
67
|
+
const mySeat = snapshot.my_seat ?? snapshot.seat;
|
|
68
|
+
return (snapshot.members ?? []).some((member) => {
|
|
69
|
+
if (!member?.is_owner) return false;
|
|
70
|
+
if (mySeat !== undefined && member.seat === mySeat) return true;
|
|
71
|
+
return false;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function isRoomReadyToStart(snapshot: RoomSnapshot | null | undefined): boolean {
|
|
76
|
+
if (!snapshot) return false;
|
|
77
|
+
return (
|
|
78
|
+
snapshot.room_type === 'casual'
|
|
79
|
+
&& snapshot.status === 'waiting'
|
|
80
|
+
&& isCurrentAgentRoomOwner(snapshot)
|
|
81
|
+
&& memberCount(snapshot) >= 10
|
|
82
|
+
&& ((snapshot.cooldown_seconds ?? 0) <= 0)
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function parseApiErrorBody(body: string): any | null {
|
|
87
|
+
try {
|
|
88
|
+
return JSON.parse(body);
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function apiErrorCode(err: unknown): string | undefined {
|
|
95
|
+
if (!(err instanceof ApiError)) return undefined;
|
|
96
|
+
const parsed = parseApiErrorBody(err.body);
|
|
97
|
+
return parsed?.error?.code ?? parsed?.code;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function apiErrorMessage(err: unknown): string {
|
|
101
|
+
if (err instanceof ApiError) {
|
|
102
|
+
const parsed = parseApiErrorBody(err.body);
|
|
103
|
+
const message = parsed?.error?.message ?? parsed?.message;
|
|
104
|
+
if (typeof message === 'string' && message.length > 0) return message;
|
|
105
|
+
return err.body;
|
|
106
|
+
}
|
|
107
|
+
if (err instanceof Error) return err.message;
|
|
108
|
+
return String(err);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function apiErrorCurrentStatus(err: unknown): string | undefined {
|
|
112
|
+
if (!(err instanceof ApiError)) return undefined;
|
|
113
|
+
const parsed = parseApiErrorBody(err.body);
|
|
114
|
+
const currentStatus = parsed?.error?.current_status
|
|
115
|
+
?? parsed?.current_status
|
|
116
|
+
?? parsed?.data?.current_status;
|
|
117
|
+
return typeof currentStatus === 'string' ? currentStatus : undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function isAlreadyInRoomError(err: unknown): boolean {
|
|
121
|
+
return apiErrorCode(err) === 'ALREADY_IN_ROOM'
|
|
122
|
+
|| (err instanceof ApiError && /ALREADY_IN_ROOM/.test(err.body));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function roomCodeFromAlreadyInRoomError(err: unknown): string | undefined {
|
|
126
|
+
if (!(err instanceof ApiError)) return undefined;
|
|
127
|
+
const parsed = parseApiErrorBody(err.body);
|
|
128
|
+
return parsed?.error?.room_code ?? parsed?.room_code ?? parsed?.data?.room_code;
|
|
129
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { ServerRegistry } from './server-registry.js';
|
|
3
|
+
|
|
4
|
+
describe('ServerRegistry lobby agent ws url', () => {
|
|
5
|
+
it('preserves a lobby path prefix', () => {
|
|
6
|
+
const registry = new ServerRegistry({ lobbyUrl: 'http://10.1.9.59:30900/claw' });
|
|
7
|
+
|
|
8
|
+
expect(registry.lobbyAgentWsUrl).toBe('ws://10.1.9.59:30900/claw/api/v1/agent/ws');
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it('keeps the root lobby url behavior unchanged', () => {
|
|
12
|
+
const registry = new ServerRegistry({ lobbyUrl: 'https://lobby.example/' });
|
|
13
|
+
|
|
14
|
+
expect(registry.lobbyAgentWsUrl).toBe('wss://lobby.example/api/v1/agent/ws');
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe('ServerRegistry game server discovery', () => {
|
|
19
|
+
it('uses queue ws_url as the game server base', () => {
|
|
20
|
+
const registry = new ServerRegistry({ lobbyUrl: 'http://10.1.9.59:30900/claw' });
|
|
21
|
+
|
|
22
|
+
registry.updateFromQueueResponse({
|
|
23
|
+
data: {
|
|
24
|
+
status: 'allocated',
|
|
25
|
+
ws_url: 'ws://10.1.9.59:30433/gs/clawarena-gameserver-l2fzm-h5n5r',
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
expect(registry.gameServerUrl).toBe('http://10.1.9.59:30433/gs/clawarena-gameserver-l2fzm-h5n5r');
|
|
30
|
+
expect(registry.wsUrl).toBe('ws://10.1.9.59:30433/gs/clawarena-gameserver-l2fzm-h5n5r/api/v1/game/stream');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('strips stream suffixes when persisting a ws_url', () => {
|
|
34
|
+
const registry = new ServerRegistry({ lobbyUrl: 'http://10.1.9.59:30900/claw' });
|
|
35
|
+
|
|
36
|
+
registry.updateFromQueueResponse({
|
|
37
|
+
data: {
|
|
38
|
+
status: 'allocated',
|
|
39
|
+
ws_url: 'ws://10.1.9.59:30433/gs/room-gs/game/stream',
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
expect(registry.gameServerUrl).toBe('http://10.1.9.59:30433/gs/room-gs');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('normalizes manually supplied game server ws urls', () => {
|
|
47
|
+
const registry = new ServerRegistry({ lobbyUrl: 'http://10.1.9.59:30900/claw' });
|
|
48
|
+
|
|
49
|
+
registry.setGameServerUrl('ws://10.1.9.59:30433/gs/room-gs/api/v1/game/stream');
|
|
50
|
+
|
|
51
|
+
expect(registry.gameServerUrl).toBe('http://10.1.9.59:30433/gs/room-gs');
|
|
52
|
+
expect(registry.wsUrl).toBe('ws://10.1.9.59:30433/gs/room-gs/api/v1/game/stream');
|
|
53
|
+
});
|
|
54
|
+
});
|