@myclaw163/clawclaw-cli 0.8.2 → 0.8.4

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 (81) hide show
  1. package/README.md +1 -1
  2. package/docs/configuration.md +1 -1
  3. package/docs/custom-modules/README.md +4 -4
  4. package/docs/custom-modules/api-reference.md +20 -10
  5. package/docs/custom-modules/behavior.md +10 -6
  6. package/docs/custom-modules/perception.md +26 -3
  7. package/docs/custom-modules/trigger.md +1 -1
  8. package/docs/runtime/README.md +1 -1
  9. package/docs/runtime/behavior-runtime.md +6 -2
  10. package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
  11. package/package.json +1 -1
  12. package/skills/clawclaw/SKILL.md +30 -37
  13. package/skills/clawclaw/references/COMMANDS.md +2 -3
  14. package/skills/clawclaw/references/GAME-MECHANICS.md +16 -18
  15. package/skills/clawclaw/references/STREAM.md +25 -10
  16. package/src/behaviors/official-finite/do-task.ts +70 -0
  17. package/src/behaviors/official-finite/index.test.ts +69 -22
  18. package/src/behaviors/official-finite/index.ts +0 -3
  19. package/src/commands/behavior.test.ts +1 -1
  20. package/src/commands/load.ts +8 -3
  21. package/src/commands/trigger.ts +12 -5
  22. package/src/lib/behavior-export.test.ts +53 -9
  23. package/src/lib/behavior-export.ts +26 -3
  24. package/src/lib/clawclaw-skill-spectate-guidance.test.ts +21 -0
  25. package/src/lib/trigger-export.test.ts +80 -0
  26. package/src/lib/trigger-export.ts +210 -0
  27. package/src/lib/user-data.test.ts +4 -0
  28. package/src/lib/user-data.ts +4 -0
  29. package/src/pipeline/canonical-event-presentation.test.ts +2 -0
  30. package/src/pipeline/event-format.test.ts +113 -0
  31. package/src/pipeline/event-format.ts +51 -5
  32. package/src/pipeline/event-hints.test.ts +28 -3
  33. package/src/pipeline/event-hints.ts +20 -6
  34. package/src/pipeline/game-sync-event-normalization.test.ts +49 -1
  35. package/src/pipeline/game-sync-event-normalization.ts +9 -0
  36. package/src/pipeline/role-display.ts +22 -0
  37. package/src/runtime/clawclaw/agent-ability-state.ts +69 -0
  38. package/src/runtime/clawclaw/agent-event-policy.test.ts +6 -0
  39. package/src/runtime/clawclaw/agent-event-policy.ts +5 -0
  40. package/src/runtime/clawclaw/behavior-decision.test.ts +14 -0
  41. package/src/runtime/clawclaw/behavior-decision.ts +8 -1
  42. package/src/runtime/clawclaw/behavior-input.test.ts +22 -0
  43. package/src/runtime/clawclaw/behavior-input.ts +3 -0
  44. package/src/runtime/clawclaw/owner.test.ts +16 -0
  45. package/src/runtime/clawclaw/owner.ts +21 -8
  46. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +24 -0
  47. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +8 -1
  48. package/src/runtime/clawclaw/plugins/action/automated-action-normalization.ts +0 -1
  49. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -1
  50. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +3 -0
  51. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +246 -0
  52. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +135 -6
  53. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +0 -9
  54. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +118 -1
  55. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +13 -2
  56. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +156 -0
  57. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +0 -1
  58. package/src/runtime/clawclaw-event-catalog.test.ts +6 -0
  59. package/src/runtime/clawclaw-event-catalog.ts +6 -0
  60. package/src/runtime/framework/action-diagnostics.ts +1 -0
  61. package/src/runtime/framework/modules/runtime-module-loader.test.ts +1 -1
  62. package/src/runtime/framework/modules/runtime-module-loader.ts +0 -1
  63. package/src/sdk/action.test.ts +8 -0
  64. package/src/sdk/action.ts +8 -6
  65. package/src/sdk/behavior-plugin/index.ts +11 -2
  66. package/src/sdk/behavior-toolkit/model.ts +2 -0
  67. package/src/sdk/module-input/index.ts +16 -2
  68. package/src/strategies/custom-module.test.ts +0 -1
  69. package/src/strategies/game-utils.test.ts +0 -1
  70. package/src/strategies/goals/avoid-players-top.test.ts +0 -1
  71. package/src/strategies/goals/crab-sabotage-top.test.ts +11 -25
  72. package/src/strategies/goals/crab-sabotage-top.ts +5 -61
  73. package/src/strategies/goals/kill-lone-top.test.ts +0 -1
  74. package/src/strategies/goals/kill-target-top.test.ts +0 -1
  75. package/src/strategies/goals/lone-kill-task-top.test.ts +0 -1
  76. package/src/strategies/goals/normal-shrimp-top.test.ts +0 -1
  77. package/src/strategies/goals/paradise-fish-top.test.ts +0 -1
  78. package/src/strategies/goals/task-only-top.test.ts +0 -1
  79. package/src/strategies/goals/warrior-shrimp-top.test.ts +0 -1
  80. package/src/strategies/types.ts +0 -6
  81. package/src/behaviors/official-finite/trigger-alarm.ts +0 -53
@@ -2,6 +2,8 @@ import { projectPlayers } from './player-projection.js';
2
2
  import { headingDirection } from '../runtime/clawclaw/plugins/perception/shared/math.js';
3
3
  import { isRoomMode } from '../lib/room.js';
4
4
  import { isSelfKillerMurderWitnessed } from './event-hints.js';
5
+ import { projectAgentAbilities } from '../runtime/clawclaw/agent-ability-state.js';
6
+ import { roleDisplayName } from './role-display.js';
5
7
 
6
8
  export interface EventFormatContext {
7
9
  summary?: any | null;
@@ -49,6 +51,12 @@ function stringValue(value: unknown): string | undefined {
49
51
  return typeof value === 'string' && value.length > 0 ? value : undefined;
50
52
  }
51
53
 
54
+ function killerRoleSuffix(event: Record<string, any>): string {
55
+ if (event.killer_kind === 'system') return '';
56
+ const role = roleDisplayName(event.killer_role, 'zh-CN');
57
+ return role ? `(${role})` : '';
58
+ }
59
+
52
60
  function trainingRoomTypeLabel(value: unknown): string {
53
61
  if (value === 'training_simulation') return '模拟训练';
54
62
  if (value === 'training_dummy') return '木桩训练';
@@ -375,7 +383,7 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
375
383
  case 'kill':
376
384
  return `你在${firstString(event, ['room'])}击杀了${playerLabel(event.target_name, firstNumber(event, ['target_seat', 'target_player_seat']), ctx)}。`;
377
385
  case 'killed':
378
- return `你在${firstString(event, ['room'])}被${killerLabel(event.killer_name, firstNumber(event, ['killer_seat', 'killer_player_seat']), event.killer_kind, ctx)}击杀了,你已死亡。`;
386
+ return `你在${firstString(event, ['room'])}被${killerLabel(event.killer_name, firstNumber(event, ['killer_seat', 'killer_player_seat']), event.killer_kind, ctx)}${killerRoleSuffix(event)}击杀了,你已死亡。`;
379
387
  case 'murder_witnessed':
380
388
  if (isSelfKillerMurderWitnessed(event, ctx.summary)) {
381
389
  return '收到一条与自身击杀身份冲突的 murder_witnessed 事件;该事件已降级为诊断信息,不能据此判断任何目击者。';
@@ -403,6 +411,11 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
403
411
  }
404
412
  case 'task_sabotaged':
405
413
  return `破坏任务完成:${firstString(event, ['task_name'])}(${firstString(event, ['room'])})。`;
414
+ case 'task_interrupted': {
415
+ const cooldown = numberValue(event.cooldown_remaining_secs);
416
+ const cooldownText = cooldown === undefined ? '' : `;共享冷却剩余${cooldown}秒`;
417
+ return `破坏任务“${firstString(event, ['task_name'])}”因紧急任务开始而中断,任务未消耗${cooldownText}。`;
418
+ }
406
419
  case 'tasks_changed':
407
420
  return `任务列表已更新(${firstString(event, ['reason'])})。`;
408
421
  case 'players_changed':
@@ -422,8 +435,14 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
422
435
  return `你听到${firstString(event, ['room'])}附近有尸体倒地。`;
423
436
  case 'octopus_time_start':
424
437
  return '章鱼时间开始:存活人数已降至3人或更少,章鱼存活60秒将获胜;会议已禁用,但虾方任务完成或紧急任务超时仍可先结束本局。';
425
- case 'emergency_started':
426
- return `紧急任务:${firstString(event, ['task_name'])}在${firstString(event, ['room'])},${text(event.timeout_secs, '?')}秒内处理。`;
438
+ case 'emergency_started': {
439
+ const sabotageCause = event.cause === 'sabotage'
440
+ ? '蟹刚完成对应破坏任务并触发了该紧急事件;'
441
+ : '';
442
+ return `紧急任务:${firstString(event, ['task_name'])}在${firstString(event, ['room'])},${sabotageCause}${text(event.timeout_secs, '?')}秒内处理。`;
443
+ }
444
+ case 'emergency_countdown_warning':
445
+ return `紧急任务${firstString(event, ['task_name'])}只剩${text(event.remaining_secs, '?')}秒(${text(event.threshold_secs, '?')}秒提醒)。`;
427
446
  case 'emergency_resolved':
428
447
  if (event.reason === 'meeting_started') {
429
448
  return `会议开始,紧急任务${firstString(event, ['task_name'])}已自动解除。`;
@@ -433,7 +452,13 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
433
452
  }
434
453
  return `紧急任务已解决:${firstString(event, ['task_name'])}。`;
435
454
  case 'emergency_interrupted':
436
- return `${playerLabel(event.actor_name, firstNumber(event, ['actor_seat', 'seat']), ctx)}在处理${firstString(event, ['task_name'])}时死亡,紧急任务仍未解除。`;
455
+ return `你在处理${firstString(event, ['task_name'])}时死亡,紧急任务仍未解除。`;
456
+ case 'ability.ready':
457
+ return `能力“${firstString(event, ['ability_name', 'ability_id'])}”现在可以使用。`;
458
+ case 'ability.remaining_uses_changed':
459
+ return `能力“${firstString(event, ['ability_name', 'ability_id'])}”剩余${text(event.remaining_uses, '?')}次。`;
460
+ case 'ability.exhausted':
461
+ return `能力“${firstString(event, ['ability_name', 'ability_id'])}”已无剩余次数。`;
437
462
  case 'meeting_briefing': {
438
463
  const callerName = firstString(event, ['meeting_caller_name', 'caller', 'actor_name']);
439
464
  const caller = playerLabel(callerName, firstNumber(event, ['meeting_caller_seat', 'caller_seat', 'actor_seat']), ctx);
@@ -819,6 +844,23 @@ export function compactEventFields(
819
844
  });
820
845
  }
821
846
 
847
+ function compactEmergencyState(summary: Record<string, any>): Record<string, any> | undefined {
848
+ const emergency = summary.emergency
849
+ && typeof summary.emergency === 'object'
850
+ && !Array.isArray(summary.emergency)
851
+ ? summary.emergency as Record<string, any>
852
+ : null;
853
+ if (!emergency || typeof emergency.active !== 'boolean') return undefined;
854
+ return cleanObject({
855
+ active: emergency.active,
856
+ task_name: stringValue(emergency.task_name),
857
+ room: stringValue(emergency.room),
858
+ x: numberValue(emergency.x),
859
+ y: numberValue(emergency.y),
860
+ remaining_secs: numberValue(emergency.remaining_secs),
861
+ });
862
+ }
863
+
822
864
  /** Compact, decision-oriented projection used by realtime Agent adapters. */
823
865
  export function compactStateForChannel(
824
866
  summary: any | null | undefined,
@@ -918,6 +960,8 @@ export function compactStateForChannel(
918
960
  cooldown_remaining_secs: numberValue(crabSabotage.cooldown_remaining_secs),
919
961
  })
920
962
  : undefined,
963
+ emergency: compactEmergencyState(summary),
964
+ abilities: projectAgentAbilities(summary),
921
965
  urgent: summary.urgent,
922
966
  automation: summary.automation,
923
967
  });
@@ -1021,6 +1065,8 @@ export function compactStateForEvents(
1021
1065
  cooldown_remaining_secs: numberValue(crabSabotage.cooldown_remaining_secs),
1022
1066
  })
1023
1067
  : undefined,
1068
+ emergency: compactEmergencyState(summary),
1069
+ abilities: projectAgentAbilities(summary),
1024
1070
  urgent: summary.urgent,
1025
1071
  automation: summary.automation,
1026
1072
  });
@@ -1054,7 +1100,7 @@ export function shortStateText(summary: any | null | undefined): string {
1054
1100
  ? summary.players.filter((player: any) => player?.known_status?.is_alive !== false).length
1055
1101
  : undefined;
1056
1102
  if (aliveCount !== undefined) parts.push(`alive=${aliveCount}`);
1057
- if (summary.urgent?.emergency_active) parts.push('urgent=emergency');
1103
+ if (summary.emergency?.active === true || summary.urgent?.emergency_active) parts.push('urgent=emergency');
1058
1104
  if (summary.urgent?.corpse_nearby) parts.push('urgent=corpse');
1059
1105
  return parts.join('; ');
1060
1106
  }
@@ -11,12 +11,12 @@ import {
11
11
  } from './event-hints.js';
12
12
 
13
13
  describe('Mailbox-owned Event hint registries', () => {
14
- it('keeps 30 backend hint formatters and classifies 15 Agent Events as unregistered', () => {
14
+ it('keeps 31 backend hint formatters and classifies 15 Agent Events as unregistered', () => {
15
15
  const unregistered = CLAWCLAW_BACKEND_AGENT_EVENT_TYPES.filter((type) => (
16
16
  BACKEND_EVENT_HINT_FORMATTERS[type] === undefined
17
17
  ));
18
18
 
19
- expect(Object.keys(BACKEND_EVENT_HINT_FORMATTERS)).toHaveLength(30);
19
+ expect(Object.keys(BACKEND_EVENT_HINT_FORMATTERS)).toHaveLength(31);
20
20
  expect(unregistered).toEqual([
21
21
  'task_completed',
22
22
  'task_sabotaged',
@@ -56,6 +56,27 @@ describe('Mailbox-owned Event hint registries', () => {
56
56
  )).toContain('Do not retry matchmaking');
57
57
  });
58
58
 
59
+ it('uses private second-person emergency guidance and authoritative killer roles', () => {
60
+ expect(formatCanonicalEventHint(
61
+ { producer: 'backend_push' },
62
+ {
63
+ type: 'emergency_interrupted',
64
+ actor_name: 'Alpha',
65
+ task_name: 'repair reactor',
66
+ },
67
+ )).toBe('You died while resolving repair reactor. The emergency is still active and needs another response.');
68
+ expect(formatCanonicalEventHint(
69
+ { producer: 'backend_push' },
70
+ {
71
+ type: 'killed',
72
+ killer_kind: 'player',
73
+ killer_name: 'Alpha',
74
+ killer_seat: 2,
75
+ killer_role: 'crab_assassin',
76
+ },
77
+ )).toBe('YOU ARE DEAD: seat 2 Alpha (Assassin Crab) removed you from play.');
78
+ });
79
+
59
80
  it('classifies Source and Derived lifecycle Events with list changes factual-only', () => {
60
81
  const excluded = new Set(['robot_speak_rule', 'strategy_alert']);
61
82
  const sourceTypes = CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter((type) => (
@@ -83,6 +104,10 @@ describe('Mailbox-owned Event hint registries', () => {
83
104
  'behavior.replaced',
84
105
  'players_changed',
85
106
  'tasks_changed',
107
+ 'emergency_countdown_warning',
108
+ 'ability.ready',
109
+ 'ability.remaining_uses_changed',
110
+ 'ability.exhausted',
86
111
  ]);
87
112
  });
88
113
 
@@ -306,7 +331,7 @@ describe('Mailbox-owned Event hint registries', () => {
306
331
  ...Object.values(DERIVED_EVENT_HINT_FORMATTERS).map((formatter) => formatter(sample, {})),
307
332
  ].filter((hint): hint is string => typeof hint === 'string');
308
333
 
309
- expect(hints).toHaveLength(50);
334
+ expect(hints).toHaveLength(51);
310
335
  for (const hint of hints) expect(hint).not.toMatch(/[一-鿿]/);
311
336
  });
312
337
  });
@@ -1,4 +1,5 @@
1
1
  import { isRoomMode, isTrainingRoomMode } from '../lib/room.js';
2
+ import { roleDisplayName } from './role-display.js';
2
3
 
3
4
  export interface EventHintContext {
4
5
  summary?: any | null;
@@ -38,6 +39,12 @@ function nonEmptyString(value: unknown): string | undefined {
38
39
  return typeof value === 'string' && value.length > 0 ? value : undefined;
39
40
  }
40
41
 
42
+ function killerRoleSuffix(event: Record<string, any>): string {
43
+ if (event.killer_kind === 'system') return '';
44
+ const role = roleDisplayName(event.killer_role, 'en');
45
+ return role ? ` (${role})` : '';
46
+ }
47
+
41
48
  /** Defensive recipient check for a backend event that contradicts witness semantics. */
42
49
  export function isSelfKillerMurderWitnessed(
43
50
  event: Record<string, any>,
@@ -168,7 +175,7 @@ export const BACKEND_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFor
168
175
  + "Blood is on the floor, one voice is gone, and the killer's side moves closer to victory."
169
176
  ),
170
177
  killed: (event) => (
171
- `YOU ARE DEAD: ${optionalSeatPlayerLabel(event.killer_name, firstNumber(event, ['killer_seat', 'killer_player_seat']))} removed you from play.`
178
+ `YOU ARE DEAD: ${optionalSeatPlayerLabel(event.killer_name, firstNumber(event, ['killer_seat', 'killer_player_seat']))}${killerRoleSuffix(event)} removed you from play.`
172
179
  ),
173
180
  murder_witnessed: (event, ctx) => (
174
181
  isSelfKillerMurderWitnessed(event, ctx.summary)
@@ -188,11 +195,18 @@ export const BACKEND_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFor
188
195
  octopus_time_start: () => (
189
196
  '⚠️ OCTOPUS TIME. At most three players remain; if the Octopus survives 60 seconds, it wins. Meetings are disabled, but Lobster task completion or an emergency timeout can still end the match first.'
190
197
  ),
191
- emergency_started: (event) => (
192
- `EMERGENCY: ${text(event.task_name, 'A sabotage')} detonated in ${text(event.room, 'somewhere')} `
193
- + `at ${coordPair(event.x ?? event.task_x, event.y ?? event.task_y)}. `
194
- + `${text(event.timeout_secs, '30')}s until Crabs turn sabotage into victory. Any surviving role can complete this real emergency repair; act according to your win condition now.`
198
+ task_interrupted: (event) => (
199
+ `Your sabotage task ${text(event.task_name, 'your task')} was interrupted because an emergency started. `
200
+ + `The task was not consumed; wait for the authoritative shared cooldown${event.cooldown_remaining_secs === undefined ? '' : ` (${text(event.cooldown_remaining_secs)}s remaining)`}.`
195
201
  ),
202
+ emergency_started: (event) => {
203
+ const cause = event.cause === 'sabotage'
204
+ ? "A Crab completed the paired sabotage task here and activated this emergency; the saboteur's identity is not exposed. "
205
+ : '';
206
+ return `EMERGENCY: ${text(event.task_name, 'A sabotage')} detonated in ${text(event.room, 'somewhere')} `
207
+ + `at ${coordPair(event.x ?? event.task_x, event.y ?? event.task_y)}. ${cause}`
208
+ + `${text(event.timeout_secs, '30')}s until Crabs turn sabotage into victory. Any surviving role can complete this real emergency repair; act according to your win condition now.`;
209
+ },
196
210
  emergency_resolved: (event) => {
197
211
  const taskName = text(event.task_name, 'The emergency');
198
212
  if (event.reason === 'meeting_started') {
@@ -204,7 +218,7 @@ export const BACKEND_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFor
204
218
  return `${taskName} was resolved. The repairer's identity is not visible to you. Crab pressure collapses, for now.`;
205
219
  },
206
220
  emergency_interrupted: (event) => (
207
- `${actorName(event, 'The responder')} was interrupted while resolving ${text(event.task_name, 'the emergency')}. `
221
+ `You died while resolving ${text(event.task_name, 'the emergency')}. `
208
222
  + 'The emergency is still active and needs another response.'
209
223
  ),
210
224
  exile: (event) => (
@@ -139,6 +139,43 @@ describe('GameSync v2 Event normalization', () => {
139
139
  expect(wire.target).toEqual({ seat: 5, name: 'agent_5' });
140
140
  });
141
141
 
142
+ it('preserves sabotage cause and private task interruption facts without internal routing fields', () => {
143
+ expect(normalizeGameSyncEvent({
144
+ event_id: 'emergency-1',
145
+ tick: 70,
146
+ type: 'emergency_started',
147
+ actor: null,
148
+ cause: 'sabotage',
149
+ task_id: '1011',
150
+ task_name: '稳定反应堆',
151
+ })).toMatchObject({
152
+ tick: 70,
153
+ type: 'emergency_started',
154
+ cause: 'sabotage',
155
+ task_id: '1011',
156
+ task_name: '稳定反应堆',
157
+ });
158
+
159
+ const interrupted = normalizeGameSyncEvent({
160
+ event_id: 'interrupted-1',
161
+ tick: 70,
162
+ type: 'task_interrupted',
163
+ task_id: '102',
164
+ task_name: '投放毒药',
165
+ reason: 'emergency_started',
166
+ cooldown_remaining_secs: 100,
167
+ });
168
+ expect(interrupted).toEqual({
169
+ tick: 70,
170
+ type: 'task_interrupted',
171
+ task_id: '102',
172
+ task_name: '投放毒药',
173
+ reason: 'emergency_started',
174
+ cooldown_remaining_secs: 100,
175
+ });
176
+ expect(interrupted).not.toHaveProperty('_recipient_agent_id');
177
+ });
178
+
142
179
  it('projects every semantic single-player field without retaining wire objects', () => {
143
180
  const normalized = normalizeGameSyncEvent({
144
181
  event_id: '6e1ec10d-77a3-4632-935d-b12e8a894fef',
@@ -182,6 +219,8 @@ describe('GameSync v2 Event normalization', () => {
182
219
  type: 'killed',
183
220
  actor: { seat: 4, name: 'victim' },
184
221
  killer: { kind: 'player', player: { seat: 2, name: 'killer' } },
222
+ killer_role: 'crab_assassin',
223
+ killer_faction: 'crab',
185
224
  room: 'engine',
186
225
  });
187
226
  expect(playerKilled).toMatchObject({
@@ -190,10 +229,12 @@ describe('GameSync v2 Event normalization', () => {
190
229
  killer_kind: 'player',
191
230
  killer_name: 'killer',
192
231
  killer_seat: 2,
232
+ killer_role: 'crab_assassin',
233
+ killer_faction: 'crab',
193
234
  });
194
235
  expect(playerKilled).not.toHaveProperty('killer');
195
236
  expect(presentCanonicalEvent(canonical(playerKilled), null).hint)
196
- .toBe('YOU ARE DEAD: seat 2 killer removed you from play.');
237
+ .toBe('YOU ARE DEAD: seat 2 killer (Assassin Crab) removed you from play.');
197
238
 
198
239
  const systemKilled = normalizeGameSyncEvent({
199
240
  event_id: 'system-killed',
@@ -215,6 +256,13 @@ describe('GameSync v2 Event normalization', () => {
215
256
  .toBe('YOU ARE DEAD: Shrimp God removed you from play.');
216
257
  });
217
258
 
259
+ it('rejects malformed killed role metadata', () => {
260
+ expect(() => normalizeGameSyncEvent({ type: 'killed', killer_role: {} }))
261
+ .toThrow('GameSync Event.killer_role must be a non-empty string');
262
+ expect(() => normalizeGameSyncEvent({ type: 'killed', killer_faction: '' }))
263
+ .toThrow('GameSync Event.killer_faction must be a non-empty string');
264
+ });
265
+
218
266
  it('rejects malformed structured killers', () => {
219
267
  expect(() => normalizeGameSyncEvent({
220
268
  type: 'killed', killer: { kind: 'player', player: { seat: 2 } },
@@ -194,6 +194,15 @@ export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
194
194
  if (raw !== null && raw !== undefined) Object.assign(normalized, projectKiller(raw));
195
195
  }
196
196
 
197
+ if (normalized.type === 'killed') {
198
+ for (const field of ['killer_role', 'killer_faction'] as const) {
199
+ if (!Object.hasOwn(normalized, field)) continue;
200
+ if (typeof normalized[field] !== 'string' || normalized[field].length === 0) {
201
+ throw new TypeError(`GameSync Event.${field} must be a non-empty string`);
202
+ }
203
+ }
204
+ }
205
+
197
206
  for (const field of PLAYER_REF_ARRAY_FIELDS) {
198
207
  if (!Object.hasOwn(normalized, field)) continue;
199
208
  normalized[field] = playerRefArray(normalized[field], `GameSync Event.${field}`);
@@ -0,0 +1,22 @@
1
+ export type RoleDisplayLocale = 'en' | 'zh-CN';
2
+
3
+ const ROLE_DISPLAY_NAMES: Readonly<Record<string, Readonly<Record<RoleDisplayLocale, string>>>> = Object.freeze({
4
+ generic: { en: 'Generic', 'zh-CN': '通用身份' },
5
+ shrimp_generic: { en: 'Shrimp', 'zh-CN': '普通虾' },
6
+ shrimp_warrior: { en: 'Warrior Shrimp', 'zh-CN': '武士虾' },
7
+ shrimp_pistol: { en: 'Pistol Shrimp', 'zh-CN': '枪虾' },
8
+ shrimp_krill: { en: 'Krill', 'zh-CN': '磷虾' },
9
+ shrimp_pipi: { en: 'Mantis Shrimp', 'zh-CN': '皮皮虾' },
10
+ crab_generic: { en: 'Crab', 'zh-CN': '蟹' },
11
+ crab_assassin: { en: 'Assassin Crab', 'zh-CN': '刺客蟹' },
12
+ crab_honest: { en: 'Honest Crab', 'zh-CN': '诚实蟹' },
13
+ crab_spy: { en: 'Spy Crab', 'zh-CN': '间谍蟹' },
14
+ neutral_paradise_fish: { en: 'Paradise Fish', 'zh-CN': '天堂鱼' },
15
+ neutral_jellyfish: { en: 'Jellyfish', 'zh-CN': '水母' },
16
+ neutral_octopus: { en: 'Octopus', 'zh-CN': '章鱼' },
17
+ });
18
+
19
+ export function roleDisplayName(value: unknown, locale: RoleDisplayLocale): string | undefined {
20
+ if (typeof value !== 'string' || value.length === 0) return undefined;
21
+ return ROLE_DISPLAY_NAMES[value]?.[locale] ?? value;
22
+ }
@@ -0,0 +1,69 @@
1
+ export type AgentAbilityId = 'kill';
2
+
3
+ export interface AgentAbilityState extends Record<string, unknown> {
4
+ id: AgentAbilityId;
5
+ name: string;
6
+ ready: boolean;
7
+ cooldown_remaining_secs?: number;
8
+ remaining_uses: number | null;
9
+ effective_range_px?: number;
10
+ status?: string;
11
+ }
12
+
13
+ const KILL_ROLES = new Set([
14
+ 'crab_generic',
15
+ 'neutral_octopus',
16
+ 'shrimp_warrior',
17
+ 'shrimp_pistol',
18
+ ]);
19
+
20
+ const LONG_RANGE_KILL_ROLES = new Set([
21
+ 'shrimp_warrior',
22
+ 'shrimp_pistol',
23
+ ]);
24
+
25
+ function finiteNumber(value: unknown): number | undefined {
26
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
27
+ }
28
+
29
+ function nonEmptyString(value: unknown): string | undefined {
30
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
31
+ }
32
+
33
+ /**
34
+ * Project only the stateful abilities that the current Game State can describe
35
+ * authoritatively. Reporting/body interactions have no independent cooldown or
36
+ * charge state in this contract, so they are intentionally absent.
37
+ */
38
+ export function projectAgentAbilities(summary: Record<string, any>): AgentAbilityState[] | undefined {
39
+ const you = summary.you && typeof summary.you === 'object' && !Array.isArray(summary.you)
40
+ ? summary.you as Record<string, any>
41
+ : null;
42
+ if (!you) return undefined;
43
+
44
+ const role = nonEmptyString(you.role);
45
+ const alive = you.is_alive !== false;
46
+ const actionablePhase = summary.phase === 'wandering';
47
+ const abilities: AgentAbilityState[] = [];
48
+ const killCooldown = finiteNumber(you.kill_cooldown_secs);
49
+ const killsRemaining = finiteNumber(you.kills_remaining);
50
+ if ((role && KILL_ROLES.has(role)) || killCooldown !== undefined || killsRemaining !== undefined) {
51
+ const remainingUses = killsRemaining === undefined ? null : Math.max(0, Math.trunc(killsRemaining));
52
+ abilities.push({
53
+ id: 'kill',
54
+ name: role === 'shrimp_pistol' ? '攻击' : '击杀',
55
+ ready: actionablePhase
56
+ && alive
57
+ && killCooldown !== undefined
58
+ && killCooldown <= 0
59
+ && remainingUses !== 0,
60
+ ...(killCooldown === undefined
61
+ ? {}
62
+ : { cooldown_remaining_secs: Math.max(0, killCooldown) }),
63
+ remaining_uses: remainingUses,
64
+ effective_range_px: role && LONG_RANGE_KILL_ROLES.has(role) ? 160 : 80,
65
+ });
66
+ }
67
+
68
+ return abilities.length > 0 ? abilities : undefined;
69
+ }
@@ -19,6 +19,10 @@ describe('ClawClaw Monitor Event policy', () => {
19
19
  'kill',
20
20
  'killed',
21
21
  'murder_witnessed',
22
+ 'emergency_countdown_warning',
23
+ 'ability.ready',
24
+ 'ability.remaining_uses_changed',
25
+ 'ability.exhausted',
22
26
  'behavior.completed',
23
27
  'behavior.failed',
24
28
  'behavior.cancelled',
@@ -48,6 +52,8 @@ describe('ClawClaw Monitor Event policy', () => {
48
52
  it('does not hold decision Events behind an artificial delay', () => {
49
53
  expect(clawclawMonitorDelayMs('kill')).toBe(0);
50
54
  expect(clawclawMonitorDelayMs('emergency_started')).toBe(0);
55
+ expect(clawclawMonitorPriority('task_interrupted')).toBe(95);
56
+ expect(clawclawMonitorDelayMs('task_interrupted')).toBe(0);
51
57
  expect(clawclawMonitorDelayMs('corpse_spotted')).toBe(0);
52
58
  expect(clawclawMonitorDelayMs('speech')).toBe(0);
53
59
  });
@@ -5,6 +5,11 @@ export const CLAWCLAW_MONITOR_EVENT_PRIORITY: Readonly<Record<string, number>> =
5
5
  kill: 99,
6
6
  killed: 99,
7
7
  murder_witnessed: 95,
8
+ task_interrupted: 95,
9
+ emergency_countdown_warning: 95,
10
+ 'ability.ready': 80,
11
+ 'ability.remaining_uses_changed': 80,
12
+ 'ability.exhausted': 90,
8
13
  'behavior.completed': 90,
9
14
  'behavior.failed': 95,
10
15
  'behavior.cancelled': 90,
@@ -26,4 +26,18 @@ describe('normalizeBehaviorDecision', () => {
26
26
  status: { summary: 'running', lifecycle: 'completed' },
27
27
  }, { finite: false })).toThrow('behavior_status_field_unknown:lifecycle');
28
28
  });
29
+
30
+ it('accepts one declared delegation and rejects hidden delegation fields', () => {
31
+ expect(normalizeBehaviorDecision({
32
+ delegate: { behavior: 'report_corpse', input: { seat: 3 } },
33
+ })).toMatchObject({
34
+ delegate: { behavior: 'report_corpse', input: { seat: 3 } },
35
+ });
36
+ expect(() => normalizeBehaviorDecision({
37
+ delegate: { behavior: 'report_corpse', input: {}, layer: 'reflex' },
38
+ })).toThrow('behavior_delegate_field_unknown:layer');
39
+ expect(() => normalizeBehaviorDecision({
40
+ delegate: { behavior: '', input: {} },
41
+ })).toThrow('behavior_delegate_id_invalid');
42
+ });
29
43
  });
@@ -3,9 +3,10 @@ import type {
3
3
  FiniteBehaviorDecision,
4
4
  } from '../../sdk/behavior-plugin/index.js';
5
5
 
6
- const DECISION_KEYS = new Set(['actions', 'status', 'events', 'finish']);
6
+ const DECISION_KEYS = new Set(['actions', 'status', 'events', 'delegate', 'finish']);
7
7
  const STATUS_KEYS = new Set(['summary', 'activity', 'room', 'task', 'targetPlayer', 'data']);
8
8
  const EVENT_KEYS = new Set(['type', 'payload', 'occurredAt']);
9
+ const DELEGATE_KEYS = new Set(['behavior', 'input']);
9
10
  const FINISH_KEYS = new Set(['outcome', 'reason', 'summary']);
10
11
 
11
12
  function objectRecord(value: unknown, code: string): Record<string, unknown> {
@@ -67,6 +68,12 @@ export function normalizeBehaviorDecision(
67
68
  }
68
69
  }
69
70
  }
71
+ if (source.delegate !== undefined) {
72
+ const delegate = objectRecord(source.delegate, 'behavior_delegate_invalid');
73
+ rejectUnknownFields(delegate, DELEGATE_KEYS, 'behavior_delegate_field_unknown');
74
+ nonEmptyString(delegate.behavior, 'behavior_delegate_id_invalid');
75
+ if (delegate.input !== undefined) objectRecord(delegate.input, 'behavior_delegate_input_invalid');
76
+ }
70
77
  if (source.finish !== undefined) {
71
78
  const finish = objectRecord(source.finish, 'behavior_finish_invalid');
72
79
  rejectUnknownFields(finish, FINISH_KEYS, 'behavior_finish_field_unknown');
@@ -135,6 +135,28 @@ describe('createBehaviorInput', () => {
135
135
  expect(createBehaviorInput(value, {})).toBeNull();
136
136
  });
137
137
 
138
+ it('deep-freezes an optional delegated Behavior continuation', () => {
139
+ const result = createBehaviorInput(runtimeInput(), {}, {
140
+ delegatedBehavior: {
141
+ activationId: 'short-1',
142
+ behavior: 'report_corpse',
143
+ outcome: 'completed',
144
+ reason: 'corpse_reported',
145
+ summary: 'reported',
146
+ },
147
+ });
148
+
149
+ expect(result?.continuation).toEqual({
150
+ delegatedBehavior: expect.objectContaining({
151
+ activationId: 'short-1',
152
+ behavior: 'report_corpse',
153
+ outcome: 'completed',
154
+ }),
155
+ });
156
+ expect(Object.isFrozen(result?.continuation)).toBe(true);
157
+ expect(Object.isFrozen(result?.continuation?.delegatedBehavior)).toBe(true);
158
+ });
159
+
138
160
  it('gives Behavior and Perception the same canonical Game State for one frame', () => {
139
161
  const value = runtimeInput();
140
162
  const behavior = createBehaviorInput(value, {});
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ BehaviorContinuation,
2
3
  BehaviorInput,
3
4
  GameEvent,
4
5
  GameState,
@@ -47,6 +48,7 @@ export function createBehaviorInput<
47
48
  >(
48
49
  input: RuntimeEpochPluginInput<Record<string, any>>,
49
50
  behaviorInput: TInput,
51
+ continuation?: Readonly<BehaviorContinuation>,
50
52
  ): BehaviorInput<TInput> | null {
51
53
  const runtimeState = input.epoch.state;
52
54
  if (!isClawclawRuntimeState(runtimeState) || runtimeState.game_snapshot.status !== 'fresh') {
@@ -66,5 +68,6 @@ export function createBehaviorInput<
66
68
  gameState,
67
69
  events: behaviorEvents(input),
68
70
  input: structuredClone(behaviorInput),
71
+ ...(continuation === undefined ? {} : { continuation: structuredClone(continuation) }),
69
72
  });
70
73
  }
@@ -2,9 +2,14 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import { describe, expect, it, vi } from 'vitest';
5
+ import {
6
+ presentCanonicalEventForCclEvents,
7
+ presentCanonicalEventForDesktop,
8
+ } from '../../pipeline/canonical-event-presentation.js';
5
9
  import { gameStartRuntimePath } from '../owner-control.js';
6
10
  import {
7
11
  channelOwnerDeliveryPolicy,
12
+ ownerAgentEventPresenter,
8
13
  performOwnerAgentAction,
9
14
  publishOwnerRuntimePointer,
10
15
  roleFallbackBehaviors,
@@ -56,6 +61,17 @@ describe('Channel owner delivery policy', () => {
56
61
  });
57
62
  });
58
63
 
64
+ describe('Owner Agent Event presentation', () => {
65
+ it('sanitizes both Desktop IPC delivery and Desktop-host ccl events', () => {
66
+ expect(ownerAgentEventPresenter('desktop_ipc', true))
67
+ .toBe(presentCanonicalEventForDesktop);
68
+ expect(ownerAgentEventPresenter('ccl_events', true))
69
+ .toBe(presentCanonicalEventForDesktop);
70
+ expect(ownerAgentEventPresenter('ccl_events', false))
71
+ .toBe(presentCanonicalEventForCclEvents);
72
+ });
73
+ });
74
+
59
75
  describe('owner direct Agent Action handoff', () => {
60
76
  it('does not disturb Behavior control when a delayed Action belongs to a stale scope', async () => {
61
77
  const runtime = {