@myclaw163/clawclaw-cli 0.10.15 → 0.10.16

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 (50) hide show
  1. package/README.md +1 -1
  2. package/cli-runtime/runtime/clawclaw/behavior-reflex-control.js +27 -36
  3. package/cli-runtime/runtime/clawclaw/behavior-trigger.js +25 -46
  4. package/cli-runtime/runtime/clawclaw/owner.js +7 -6
  5. package/cli-runtime/runtime/clawclaw/plugins/assembly.js +8 -7
  6. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-source.js +6 -5
  7. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-plugin.js +5 -2
  8. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-runner.js +2 -1
  9. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-worker.js +7 -1
  10. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-worker.ts +7 -1
  11. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-module-loader.js +7 -17
  12. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-plugin.js +3 -30
  13. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-thread-worker.js +0 -2
  14. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +0 -2
  15. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +58 -1
  16. package/docs/custom-modules/README.md +1 -2
  17. package/docs/custom-modules/api-reference.md +8 -10
  18. package/docs/custom-modules/behavior.md +21 -23
  19. package/docs/custom-modules/examples/auto-escape.ts +17 -19
  20. package/docs/custom-modules/perception.md +2 -2
  21. package/docs/runtime/README.md +1 -1
  22. package/docs/runtime/behavior-runtime.md +4 -5
  23. package/docs/runtime/components-and-boundaries.md +4 -5
  24. package/docs/runtime/events-and-state.md +1 -1
  25. package/docs/runtime/owner-lifecycle-and-observability.md +2 -2
  26. package/docs/user-guide/README.md +1 -1
  27. package/docs/user-guide/api-reference.md +8 -10
  28. package/docs/user-guide/behavior.md +21 -23
  29. package/docs/user-guide/perception.md +2 -2
  30. package/package.json +1 -1
  31. package/skills/clawclaw/SKILL.md +3 -3
  32. package/skills/clawclaw/references/BEHAVIORS.md +1 -1
  33. package/skills/clawclaw-creator/SKILL.md +1 -1
  34. package/skills/clawclaw-creator/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +21 -23
  35. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +8 -10
  36. package/skills/clawclaw-creator/references/CUSTOM-MODULES.md +1 -2
  37. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +2 -2
  38. package/src/runtime/clawclaw/behavior-reflex-control.ts +26 -22
  39. package/src/runtime/clawclaw/behavior-trigger.ts +20 -41
  40. package/src/runtime/clawclaw/owner.ts +7 -6
  41. package/src/runtime/clawclaw/plugins/assembly.ts +11 -8
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +7 -6
  43. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +6 -2
  44. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +2 -1
  45. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +7 -1
  46. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +1 -0
  47. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +8 -19
  48. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +4 -37
  49. package/src/runtime/clawclaw/plugins/trigger/trigger-source.ts +0 -2
  50. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +0 -2
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: clawclaw
3
3
  description: ClawClaw/龙虾杀的完整玩法 Skill,仅在游戏事件流接通后读取。开局或恢复连接之前不要读取本 Skill,此阶段只读取 clawclaw-start。start/join 成功接流后立即调用本 Skill,不必等待匹配完成或身份分配。用于处理实时游戏事件、角色行动、策略、会议发言与投票、结算和复盘。资源创作使用 clawclaw-creator。
4
- version: 4.8.132
4
+ version: 4.8.133
5
5
  ---
6
6
 
7
7
  # 龙虾杀完整玩法(接流后调用)
@@ -131,7 +131,7 @@ Runtime 使用固定优先级 `reflex > short > long`。服务端角色确定后
131
131
 
132
132
  Reaction 的 `strategies` 声明固定策略绑定:`name` 必填,使用操作名或同一源码重名组的原名;`resourceId` 可选,匹配不到时仍按名字找。只选当前已启用且可加载的策略:优先资源 ID,其次无后缀操作名,再选对应重名别名。两个同名 `escape` / `escape_1` 均不匹配 ID 时用 `escape`;用户 fork 后 ID 变化不应仅因此要求重绑。声明里的示例名称不证明账号已安装该策略,按 `ccl strategy list/info` 核对参数;不擅自自动下载安装依赖。
133
133
 
134
- 已装配的单文件策略在必填参数齐全时默认开启反射。用 ccl strategy status [id] 核对监听、缺参、冷却和实际执行。strategy watch/unwatch 控制本局监听,unwatch 同时取消关联 Reflex。strategy update 更新触发判断、现有执行和后续默认参数,保留 Activation ID 与原截止时间。仅修改一次执行时,指定 Activation ID 并加 --activation。换局或 Owner 退出时重置。
134
+ 单文件策略中的触发感知由 Perception 运行,装配后默认允许自动激活。用 ccl strategy status [id] 核对开关、冷却和实际执行。strategy watch/unwatch 控制本局自动激活,unwatch 同时取消关联 Reflex,感知继续观察。strategy update 更新触发判断、现有执行和后续默认参数,保留 Activation ID 与原截止时间。仅修改一次执行时,指定 Activation ID 并加 --activation。换局或 Owner 退出时重置。
135
135
 
136
136
  用户要求修改已安装策略源码时交给 `clawclaw-creator`;仅调整本局参数、开关或运行层仍使用本玩法技能。`ccl prepare` 不会热替换正在运行的 Owner。
137
137
 
@@ -187,7 +187,7 @@ Strategy manifest 中类型为 `player_seat` 或 `player_seats` 的输入只接
187
187
  6. `ccl strategy start` 输出只确认 `accepted`。等待 `behavior.completed`、`behavior.failed`、`behavior.cancelled` 或 `behavior.replaced` 再判断终态;中途确需进度时运行 `ccl strategy status`,不要把 status 忙轮询成新的主循环。`behavior.suspended` / `behavior.restarted` 表示高层抢占及新实例恢复,不是完成。
188
188
  7. 新事实改变目标时直接启动新的同层 Strategy(旧 Activation 会收到 `behavior.replaced`),或按 activation id 运行 `ccl strategy cancel <activation-id>`。取消只停止后续规划并释放本地控制权;已经交给 Action 模块的请求不能靠取消撤回,后端已接受的移动可能继续到目标。需要接管移动时启动新的移动类 Strategy,并以命令输出和随后权威 State/Event 确认结果。
189
189
  8. 在关键变化或用户关心时简短评论位置、当前目标、风险或下一步,不逐项重复汇报。需要改变空闲 fallback 时根据有效的 `list/info` 检查输入;当前 fallback 命令绑定空输入,因此有未满足必填输入的 Strategy 不适合作 fallback。用 `ccl strategy fallback set <id> --role <role>` 显式指定,`default --role <role>` 恢复当前角色默认值,`none --role <role>` 表示完全不使用 fallback。当前角色已确定时,成功的 Runtime 回执表示绑定已更新,会议中也可修改并立即用 `strategy status` 验证;会议期间暂停执行,会后按原规则恢复显式 long 或启动空栈 fallback。需要带动态输入持续运行时,直接重新 `start ... --layer long --input ...`,不要寻找已删除的热控制命令。
190
- 9. 自动反射由策略内置 Trigger 请求。本局使用 strategy watch/unwatch 切换监听,strategy update 修改触发和执行参数。跨层顺序 reflex > short > long,只有严格更高优先级的 Reflex 能替换当前 Reflex。
190
+ 9. 自动反射由策略内置 Trigger 请求。本局使用 strategy watch/unwatch 切换自动激活,strategy update 修改感知配置和策略输入。跨层顺序 reflex > short > long,只有严格更高优先级的 Reflex 能替换当前 Reflex。
191
191
 
192
192
  **游走发言分工:** 角色扮演、说服、指控、会议准备和面向用户的评论是 LLM 决策:`ccl speak` 用于玩家可见发言,`ccl aside` 用于仅用户/观战玩家可见叙述。
193
193
 
@@ -119,7 +119,7 @@ fallback 绑定当前固定传空输入。先用 `strategy info` 确认模块没
119
119
 
120
120
  ## 5. Reflex:策略内置 Trigger 请求及时抢占
121
121
 
122
- 已装配的单文件策略在必填参数齐全时默认开启反射。用 ccl strategy status [id] 核对监听、缺参、冷却和实际执行。strategy watch/unwatch 控制本局监听,unwatch 同时取消关联 Reflex。strategy update 更新触发判断、现有执行和后续默认参数,保留 Activation ID 与原截止时间。仅修改一次执行时,指定 Activation ID 并加 --activation。换局或 Owner 退出时重置。 创作源码使用 [clawclaw-creator](../../clawclaw-creator/SKILL.md)。
122
+ 单文件策略中的触发感知由 Perception 运行,装配后默认允许自动激活。用 ccl strategy status [id] 核对开关、冷却和实际执行。strategy watch/unwatch 控制本局自动激活,unwatch 同时取消关联 Reflex,感知继续观察。strategy update 更新触发判断、现有执行和后续默认参数,保留 Activation ID 与原截止时间。仅修改一次执行时,指定 Activation ID 并加 --activation。换局或 Owner 退出时重置。 创作源码使用 [clawclaw-creator](../../clawclaw-creator/SKILL.md)。
123
123
 
124
124
 
125
125
  ```powershell
@@ -22,7 +22,7 @@ metadata:
22
22
  | 教 Agent 分析、组织发言或执行一套流程 | Skill | [游戏 Skill](references/CUSTOM-SKILL-DEVELOPMENT.md) |
23
23
  | 玩家声音、性格和表达风格 | 人设 | [人设 Markdown](references/CUSTOM-PERSONA-DEVELOPMENT.md) |
24
24
 
25
- 精确字段与签名查 [API 参考](references/CUSTOM-MODULE-API.md),不要一次加载所有教程。自动反射在同一个策略文件中添加具名 Trigger,安装并启用一个 Strategy 资源。只需要修改当前局参数时,按现有模块的 manifest 使用 `ccl strategy update` / `ccl perception update`,不用新建源码。
25
+ 精确字段与签名查 [API 参考](references/CUSTOM-MODULE-API.md),不要一次加载所有教程。自动反射在同一个策略文件中添加继承 ClawclawPerception 的具名 Trigger,安装并启用一个 Strategy 资源。只需要修改当前局参数时,按现有模块的 manifest 使用 `ccl strategy update` / `ccl perception update`,不用新建源码。
26
26
 
27
27
  ## 2. 同步编辑基线,定位当前账号和原文件
28
28
 
@@ -101,7 +101,7 @@ export default class GoToPoint extends ClawclawStrategy<GoToPointInput> {
101
101
 
102
102
  ## 单文件反射与局中控制
103
103
 
104
- 一个反射策略只需装配一个 Strategy 资源。默认导出的 `ClawclawStrategy` 实现 `decide()`。具名导出的 `Trigger` 继承 `ClawclawTrigger`,实现 `evaluate()`。两个 Worker 分别运行。Trigger 读取观察帧和声明订阅的后端事件,命中后请求同一资源的策略。Strategy 获得控制权后执行。
104
+ 运行对局的 CCL 需要 0.10.16 或更新版本,桌面端以实际使用的 CCL 版本为准。一个策略文件同时导出执行类和触发感知。默认导出的 `ClawclawStrategy` 在取得控制权后执行 `decide()`。具名导出的 `Trigger extends ClawclawPerception` 使用感知 API v3,在 `evaluate()` 中通过 `activations` 请求已声明的同文件策略绑定。示例在玩家进入指定范围时前往撤离点。
105
105
 
106
106
  ```ts
107
107
  import {
@@ -109,13 +109,12 @@ import {
109
109
  } from '@myclaw163/clawclaw-cli/strategy-plugin';
110
110
 
111
111
  import {
112
- ClawclawTrigger, type StrategyTriggerManifest, type TriggerInput, type TriggerMatch,
113
- } from '@myclaw163/clawclaw-cli/trigger-plugin';
112
+ ClawclawPerception, type PerceptionModuleInput, type PerceptionModuleResult,
113
+ } from '@myclaw163/clawclaw-cli/perception-plugin';
114
114
 
115
115
  type Parameters = {
116
116
  readonly x: number;
117
117
  readonly y: number;
118
- readonly triggerDistance: number;
119
118
  };
120
119
 
121
120
  /** The strategy executes when it is granted control. */
@@ -126,9 +125,8 @@ export default class AutoEscape extends ClawclawStrategy<Parameters> {
126
125
  description: '有人进入设定范围时,前往 Agent 指定的撤离点。靠近不等于对方有敌意。',
127
126
  execution: 'serial',
128
127
  inputs: [
129
- { id: 'x', type: 'number', description: '当前地图上可达的撤离点 X。', required: true },
130
- { id: 'y', type: 'number', description: '当前地图上可达的撤离点 Y。', required: true },
131
- { id: 'triggerDistance', type: 'number', description: '触发距离(像素)。', default: 160, min: 1, max: 1000 },
128
+ { id: 'x', type: 'number', description: '当前地图上可达的撤离点 X。', default: 2708 },
129
+ { id: 'y', type: 'number', description: '当前地图上可达的撤离点 Y。', default: 2320 },
132
130
  ],
133
131
  runtime: { defaultMs: 10000 },
134
132
  } as const satisfies ClawclawStrategyManifest;
@@ -152,22 +150,22 @@ export default class AutoEscape extends ClawclawStrategy<Parameters> {
152
150
  }
153
151
  }
154
152
 
155
- export class Trigger extends ClawclawTrigger<Parameters> {
153
+ export class Trigger extends ClawclawPerception {
156
154
  static readonly manifest = {
157
- apiVersion: 4,
158
- defaultReflexPriority: 40,
159
- defaultCooldownMs: 3000,
160
- defaultRearm: 'after_clear',
161
- defaultMaxRuntimeMs: 10000,
162
- } as const satisfies StrategyTriggerManifest;
163
-
164
- evaluate(input: Readonly<TriggerInput<Parameters>>): TriggerMatch | void {
165
- const players = input.frame.observation.players;
155
+ apiVersion: 3,
156
+ id: 'community.nearby',
157
+ description: '有玩家靠近时请求本策略撤离。',
158
+ inputs: [{ id: 'triggerDistance', type: 'number', description: '触发距离(像素)。', default: 160, min: 1, max: 1000 }],
159
+ strategies: { escape: { name: 'community.auto-escape', reflexPriority: 40, cooldownMs: 3000, rearm: 'after_clear', maxRuntimeMs: 10000 } },
160
+ } as const;
161
+
162
+ evaluate(input: Readonly<PerceptionModuleInput>): PerceptionModuleResult {
163
+ const players = input.frame?.observation.players ?? [];
166
164
  const self = players.find(player => player.observer);
167
- if (!self) return;
168
- const other = players.find(player => !player.observer
169
- && Math.hypot(player.x - self.x, player.y - self.y) <= input.input.triggerDistance);
170
- if (other) return { reason: 'player_nearby', evidence: { seat: other.seat } };
165
+ if (!self) return {};
166
+ const distance = Number(input.config.triggerDistance);
167
+ const nearby = players.some(player => !player.observer && Math.hypot(player.x - self.x, player.y - self.y) <= distance);
168
+ return { activations: nearby ? [{ strategy: 'escape', reason: 'player_nearby' }] : [] };
171
169
  }
172
170
  }
173
171
  ```
@@ -181,9 +179,9 @@ ccl strategy status community.auto-escape
181
179
  ccl strategy unwatch community.auto-escape
182
180
  ```
183
181
 
184
- 策略装配后默认开启自动反射。策略声明的必填参数还没提供时,状态为 `waiting_for_input`。提供参数后可以开始监听。`watch/unwatch` 控制本局监听,关闭时取消它启动的 Reflex。手动 long/short 仍可用。
182
+ 装配一个策略文件后,触发感知随对局运行,默认允许自动激活。`unwatch` 禁止自动激活并取消该绑定正在执行的反射,感知继续观察和保存状态。`watch` 恢复自动激活。
185
183
 
186
- `strategy update` 使用策略 manifest 的同一份参数定义,更新触发判断、本策略当前执行及后续启动默认值。动态命中参数和显式启动参数覆盖本局默认值。只改一次执行时加 `--activation` 并指定 Activation ID。改参保留 Activation ID 和原截止时间,增加实例代际。暂停实例继续暂停。设置在换局或 Owner 退出时清空。
184
+ `strategy update` 按两个类各自声明的字段更新感知配置或策略输入。策略输入影响本策略当前执行及后续启动默认值。动态命中参数和显式启动参数覆盖本局默认值。只改一次执行时加 `--activation` 并指定 Activation ID。改参保留 Activation ID 和原截止时间,增加实例代际。暂停实例继续暂停。设置在换局或 Owner 退出时清空。
187
185
 
188
186
  跨激活去重使用 `api.memory`。例如 Trigger 查 `handled:<尸体ID>`,追尸策略实际接手现场后再写。单次执行进度可以用实例字段。
189
187
 
@@ -95,16 +95,16 @@ const maySelect = candidates[0] && isTaskAvailable(input.gameState, candidates[0
95
95
 
96
96
  从公开 perception-plugin 入口导入 ClawclawPerception、PerceptionModuleInput、PerceptionModuleResult、PerceptionModuleEvent 和 PerceptionModuleManifest;版本常量为 PERCEPTION_MODULE_API_VERSION=3。新脚本没有三选一的 kind,通过同一个 evaluate(input, api) 组合观察、通知和私有记忆。
97
97
 
98
- Manifest 的必需项为 apiVersion:3、id、description;可选 name、localizations、consumes、produces、inputs、config。输入包含 moduleId、scope、gameState、frame、events、taskChanges、boundary、lifecycle、source、roomState、queueState、eventStates、nowMs、cycle、config、state。frame/gameState 可以为 null;events 只含订阅的源/后端原始事实,taskChanges 由该模块自己的基线与本轮权威任务列表比较得到,结合同轮后端事实;不是订阅 tasks_changed。 内置任务感知及 evaluateReminder('tasks') 只把后端 task_* 事实转为基础任务通知,不按 taskChanges 再输出同一信息;紧急生命周期和阈值由内置紧急感知负责。
98
+ Manifest 的必需项为 apiVersion:3、id、description;可选 name、localizations、consumes、produces、inputs、config、strategies。输入包含 moduleId、scope、gameState、frame、events、taskChanges、boundary、lifecycle、source、roomState、queueState、eventStates、nowMs、cycle、config、state。frame/gameState 可以为 null;events 只含订阅的源/后端原始事实,taskChanges 由该模块自己的基线与本轮权威任务列表比较得到,结合同轮后端事实;不是订阅 tasks_changed。 内置任务感知及 evaluateReminder('tasks') 只把后端 task_* 事实转为基础任务通知,不按 taskChanges 再输出同一信息;紧急生命周期和阈值由内置紧急感知负责。
99
99
 
100
100
  阶段变化不清空 state。`enteredPhase` / `leftPhase` 匹配本轮实际阶段转换,`hasPerceptionBoundary` 检查 initial、recovery 等边界;`resetPerceptionState(state, patch)` 纯函数式替换指定字段,原状态与 api.memory 不受影响。恢复不伪造阶段转换。API 还提供只读 `api.spatial`。事件可带 `occurredAt` 保留观察发生时间;`forwards` 只能由宿主授予转发权限的原生模块使用。
101
101
 
102
- 结果为 { state?, events? }。events 项为 { type, key, wakeAgent?, occurredAt?, payload },type 必须在 produces 中声明,key 是稳定发生标识,wakeAgent 省略为 true。false 不独立唤醒且保留事件;不生成事件表示没有这条通知。事件类型的可见范围仍受 Catalog 和配置约束,模块不能重写原始事件或其他模块的通知。
102
+ 结果为 { state?, events?, activations? }。events 项为 { type, key, wakeAgent?, occurredAt?, payload },type 必须在 produces 中声明,key 是稳定发生标识,wakeAgent 省略为 true。false 不独立唤醒且保留事件;不生成事件表示没有这条通知。事件类型的可见范围仍受 Catalog 和配置约束,模块不能重写原始事件或其他模块的通知。
103
103
 
104
104
 
105
105
  每次计算使用 fresh 实例,跨回调状态必须从 input.state 读取并作为结果 state 返回,由 Host 检查点恢复。新脚本不能订阅其他感知、Strategy 或 decision 输出;运行时还按 producerPluginId 过滤,只接纳 Source/后端原始事实。produces 不能冒充系统保留类型;reminder.task/reminder.speech 是兼容通知输出,不是权威任务事实。
106
106
 
107
- 感知可请求固定 Reflex,感知和策略分别安装并启用。
107
+ 策略文件中的具名触发感知通过 activations 请求同文件策略的 Reflex。
108
108
 
109
109
  ## Strategy API
110
110
 
@@ -683,19 +683,17 @@ import type {
683
683
  - 查询 API 只在当前回调活动期间有效,不要保存后延迟调用;
684
684
  - 自定义模块是本机可信代码,不是安全沙箱,只安装可信来源。
685
685
 
686
- ## 策略内置 Trigger
686
+ ## 策略内置触发感知
687
687
 
688
- 策略模块可从同一文件具名导出 `Trigger`,继承 `ClawclawTrigger`。类型从 `@myclaw163/clawclaw-cli/trigger-plugin` 导入。`StrategyTriggerManifest` 的 `apiVersion` 为 4,可选 `consumes`、`defaultReflexPriority`、`defaultCooldownMs`、`defaultRearm`、`defaultMaxRuntimeMs`。默认只读观察帧,优先级 0、冷却 1000ms、重新满足条件后重臂、最长 10000ms。`defaultRearm` 可设为 `after_clear` 或 `after_cooldown`。
688
+ CCL 0.10.16 起,策略文件可以具名导出继承 `ClawclawPerception` 的 `Trigger`。使用 `@myclaw163/clawclaw-cli/perception-plugin` 的感知 API v3。`Trigger.manifest` 和普通感知一样声明 `id`、`description`,在 `strategies` 里给本文件默认策略的声明 ID 配置固定绑定。绑定可以指定 `reflexPriority`、`cooldownMs`、`rearm` 和 `maxRuntimeMs`。
689
689
 
690
- ```ts
691
- evaluate(input: Readonly<TriggerInput>, api: TriggerReadApi): TriggerMatch | void | Promise<TriggerMatch | void>
692
- ```
690
+ `evaluate(input, api)` 接收 `PerceptionModuleInput`,通过 `input.frame`、`input.events`、`input.config` 和 `input.state` 读取观察、事实、配置和上次返回的私有状态。返回 `PerceptionModuleResult`,可含 `state`、`events` 和 `activations`。例如 `{ activations: [{ strategy: 'escape', input: { x: 2708, y: 2320 }, reason: 'player_nearby' }] }` 使用清单里的 `escape` 绑定,激活参数覆盖策略默认值。
693
691
 
694
- `input` 包含 `frame`、`events`、`input` 和可选 `cycle`。返回 `{ reason, evidence?, behaviorInput? }` 请求本资源的策略。`behaviorInput` 是本次激活的动态参数,覆盖本局默认值。`api.memory` 与同一文件的策略类共享。发生阶段变化或观测中断时,可以在 `reset(reason)` 清理本次连续观察所用的实例字段。
692
+ 跨帧判断保存在返回的 `state` 中。触发感知与执行类需要共享的局内记录使用 `api.memory`。例如触发感知按尸体 ID 查询,执行类接手后记录,避免一次未获准的请求占用现场。
695
693
 
696
694
  ### api.memory:局内持续记忆
697
695
 
698
- StrategyReadApi、TriggerReadApi 和 PerceptionModuleApi 均提供以下接口。
696
+ StrategyReadApi 和 PerceptionModuleApi 均提供以下接口。
699
697
 
700
698
  ```ts
701
699
  type StrategyMemoryValue = null | boolean | number | string
@@ -61,8 +61,7 @@ flowchart LR
61
61
  Input["当前 State / 可见观察 / 源与后端原始事实"] --> Perception["统一感知 API v3"]
62
62
  Perception --> Events["提交自己的事件"]
63
63
  Events --> Mailbox["Mailbox / Agent"]
64
- Input --> Trigger["策略内置 Trigger"]
65
- Trigger -->|"请求所属策略"| Strategy["策略执行类"]
64
+ Perception -->|"请求所属策略"| Strategy["策略执行类"]
66
65
  Strategy --> Runtime["Runtime 检查并提交动作"]
67
66
  ```
68
67
 
@@ -68,7 +68,7 @@ export default class FirstSighting extends ClawclawPerception {
68
68
  | config / state | Manifest 参数与上一轮提交后的私有检查点 |
69
69
  | availableStrategies | 当前可加载的策略操作名 |
70
70
 
71
- 结果可同时包含 `state`、`events`,也可以只返回其中需要的部分。每次计算使用新实例,跨回调记忆用返回的 state,不能依赖实例字段。宿主只在更换对局/作用域时清空私有状态,不在进出会议时统一清空。阶段切换通过 lifecycle 传入,由脚本按需收尾观察片段、刷新部分字段并返回下一份 state。连接恢复保留检查点并显式标记 recovery,不伪造进入/离开会议,也不应重放旧通知。
71
+ 结果可同时包含 `state`、`events` 和 `activations`,也可以只返回其中需要的部分。每次计算使用新实例,跨回调记忆用返回的 state,不能依赖实例字段。宿主只在更换对局/作用域时清空私有状态,不在进出会议时统一清空。阶段切换通过 lifecycle 传入,由脚本按需收尾观察片段、刷新部分字段并返回下一份 state。连接恢复保留检查点并显式标记 recovery,不伪造进入/离开会议,也不应重放旧通知。
72
72
 
73
73
  Manifest 使用 `apiVersion: 3`、`id`、`description`,可声明 `consumes`、`produces`、`inputs`、`config` 、可选固定 `strategies` 绑定与本地化信息。不填写 kind。事件必须在 produces 中声明,并使用稳定的 key 和可序列化 payload;text 可用于直接表达通知。不能冒充击杀、能力就绪或策略生命周期等系统事实。
74
74
 
@@ -125,7 +125,7 @@ API v3 模块只订阅 Source/后端原始事实;读取可见观察不需要
125
125
 
126
126
  `ccl perception update <感知名> --input '<补丁JSON>' ` 更新当前局的观察和通知参数。`ccl perception status <感知名>` 查看当前参数和运行状态。
127
127
 
128
- 开发自动反射时,在策略文件中增加具名 Trigger。装配该策略后用 `ccl strategy` 修改触发参数、查看状态和开关。
128
+ 开发自动反射时,在策略文件中增加具名触发感知 Trigger。装配该策略后用 `ccl strategy` 修改触发参数、查看状态和开关。
129
129
 
130
130
  ## 编写规则
131
131
 
@@ -1,8 +1,8 @@
1
1
  import { normalizeBehaviorInput } from './behavior-input-fields.js';
2
2
  import type { ClawclawBehaviorCatalog } from './plugins/behavior/behavior-catalog.js';
3
3
  import type { ClawclawBehaviorPlugin } from './plugins/behavior/behavior-plugin.js';
4
- import type { ClawclawTriggerPlugin } from './plugins/trigger/trigger-plugin.js';
5
4
  import type { ClawclawPerceptionModulePlugin } from './plugins/perception/perception-module-plugin.js';
5
+ import type { ResolvedClawclawPerceptionSource } from './plugins/perception/perception-source.js';
6
6
 
7
7
  type Scope = Readonly<{ sessionId: string; segmentId: string }>;
8
8
  const same = (a: Scope, b: Scope) => a.sessionId === b.sessionId && a.segmentId === b.segmentId;
@@ -16,21 +16,13 @@ export class BehaviorReflexControl {
16
16
  private readonly behavior: Pick<ClawclawBehaviorPlugin, 'status' | 'updateReflex' | 'configureInput'>,
17
17
  private readonly catalog: Pick<ClawclawBehaviorCatalog, 'list'>,
18
18
  private readonly scope: () => Scope,
19
- private readonly triggers?: Pick<ClawclawTriggerPlugin, 'descriptors' | 'configureEmbedded'>) {}
20
-
21
- private embedded(id?: string) {
22
- return (this.triggers?.descriptors() ?? []).filter(item => item.embedded && (id === undefined || item.behavior === id));
23
- }
19
+ private readonly embedded: readonly ResolvedClawclawPerceptionSource[] = []) {}
24
20
  status(id?: string) {
25
21
  this.refreshScope();
26
22
  const active = this.behavior.status().stack.reflex;
27
- const embedded = this.embedded(id).map(item => ({
28
- source: 'strategy' as const, behavior_id: item.behavior, trigger_id: item.id,
29
- available: true, enabled: item.enabled, waiting_for_input: item.waitingForInput,
30
- armed: item.armed, cooldown_remaining_ms: item.cooldownRemainingMs,
31
- priority: item.reflexPriority, cooldown_ms: item.cooldownMs, rearm: item.rearm, max_runtime_ms: item.maxRuntimeMs,
32
- }));
33
- return [...embedded, ...(this.modules?.bindings(id) ?? [])].map(binding => ({ ...binding,
23
+ return (this.modules?.bindings(id) ?? []).map(binding => ({ ...binding,
24
+ ...(this.embedded.some(source => source.id === binding.perception_id)
25
+ ? { source: 'strategy', behavior_id: binding.id, config: this.modules?.status(binding.perception_id)[0]?.input } : {}),
34
26
  active: active?.triggerId === binding.trigger_id,
35
27
  ...(active?.triggerId === binding.trigger_id ? { activation_id: active.activationId,
36
28
  instance_generation: active.instanceGeneration } : {}), scope: this.currentScope }));
@@ -54,8 +46,7 @@ export class BehaviorReflexControl {
54
46
  if (!guard()) throw Error('stale_runtime_scope');
55
47
  const entry = this.catalog.list().find(entry => entry.id === id);
56
48
  if (!entry) throw Error('behavior_not_found');
57
- const embedded = this.embedded(id)[0];
58
- if (operation !== 'update' && !embedded) {
49
+ if (operation !== 'update') {
59
50
  const bindings = this.modules?.bindings(id) ?? [];
60
51
  if (!bindings.length || operation === 'enable' && !bindings.some(binding => binding.available)) {
61
52
  throw Error('perception_binding_unavailable');
@@ -64,18 +55,31 @@ export class BehaviorReflexControl {
64
55
  let input = this.parameters.get(id) ?? {}, updated = 0;
65
56
  // A detector may inject required targets later; enabling alone does not prepare a Behavior.
66
57
  if (operation === 'update' || Object.keys(patch).length) {
67
- input = normalizeBehaviorInput({ ...input, ...patch },entry.inputs);
68
- updated = await this.behavior.configureInput(id,input,patch,guard,
69
- () => {
58
+ const source = this.embedded.find(source => source.embedded?.strategyId === id);
59
+ const fields = source?.module?.inputs ?? [];
60
+ const detectorPatch: Record<string, unknown> = {};
61
+ const executionPatch: Record<string, unknown> = {};
62
+ for (const [key, value] of Object.entries(patch)) {
63
+ const observed = fields.some(field => field.id === key);
64
+ if (observed) detectorPatch[key] = value;
65
+ if (!observed || entry.inputs.some(field => field.id === key)) executionPatch[key] = value;
66
+ }
67
+ const configureDetector = () => {
68
+ if (source && Object.keys(detectorPatch).length) this.modules?.configure(source.id, detectorPatch, guard);
69
+ };
70
+ if (Object.keys(executionPatch).length || !Object.keys(detectorPatch).length) {
71
+ input = normalizeBehaviorInput({ ...input, ...executionPatch }, entry.inputs);
72
+ updated = await this.behavior.configureInput(id, input, executionPatch, guard, () => {
73
+ configureDetector();
70
74
  this.parameters.set(id, input);
71
- this.triggers?.configureEmbedded(id, { input });
72
75
  this.modules?.behaviorInputChanged(id);
73
76
  });
77
+ } else {
78
+ configureDetector();
79
+ }
74
80
  }
75
81
  if (operation !== 'update') {
76
- if (!guard()) throw Error('stale_runtime_scope');
77
- if (embedded) this.triggers?.configureEmbedded(id, { enabled: operation === 'enable' });
78
- const triggerIds = embedded ? [embedded.id] : this.modules?.setWatch(id,operation === 'enable',guard);
82
+ const triggerIds = this.modules?.setWatch(id,operation === 'enable',guard);
79
83
  if (!triggerIds) throw Error('perception_binding_unavailable');
80
84
  if (operation === 'disable') for (const triggerId of triggerIds) {
81
85
  updated += Number(await this.behavior.updateReflex(triggerId,undefined,guard));
@@ -1,49 +1,28 @@
1
- import {
2
- MAX_TRIGGER_RUNTIME_MS,
3
- TRIGGER_PLUGIN_API_VERSION,
4
- type StrategyTriggerManifest,
5
- } from '../../sdk/trigger-plugin/index.js';
1
+ import { normalizePerceptionModuleManifest } from './perception-module-manifest.js';
6
2
  import type { ResolvedClawclawBehaviorSource } from './plugins/behavior/behavior-source.js';
7
- import type { ResolvedClawclawTriggerSource } from './plugins/trigger/trigger-source.js';
3
+ import type { ResolvedClawclawPerceptionSource } from './plugins/perception/perception-source.js';
8
4
 
9
- const fields = new Set(['apiVersion', 'consumes', 'defaultReflexPriority', 'defaultCooldownMs',
10
- 'defaultRearm', 'defaultMaxRuntimeMs']);
11
-
12
- export function normalizeStrategyTriggerManifest(value: unknown): Required<Omit<StrategyTriggerManifest, 'id'>> {
13
- const manifest = value as StrategyTriggerManifest | undefined;
14
- if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)
15
- || manifest.apiVersion !== TRIGGER_PLUGIN_API_VERSION
16
- || Object.keys(manifest).some(key => !fields.has(key))) {
17
- throw new Error('strategy_trigger_manifest_invalid');
18
- }
19
- const consumes = manifest.consumes === undefined ? [] : manifest.consumes;
20
- if (!Array.isArray(consumes) || consumes.some(type => typeof type !== 'string'
21
- || !/^(?:\\*|[a-z0-9][a-z0-9._-]*)$/.test(type)) || new Set(consumes).size !== consumes.length) {
22
- throw new Error('strategy_trigger_consumes_invalid');
23
- }
24
- const {
25
- defaultReflexPriority = 0,
26
- defaultCooldownMs = 1_000,
27
- defaultRearm = 'after_clear',
28
- defaultMaxRuntimeMs = 10_000,
29
- } = manifest;
30
- if (!Number.isSafeInteger(defaultReflexPriority)
31
- || !Number.isSafeInteger(defaultCooldownMs) || defaultCooldownMs < 0
32
- || (defaultRearm !== 'after_clear' && defaultRearm !== 'after_cooldown')
33
- || !Number.isSafeInteger(defaultMaxRuntimeMs) || defaultMaxRuntimeMs < 1
34
- || defaultMaxRuntimeMs > MAX_TRIGGER_RUNTIME_MS) {
35
- throw new Error('strategy_trigger_defaults_invalid');
5
+ export function normalizeStrategyPerception(value: unknown, strategyId: string) {
6
+ const manifest = normalizePerceptionModuleManifest(value);
7
+ const bindings = Object.values(manifest.behaviors ?? {});
8
+ if (!bindings.length || bindings.some(binding => binding.name !== strategyId || binding.resourceId !== undefined)) {
9
+ throw Error('strategy_perception_self_binding_required');
36
10
  }
37
- return { apiVersion: TRIGGER_PLUGIN_API_VERSION, consumes: [...consumes],
38
- defaultReflexPriority, defaultCooldownMs, defaultRearm, defaultMaxRuntimeMs };
11
+ return manifest;
39
12
  }
40
13
 
41
- export function strategyTriggerSource(source: ResolvedClawclawBehaviorSource): ResolvedClawclawTriggerSource | undefined {
14
+ /** Route a named perception through the same host as an equipped Hub perception. */
15
+ export function strategyTriggerSource(source: ResolvedClawclawBehaviorSource): ResolvedClawclawPerceptionSource | undefined {
42
16
  if (!source.trigger) return undefined;
43
- const { name, description, sourcePath, sourceRoot, inputs } = source;
44
- const id = 'behavior:' + source.id;
45
17
  const { manifest, sha256 } = source.trigger;
46
- return { apiVersion: manifest.apiVersion, id, name, description, sourcePath, sourceRoot,
47
- embedded: { manifest, sha256 },
48
- manifest: { ...manifest, id, name, description, inputs, defaultBehavior: source.id, defaultBehaviorInput: {} } };
18
+ const id = 'strategy:' + source.id;
19
+ const name = manifest.name ?? manifest.id;
20
+ const behaviors = Object.fromEntries(Object.entries(manifest.behaviors!).map(([key, binding]) =>
21
+ [key, { ...binding, name: source.id }]));
22
+ return { id, name, description: manifest.description, apiVersion: 3,
23
+ sourcePath: source.sourcePath, sourceRoot: source.sourceRoot,
24
+ embedded: { strategyId: source.id, sha256, declaredManifest: manifest },
25
+ module: { ...manifest, behaviors },
26
+ manifest: { apiVersion: 2, id, name, description: manifest.description,
27
+ subjectScope: 'self_and_others', produces: manifest.produces ?? [] } };
49
28
  }
@@ -638,9 +638,8 @@ export async function runClawclawOwner(
638
638
  behavior_id: source.id, reason: source.triggerError,
639
639
  });
640
640
  const trigger = strategyTriggerSource(source);
641
- return trigger ? [{ source: trigger, enabled: true }] : [];
641
+ return trigger ? [trigger] : [];
642
642
  });
643
- const triggers = [...legacyTriggers, ...embeddedTriggers];
644
643
  const disabledPerceptions = new Set(gameplayConfig.disabled_perception_modules);
645
644
  const agentPerceptionSources = agentWorkspace
646
645
  ? listAgentWorkspacePerceptionSources(workspaceDir, options.profile, agentWorkspace)
@@ -673,7 +672,8 @@ export async function runClawclawOwner(
673
672
  triggerDiagnosticsEnabled: fullDiagnosticsEnabled,
674
673
  fallbackBehaviors,
675
674
  behaviorEventTypes,
676
- triggers,
675
+ triggers: legacyTriggers,
676
+ embeddedPerceptions: embeddedTriggers,
677
677
  });
678
678
  await assembly.behavior.setIdleMs(gameplayConfig.idle_ms);
679
679
  const epochPlugins = assembly.plugins;
@@ -684,7 +684,7 @@ export async function runClawclawOwner(
684
684
  intent,
685
685
  );
686
686
  const reflexControl = new BehaviorReflexControl(assembly.modules,
687
- assembly.behavior, behaviorCatalog, () => runtime!.publicScope(), assembly.trigger);
687
+ assembly.behavior, behaviorCatalog, () => runtime!.publicScope(), embeddedTriggers);
688
688
  const runtimeDone = startupSpan('owner.runtime_init');
689
689
  runtime = createClawclawRuntime(options.profile, {
690
690
  processingCadence: createClawclawProcessingCadence(readRuntimeCycleIntervalMs()),
@@ -756,7 +756,7 @@ export async function runClawclawOwner(
756
756
  : null,
757
757
  },
758
758
  perception: assembly.perception.diagnosticSnapshot(),
759
- trigger: assembly.trigger.diagnosticSnapshot(),
759
+ trigger: assembly.trigger?.diagnosticSnapshot(),
760
760
  }, {
761
761
  component: 'runtime.diagnostics',
762
762
  scope: runtime?.publicScope(),
@@ -773,7 +773,7 @@ export async function runClawclawOwner(
773
773
  throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
774
774
  }
775
775
  const mailboxRepository = runtime.repository;
776
- const perceptionSourceById = new Map(perceptionSources.map(source => [source.id, source]));
776
+ const perceptionSourceById = new Map([...perceptionSources, ...embeddedTriggers].map(source => [source.id, source]));
777
777
  const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
778
778
  producerPluginIds: [assembly.perception.id, assembly.reminders.id, ...(assembly.modules ? [assembly.modules.id] : [])],
779
779
  descriptor: id => {
@@ -1358,6 +1358,7 @@ export async function runClawclawOwner(
1358
1358
  if (!currentTriggerSources.some((source) => source.id === request.trigger)) {
1359
1359
  return { ok: false, type: 'trigger_configure', error: 'trigger_source_unavailable' };
1360
1360
  }
1361
+ if (!assembly.trigger) return { ok: false, type: request.type, error: 'trigger_runtime_restart_required' };
1361
1362
  assembly.trigger.configure(triggerRegistrations(
1362
1363
  currentTriggerSources,
1363
1364
  latest,
@@ -1,7 +1,7 @@
1
1
  import type { GameClient } from '../../../lib/game-client.js';
2
2
  import { ClawclawStrategyMemory } from '../strategy-memory.js';
3
3
  import { ClawclawReminderPlugin, CLAWCLAW_REMINDER_PLUGIN_ID } from './derived-event/reminder-plugin.js';
4
- import { listClawclawPerceptionSources, isSupportedPerceptionSource } from './perception/perception-source.js';
4
+ import { listClawclawPerceptionSources, isSupportedPerceptionSource, type ResolvedClawclawPerceptionSource } from './perception/perception-source.js';
5
5
  import { DEFAULT_PERCEPTION_MODULES } from './perception/official-module-ids.js';
6
6
  import { ClawclawPerceptionModulePlugin, CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID } from './perception/perception-module-plugin.js';
7
7
  import type { RuntimeEpochPlugin } from '../../framework/plugins/index.js';
@@ -44,6 +44,7 @@ export interface ClawclawPluginAssemblyOptions {
44
44
  triggerDiagnosticsEnabled?: boolean;
45
45
  fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
46
46
  triggers?: readonly ClawclawTriggerRegistration[];
47
+ embeddedPerceptions?: readonly ResolvedClawclawPerceptionSource[];
47
48
  /** All enabled Behavior Event declarations frozen into the startup plugin graph. */
48
49
  behaviorEventTypes?: readonly string[];
49
50
  }
@@ -55,7 +56,7 @@ export interface ClawclawPluginAssembly {
55
56
  gameQuery: ClawclawGameQueryPlugin;
56
57
  perception: ClawclawPerceptionPlugin;
57
58
  reminders: ClawclawReminderPlugin;
58
- trigger: ClawclawTriggerPlugin;
59
+ trigger?: ClawclawTriggerPlugin;
59
60
  behavior: ClawclawBehaviorPlugin;
60
61
  mailbox: ClawclawMailboxPlugin;
61
62
  }
@@ -125,14 +126,16 @@ export function assembleClawclawPlugins(
125
126
  throw new Error(`Runtime Plugin ${CLAWCLAW_TRIGGER_PLUGIN_ID} is not a ClawclawTriggerPlugin.`);
126
127
  }
127
128
  const trigger = configuredTrigger as ClawclawTriggerPlugin | undefined
128
- ?? new ClawclawTriggerPlugin({
129
+ // Compatibility only for previously installed standalone Trigger resources.
130
+ ?? (options.triggers?.length ? new ClawclawTriggerPlugin({
129
131
  after: [],
130
132
  triggers: options.triggers,
131
133
  diagnosticsEnabled: options.triggerDiagnosticsEnabled,
132
- });
133
- if (!configuredTrigger) plugins.push(trigger);
134
+ }) : undefined);
135
+ if (trigger && !configuredTrigger) plugins.push(trigger);
134
136
 
135
- const modules = moduleSources.length ? new ClawclawPerceptionModulePlugin({ sources: moduleSources,
137
+ const sources = [...moduleSources, ...(options.embeddedPerceptions ?? [])];
138
+ const modules = sources.length ? new ClawclawPerceptionModulePlugin({ sources,
136
139
  after: [],
137
140
  behaviors: () => options.behaviorCatalog?.list?.() ?? [],
138
141
  }) : undefined;
@@ -160,11 +163,11 @@ export function assembleClawclawPlugins(
160
163
  if (!configuredBehavior) plugins.push(behavior);
161
164
 
162
165
  const strategyMemory = new ClawclawStrategyMemory();
163
- trigger.attachMemory(strategyMemory);
166
+ trigger?.attachMemory(strategyMemory);
164
167
  behavior.attachMemory(strategyMemory);
165
168
  modules?.attachMemory(strategyMemory);
166
169
  modules?.attachDriver(behavior);
167
- trigger.attachDriver(behavior);
170
+ trigger?.attachDriver(behavior);
168
171
  // Direct Agent/user commands remain ActionPlugin calls this round. Preserve
169
172
  // their original activity timing: mark activity at Action admission, before
170
173
  // the backend request starts, without routing the command through Behavior.
@@ -20,7 +20,7 @@ import {
20
20
  hasValidClawclawResourceLocalizations,
21
21
  } from '../../../../sdk/behavior-plugin/index.js';
22
22
  import { parseLiteralBehaviorInputFields, parseLiteralModuleManifest } from '../behavior-input-source.js';
23
- import { normalizeStrategyTriggerManifest } from '../../behavior-trigger.js';
23
+ import { normalizeStrategyPerception } from '../../behavior-trigger.js';
24
24
  import {
25
25
  behaviorProducesDiagnostic,
26
26
  deepFreezeBehaviorValue,
@@ -32,7 +32,7 @@ const MAX_BEHAVIOR_SOURCE_BYTES = 2 * 1024 * 1024;
32
32
  const SAFE_IMPORT = /(?:\bfrom\s*|\bimport\s*)["'](?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/(?:behavior|strategy)-plugin["']/;
33
33
  const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+Clawclaw(?:Behavior|Strategy)(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
34
34
  const NAMED_TRIGGER = /export\s+class\s+Trigger\b/;
35
- const TRIGGER_CLASS = /^export\s+class\s+Trigger\s+extends\s+ClawclawTrigger(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
35
+ const TRIGGER_CLASS = /^export\s+class\s+Trigger\s+extends\s+ClawclawPerception(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
36
36
  const STATIC_MANIFEST = /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/;
37
37
  const BEHAVIOR_ID = /^[a-z0-9][a-z0-9._-]*$/;
38
38
  const MANIFEST_FIELDS = new Set([
@@ -80,7 +80,7 @@ export interface ResolvedClawclawBehaviorSource {
80
80
  readonly everyTicks: number;
81
81
  readonly produces?: readonly string[];
82
82
  readonly runtime?: Readonly<BehaviorRuntimeDefaults>;
83
- readonly trigger?: Readonly<{ manifest: ReturnType<typeof normalizeStrategyTriggerManifest>; sha256: string }>;
83
+ readonly trigger?: Readonly<{ manifest: ReturnType<typeof normalizeStrategyPerception>; sha256: string }>;
84
84
  readonly triggerError?: string;
85
85
  /** Host-authenticated origin. It is never parsed from module source. */
86
86
  readonly provenance?: Readonly<ClawclawBehaviorSourceProvenance>;
@@ -598,10 +598,11 @@ export function inspectClawclawBehaviorSource(
598
598
  if (namedTrigger) {
599
599
  try {
600
600
  const match = TRIGGER_CLASS.exec(masked.slice(namedTrigger.index));
601
- if (match) match.index = namedTrigger.index;
602
- const literal = match && classManifest(source, match);
601
+ if (!match) throw Error('strategy_trigger_requires_perception_v3');
602
+ match.index = namedTrigger.index;
603
+ const literal = classManifest(source, match);
603
604
  trigger = {
604
- manifest: normalizeStrategyTriggerManifest(literal && parseLiteralModuleManifest(literal)),
605
+ manifest: normalizeStrategyPerception(literal && parseLiteralModuleManifest(literal), compatible.id),
605
606
  sha256: createHash('sha256').update(source).digest('hex'),
606
607
  };
607
608
  } catch (error) {
@@ -103,10 +103,13 @@ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapte
103
103
  const { input, game, frame, facts, eventStates, boundary, common } = prepared.value as Prepared;
104
104
  const events = facts.filter(event => source.module.consumes?.includes(event.type));
105
105
  const comparison = comparePerceptionTasks(baseline as PerceptionTaskBaseline | undefined, input, boundary);
106
+ const embedded = sourceValue(source).embedded;
107
+ const declaredTargets = embedded && bindings.availableBindings.length
108
+ ? Object.values(embedded.declaredManifest.behaviors ?? {}).map(binding => binding.name) : [];
106
109
  const moduleInput: PerceptionModuleInput = { ...common, moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
107
110
  ...(isClawclawRuntimeState(input.epoch.state) && input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
108
111
  events, eventStates: Object.fromEntries(events.map(event => [event.eventId, eventStates[event.eventId]])), nowMs: prepared.nowMs,
109
- state, config, ...bindings, availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes, boundary };
112
+ state, config, ...bindings, availableStrategies: [...new Set([...bindings.availableBehaviors, ...declaredTargets])], taskChanges: comparison.changes, boundary };
110
113
  return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline,
111
114
  evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || !!common.roomState || !!common.queueState
112
115
  || moduleInput.events.length > 0 || !!moduleInput.lifecycle?.length };
@@ -125,6 +128,7 @@ export class ClawclawPerceptionModulePlugin extends PerceptionHost {
125
128
  sources: options.sources.filter(source => source.module).map(source => ({ id: source.id, name: source.name, module: source.module!, value: source })) });
126
129
  }
127
130
  override localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] {
128
- return super.localizedModuleDescriptors(locale) as ClawclawResolvedResourceMetadata[];
131
+ const descriptors = super.localizedModuleDescriptors(locale) as ClawclawResolvedResourceMetadata[];
132
+ return descriptors.filter(item => !item.id.startsWith('strategy:'));
129
133
  }
130
134
  }
@@ -6,7 +6,8 @@ import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runt
6
6
  import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
7
7
  export class PerceptionModuleRunner extends PerceptionWorker<PerceptionModuleInput, PerceptionModuleResult> {
8
8
  constructor(readonly source: ResolvedClawclawPerceptionSource, bindMemory?: (input: PerceptionModuleInput, active: () => boolean) => StrategyMemory) {
9
- super({ compatibilityError: source.compatibilityError, workerData: { modulePath: source.sourcePath, expectedManifest: source.module,
9
+ super({ compatibilityError: source.compatibilityError, workerData: { modulePath: source.sourcePath, expectedManifest: source.embedded?.declaredManifest ?? source.module,
10
+ embeddedSha256: source.embedded?.sha256,
10
11
  legacy: !!source.reaction, runtimeModuleBootstrap: { hostUrl: new URL('./perception-module-worker.ts', import.meta.url).href,
11
12
  ...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(source.sourcePath)).href] } } }, bindMemory);
12
13
  }
@@ -1,3 +1,5 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
1
3
  import { pathToFileURL } from 'node:url';
2
4
  import { runPerceptionWorker } from '@myclaw163/game-agent-runtime/perception/perception-worker-host.js';
3
5
  import { ClawclawPerception, ClawclawReaction } from '../../../../sdk/perception-plugin/index.js';
@@ -7,7 +9,11 @@ import { normalizeReactionManifest } from '../../reaction-manifest.js';
7
9
  import { CLAWCLAW_PERCEPTION_SPATIAL_API } from './spatial-facts.js';
8
10
 
9
11
  await runPerceptionWorker<PerceptionModuleInput>(async data => {
10
- const Module = (await import(pathToFileURL(data.modulePath).href)).default;
12
+ if (data.embeddedSha256 && createHash('sha256').update(readFileSync(data.modulePath)).digest('hex') !== data.embeddedSha256) {
13
+ throw Error('strategy_perception_source_changed');
14
+ }
15
+ const exports = await import(pathToFileURL(data.modulePath).href);
16
+ const Module = data.embeddedSha256 ? exports.Trigger : exports.default;
11
17
  if (!(Module?.prototype instanceof (data.legacy ? ClawclawReaction : ClawclawPerception))
12
18
  || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw Error('PERCEPTION_MODULE_CLASS_INVALID');
13
19
  const legacy = data.legacy ? normalizeReactionManifest(Module.manifest) : undefined;
@@ -51,6 +51,7 @@ export interface ResolvedClawclawPerceptionSource {
51
51
  readonly reminder?: ClawclawReminderManifest;
52
52
  readonly module?: PerceptionModuleManifest;
53
53
  readonly reaction?: ClawclawReactionManifest;
54
+ readonly embedded?: Readonly<{ strategyId: string; sha256: string; declaredManifest: PerceptionModuleManifest }>;
54
55
  readonly sourcePath: string;
55
56
  readonly sourceRoot: string;
56
57
  }