@myclaw163/clawclaw-cli 0.6.96 → 0.6.101

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 (37) hide show
  1. package/bin/clawclaw-cli.mjs +3 -3
  2. package/package.json +1 -1
  3. package/skills/clawclaw/SKILL.md +26 -10
  4. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
  5. package/skills/clawclaw/references/COMMANDS.md +17 -5
  6. package/skills/clawclaw/references/STREAM.md +15 -12
  7. package/src/commands/config.ts +30 -30
  8. package/src/commands/do.test.ts +27 -1
  9. package/src/commands/do.ts +61 -0
  10. package/src/commands/events.test.ts +21 -3
  11. package/src/commands/events.ts +8 -2
  12. package/src/commands/game-start-plan.test.ts +158 -0
  13. package/src/commands/game.ts +670 -64
  14. package/src/commands/history-player.test.ts +3 -0
  15. package/src/commands/setup/hermes.test.ts +96 -96
  16. package/src/commands/setup/hermes.ts +76 -76
  17. package/src/commands/setup/index.ts +13 -13
  18. package/src/commands/setup/openclaw.test.ts +124 -114
  19. package/src/commands/setup/openclaw.ts +162 -147
  20. package/src/commands/watch.test.ts +272 -0
  21. package/src/commands/watch.ts +185 -25
  22. package/src/lib/game-client.ts +34 -0
  23. package/src/lib/host-config-patcher.test.ts +130 -130
  24. package/src/lib/host-config-patcher.ts +151 -151
  25. package/src/lib/room.test.ts +74 -0
  26. package/src/lib/room.ts +129 -0
  27. package/src/lib/server-registry.test.ts +54 -0
  28. package/src/lib/server-registry.ts +35 -2
  29. package/src/perception/player-history-store.test.ts +92 -2
  30. package/src/perception/player-history-store.ts +68 -0
  31. package/src/pipeline/event-format.test.ts +61 -1
  32. package/src/pipeline/event-format.ts +88 -0
  33. package/src/pipeline/event-hints.ts +10 -1
  34. package/src/runtime/event-daemon.test.ts +43 -0
  35. package/src/runtime/event-daemon.ts +8 -4
  36. package/src/runtime/room-lobby-runtime.test.ts +95 -0
  37. package/src/runtime/room-lobby-runtime.ts +367 -0
@@ -1,147 +1,162 @@
1
- /**
2
- * `ccl setup openclaw` — install recommended OpenClaw config snippet.
3
- *
4
- * Pure function `computeOpenclawPatch` is exported for tests.
5
- * IO / diff / atomic write / backup is delegated to lib/host-config-patcher.ts.
6
- */
7
-
8
- import { Command } from 'commander';
9
- import { homedir } from 'os';
10
- import { join } from 'path';
11
- import {
12
- runHostConfigSetup,
13
- unionArrayField,
14
- type HostPatchResult,
15
- } from '../../lib/host-config-patcher.js';
16
-
17
- export const PLUGIN_ID = 'clawclaw';
18
-
19
- export interface ComputeOpenclawPatchOpts {
20
- skipPluginsAllow?: boolean;
21
- skipToolsAllow?: boolean;
22
- }
23
-
24
- export function resolveOpenclawConfigPath(env: NodeJS.ProcessEnv = process.env): string {
25
- const home = env.OPENCLAW_HOME?.trim();
26
- if (home) return join(home, 'openclaw.json');
27
- return join(homedir(), '.openclaw', 'openclaw.json');
28
- }
29
-
30
- /** Pure: compute the minimal additive patch to make `clawclaw` work under `coding` profile. */
31
- export function computeOpenclawPatch(current: unknown, opts: ComputeOpenclawPatchOpts): HostPatchResult {
32
- const changes: string[] = [];
33
- const warnings: string[] = [];
34
- const cfg: Record<string, unknown> =
35
- current !== null && typeof current === 'object' && !Array.isArray(current)
36
- ? { ...(current as Record<string, unknown>) }
37
- : {};
38
-
39
- // ── plugins.allow + plugins.entries.clawclaw.enabled ──────────────────
40
- if (!opts.skipPluginsAllow) {
41
- const plugins: Record<string, unknown> =
42
- cfg.plugins !== null && typeof cfg.plugins === 'object' && !Array.isArray(cfg.plugins)
43
- ? { ...(cfg.plugins as Record<string, unknown>) }
44
- : {};
45
-
46
- const allowResult = unionArrayField(plugins.allow, PLUGIN_ID);
47
- if ('warning' in allowResult) {
48
- warnings.push(`plugins.allow ${allowResult.warning}`);
49
- } else {
50
- if (allowResult.added) {
51
- if (plugins.allow === undefined) {
52
- changes.push(`create plugins.allow with ["${PLUGIN_ID}"]`);
53
- } else {
54
- changes.push(`add "${PLUGIN_ID}" to plugins.allow`);
55
- }
56
- }
57
- plugins.allow = allowResult.next;
58
- }
59
-
60
- const entries: Record<string, unknown> =
61
- plugins.entries !== null && typeof plugins.entries === 'object' && !Array.isArray(plugins.entries)
62
- ? { ...(plugins.entries as Record<string, unknown>) }
63
- : {};
64
- const existingEntry =
65
- entries[PLUGIN_ID] !== null && typeof entries[PLUGIN_ID] === 'object' && !Array.isArray(entries[PLUGIN_ID])
66
- ? { ...(entries[PLUGIN_ID] as Record<string, unknown>) }
67
- : {};
68
-
69
- if (existingEntry.enabled === false) {
70
- warnings.push(
71
- `plugins.entries.${PLUGIN_ID}.enabled is explicitly false; not flipping it on. Remove the line manually if you want it enabled.`,
72
- );
73
- } else if (existingEntry.enabled !== true) {
74
- existingEntry.enabled = true;
75
- entries[PLUGIN_ID] = existingEntry;
76
- plugins.entries = entries;
77
- changes.push(`set plugins.entries.${PLUGIN_ID}.enabled = true (equivalent to: openclaw plugins enable ${PLUGIN_ID})`);
78
- }
79
-
80
- cfg.plugins = plugins;
81
- }
82
-
83
- // ── tools.alsoAllow ────────────────────────────────────────────────────
84
- if (!opts.skipToolsAllow) {
85
- const tools: Record<string, unknown> =
86
- cfg.tools !== null && typeof cfg.tools === 'object' && !Array.isArray(cfg.tools)
87
- ? { ...(cfg.tools as Record<string, unknown>) }
88
- : {};
89
-
90
- const alsoAllowResult = unionArrayField(tools.alsoAllow, PLUGIN_ID);
91
- if ('warning' in alsoAllowResult) {
92
- warnings.push(`tools.alsoAllow ${alsoAllowResult.warning}`);
93
- } else {
94
- if (alsoAllowResult.added) {
95
- if (tools.alsoAllow === undefined) {
96
- changes.push(`create tools.alsoAllow with ["${PLUGIN_ID}"]`);
97
- } else {
98
- changes.push(`add "${PLUGIN_ID}" to tools.alsoAllow`);
99
- }
100
- }
101
- tools.alsoAllow = alsoAllowResult.next;
102
- }
103
-
104
- cfg.tools = tools;
105
- }
106
-
107
- return { next: cfg, changes, warnings };
108
- }
109
-
110
- export function createSetupOpenclawSubcommand(): Command {
111
- return new Command('openclaw')
112
- .description('Install recommended OpenClaw config (plugins.allow + tools.alsoAllow) for the clawclaw plugin.')
113
- .option('-y, --yes', 'Apply changes (default is dry-run with diff preview)')
114
- .option('--print', 'Only print the recommended JSON patch; do not read or write files')
115
- .option('--config <path>', 'Override openclaw.json path (default: $OPENCLAW_HOME/openclaw.json or ~/.openclaw/openclaw.json)')
116
- .option('--skip-plugins-allow', "Do not touch plugins.allow / plugins.entries.clawclaw")
117
- .option('--skip-tools-allow', "Do not touch tools.alsoAllow")
118
- .option('--no-backup', 'Do not write a timestamped .bak.* before applying')
119
- .action((opts: {
120
- yes?: boolean;
121
- print?: boolean;
122
- config?: string;
123
- skipPluginsAllow?: boolean;
124
- skipToolsAllow?: boolean;
125
- backup?: boolean;
126
- }) => {
127
- const result = runHostConfigSetup(
128
- {
129
- hostName: 'OpenClaw',
130
- resolveConfigPath: () => resolveOpenclawConfigPath(),
131
- computePatch: (current, hostOpts) => computeOpenclawPatch(current, hostOpts),
132
- },
133
- {
134
- skipPluginsAllow: opts.skipPluginsAllow,
135
- skipToolsAllow: opts.skipToolsAllow,
136
- },
137
- {
138
- yes: opts.yes,
139
- print: opts.print,
140
- configPath: opts.config,
141
- backup: opts.backup,
142
- },
143
- );
144
- for (const line of result.output) console.log(line);
145
- if (result.exitCode !== 0) process.exit(result.exitCode);
146
- });
147
- }
1
+ /**
2
+ * `ccl setup openclaw` — install recommended OpenClaw config snippet.
3
+ *
4
+ * Pure function `computeOpenclawPatch` is exported for tests.
5
+ * IO / diff / atomic write / backup is delegated to lib/host-config-patcher.ts.
6
+ */
7
+
8
+ import { Command } from 'commander';
9
+ import { homedir } from 'os';
10
+ import { join } from 'path';
11
+ import {
12
+ runHostConfigSetup,
13
+ unionArrayField,
14
+ type HostPatchResult,
15
+ } from '../../lib/host-config-patcher.js';
16
+
17
+ export const PLUGIN_ID = 'clawclaw';
18
+ export const PLUGIN_TOOL_GLOB = 'clawclaw:*';
19
+
20
+ export interface ComputeOpenclawPatchOpts {
21
+ skipPluginsAllow?: boolean;
22
+ skipToolsAllow?: boolean;
23
+ }
24
+
25
+ export function resolveOpenclawConfigPath(env: NodeJS.ProcessEnv = process.env): string {
26
+ const home = env.OPENCLAW_HOME?.trim();
27
+ if (home) return join(home, 'openclaw.json');
28
+ return join(homedir(), '.openclaw', 'openclaw.json');
29
+ }
30
+
31
+ /** Pure: compute the minimal additive patch to make `clawclaw` work under `coding` profile. */
32
+ export function computeOpenclawPatch(current: unknown, opts: ComputeOpenclawPatchOpts): HostPatchResult {
33
+ const changes: string[] = [];
34
+ const warnings: string[] = [];
35
+ const cfg: Record<string, unknown> =
36
+ current !== null && typeof current === 'object' && !Array.isArray(current)
37
+ ? { ...(current as Record<string, unknown>) }
38
+ : {};
39
+
40
+ // ── plugins.allow + plugins.entries.clawclaw.enabled ──────────────────
41
+ if (!opts.skipPluginsAllow) {
42
+ const plugins: Record<string, unknown> =
43
+ cfg.plugins !== null && typeof cfg.plugins === 'object' && !Array.isArray(cfg.plugins)
44
+ ? { ...(cfg.plugins as Record<string, unknown>) }
45
+ : {};
46
+
47
+ // Only append to plugins.allow if it already exists as a restrictive
48
+ // allowlist. Never create it from scratch — that would inadvertently
49
+ // restrict all other plugins (browser, etc.) that were previously
50
+ // allowed by default.
51
+ if (plugins.allow !== undefined) {
52
+ const allowResult = unionArrayField(plugins.allow, PLUGIN_ID);
53
+ if ('warning' in allowResult) {
54
+ warnings.push(`plugins.allow ${allowResult.warning}`);
55
+ } else {
56
+ if (allowResult.added) {
57
+ changes.push(`add "${PLUGIN_ID}" to plugins.allow`);
58
+ }
59
+ plugins.allow = allowResult.next;
60
+ }
61
+ }
62
+
63
+ const entries: Record<string, unknown> =
64
+ plugins.entries !== null && typeof plugins.entries === 'object' && !Array.isArray(plugins.entries)
65
+ ? { ...(plugins.entries as Record<string, unknown>) }
66
+ : {};
67
+ const existingEntry =
68
+ entries[PLUGIN_ID] !== null && typeof entries[PLUGIN_ID] === 'object' && !Array.isArray(entries[PLUGIN_ID])
69
+ ? { ...(entries[PLUGIN_ID] as Record<string, unknown>) }
70
+ : {};
71
+
72
+ if (existingEntry.enabled === false) {
73
+ warnings.push(
74
+ `plugins.entries.${PLUGIN_ID}.enabled is explicitly false; not flipping it on. Remove the line manually if you want it enabled.`,
75
+ );
76
+ } else if (existingEntry.enabled !== true) {
77
+ existingEntry.enabled = true;
78
+ entries[PLUGIN_ID] = existingEntry;
79
+ plugins.entries = entries;
80
+ changes.push(`set plugins.entries.${PLUGIN_ID}.enabled = true (equivalent to: openclaw plugins enable ${PLUGIN_ID})`);
81
+ }
82
+
83
+ cfg.plugins = plugins;
84
+ }
85
+
86
+ // ── tools.alsoAllow ────────────────────────────────────────────────────
87
+ if (!opts.skipToolsAllow) {
88
+ const tools: Record<string, unknown> =
89
+ cfg.tools !== null && typeof cfg.tools === 'object' && !Array.isArray(cfg.tools)
90
+ ? { ...(cfg.tools as Record<string, unknown>) }
91
+ : {};
92
+
93
+ const alsoAllowResult = unionArrayField(tools.alsoAllow, PLUGIN_ID);
94
+ if ('warning' in alsoAllowResult) {
95
+ warnings.push(`tools.alsoAllow ${alsoAllowResult.warning}`);
96
+ } else {
97
+ if (alsoAllowResult.added) {
98
+ if (tools.alsoAllow === undefined) {
99
+ changes.push(`create tools.alsoAllow with ["${PLUGIN_ID}"]`);
100
+ } else {
101
+ changes.push(`add "${PLUGIN_ID}" to tools.alsoAllow`);
102
+ }
103
+ }
104
+ tools.alsoAllow = alsoAllowResult.next;
105
+ }
106
+
107
+ // Also add the namespace glob so host-side tool-ID matching works even
108
+ // when plugin-group expansion hasn't run yet (e.g. freshly loaded plugin).
109
+ const globResult = unionArrayField(tools.alsoAllow, PLUGIN_TOOL_GLOB);
110
+ if ('warning' in globResult) {
111
+ warnings.push(`tools.alsoAllow ${globResult.warning}`);
112
+ } else {
113
+ if (globResult.added) {
114
+ changes.push(`add "${PLUGIN_TOOL_GLOB}" to tools.alsoAllow`);
115
+ }
116
+ tools.alsoAllow = globResult.next;
117
+ }
118
+
119
+ cfg.tools = tools;
120
+ }
121
+
122
+ return { next: cfg, changes, warnings };
123
+ }
124
+
125
+ export function createSetupOpenclawSubcommand(): Command {
126
+ return new Command('openclaw')
127
+ .description('Install recommended OpenClaw config (plugins.allow + tools.alsoAllow) for the clawclaw plugin.')
128
+ .option('-y, --yes', 'Apply changes (default is dry-run with diff preview)')
129
+ .option('--print', 'Only print the recommended JSON patch; do not read or write files')
130
+ .option('--config <path>', 'Override openclaw.json path (default: $OPENCLAW_HOME/openclaw.json or ~/.openclaw/openclaw.json)')
131
+ .option('--skip-plugins-allow', "Do not touch plugins.allow / plugins.entries.clawclaw")
132
+ .option('--skip-tools-allow', "Do not touch tools.alsoAllow")
133
+ .option('--no-backup', 'Do not write a timestamped .bak.* before applying')
134
+ .action((opts: {
135
+ yes?: boolean;
136
+ print?: boolean;
137
+ config?: string;
138
+ skipPluginsAllow?: boolean;
139
+ skipToolsAllow?: boolean;
140
+ backup?: boolean;
141
+ }) => {
142
+ const result = runHostConfigSetup(
143
+ {
144
+ hostName: 'OpenClaw',
145
+ resolveConfigPath: () => resolveOpenclawConfigPath(),
146
+ computePatch: (current, hostOpts) => computeOpenclawPatch(current, hostOpts),
147
+ },
148
+ {
149
+ skipPluginsAllow: opts.skipPluginsAllow,
150
+ skipToolsAllow: opts.skipToolsAllow,
151
+ },
152
+ {
153
+ yes: opts.yes,
154
+ print: opts.print,
155
+ configPath: opts.config,
156
+ backup: opts.backup,
157
+ },
158
+ );
159
+ for (const line of result.output) console.log(line);
160
+ if (result.exitCode !== 0) process.exit(result.exitCode);
161
+ });
162
+ }
@@ -8,6 +8,7 @@ import {
8
8
  MONITOR_EVENT_CONFIG,
9
9
  NOTABLE_EVENT_TYPES,
10
10
  nextStepFor,
11
+ nextStepForTriggers,
11
12
  POLL_INTERVAL_MS,
12
13
  readFeedSummary,
13
14
  runStreaming,
@@ -102,6 +103,13 @@ describe('classifyEvent + NOTABLE_EVENT_TYPES', () => {
102
103
  expect(eventKey(a)).not.toBe(eventKey(c));
103
104
  });
104
105
 
106
+ it('eventKey keeps room events distinct even without game ticks', () => {
107
+ const a = { type: 'room.member_joined', seat: 1, name: 'a', ts: '2026-07-03T01:00:00Z' };
108
+ const b = { type: 'room.member_joined', seat: 2, name: 'b', ts: '2026-07-03T01:00:01Z' };
109
+
110
+ expect(eventKey(a)).not.toBe(eventKey(b));
111
+ });
112
+
105
113
  it('classifyEvent returns notable=false for non-notable types regardless of actor', () => {
106
114
  expect(classifyEvent({ type: 'heartbeat', tick: 1, actor_name: 'them' }, 'me').notable).toBe(false);
107
115
  expect(classifyEvent({ type: 'heartbeat', tick: 1, actor_name: 'me' }, 'me').notable).toBe(false);
@@ -746,6 +754,27 @@ describe('runStreaming — game_over exits', () => {
746
754
  expect(lines.some((l) => JSON.parse(l).events?.includes('game_over'))).toBe(true);
747
755
  });
748
756
 
757
+ it('uses room-mode wording and next_step for room game_over', async () => {
758
+ const { feedPath, sessionPath } = makeTmpFiles();
759
+ writeFileSync(feedPath, JSON.stringify({
760
+ phase: 'game_over',
761
+ you: { name: 'me' },
762
+ game: { mode: 'room' },
763
+ meeting: {},
764
+ urgent: {},
765
+ }));
766
+ const lines: string[] = [];
767
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), pollIntervalMs: 20 });
768
+ await new Promise((r) => setTimeout(r, 30));
769
+ appendFileSync(sessionPath, JSON.stringify({ type: 'game_over', tick: 1, game_mode: 'room', reason: 'game_timeout' }) + '\n');
770
+ await Promise.race([run, new Promise((_, rej) => setTimeout(() => rej(new Error('did not exit')), 3000))]);
771
+
772
+ const notice = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('game_over'));
773
+ expect(notice.messages).toContain('t1 game_over 本轮房间对局结束,将回到房间等待。');
774
+ expect(notice.next_step).toBe('This room match round has ended. Wait for the room stream to resume; do not start normal matchmaking.');
775
+ expect(notice.game_mode).toBe('room');
776
+ });
777
+
749
778
  it('returns from the loop after a user_left_game event', async () => {
750
779
  const { feedPath, sessionPath } = makeTmpFiles();
751
780
  writeFileSync(feedPath, JSON.stringify({ phase: 'user_left_game', you: { name: 'me' }, meeting: {}, urgent: {} }));
@@ -760,6 +789,21 @@ describe('runStreaming — game_over exits', () => {
760
789
  expect(notice.messages.some((message: string) => message.includes('The user left the game from the web page. This match has ended; stop playing and do not restart unless the user asks.'))).toBe(true);
761
790
  expect(notice.state).toContain('user_left_game');
762
791
  });
792
+
793
+ it('returns from the loop after a room.self_left event', async () => {
794
+ const { feedPath, sessionPath } = makeTmpFiles();
795
+ writeFileSync(feedPath, JSON.stringify({ phase: 'room_left', you: { name: 'me' }, room: null, recent_events: [] }));
796
+ const lines: string[] = [];
797
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), pollIntervalMs: 20 });
798
+ await new Promise((r) => setTimeout(r, 30));
799
+ appendFileSync(sessionPath, JSON.stringify({ type: 'room.self_left' }) + '\n');
800
+ await Promise.race([run, new Promise((_, rej) => setTimeout(() => rej(new Error('did not exit')), 3000))]);
801
+
802
+ const notice = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('room.self_left'));
803
+ expect(notice).toBeTruthy();
804
+ expect(notice.messages.some((message: string) => message.includes('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.'))).toBe(true);
805
+ expect(notice.state).toContain('room_left');
806
+ });
763
807
  });
764
808
 
765
809
  describe('runStreaming — NDJSON discipline', () => {
@@ -808,6 +852,138 @@ describe('runStreaming — matchmaking synthetic events', () => {
808
852
  });
809
853
  });
810
854
 
855
+ describe('room ready routing', () => {
856
+ it('asks for user confirmation before starting a full room', () => {
857
+ expect(nextStepForTriggers(['room_ready_to_start'])).toBe('Room is full. Ask the user whether to start now before running `ccl game start-room`.');
858
+ expect(nextStepForTriggers(['room.full'])).toBe('Room is full. Ask the user whether to start now before running `ccl game start-room`.');
859
+ });
860
+
861
+ it('routes room.game_finished without ending the room stream', () => {
862
+ expect(classifyEvent({ type: 'room.game_finished', game_id: 'game-1' }).notable).toBe(true);
863
+ expect(nextStepForTriggers(['room.game_finished'])).toContain('上一轮房间对局已结束');
864
+ });
865
+ });
866
+
867
+ describe('runStreaming — room heartbeat snapshots', () => {
868
+ it('emits room.game_finished as a notable room event', async () => {
869
+ const { feedPath, sessionPath } = makeTmpFiles();
870
+ writeFileSync(feedPath, JSON.stringify({
871
+ phase: 'room_waiting',
872
+ you: { name: 'me', seat: 1, is_owner: false },
873
+ room: { room_code: '123456', status: 'waiting', member_count: 10, members: [] },
874
+ recent_events: [],
875
+ }));
876
+ const lines: string[] = [];
877
+ const ctrl = new AbortController();
878
+ const run = runStreaming({
879
+ feedPath,
880
+ sessionPath,
881
+ stdout: (s) => lines.push(s),
882
+ signal: ctrl.signal,
883
+ pollIntervalMs: 10,
884
+ heartbeatIntervalMs: 0,
885
+ });
886
+
887
+ await new Promise((r) => setTimeout(r, 20));
888
+ appendFileSync(sessionPath, JSON.stringify({ type: 'room.game_finished', game_id: 'game-1' }) + '\n');
889
+ await new Promise((r) => setTimeout(r, 60));
890
+ ctrl.abort(); await run;
891
+
892
+ const notice = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('room.game_finished'));
893
+ expect(notice).toBeTruthy();
894
+ expect(notice.messages[0]).toContain('上一轮房间对局已结束');
895
+ expect(notice.state).toContain('room=123456');
896
+ });
897
+
898
+ it('emits a room waiting snapshot when room events are quiet', async () => {
899
+ const { feedPath, sessionPath } = makeTmpFiles();
900
+ writeFileSync(feedPath, JSON.stringify({
901
+ phase: 'room_waiting',
902
+ you: { name: 'me', seat: 1, is_owner: false },
903
+ room: { room_code: '123456', status: 'waiting', member_count: 6, members: [] },
904
+ recent_events: [],
905
+ }));
906
+ const lines: string[] = [];
907
+ const ctrl = new AbortController();
908
+ const run = runStreaming({
909
+ feedPath,
910
+ sessionPath,
911
+ stdout: (s) => lines.push(s),
912
+ signal: ctrl.signal,
913
+ pollIntervalMs: 10,
914
+ heartbeatIntervalMs: 30,
915
+ });
916
+
917
+ await new Promise((r) => setTimeout(r, 80));
918
+ ctrl.abort(); await run;
919
+
920
+ const heartbeat = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('heartbeat'));
921
+ expect(heartbeat).toBeTruthy();
922
+ expect(heartbeat.messages[0]).toContain('房间 123456 当前 6/10 人');
923
+ expect(heartbeat.messages[0]).toContain('正在等待更多玩家加入');
924
+ expect(heartbeat.state).toContain('room=123456');
925
+ expect(heartbeat.state).toContain('members=6/10');
926
+ });
927
+
928
+ it('does not tell the agent to confirm starting from a full-room heartbeat', async () => {
929
+ const { feedPath, sessionPath } = makeTmpFiles();
930
+ writeFileSync(feedPath, JSON.stringify({
931
+ phase: 'room_waiting',
932
+ you: { name: 'me', seat: 1, is_owner: true },
933
+ room: { room_code: '123456', status: 'waiting', member_count: 10, is_owner: true, ready_to_start: true, members: [] },
934
+ recent_events: [],
935
+ }));
936
+ const lines: string[] = [];
937
+ const ctrl = new AbortController();
938
+ const run = runStreaming({
939
+ feedPath,
940
+ sessionPath,
941
+ stdout: (s) => lines.push(s),
942
+ signal: ctrl.signal,
943
+ pollIntervalMs: 10,
944
+ heartbeatIntervalMs: 30,
945
+ });
946
+
947
+ await new Promise((r) => setTimeout(r, 80));
948
+ ctrl.abort(); await run;
949
+
950
+ const heartbeat = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('heartbeat'));
951
+ expect(heartbeat).toBeTruthy();
952
+ expect(heartbeat.messages[0]).toContain('房间 123456 当前 10/10 人');
953
+ expect(heartbeat.messages[0]).toContain('等待房主操作');
954
+ expect(heartbeat.messages[0]).not.toContain('用户确认');
955
+ expect(heartbeat.messages[0]).not.toContain('start-room');
956
+ });
957
+
958
+ it('describes room playing as waiting for other players to finish', async () => {
959
+ const { feedPath, sessionPath } = makeTmpFiles();
960
+ writeFileSync(feedPath, JSON.stringify({
961
+ phase: 'room_playing',
962
+ you: { name: 'me', seat: 1, is_owner: false },
963
+ room: { room_code: '123456', status: 'playing', member_count: 10, members: [] },
964
+ recent_events: [],
965
+ }));
966
+ const lines: string[] = [];
967
+ const ctrl = new AbortController();
968
+ const run = runStreaming({
969
+ feedPath,
970
+ sessionPath,
971
+ stdout: (s) => lines.push(s),
972
+ signal: ctrl.signal,
973
+ pollIntervalMs: 10,
974
+ heartbeatIntervalMs: 30,
975
+ });
976
+
977
+ await new Promise((r) => setTimeout(r, 80));
978
+ ctrl.abort(); await run;
979
+
980
+ const heartbeat = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('heartbeat'));
981
+ expect(heartbeat).toBeTruthy();
982
+ expect(heartbeat.messages[0]).toContain('上一轮对局仍在进行');
983
+ expect(heartbeat.messages[0]).toContain('正在等待其他玩家结束');
984
+ });
985
+ });
986
+
811
987
  describe('runStreaming — speech_your_turn fires as notable event', () => {
812
988
  it('fires speech_your_turn as exit_reason when speech_your_turn event arrives', async () => {
813
989
  const { feedPath, sessionPath } = makeTmpFiles();
@@ -997,6 +1173,64 @@ describe('runStreaming startup monitor payload', () => {
997
1173
  expect(first.messages[0]).toContain('game_start');
998
1174
  });
999
1175
 
1176
+ it('does not emit a synthetic game_start when startup emission is disabled', async () => {
1177
+ const { feedPath, sessionPath } = makeTmpFiles();
1178
+ writeFileSync(
1179
+ feedPath,
1180
+ JSON.stringify({ you: { name: 'me' }, phase: 'room_waiting', room: { room_code: '123456' }, urgent: {}, meeting: null }),
1181
+ );
1182
+ const lines: string[] = [];
1183
+ const ctrl = new AbortController();
1184
+
1185
+ const run = runStreaming({
1186
+ feedPath,
1187
+ sessionPath,
1188
+ stdout: (s) => lines.push(s),
1189
+ signal: ctrl.signal,
1190
+ pollIntervalMs: 20,
1191
+ emitGameStart: false,
1192
+ heartbeatIntervalMs: 0,
1193
+ });
1194
+
1195
+ await new Promise((r) => setTimeout(r, 80));
1196
+ ctrl.abort();
1197
+ await run;
1198
+
1199
+ expect(lines).toEqual([]);
1200
+ });
1201
+
1202
+ it('final-drains written room events before an intentional stream handoff exits', async () => {
1203
+ const { feedPath, sessionPath } = makeTmpFiles();
1204
+ writeFileSync(
1205
+ feedPath,
1206
+ JSON.stringify({ you: { name: 'me' }, phase: 'room_waiting', room: { room_code: '123456' }, urgent: {}, meeting: null }),
1207
+ );
1208
+ const lines: string[] = [];
1209
+ const ctrl = new AbortController();
1210
+
1211
+ const run = runStreaming({
1212
+ feedPath,
1213
+ sessionPath,
1214
+ stdout: (s) => lines.push(s),
1215
+ signal: ctrl.signal,
1216
+ pollIntervalMs: 1000,
1217
+ emitGameStart: false,
1218
+ heartbeatIntervalMs: 0,
1219
+ finalDrainOnAbort: true,
1220
+ finalDrainTimeoutMs: 500,
1221
+ });
1222
+
1223
+ await new Promise((r) => setTimeout(r, 50));
1224
+ appendFileSync(sessionPath, JSON.stringify({ type: 'room.game_started', game_id: 'game-1' }) + '\n');
1225
+ ctrl.abort();
1226
+ await run;
1227
+
1228
+ expect(lines.length).toBe(1);
1229
+ const notice = JSON.parse(lines[0]);
1230
+ expect(notice.events).toEqual(['room.game_started']);
1231
+ expect(notice.messages[0]).toContain('room.game_started');
1232
+ });
1233
+
1000
1234
  it('compacts role_assigned inside caught_up notable events', async () => {
1001
1235
  const { feedPath, sessionPath } = makeTmpFiles();
1002
1236
  writeFileSync(
@@ -1038,4 +1272,42 @@ describe('runStreaming startup monitor payload', () => {
1038
1272
  expect(first.messages[0]).toContain('role_assigned');
1039
1273
  expect(first).not.toHaveProperty('caught_up');
1040
1274
  });
1275
+
1276
+ it('does not replay room waiting events when a game-stage session is attached', async () => {
1277
+ const { dir, feedPath, sessionPath: gameSessionPath } = makeTmpFiles();
1278
+ const roomSessionPath = join(dir, 'room-session.jsonl');
1279
+ writeFileSync(
1280
+ feedPath,
1281
+ JSON.stringify({ you: { name: 'me' }, phase: 'preparing', urgent: {}, meeting: null }),
1282
+ );
1283
+ appendFileSync(roomSessionPath, JSON.stringify({ type: 'room_ready_to_start', room_code: '123456' }) + '\n');
1284
+ appendFileSync(roomSessionPath, JSON.stringify({ type: 'room.full', room_code: '123456' }) + '\n');
1285
+ appendFileSync(gameSessionPath, JSON.stringify({
1286
+ type: 'role_assigned',
1287
+ tick: 0,
1288
+ role: 'shrimp_generic',
1289
+ faction: 'lobster',
1290
+ }) + '\n');
1291
+ const lines: string[] = [];
1292
+ const ctrl = new AbortController();
1293
+
1294
+ const run = runStreaming({
1295
+ feedPath,
1296
+ sessionPath: gameSessionPath,
1297
+ getSessionPath: () => gameSessionPath,
1298
+ stdout: (s) => lines.push(s),
1299
+ signal: ctrl.signal,
1300
+ pollIntervalMs: 20,
1301
+ });
1302
+
1303
+ await new Promise((r) => setTimeout(r, 60));
1304
+ ctrl.abort();
1305
+ await run;
1306
+
1307
+ const first = JSON.parse(lines[0]);
1308
+ expect(first.events).toEqual(['role_assigned']);
1309
+ expect(first.messages[0]).toContain('role_assigned');
1310
+ expect(first.events).not.toContain('room_ready_to_start');
1311
+ expect(first.events).not.toContain('room.full');
1312
+ });
1041
1313
  });