@myclaw163/clawclaw-cli 0.8.41 → 0.9.1

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 (49) hide show
  1. package/README.md +5 -3
  2. package/docs/custom-modules/README.md +12 -16
  3. package/docs/custom-modules/api-reference.md +56 -3
  4. package/docs/custom-modules/behavior.md +6 -0
  5. package/docs/custom-modules/examples/first-sighting-v3.ts +29 -0
  6. package/docs/custom-modules/perception.md +139 -58
  7. package/docs/custom-modules/trigger.md +2 -0
  8. package/docs/runtime/README.md +17 -8
  9. package/docs/runtime/agent-notifications.md +32 -15
  10. package/docs/runtime/behavior-runtime.md +28 -21
  11. package/docs/runtime/components-and-boundaries.md +57 -17
  12. package/docs/runtime/events-and-state.md +42 -2
  13. package/docs/runtime/owner-lifecycle-and-observability.md +5 -3
  14. package/docs/user-guide/README.md +50 -0
  15. package/docs/user-guide/api-reference.md +760 -0
  16. package/docs/user-guide/behavior.md +369 -0
  17. package/docs/user-guide/installation.md +123 -0
  18. package/docs/user-guide/perception.md +869 -0
  19. package/docs/user-guide/skill.md +67 -0
  20. package/package.json +4 -2
  21. package/skills/clawclaw/SKILL.md +4 -4
  22. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  23. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +6 -0
  24. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +56 -3
  25. package/skills/clawclaw/references/CUSTOM-MODULES.md +12 -16
  26. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +139 -58
  27. package/src/commands/load.ts +13 -11
  28. package/src/commands/perception.ts +2 -2
  29. package/src/commands/trigger.ts +1 -1
  30. package/src/lib/agent-workspace-sync.ts +2 -2
  31. package/src/runtime/clawclaw/owner.ts +3 -2
  32. package/src/runtime/clawclaw/perception-module-manifest.ts +27 -0
  33. package/src/runtime/clawclaw/plugins/assembly.ts +17 -5
  34. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +28 -0
  35. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  36. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +21 -0
  37. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +47 -12
  38. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +2 -2
  39. package/src/runtime/clawclaw/task-choice-projection.ts +19 -25
  40. package/src/runtime/clawclaw-event-catalog.ts +5 -2
  41. package/src/sdk/behavior-plugin/index.ts +3 -0
  42. package/src/sdk/index.ts +4 -0
  43. package/src/sdk/module-input/index.ts +15 -1
  44. package/src/sdk/perception-plugin/index.ts +25 -8
  45. package/src/sdk/perception-plugin/module.ts +46 -0
  46. package/src/sdk/perception-plugin/reaction.ts +1 -0
  47. package/src/sdk/perception-plugin/reminder.ts +1 -0
  48. package/src/sdk/task-availability.ts +70 -0
  49. package/src/sdk/trigger-plugin/index.ts +1 -0
@@ -0,0 +1,760 @@
1
+ # 自定义模块公共 API 参考
2
+
3
+ 这是一份查接口、字段和约束的参考手册,不重复讲模块生命周期、执行模式选择或完整开发流程。需要教程时分别阅读:
4
+
5
+ - [开发策略](./behavior.md)
6
+ - [感知开发总览](./perception.md)
7
+ - [视觉感知](./perception.md#视觉感知)、[提醒型感知](./perception.md#提醒型感知)、[反应型感知](./perception.md#反应型感知)
8
+ - [自定义模块总览](./README.md)
9
+
10
+ 本文按模块组织;每个模块内部依次说明 Runtime 主动输入、只读查询 API、允许输出和 Manifest。策略与感知共用的数据结构统一放在文末。
11
+
12
+ | 模块 | Runtime 主动输入 | 只读查询 | 允许输出 |
13
+ |---|---|---|---|
14
+ | 策略 | 当前 `GameState`、待处理 Event、Activation 参数 | 地图、路径距离、最近观察 | Action、Status、自定义 Event、结束结果 |
15
+ | 视觉感知 | `ObservationFrame` | 静态地图 | 视觉事件 |
16
+ | 提醒型感知 | 当前状态、可见帧、订阅事实、任务变化、配置和私有 state | 无查询 API | 任务或附近发言提醒、下一轮私有 state |
17
+ | 反应型感知 | 当前状态、可见帧、订阅事件、配置和私有 state | 无查询 API | 自己的通知、固定策略激活请求、下一轮私有 state |
18
+
19
+ 所有输入和查询结果都是当前回调内的只读值。任何模块都不能直接修改权威 `GameState`。
20
+
21
+ ### 完整任务与当前可用性
22
+
23
+ `you.tasks` 是自己完整的当前分配列表。冷却中、暂被紧急事件阻止、正在执行和已完成的任务都可能在列表里;只有服务端真正移除分配时才消失。地图任务点只是空间资料,不能作为个人分配列表。
24
+
25
+ 每项任务的 `kind` 为 `ordinary / fake_shrimp / sabotage / emergency`;执行状态 `status` 仍为 `normal / in_progress / completed`。CCL 的只读投影另外附带 `availability`,Agent 的 `ccl events` 和策略读取相同的可用性:
26
+
27
+ | availability.state | 含义与处理 |
28
+ |---|---|
29
+ | `ready` | 当前已知条件允许选为任务目标;仍须前往任务点 |
30
+ | `cooldown` | 共享破坏冷却;已知时提供 `remaining_secs`,可规划或等待,不提交任务 |
31
+ | `blocked` | 紧急事件、死亡、非游荡阶段、任务已移除等阻止开始,原因在 `reason` |
32
+ | `in_progress` | 正在执行,跟踪后续权威完成/中断,不重复提交 |
33
+ | `completed` | 已完成,跳过 |
34
+ | `unknown` | 玩家、任务或破坏准入状态缺失,等待新状态,不能当成已就绪 |
35
+
36
+ 统一判断从公共 SDK 导入:
37
+
38
+ ```ts
39
+ import {
40
+ getAvailableTasks, getTaskAvailability, isTaskAvailable,
41
+ } from '@myclaw163/clawclaw-cli/behavior-plugin';
42
+
43
+ const allTasks = input.gameState.you?.tasks; // 保留完整任务,可做后续规划
44
+ const candidates = getAvailableTasks(input.gameState); // 仅当前 ready 的个人任务
45
+ const availability = getTaskAvailability(input.gameState, '投放毒药');
46
+ if (availability.state === 'cooldown') {
47
+ const remaining = availability.remaining_secs; // 未提供时是未知,不是 0
48
+ }
49
+ // 保存过目标时,每轮用当前快照重查,不能缓存“可用”或自行递减倒计时。
50
+ const maySelect = candidates[0] && isTaskAvailable(input.gameState, candidates[0]);
51
+ ```
52
+
53
+ `getTaskAvailability(state, taskOrName)` 接受任务对象、任务名称或任务 ID;返回 `{ state, reason?, remaining_secs? }`,重新按当前分配和共享状态判断,不信任旧对象上的 availability。`getAvailableTasks(state)` 返回只读任务数组,不修改 `you.tasks`。`isTaskAvailable(state, taskOrName)` 仅在 `ready` 时返回 true。公共根入口也导出这些方法和 `GameTaskAvailability / GameTaskKind` 类型。
54
+
55
+ `normal` 不表示冷却结束;蟹方共享状态仍来自 `crab_sabotage.status` 和 `cooldown_remaining_secs`。倒计时使用最新权威快照,不每秒生成提醒。目标在途中被队友触发的紧急事件阻止时,立即停止任务提交、重新选取可用目标或等待;未知状态同样不提交。
56
+
57
+ `ready` 不保证动作一定成功:距离、路径、队友占用等最终执行条件仍由 Action/服务端校验。任务动作只提交一次,之后从权威 State/Event 确认结果,不能每帧重复请求。未使用这些判断的第三方旧脚本需要修改,恢复完整列表不会自动修正它的选任务逻辑。
58
+
59
+ ## 统一感知 API v3
60
+
61
+ 从公开 perception-plugin 入口导入 ClawclawPerception、PerceptionModuleInput、PerceptionModuleResult、PerceptionModuleEvent 和 PerceptionModuleManifest;版本常量为 PERCEPTION_MODULE_API_VERSION=3。新脚本没有三选一的 kind,通过同一个 evaluate(input) 组合观察、通知和固定策略激活。
62
+
63
+ Manifest 的必需项为 apiVersion:3、id、description;可选 name、localizations、consumes、produces、behaviors、inputs、config。输入包含 moduleId、scope、gameState、frame、events、taskChanges、boundary、nowMs、config、state、availableBehaviors。frame/gameState 可以为 null;events 只含订阅的源/系统事实,taskChanges 独立来自 Source 对任务列表的比较。
64
+
65
+ 结果为 { state?, events?, activations? }。events 项为 { type, key, wakeAgent?, payload },type 必须在 produces 中声明,key 是稳定发生标识,wakeAgent 省略为 true。false 不独立唤醒且保留事件;不生成事件表示没有这条通知。事件类型的可见范围仍受 Catalog 和配置约束,模块不能重写原始事件或其他模块的通知。
66
+
67
+ behaviors 使用固定 key 声明 name、可选 resourceId、layer、input、reflexPriority、cooldownMs、rearm 和 maxRuntimeMs;activations 项引用 { behavior, input?, reason? }。layer 默认 reflex,可指定 short/long。目标按 Hub ID 优先、同名和别名兜底解析;依赖缺失只影响对应绑定。激活不等于动作完成。
68
+
69
+ 每次计算使用 fresh 实例,跨回调状态必须从 input.state 读取并作为结果 state 返回,由 Host 检查点恢复。新脚本不能订阅其他感知、Behavior 或 decision 输出;运行时还按 producerPluginId 过滤,只接纳 Source/后端和系统派生事实。produces 不能冒充系统保留类型;reminder.task/reminder.speech 是兼容通知输出,不是权威任务事实。
70
+
71
+ API v2 的三种旧作者契约继续兼容,以下旧接口章节仍适用于它们;后续可能停止支持。独立 Trigger 也仅保留兼容用途,后续可能停止支持。完整 v3 文件、安装与通知说明见感知教程开头。
72
+
73
+
74
+ ## 策略 API
75
+
76
+ 导入入口与当前版本:
77
+
78
+ ```ts
79
+ import {
80
+ BEHAVIOR_PLUGIN_API_VERSION,
81
+ ClawclawBehavior,
82
+ } from '@myclaw163/clawclaw-cli/behavior-plugin';
83
+
84
+ // BEHAVIOR_PLUGIN_API_VERSION === 3
85
+ ```
86
+
87
+ ### Runtime 输入:`BehaviorInput<TInput>`
88
+
89
+ ```ts
90
+ interface BehaviorInput<TInput extends Readonly<Record<string, unknown>>> {
91
+ readonly epochId: number;
92
+ readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
93
+ readonly nowMs: number;
94
+ readonly gameState: Readonly<GameState>;
95
+ readonly events: readonly Readonly<GameEvent>[];
96
+ readonly input: Readonly<TInput>;
97
+ readonly continuation?: Readonly<BehaviorContinuation>;
98
+ }
99
+ ```
100
+
101
+ | 字段 | 含义 |
102
+ |---|---|
103
+ | `epochId` | Runtime 输入序号;不是后端游戏 tick |
104
+ | `scope` | 当前 Runtime session 与 segment |
105
+ | `nowMs` | Runtime 接受本轮输入的时间,适合确定性的超时计算 |
106
+ | `gameState` | 当前玩家视角的权威 GameSync 快照 |
107
+ | `events` | 该 Activation 尚未消费的有序 Event 片段 |
108
+ | `input` | 按 Manifest 校验并经可选 `normalize()` 处理后的 Activation 参数 |
109
+ | `continuation` | 仅 long 委派的 short 结束并恢复后出现一次;包含 Runtime 生成的 child 终态 |
110
+
111
+ `events` 在策略真正执行一轮时才消费;因 `everyTicks` 跳过的输入不会丢失 Event。
112
+
113
+ ### 查询:`BehaviorReadApi`
114
+
115
+ ```ts
116
+ interface BehaviorReadApi {
117
+ readonly spatial: SpatialApi;
118
+ readonly navigation: {
119
+ pathDistance(from: Readonly<Position>, to: Readonly<Position>): Promise<number | null>;
120
+ pathDistances(
121
+ queries: readonly Readonly<{ from: Readonly<Position>; to: Readonly<Position> }>[]
122
+ ): Promise<readonly (number | null)[]>;
123
+ };
124
+ readonly observation: {
125
+ lastSeenPlayer(targetSeat: number, maxAgeMs?: number):
126
+ Readonly<ObservedPlayer> | undefined;
127
+ lastSeenCorpse(targetSeat?: number):
128
+ Readonly<ObservedCorpse> | undefined;
129
+ };
130
+ }
131
+ ```
132
+
133
+ #### `api.spatial`
134
+
135
+ ```ts
136
+ interface SpatialApi {
137
+ readonly xPositive: 'right';
138
+ readonly yPositive: 'down';
139
+ readonly playerBodyLengthPx: number;
140
+ readonly rooms: readonly Readonly<SpatialRoom>[];
141
+ roomAt(x: number, y: number): Readonly<SpatialRoom> | null;
142
+ sideInRoom(position: Readonly<SpatialPosition>): string | null;
143
+ placeLabel(position: Readonly<SpatialPosition>): string;
144
+ transitionIsMapped(from: string | null, to: string | null): boolean;
145
+ }
146
+
147
+ interface SpatialPosition extends Position {
148
+ readonly room: string | null;
149
+ }
150
+
151
+ interface SpatialRoom {
152
+ readonly name: string;
153
+ readonly polygon: readonly (readonly [number, number])[];
154
+ readonly bbox: Readonly<{ left: number; top: number; right: number; bottom: number }>;
155
+ }
156
+ ```
157
+
158
+ 这组接口只提供静态地图事实与确定性的空间派生,不会暴露隐藏玩家或其他动态状态。
159
+
160
+ #### `api.navigation.pathDistance()`
161
+
162
+ ```ts
163
+ const distance = await api.navigation.pathDistance(from, to);
164
+ ```
165
+
166
+ - `from`、`to`:`{ x: number, y: number }`;
167
+ - 返回本地导航网格的路径距离;不可达或无法求值时返回 `null`;
168
+ - 结果不承诺等于服务器最终路线,也不包含玩家等动态障碍。
169
+
170
+ #### `api.navigation.pathDistances()`
171
+
172
+ ```ts
173
+ const distances = await api.navigation.pathDistances([
174
+ { from, to: targetA },
175
+ { from, to: targetB },
176
+ ]);
177
+ ```
178
+
179
+ 批量结果与查询数组一一对应;每一项都是 `number | null`。
180
+
181
+ #### `api.observation.lastSeenPlayer()`
182
+
183
+ ```ts
184
+ interface ObservedPlayer extends Position {
185
+ readonly name: string;
186
+ readonly seat: number;
187
+ readonly room?: string;
188
+ readonly distance?: number;
189
+ readonly isAlive?: boolean;
190
+ readonly observedAtMs: number;
191
+ readonly ageMs: number;
192
+ }
193
+
194
+ const player = api.observation.lastSeenPlayer(targetSeat, maxAgeMs);
195
+ ```
196
+
197
+ - `targetSeat`:`1..10` 的数字座位;
198
+ - `maxAgeMs`:可选的最大观察年龄;
199
+ - 没有符合条件的记录时返回 `undefined`。
200
+
201
+ #### `api.observation.lastSeenCorpse()`
202
+
203
+ ```ts
204
+ interface ObservedCorpse extends Position {
205
+ readonly id: string;
206
+ readonly name?: string;
207
+ readonly seat?: number;
208
+ readonly room?: string;
209
+ readonly distance?: number;
210
+ readonly observedAtMs: number;
211
+ readonly ageMs: number;
212
+ }
213
+
214
+ const corpse = api.observation.lastSeenCorpse(targetSeat);
215
+ ```
216
+
217
+ 省略 `targetSeat` 时返回最近观察到的尸体;没有记录时返回 `undefined`。最近观察是历史事实,使用前必须结合 `ageMs` 与当前 `gameState` 复核。
218
+
219
+ ### 输出:`BehaviorDecision`
220
+
221
+ ```ts
222
+ interface BehaviorDecision {
223
+ readonly actions?: readonly Readonly<GameAction>[];
224
+ readonly status?: Readonly<BehaviorStatus>;
225
+ readonly events?: readonly Readonly<BehaviorEventProposal>[];
226
+ readonly delegate?: Readonly<BehaviorDelegation>;
227
+ readonly finish?: Readonly<BehaviorFinish>;
228
+ }
229
+ ```
230
+
231
+ 五个字段都可省略。返回 `undefined` 或空对象表示本轮没有新效果,不会自动结束 Activation。Decision 不接受未声明字段,并且必须能被 `structuredClone`。
232
+
233
+ #### Action 通用规则
234
+
235
+ - 每个 Action 都可带可选的 `thinking_content?: string`;
236
+ - Action 只是一项请求,仍会经过控制权、阶段、角色和安全检查;
237
+ - 未列出的字段会被拒绝,不会透传给后端;
238
+ - 玩家控制目标只使用数字座位,不使用姓名;
239
+ - 策略不读取 HTTP ACK 或 Action receipt,应通过后续权威 State/Event 判断业务目标是否完成。
240
+
241
+ #### `move`:移动到房间
242
+
243
+ ```ts
244
+ {
245
+ action: 'move',
246
+ target: '控制室',
247
+ stop_on_player: true,
248
+ thinking_content: '前往控制室',
249
+ }
250
+ ```
251
+
252
+ `target` 必须是非空房间名;不能同时提供 `target_x`、`target_y`。
253
+
254
+ #### `move`:移动到坐标
255
+
256
+ ```ts
257
+ {
258
+ action: 'move',
259
+ target_x: 640,
260
+ target_y: 360,
261
+ stop_on_player: false,
262
+ thinking_content: '靠近目标位置',
263
+ }
264
+ ```
265
+
266
+ `target_x`、`target_y` 必须同时存在且为有限数字;不能同时提供 `target`。
267
+
268
+ #### `kill`
269
+
270
+ ```ts
271
+ {
272
+ action: 'kill',
273
+ target_seat: 3,
274
+ thinking_content: '攻击 3 号',
275
+ }
276
+ ```
277
+
278
+ `target_seat` 必须是 `1..10` 的整数。策略应先自行追踪目标、复核可见性、距离、角色能力和冷却,再提交击杀请求,并从后续 State/Event 确认结果。
279
+
280
+ #### `speech`
281
+
282
+ ```ts
283
+ {
284
+ action: 'speech',
285
+ text: '我在控制室看到可疑移动。',
286
+ thinking_content: '分享观察',
287
+ }
288
+ ```
289
+
290
+ `text` 必须是非空字符串。
291
+
292
+ #### `task`
293
+
294
+ ```ts
295
+ { action: 'task' }
296
+ // 或
297
+ { action: 'task', task_name: '校准航行路线' }
298
+ ```
299
+
300
+ `task_name` 可省略;提供时必须是非空字符串。任务开始不等于完成,完成条件应读取任务状态或 `task_completed` Event。蟹破坏任务同样使用 `task`:完成后服务端自动触发对应紧急任务;被队友打断时会收到私有 `task_interrupted`。
301
+
302
+ #### `report`
303
+
304
+ ```ts
305
+ { action: 'report' }
306
+ ```
307
+
308
+ `report` 没有目标字段;后端报告当前范围内可报告的尸体。策略可用尸体座位选择导航目标,但不能把座位或姓名放进 Action payload。
309
+
310
+ #### `think`
311
+
312
+ ```ts
313
+ { action: 'think', thinking_content: '等待更多信息' }
314
+ ```
315
+
316
+ 独立 `trigger_alarm` 动作已移除。旧代码应改为在 `GameCrabSabotage.status === 'ready'` 时提交自己持有的破坏任务;不要在任务完成后再请求第二个动作。
317
+
318
+ 会议投票不属于 `GameAction`。Agent 或用户在会议阶段使用现有 `ccl vote`,由 Action Plugin 直接提交后端;策略不预占 `meeting_vote` 控制域。
319
+
320
+ #### `BehaviorStatus`
321
+
322
+ ```ts
323
+ interface BehaviorStatus {
324
+ readonly summary: string;
325
+ readonly activity?: string;
326
+ readonly room?: string;
327
+ readonly task?: string;
328
+ readonly targetPlayer?: string;
329
+ readonly data?: Readonly<Record<string, unknown>>;
330
+ }
331
+ ```
332
+
333
+ `summary` 必须是非空字符串,其余文本字段提供时也必须非空。Status 会发布到 Runtime 的 `behavior.status` 视图;它不是 `GameState` patch,也不是模块私有持久化存储。
334
+
335
+ #### `BehaviorEventProposal`
336
+
337
+ ```ts
338
+ interface BehaviorEventProposal {
339
+ readonly type: string;
340
+ readonly payload: Readonly<Record<string, unknown>>;
341
+ readonly occurredAt?: string;
342
+ }
343
+ ```
344
+
345
+ `type` 必须先列在 `manifest.produces` 中;`payload` 必须是普通 JSON 对象。Event 应表示模块已经确认成立的事实。
346
+
347
+ #### `BehaviorDelegation`
348
+
349
+ ```ts
350
+ interface BehaviorDelegation {
351
+ readonly behavior: string;
352
+ readonly input?: Readonly<Record<string, unknown>>;
353
+ }
354
+ ```
355
+
356
+ 只有当前 long Activation 可以使用 `delegate` 启动一个 short。Runtime 会先通过策略 Catalog 校验目标与输入,再改变控制栈。`delegate` 不能与 `actions` 或 `finish` 同时返回;short 使用会让当前 Activation failed。委派 short 的终态通过 long 恢复后的 `continuation.delegatedBehavior` 一次性返回。
357
+
358
+ #### `BehaviorFinish`
359
+
360
+ ```ts
361
+ interface BehaviorFinish {
362
+ readonly outcome: 'completed' | 'failed';
363
+ readonly reason: string;
364
+ readonly summary?: string;
365
+ }
366
+ ```
367
+
368
+ `reason` 必须是非空、稳定、适合程序判断的原因。Runtime 不允许同一 Decision 同时首次提交 Action 并 `finish` 或 `delegate`;应先请求 Action,再在后续权威输入确认目标后结束或委派。
369
+
370
+ ### Manifest:`ClawclawBehaviorManifest`
371
+
372
+ 首次自动上传 Hub 时,默认展示名称取脚本 `id`,默认展示描述取脚本 `description`,分别按 Hub 的 50/600 字符限制截取。之后 Hub 名称、描述独立维护,CCL 随装配版本缓存,用于人类界面和当前策略上报;修改脚本说明不会覆盖 Hub 文案。`ccl load` 和模块详情仍向 Agent 提供脚本描述。本地尚未上传或离线时使用本地登记、缓存的展示信息。新脚本无需填写模块级 `name`,已有脚本仍可读取;感知事件的 `eventMetadata.name`、参数说明和玩家名字不受影响。
373
+
374
+ | 字段 | 类型 | 约束 |
375
+ |---|---|---|
376
+ | `apiVersion` | `3` | 必须等于 `BEHAVIOR_PLUGIN_API_VERSION` |
377
+ | `id` | `string` | 稳定且唯一 |
378
+ | `description` | `string` | 非空的 Agent 能力说明 |
379
+ | `name` | `string`,可选 | 兼容已有脚本;新脚本省略,展示信息由 CCL 管理 |
380
+ | `localizations` | object,可选 | 兼容已有脚本的模块文案;人类展示优先采用本地登记或 Hub 下发的文案 |
381
+ | `inputs` | `BehaviorInputFieldSpec[]` | Activation 参数 schema |
382
+ | `execution` | `'parallel' \| 'serial'`,可选 | 省略为 parallel |
383
+ | `stateMode` | `'isolated' \| 'snapshot'`,可选 | 默认 isolated;snapshot 仅支持 parallel,继承同一 activation 内已完成计算的实例快照,不跨进程持久恢复 |
384
+ | `everyTicks` | `number`,可选 | 正整数;第一次 eligible tick 总会运行 |
385
+ | `produces` | `string[]`,可选 | 允许发布的自定义 Event type |
386
+ | `runtime` | `BehaviorRuntimeDefaults`,可选 | finite Activation 的默认运行预算 |
387
+
388
+ ```ts
389
+ interface BehaviorRuntimeDefaults {
390
+ readonly defaultMs: number;
391
+ readonly deadlineOutcome?: 'completed' | 'failed';
392
+ readonly controlGraceMs?: number;
393
+ }
394
+ ```
395
+
396
+ `defaultMs` 必须是 `1000..120000` 的安全整数;`controlGraceMs` 必须是 `0..30000` 的安全整数。
397
+
398
+ ### 参数字段:`BehaviorInputFieldSpec`
399
+
400
+ 每个字段都必须包含 `id`、`type` 和非空 `description`。`id` 必须匹配 `[A-Za-z][A-Za-z0-9_.-]{0,79}`。
401
+
402
+ | `type` | 值 | 可用约束 |
403
+ |---|---|---|
404
+ | `string` | 非空字符串 | `required`、`default` |
405
+ | `number` | 有限数字 | `required`、`default`、`min`、`max` |
406
+ | `boolean` | `true` / `false` | `required`、`default` |
407
+ | `enum` | `values` 中的字符串 | `required`、`default`、非空且不重复的 `values` |
408
+ | `string_list` | 字符串数组;每项非空 | `required`、`default`、`maxItems` |
409
+ | `player_seat` | `1..10` 的整数 | `required`、`default` |
410
+ | `player_seats` | 每项为 `1..10` 整数的数组 | `required`、`default`、`maxItems` |
411
+
412
+ `required: true` 不能同时声明 `default`。Runtime 不做字符串到数字等隐式转换;Activation 输入中的未知字段会被拒绝。
413
+ `string_list` 或 `player_seats` 标记为 required 时,数组本身也不能为空。
414
+
415
+ ### 可选参数整理:`BehaviorNormalizationApi`
416
+
417
+ `normalize(input, api)` 只在一次 Activation 启动前调用一次。它可以使用:
418
+
419
+ ```ts
420
+ interface BehaviorNormalizationApi {
421
+ readonly manifest: Readonly<ClawclawBehaviorManifest>;
422
+ timing(input: Readonly<Record<string, unknown>>):
423
+ { readonly timeout_ms?: number; readonly duration_ms?: number };
424
+ string(value: unknown, field: string): string;
425
+ optionalString(value: unknown, field: string): string | undefined;
426
+ number(
427
+ value: unknown,
428
+ field: string,
429
+ constraints?: Readonly<{ min?: number; max?: number; integer?: boolean }>,
430
+ ): number;
431
+ stringArray(
432
+ value: unknown,
433
+ field: string,
434
+ constraints?: Readonly<{ maxItems?: number }>,
435
+ ): readonly string[];
436
+ choice<T extends string>(value: unknown, field: string, values: readonly T[]): T;
437
+ }
438
+ ```
439
+
440
+ 这里没有动态 `GameState` 或 Action 能力;动态判断放在 `decide()` 中。
441
+
442
+ ## 感知 API
443
+
444
+ ### 反应型感知
445
+
446
+ 需要“检测条件后通知或启动策略”,使用 `ClawclawReaction`,完整可复制示例见[反应型感知教程](./perception.md#反应型感知)。它从 `@myclaw163/clawclaw-cli/perception-plugin` 导出,沿用感知 API v2 和本地/Hub 感知装配。
447
+
448
+ `manifest` 声明 `kind: 'reaction'`、`consumes`、`produces` 及 `behaviors`。每个绑定必填 `name`,可选 `resourceId`、`layer`、`input`、`reflexPriority`、`cooldownMs`、`rearm`、`maxRuntimeMs`。查找可用策略时优先 ID,再按同名操作名和重名别名选择;缺依赖只警告并跳过对应激活。
449
+
450
+ `evaluate(input)` 返回 `{ state?, events?, activations? }`。自己的通知是 `{ type, key, wakeAgent?, payload: { text, ... } }`,type 使用声明的 `reaction.*`;激活请求是 `{ behavior, input?, reason? }`,behavior 为绑定键。跨调用状态使用返回的 state 和下次的 input.state。当前帧与订阅事件对所有模块独立提供,不重写原事件、不排除其他模块。
451
+
452
+ 提醒型感知的主题、输入和输出见[提醒教程](./perception.md#提醒型感知)。以下字段介绍视觉感知类,对应[视觉教程](./perception.md#视觉感知)。
453
+
454
+ 导入入口与当前版本:
455
+
456
+ ```ts
457
+ import {
458
+ PERCEPTION_PLUGIN_API_VERSION,
459
+ ClawclawPerception,
460
+ ClawclawParallelPerception,
461
+ } from '@myclaw163/clawclaw-cli/perception-plugin';
462
+
463
+ // PERCEPTION_PLUGIN_API_VERSION === 2
464
+ ```
465
+
466
+ ### `PerceptionFrame`
467
+
468
+ `PerceptionFrame` 是共享 `ObservationFrame` 的类型别名,字段见[共享观察帧](#共享观察帧)。普通感知的入口是:
469
+
470
+ ```ts
471
+ update(
472
+ frame: Readonly<PerceptionFrame>,
473
+ api: PerceptionApi,
474
+ ): readonly PerceptionEventProposal[] | void | Promise<readonly PerceptionEventProposal[] | void>;
475
+ ```
476
+
477
+ 需要 Worker 分析时继承 `ClawclawParallelPerception<TAnalysis>`:
478
+
479
+ ```ts
480
+ interface PerceptionAnalysisInput {
481
+ readonly frame: Readonly<PerceptionFrame>;
482
+ readonly history: readonly Readonly<PerceptionFrame>[];
483
+ readonly gapBefore: boolean;
484
+ }
485
+
486
+ analyze(input: Readonly<PerceptionAnalysisInput>, api: PerceptionApi): TAnalysis | Promise<TAnalysis>;
487
+
488
+ commit(
489
+ frame: Readonly<PerceptionFrame>,
490
+ analysis: Readonly<TAnalysis>,
491
+ api: PerceptionApi,
492
+ ): readonly PerceptionEventProposal[] | void | Promise<readonly PerceptionEventProposal[] | void>;
493
+ ```
494
+
495
+ `history` 只包含旧帧,按时间升序且不包含当前 `frame`;整个窗口最多 10 帧。`gapBefore` 表示已存在前帧,但无法证明轨迹连续。执行模型与状态放置规则见[开发感知](./perception.md)。
496
+
497
+ ### 查询:`PerceptionApi`
498
+
499
+ ```ts
500
+ interface PerceptionApi {
501
+ readonly spatial: SpatialApi;
502
+ }
503
+ ```
504
+
505
+ `SpatialApi` 与策略的 `api.spatial` 相同。感知不提供 navigation 或 observation 查询;它应只根据当前/历史观察帧和静态地图形成视觉事实。
506
+
507
+ ### 输出:`PerceptionEventProposal`
508
+
509
+ ```ts
510
+ interface PerceptionEventProposal {
511
+ wakeAgent?: boolean; // 覆盖 Manifest 默认值;省略时继承,最终默认 true
512
+ readonly type: string;
513
+ readonly dedupeKey: string;
514
+ readonly dedupeScope?: 'segment' | 'session';
515
+ readonly payload: Readonly<Record<string, unknown>>;
516
+ readonly occurredAt?: string;
517
+ }
518
+ ```
519
+
520
+ | 字段 | 约束 |
521
+ |---|---|
522
+ | `type` | 非空,且必须列在 `manifest.produces` |
523
+ | `dedupeKey` | 当前语义片段的稳定、非空身份 |
524
+ | `dedupeScope` | 省略时为 `segment`;可显式选 `segment` 或 `session` |
525
+ | `payload` | 普通、可 clone 的 JSON 对象 |
526
+ | `occurredAt` | 可选的事件发生时间字符串 |
527
+
528
+ 感知不能返回 Action、Status、State patch 或策略 Activation。
529
+
530
+ ### 边界回调
531
+
532
+ ```ts
533
+ interface PerceptionBoundary {
534
+ readonly kind:
535
+ | 'events_requested'
536
+ | 'phase_changed'
537
+ | 'trajectory_gap'
538
+ | 'segment_ending'
539
+ | 'shutdown';
540
+ readonly mode: 'snapshot' | 'close';
541
+ readonly through: Readonly<PerceptionFrame> | null;
542
+ }
543
+
544
+ flush?(boundary: Readonly<PerceptionBoundary>, api: PerceptionApi):
545
+ readonly PerceptionEventProposal[] | void | Promise<readonly PerceptionEventProposal[] | void>;
546
+
547
+ reset?(reason: 'phase_changed' | 'trajectory_gap' | 'segment_ending' | 'shutdown' | 'replay'):
548
+ void | Promise<void>;
549
+
550
+ debugSnapshot?(): unknown;
551
+ ```
552
+
553
+ `flush()` 只在 Runtime 要求报告未关闭的长语义片段时调用;`debugSnapshot()` 仅进入诊断和离线 replay,不会成为 Agent Event。
554
+
555
+ ### Manifest:`ClawclawPerceptionManifest`
556
+
557
+ | 字段 | 类型 | 约束 |
558
+ |---|---|---|
559
+ | `apiVersion` | `2` | 必须等于 `PERCEPTION_PLUGIN_API_VERSION` |
560
+ | `id` | `string` | 稳定的模块 ID |
561
+ | `description` | `string` | 非空的 Agent 能力说明 |
562
+ | `name` | `string`,可选 | 兼容已有脚本;新脚本省略,展示信息由 CCL 管理 |
563
+ | `localizations` | object,可选 | 兼容已有脚本的模块文案;人类展示优先采用本地登记或 Hub 下发的文案 |
564
+ | `subjectScope` | `'others' \| 'self_and_others' \| 'visible_pairs' \| 'corpses'` | 描述 Event 主体范围 |
565
+ | `produces` | `string[]` | 允许输出的 Event type |
566
+ | `wakeAgent` | boolean,可选 | 模块默认是否主动唤醒 Agent,省略为 true;单条 proposal 可覆盖 |
567
+ | `eventMetadata` | object,可选 | 每种 Event 的名称、说明和本地化 |
568
+ | `execution` | `'parallel_analysis'`,可选 | 启用 `analyze/commit` 接口 |
569
+ | `boundaryBaseline` | `'current_only'`,可选 | 声明边界重建能力 |
570
+
571
+ ## 共享数据结构
572
+
573
+ ### 基础引用
574
+
575
+ ```ts
576
+ interface Position {
577
+ readonly x: number;
578
+ readonly y: number;
579
+ }
580
+
581
+ interface PlayerRef {
582
+ readonly seat: number;
583
+ readonly name: string;
584
+ }
585
+ ```
586
+
587
+ 业务身份与控制目标使用 `seat`;`name` 只用于展示。
588
+
589
+ ### `GameState`
590
+
591
+ ```ts
592
+ interface GameState {
593
+ readonly game_id: string;
594
+ readonly tick: number;
595
+ readonly phase?: 'preparing' | 'wandering' | 'meeting' | 'game_over';
596
+ readonly you?: Readonly<GameSelf>;
597
+ readonly players?: readonly Readonly<KnownPlayer>[];
598
+ readonly visible_players?: readonly Readonly<VisiblePlayer>[];
599
+ readonly visible_corpses?: readonly Readonly<VisibleCorpse>[];
600
+ readonly task_progress?: Readonly<{ completed: number; goal: number }>;
601
+ readonly emergency?: Readonly<GameEmergency>;
602
+ readonly crab_sabotage?: Readonly<GameCrabSabotage>;
603
+ readonly meeting?: Readonly<GameMeeting>;
604
+ readonly octopus_time?: Readonly<GameOctopusTime>;
605
+ readonly winner?: Readonly<GameWinner>;
606
+ readonly settlement?: Readonly<Record<string, unknown>>;
607
+ }
608
+ ```
609
+
610
+ 除 `game_id` 和 `tick` 外,字段可能因阶段、角色权限或降级输入而缺失。缺失表示当前快照没有提供该事实,不等于 `false`、空数组或全场不存在。
611
+
612
+ #### `GameSelf`
613
+
614
+ | 字段 | 类型 |
615
+ |---|---|
616
+ | `player` | `PlayerRef` |
617
+ | `x` / `y` | `number` |
618
+ | `room` / `role` / `faction` | `string` |
619
+ | `is_alive` | `boolean` |
620
+ | `completed_task_count` | `number` |
621
+ | `kill_cooldown_secs` | `number` |
622
+ | `kills_remaining` | `number \| null` |
623
+ | `activity` | `GamePlayerActivity` |
624
+ | `crab_teammates` | `PlayerRef[]` |
625
+ | `tasks` | `GameTask[]` |
626
+
627
+ 所有字段都可缺失。`GamePlayerActivity.kind` 为 `idle | moving | task`,并可带 `task_name`、`remaining_secs`、`target_x`、`target_y`。
628
+
629
+ #### `GameTask`
630
+
631
+ | 字段 | 类型 | 是否必有 |
632
+ |---|---|:---:|
633
+ | `task_id` | `string` | |
634
+ | `name` / `room` | `string` | ✓ |
635
+ | `x` / `y` | `number` | ✓ |
636
+ | `is_fake_shrimp` | `boolean` | ✓ |
637
+ | `status` | `'normal' \| 'in_progress' \| 'completed'` | |
638
+ | `task_note` | `string` | |
639
+
640
+ #### 玩家与尸体
641
+
642
+ ```ts
643
+ interface KnownPlayer extends PlayerRef {
644
+ readonly known_status: {
645
+ readonly is_alive?: boolean;
646
+ readonly death_cause?: 'killed' | 'exiled';
647
+ readonly killer?:
648
+ | { readonly kind: 'player'; readonly player: Readonly<PlayerRef> }
649
+ | { readonly kind: 'system'; readonly name: string };
650
+ readonly reported_in_current_meeting?: boolean;
651
+ };
652
+ readonly tier?: string;
653
+ readonly tier_display?: string;
654
+ }
655
+
656
+ interface VisiblePlayer extends Position {
657
+ readonly player: Readonly<PlayerRef>;
658
+ readonly room: string;
659
+ readonly distance?: number;
660
+ readonly is_alive?: boolean;
661
+ }
662
+
663
+ interface VisibleCorpse extends Position {
664
+ readonly corpse_id: string;
665
+ readonly player?: Readonly<PlayerRef>;
666
+ readonly room: string;
667
+ readonly distance?: number;
668
+ }
669
+ ```
670
+
671
+ `players` 是当前有权知道的 roster/公开状态;`visible_players` 和 `visible_corpses` 才是当前真正可见对象。
672
+
673
+ #### 紧急、会议与终局
674
+
675
+ | 类型 | 字段 |
676
+ |---|---|
677
+ | `GameEmergency` | `active`;可选 `task_name`、`room`、`x`、`y`、`remaining_secs` |
678
+ | `GameCrabSabotage` | `status`;可选 `cooldown_remaining_secs` |
679
+ | `GameMeeting` | `active`;可选 `sub_phase`、`caller`、`speech_order`、`current_speaker`、`deadline_at_ms`、`server_time_ms`、`speeches`、`speech_skipped`、`votes_submitted` |
680
+ | `GameOctopusTime` | `active`;可选 `remaining_secs` |
681
+ | `GameWinner` | faction 胜利,或带具体 `player`、`role` 的 neutral 胜利 |
682
+
683
+ `GameCrabSabotage.status` 可能为 `ready`、`cooldown_charged` 或 `emergency_active`。`ready` 表示可执行自己持有的蟹破坏任务,另外两个状态都不得发起新破坏。
684
+
685
+ ### 共享观察帧
686
+
687
+ ```ts
688
+ interface ObservationFrame {
689
+ readonly frameKey: string;
690
+ readonly frameSeq: number;
691
+ readonly tick: number;
692
+ readonly timeMs: number;
693
+ readonly tickDelta: number | null;
694
+ readonly continuousFromPrevious: boolean;
695
+ readonly gameState: Readonly<GameState>;
696
+ readonly observation: Readonly<VisualObservation>;
697
+ }
698
+
699
+ interface VisualObservation {
700
+ readonly players: readonly VisualPlayer[];
701
+ readonly corpses: readonly VisualCorpse[];
702
+ readonly visibleSetComplete: boolean;
703
+ }
704
+ ```
705
+
706
+ `frameSeq` 是 CCL State History 序号,不是游戏 tick。`visibleSetComplete: false` 时,某对象未出现在本帧不能被解释为已经离开视野。
707
+
708
+ ```ts
709
+ interface VisualPlayer {
710
+ readonly id: string;
711
+ readonly name?: string;
712
+ readonly seat?: number;
713
+ readonly observer: boolean;
714
+ readonly alive?: boolean;
715
+ readonly x: number;
716
+ readonly y: number;
717
+ readonly room: string | null;
718
+ }
719
+
720
+ interface VisualCorpse {
721
+ readonly id: string;
722
+ readonly playerId?: string;
723
+ readonly name?: string;
724
+ readonly seat?: number;
725
+ readonly x: number;
726
+ readonly y: number;
727
+ readonly room: string | null;
728
+ }
729
+ ```
730
+
731
+ ### `GameEvent`
732
+
733
+ ```ts
734
+ interface GameEvent {
735
+ readonly eventId: string;
736
+ readonly epochId?: number;
737
+ readonly type: string;
738
+ readonly occurredAt: string;
739
+ readonly payload: Readonly<Record<string, unknown>>;
740
+ }
741
+ ```
742
+
743
+ 按 `type` 和结构化 `payload` 判断业务含义,不要解析面向玩家的展示文案。Event payload 由生产者定义;模块必须只消费自己识别且已校验结构的 type。官方视觉 Event 的 type、公共 payload 字段和观察边界见[开发感知](./perception.md)。
744
+
745
+ ## 公共导入与约束
746
+
747
+ ```ts
748
+ import type {
749
+ BehaviorInput,
750
+ GameEvent,
751
+ GameState,
752
+ ObservationFrame,
753
+ } from '@myclaw163/clawclaw-cli/module-input';
754
+ ```
755
+
756
+ - 不要从包内 `src/...` 路径导入;它们不是公共 API;
757
+ - Manifest 关键字段必须是可静态扫描的字面量;
758
+ - 输入、输出和 Worker 分析值必须支持 `structuredClone`;
759
+ - 查询 API 只在当前回调活动期间有效,不要保存后延迟调用;
760
+ - 自定义模块是本机可信代码,不是安全沙箱,只安装可信来源。