@myclaw163/clawclaw-cli 0.6.92 → 0.6.94

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.6.92",
3
+ "version": "0.6.94",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -1,5 +1,5 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { normalizeDoOptions, parseIntents } from './do.js';
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { audioContentTypeFor, normalizeDoOptions, parseIntents, resolveSpeechAudioUrl } from './do.js';
3
3
 
4
4
  describe('normalizeDoOptions', () => {
5
5
  it('joins unquoted speech words passed as extra arguments', () => {
@@ -29,6 +29,15 @@ describe('parseIntents', () => {
29
29
  expect(action).not.toHaveProperty('audio_url');
30
30
  });
31
31
 
32
+ it('includes audio_url when an uploaded speech audio URL is provided', () => {
33
+ const action = parseIntents({ speech: 'hi', audioUrl: 'https://cdn.example.com/a.mp3' })[0].build().toJSON();
34
+ expect(action).toMatchObject({
35
+ action: 'speech',
36
+ text: 'hi',
37
+ audio_url: 'https://cdn.example.com/a.mp3',
38
+ });
39
+ });
40
+
32
41
  it('builds vote intents', () => {
33
42
  const action = parseIntents({ vote: 'player1' })[0].build().toJSON();
34
43
  expect(action).toMatchObject({ action: 'vote', target: 'player1' });
@@ -38,3 +47,45 @@ describe('parseIntents', () => {
38
47
  expect(parseIntents({ move: '2424,237', task: true, kill: 'p1', report: true, alarm: true })).toEqual([]);
39
48
  });
40
49
  });
50
+
51
+ describe('audioContentTypeFor', () => {
52
+ it('maps backend-supported audio extensions', () => {
53
+ expect(audioContentTypeFor('/tmp/a.mp3')).toBe('audio/mpeg');
54
+ expect(audioContentTypeFor('/tmp/a.wav')).toBe('audio/wav');
55
+ expect(audioContentTypeFor('/tmp/a.m4a')).toBe('audio/mp4');
56
+ expect(audioContentTypeFor('/tmp/a.mp4')).toBe('audio/mp4');
57
+ expect(audioContentTypeFor('/tmp/A.OGG')).toBe('audio/ogg');
58
+ expect(audioContentTypeFor('/tmp/a.webm')).toBe('audio/webm');
59
+ });
60
+
61
+ it('defaults extensionless files to audio/mpeg', () => {
62
+ expect(audioContentTypeFor('/tmp/clip')).toBe('audio/mpeg');
63
+ });
64
+
65
+ it('rejects unsupported audio extensions', () => {
66
+ expect(() => audioContentTypeFor('/tmp/a.flac')).toThrow(/Unsupported audio file type/);
67
+ });
68
+ });
69
+
70
+ describe('resolveSpeechAudioUrl', () => {
71
+ it('uploads the local file and returns the cloud audio_url', async () => {
72
+ const uploadAudio = vi.fn().mockResolvedValue({ audio_url: 'https://cdn.example.com/uploaded.mp3' });
73
+ const url = await resolveSpeechAudioUrl({ speech: 'hi', file: '/tmp/clip.wav' }, { uploadAudio } as any);
74
+ expect(url).toBe('https://cdn.example.com/uploaded.mp3');
75
+ expect(uploadAudio).toHaveBeenCalledWith('/tmp/clip.wav', undefined, 'audio/wav');
76
+ });
77
+
78
+ it('does not upload when no file is given', async () => {
79
+ const uploadAudio = vi.fn();
80
+ const url = await resolveSpeechAudioUrl({ speech: 'hi' }, { uploadAudio } as any);
81
+ expect(url).toBeUndefined();
82
+ expect(uploadAudio).not.toHaveBeenCalled();
83
+ });
84
+
85
+ it('requires speech when a file is given', async () => {
86
+ const uploadAudio = vi.fn();
87
+ await expect(resolveSpeechAudioUrl({ file: '/tmp/clip.mp3' }, { uploadAudio } as any))
88
+ .rejects.toThrow(/--file requires --speech/);
89
+ expect(uploadAudio).not.toHaveBeenCalled();
90
+ });
91
+ });
@@ -1,4 +1,5 @@
1
1
  import { Command, Option } from 'commander';
2
+ import { extname } from 'path';
2
3
  import { GameClient } from '../lib/game-client.js';
3
4
  import { Action } from '../sdk/action.js';
4
5
  import { EventStore } from '../pipeline/event-store.js';
@@ -7,6 +8,32 @@ interface ActionIntent {
7
8
  build(): Action;
8
9
  }
9
10
 
11
+ export function audioContentTypeFor(filePath: string): string {
12
+ const ext = extname(filePath).toLowerCase();
13
+ switch (ext) {
14
+ case '':
15
+ case '.mp3': return 'audio/mpeg';
16
+ case '.wav': return 'audio/wav';
17
+ case '.ogg':
18
+ case '.oga': return 'audio/ogg';
19
+ case '.m4a':
20
+ case '.mp4': return 'audio/mp4';
21
+ case '.webm': return 'audio/webm';
22
+ default:
23
+ throw new Error(`Unsupported audio file type "${ext || '(none)'}". Supported: mp3, wav, m4a, ogg, webm.`);
24
+ }
25
+ }
26
+
27
+ export async function resolveSpeechAudioUrl(
28
+ opts: Record<string, any>,
29
+ client: { uploadAudio(filePath: string, filename?: string, contentType?: string): Promise<{ audio_url: string }> },
30
+ ): Promise<string | undefined> {
31
+ if (!opts.file) return undefined;
32
+ if (!opts.speech) throw new Error('--file requires --speech.');
33
+ const { audio_url } = await client.uploadAudio(opts.file, undefined, audioContentTypeFor(opts.file));
34
+ return audio_url;
35
+ }
36
+
10
37
  export function normalizeDoOptions(opts: Record<string, any>, extraArgs: string[] = []): Record<string, any> {
11
38
  const normalized = { ...opts };
12
39
  if (normalized.speech && extraArgs.length > 0) {
@@ -21,7 +48,7 @@ export function normalizeDoOptions(opts: Record<string, any>, extraArgs: string[
21
48
 
22
49
  export function parseIntents(opts: Record<string, any>): ActionIntent[] {
23
50
  const intents: ActionIntent[] = [];
24
- if (opts.speech) intents.push({ build: () => Action.speech(opts.speech) });
51
+ if (opts.speech) intents.push({ build: () => Action.speech(opts.speech, undefined, opts.audioUrl) });
25
52
  if (opts.vote) intents.push({ build: () => Action.vote(opts.vote) });
26
53
  return intents;
27
54
  }
@@ -31,6 +58,7 @@ export function createDoCommand(): Command {
31
58
  .alias('d')
32
59
  .description('Execute player communication actions (speech/vote/comment)')
33
60
  .option('-s, --speech <text>', 'Say something')
61
+ .option('--file <path>', 'Upload a local audio file and attach it to speech')
34
62
  .option('-v, --vote <target>', 'Vote for player')
35
63
  .option('--comment <text>', 'Send a comment visible only to the user/spectators; not public in-game speech')
36
64
  .addOption(new Option('--think <text>', 'Deprecated alias for --comment').hideHelp())
@@ -38,6 +66,11 @@ export function createDoCommand(): Command {
38
66
  .action(async (extraArgs: string[], opts) => {
39
67
  opts = normalizeDoOptions(opts, extraArgs);
40
68
 
69
+ if (opts.file && !opts.speech) {
70
+ console.error('--file requires --speech.');
71
+ process.exit(1);
72
+ }
73
+
41
74
  if (!opts.speech && !opts.vote && !opts.comment) {
42
75
  console.error('No action specified. Use -s, -v, or --comment.');
43
76
  process.exit(1);
@@ -57,6 +90,10 @@ export function createDoCommand(): Command {
57
90
  const client = GameClient.fromAuth();
58
91
  await client.discoverGameServer();
59
92
 
93
+ if (opts.speech && opts.file) {
94
+ opts.audioUrl = await resolveSpeechAudioUrl(opts, client);
95
+ }
96
+
60
97
  const intents = parseIntents(opts);
61
98
  if (intents.length === 0 && opts.comment) {
62
99
  intents.push({ build: () => Action.think() });
@@ -93,7 +93,7 @@ export class GameClient {
93
93
  */
94
94
  async submitAction(action: {
95
95
  action: string; target?: string; target_x?: number; target_y?: number;
96
- task_name?: string; text?: string; thinking_content?: string;
96
+ task_name?: string; text?: string; thinking_content?: string; audio_url?: string;
97
97
  }): Promise<any> {
98
98
  if (this.ws?.connected) {
99
99
  this.ws.send({ toJSON: () => action });
@@ -117,6 +117,33 @@ export class GameClient {
117
117
  }
118
118
  }
119
119
 
120
+ async uploadAudio(
121
+ filePathOrBuffer: string | Buffer,
122
+ filename?: string,
123
+ contentType = 'audio/mpeg',
124
+ ): Promise<{ audio_url: string }> {
125
+ const form = new FormData();
126
+
127
+ if (typeof filePathOrBuffer === 'string') {
128
+ const { existsSync, readFileSync } = await import('fs');
129
+ const { basename } = await import('path');
130
+ if (!existsSync(filePathOrBuffer)) {
131
+ throw new Error(`Audio file not found: ${filePathOrBuffer}`);
132
+ }
133
+ const buffer = readFileSync(filePathOrBuffer);
134
+ form.append('file', new Blob([buffer as any], { type: contentType }), filename ?? basename(filePathOrBuffer));
135
+ } else {
136
+ form.append('file', new Blob([filePathOrBuffer as any], { type: contentType }), filename ?? 'audio.mp3');
137
+ }
138
+
139
+ const result = await this.http.post<any>('/api/v1/agents/upload_audio', form);
140
+ const audioUrl = result?.audio_url ?? result?.data?.audio_url;
141
+ if (!audioUrl) {
142
+ throw new Error(`upload_audio: unexpected response: ${JSON.stringify(result)}`);
143
+ }
144
+ return { audio_url: audioUrl };
145
+ }
146
+
120
147
  // ─── Agent API (→ lobby) ───
121
148
 
122
149
  /**
package/src/sdk/action.ts CHANGED
@@ -68,9 +68,11 @@ export class Action {
68
68
  *
69
69
  * @param text Words spoken (audible to nearby players).
70
70
  * @param thinkingContent Optional spectator-visible reasoning.
71
+ * @param audioUrl Optional uploaded speech audio URL.
71
72
  */
72
- static speech(text: string, thinkingContent?: string): Action {
73
+ static speech(text: string, thinkingContent?: string, audioUrl?: string): Action {
73
74
  const payload: Record<string, any> = { text };
75
+ if (audioUrl) payload.audio_url = audioUrl;
74
76
  return new Action('speech', payload, thinkingContent ?? null);
75
77
  // speech: no default thinking (the speech content itself is the message)
76
78
  }
@@ -593,6 +593,13 @@ export function reportCorpseDecision(
593
593
  ctx: StrategyContext,
594
594
  opts: { respectBlock?: boolean } = {},
595
595
  ): BehaviorDecision | null {
596
+ // 章鱼时间服务端禁用会议/报尸,任何 report 都会被 cannot_report_during_octopus_time 拒绝并陷入 5s 退避重试
597
+ // 循环;此时直接放弃报尸(含靠近尸体准备报告的 move),交由上层走生存/残局目标。一处即封住全部 6 个调用方,
598
+ // 也顺带让 corpseReportWithNonTeammate 因拿到 null 而不推「抢先报尸召集会议」的 agentAlert 叙事。
599
+ if (ctx.octopusTimeActive) {
600
+ ctx.reportCorpseTarget = null;
601
+ return null;
602
+ }
596
603
  const reportBlocked = opts.respectBlock && Date.now() < ctx.reportBlockedUntil;
597
604
 
598
605
  const reportable = nearestReportableCorpse(state);
@@ -77,4 +77,21 @@ describe('NormalShrimpTop vision thresholds', () => {
77
77
  top.tick(stateWithStranger(300), ctx);
78
78
  expect(top.subGoal).not.toBeInstanceOf(KeepAwayGoal);
79
79
  });
80
+
81
+ it('does not keep corpse-report state or direct-report messaging during octopus time', () => {
82
+ const top = new NormalShrimpTop();
83
+ const ctx = context({
84
+ octopusTimeActive: true,
85
+ reportCorpseTarget: { name: 'body', room: 'control', x: 0, y: 0 },
86
+ knownCorpses: [{ name: 'body', room: 'control', x: 0, y: 0 }],
87
+ });
88
+
89
+ top.tick({
90
+ ...stateWithStranger(100),
91
+ corpses: [{ name: 'body', room: 'control', x: 0, y: 0, distance: 0 }],
92
+ }, ctx);
93
+
94
+ expect(ctx.reportCorpseTarget).toBeNull();
95
+ expect(ctx.notifications.join('\n')).not.toContain('直接报警');
96
+ });
80
97
  });
@@ -75,7 +75,13 @@ export class NormalShrimpTop extends Goal {
75
75
  if (greeting) decisions.push(greeting);
76
76
 
77
77
  // ── P0 发现尸体 → 报警 ──
78
- if (hasKnownCorpse(ctx)) {
78
+ // 章鱼时间服务端禁用报尸,reportCorpseDecision 本就会返回 null;此处把整块 P0 一并跳过,否则
79
+ // notifyCorpseWitnesses 仍会推「尸体旁发现…,直接报警」这类提示,误导 Agent 以为仍应报尸召集会议。
80
+ // 跳过后落到后续 P1 躲避 / P3 任务巡逻的生存分支,同时清掉之前“靠近尸体准备报告”的残留状态。
81
+ if (ctx.octopusTimeActive) {
82
+ ctx.reportCorpseTarget = null;
83
+ this.corpseWitnessNotified.clear();
84
+ } else if (hasKnownCorpse(ctx)) {
79
85
  // 「尸体旁目击者」只在此刻确实站在命案现场(当帧视野有尸体)时才标注——否则会把后来路上
80
86
  // 遇见的人误报成目击者。报尸本身可以追着记忆里已离开视野的尸体走回去。
81
87
  if (corpseAtScene(state)) this.notifyCorpseWitnesses(visible, ctx);
@@ -27,6 +27,12 @@ export class ReportPatrolTop extends Goal {
27
27
  }
28
28
 
29
29
  private tryReport(state: GameState, ctx: StrategyContext): BehaviorDecision | null {
30
+ // 章鱼时间禁用报尸:不报、也不靠近尸体准备报告,落回巡逻(生存优先)。这条路径不走 reportCorpseDecision,需单独短路。
31
+ if (ctx.octopusTimeActive) {
32
+ this.lastCorpseNotified = false;
33
+ ctx.reportCorpseTarget = null;
34
+ return null;
35
+ }
30
36
  const reportable = nearestReportableCorpse(state);
31
37
  if (reportable) {
32
38
  ctx.reportCorpseTarget = null;
@@ -2,6 +2,7 @@ import type { GameState } from '../sdk/types.js';
2
2
 
3
3
  const MEETING_END_EVENT_TYPES = new Set(['meeting_ended', 'meeting_result_pending']);
4
4
  const MEETING_START_EVENT_TYPES = new Set(['meeting_start', 'meeting_started']);
5
+ const OCTOPUS_TIME_START_EVENT_TYPES = new Set(['octopus_time_start']);
5
6
 
6
7
  export function meetingEndedInEvents(events: any[] | undefined): boolean {
7
8
  return (events ?? []).some((e) => MEETING_END_EVENT_TYPES.has(e.type));
@@ -11,6 +12,10 @@ export function meetingStartedInEvents(events: any[] | undefined): boolean {
11
12
  return (events ?? []).some((e) => MEETING_START_EVENT_TYPES.has(e.type));
12
13
  }
13
14
 
15
+ export function octopusTimeStartedInEvents(events: any[] | undefined): boolean {
16
+ return (events ?? []).some((e) => OCTOPUS_TIME_START_EVENT_TYPES.has(e.type));
17
+ }
18
+
14
19
  /**
15
20
  * Keep pausing while HTTP phase is still `meeting`.
16
21
  * `releasedEarly` is set after we have seen meeting end once — avoids re-pausing
@@ -4,7 +4,7 @@ import { extractNewEvents } from '../pipeline/event-store.js';
4
4
  const SUPPLEMENTAL_TYPES = new Set([
5
5
  'corpse_spotted', 'crab_teammates',
6
6
  'meeting_ended', 'meeting_result_pending', 'meeting_start', 'meeting_started',
7
- 'move_end', 'move_interrupted',
7
+ 'move_end', 'move_interrupted', 'octopus_time_start',
8
8
  'wandering_speech',
9
9
  ]);
10
10
 
@@ -14,6 +14,7 @@ import { CorpseMemory } from './game-utils.js';
14
14
  import {
15
15
  meetingEndedInEvents,
16
16
  meetingStartedInEvents,
17
+ octopusTimeStartedInEvents,
17
18
  shouldPauseForMeeting,
18
19
  } from './meeting-gate.js';
19
20
  import { createStrategyNewEventsBackfill } from './new-events-backfill.js';
@@ -41,6 +42,21 @@ export function eventsForStrategyStateLog(events: any): Record<string, any>[] {
41
42
  return extractNewEvents(events).filter((event) => !SETUP_EVENTS_BACKFILLED_BY_STATE.has(event.type));
42
43
  }
43
44
 
45
+ /** 章鱼时间进入提示,动作响应与主循环两条消费入口共用同一文案。 */
46
+ const OCTOPUS_TIME_START_NOTICE =
47
+ '章鱼时间开始,会议/报尸已禁用,切换到生存优先,不再报尸召集会议。';
48
+
49
+ /**
50
+ * 消费 octopus_time_start:置 ctx.octopusTimeActive 并提示一次。动作响应的 new_events 与主循环
51
+ * 补偿后的 state.new_events 两条入口都走它,避免置位/文案逻辑分叉。已在章鱼时间则幂等跳过,
52
+ * 因此同一事件经动作响应与日志补偿重复到达也只提示一次。
53
+ */
54
+ function enterOctopusTimeIfStarted(ctx: StrategyContext, events: any[] | undefined): void {
55
+ if (ctx.octopusTimeActive || !octopusTimeStartedInEvents(events)) return;
56
+ ctx.octopusTimeActive = true;
57
+ ctx.notifications.push(OCTOPUS_TIME_START_NOTICE);
58
+ }
59
+
44
60
  function getPidPath(): string {
45
61
  const profile = new AuthStore().getActive();
46
62
  if (!profile) throw new Error('Not logged in.');
@@ -334,6 +350,7 @@ export async function runStrategyLoop(strategyId: string, args?: string[]): Prom
334
350
  taskLocalBlockedUntil: 0,
335
351
  reportCorpseTarget: null,
336
352
  reportBlockedUntil: 0,
353
+ octopusTimeActive: false,
337
354
  notifications: [],
338
355
  lastProgressNotifyAt: 0,
339
356
  teammates,
@@ -396,6 +413,9 @@ export async function runStrategyLoop(strategyId: string, args?: string[]): Prom
396
413
  // 那条通道会被 runtime WS listener 抢游标,这里补上避免尸体坐标漏记(ctx.knownCorpses 与 list() 同引用,立即可见)。
397
414
  corpseMemory.ingestEvents(newEvents);
398
415
  learnTeammatesFromEvents(newEvents, teammates);
416
+ // 章鱼时间可能只从本次动作响应的 new_events 到达(服务端游标一次性增量,下次 GET 不再重复);
417
+ // 立即消费,避免下一 tick 前仍走报尸分支,直到 report 被拒才靠错误文本兜底进入生存模式。
418
+ enterOctopusTimeIfStarted(ctx, newEvents);
399
419
  if (currentRole === 'shrimp_pistol' && ownKillEvent(newEvents, currentPlayerName)) {
400
420
  pistolKillUsed = true;
401
421
  }
@@ -431,6 +451,10 @@ export async function runStrategyLoop(strategyId: string, args?: string[]): Prom
431
451
  activeMoveTarget = null;
432
452
  }
433
453
  if (actionType === 'report') {
454
+ // 章鱼时间服务端禁用报尸,返回 cannot_report_during_octopus_time;漏掉 octopus_time_start 事件时靠它兜底进入生存模式。
455
+ if (failureText.includes('octopus')) {
456
+ ctx.octopusTimeActive = true;
457
+ }
434
458
  // doing_task 型失败不是真报不了:服务端只是因正在做任务而拒绝,下一 tick 任务被 move 打断后即可补报。
435
459
  // 这种情况不设 5 秒退避,否则会错过「目击者刚靠近尸体」的报尸自证窗口;其余原因(距离不够等)仍退避避免空报刷屏。
436
460
  if (!failureText.includes('doing_task')) {
@@ -529,6 +553,7 @@ export async function runStrategyLoop(strategyId: string, args?: string[]): Prom
529
553
  }
530
554
 
531
555
  learnTeammatesFromEvents(state.new_events, teammates);
556
+ enterOctopusTimeIfStarted(ctx, state.new_events);
532
557
  learnSeatNames(state.all_players, playerNamesBySeat);
533
558
  const terminalMove = ownMovementTerminalEvent(state.new_events, state.you.name);
534
559
  if (terminalMove) {
@@ -591,6 +616,7 @@ export async function runStrategyLoop(strategyId: string, args?: string[]): Prom
591
616
  ctx.taskLocalBlockedUntil = 0;
592
617
  ctx.reportCorpseTarget = null;
593
618
  ctx.reportBlockedUntil = 0;
619
+ ctx.octopusTimeActive = false;
594
620
  ctx.forcePatrolAdvance = false;
595
621
  ctx.blockedMoveTarget = null;
596
622
  // 开会后尸体清场:清空尸体记忆,避免回避/报告已不存在的尸体。
@@ -72,6 +72,13 @@ export interface StrategyContext {
72
72
  taskLocalBlockedUntil: number;
73
73
  reportCorpseTarget: CorpseTarget | null;
74
74
  reportBlockedUntil: number;
75
+ /**
76
+ * 章鱼时间(剩 3 人,服务端禁用会议/报尸,report 会被 `cannot_report_during_octopus_time` 拒绝)进行中。
77
+ * strategy-loop 见到 `octopus_time_start` 事件即置 true,report 因 octopus 相关错误失败时兜底置 true;每局
78
+ * 进程独立初始化为 false,会议恢复时一并清 false(章鱼时间不会开会,纯防御)。为 true 时所有报尸决策
79
+ * (reportCorpseDecision / ReportPatrolTop.tryReport / 经前者的 corpseReportWithNonTeammate)直接放弃,改生存优先。
80
+ */
81
+ octopusTimeActive?: boolean;
75
82
  notifications: string[];
76
83
  lastProgressNotifyAt: number;
77
84
  teammates: Set<string>;