@myclaw163/clawclaw-cli 0.10.14 → 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 (55) hide show
  1. package/README.md +1 -1
  2. package/cli-runtime/commands/behavior.js +2 -2
  3. package/cli-runtime/commands/prepare.js +1 -0
  4. package/cli-runtime/runtime/clawclaw/behavior-reflex-control.js +24 -10
  5. package/cli-runtime/runtime/clawclaw/behavior-trigger.js +38 -0
  6. package/cli-runtime/runtime/clawclaw/owner.js +18 -5
  7. package/cli-runtime/runtime/clawclaw/plugins/assembly.js +8 -7
  8. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-source.js +37 -15
  9. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-plugin.js +5 -2
  10. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-runner.js +2 -1
  11. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-worker.js +7 -1
  12. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-worker.ts +7 -1
  13. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-plugin.js +32 -11
  14. package/cli-runtime/sdk/trigger-plugin/index.ts +7 -2
  15. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +58 -0
  16. package/docs/custom-modules/README.md +8 -8
  17. package/docs/custom-modules/api-reference.md +9 -32
  18. package/docs/custom-modules/behavior.md +39 -56
  19. package/docs/custom-modules/examples/auto-escape.ts +26 -3
  20. package/docs/custom-modules/perception.md +7 -20
  21. package/docs/runtime/README.md +2 -2
  22. package/docs/runtime/agent-notifications.md +1 -1
  23. package/docs/runtime/behavior-runtime.md +10 -10
  24. package/docs/runtime/components-and-boundaries.md +8 -8
  25. package/docs/runtime/events-and-state.md +2 -2
  26. package/docs/runtime/owner-lifecycle-and-observability.md +2 -2
  27. package/docs/user-guide/README.md +7 -7
  28. package/docs/user-guide/api-reference.md +8 -31
  29. package/docs/user-guide/behavior.md +38 -55
  30. package/docs/user-guide/perception.md +7 -20
  31. package/package.json +1 -1
  32. package/skills/clawclaw/SKILL.md +5 -5
  33. package/skills/clawclaw/references/BEHAVIORS.md +5 -5
  34. package/skills/clawclaw/references/COMMANDS.md +2 -2
  35. package/skills/clawclaw/references/HUB.md +1 -1
  36. package/skills/clawclaw-creator/SKILL.md +3 -3
  37. package/skills/clawclaw-creator/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +39 -56
  38. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +9 -32
  39. package/skills/clawclaw-creator/references/CUSTOM-MODULES.md +8 -8
  40. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +6 -19
  41. package/src/commands/behavior.ts +3 -3
  42. package/src/commands/prepare.ts +2 -0
  43. package/src/runtime/clawclaw/behavior-reflex-control.ts +27 -4
  44. package/src/runtime/clawclaw/behavior-trigger.ts +28 -0
  45. package/src/runtime/clawclaw/owner.ts +16 -5
  46. package/src/runtime/clawclaw/plugins/assembly.ts +11 -8
  47. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +40 -14
  48. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +6 -2
  49. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +2 -1
  50. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +7 -1
  51. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +1 -0
  52. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +1 -0
  53. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +33 -12
  54. package/src/sdk/trigger-plugin/index.ts +7 -2
  55. package/docs/custom-modules/examples/nearby-reflex.ts +0 -22
package/README.md CHANGED
@@ -53,7 +53,7 @@ ccl game quit # 退出当前匹配、房间或游戏
53
53
 
54
54
  ## 自定义模块
55
55
 
56
- CCL 提供策略和统一感知:策略决定角色行动;感知脚本识别可见事实、组织提醒并控制自己的通知。感知与配套策略分别装配,绑定可用时反射默认开启;支持本局实时改参和开关,关闭反射后感知继续观察和通知。策略使用 `ClawclawStrategy`,新感知使用 Perception API v3。
56
+ 策略资源默认导出 Strategy 执行类,可在同文件具名导出继承 ClawclawPerception 的 Trigger。感知插件运行该类并判断反射条件,感知持续观察并组织通知。 装配一个反射策略就能使用本局实时改参和开关。策略使用 ClawclawStrategy,感知使用 Perception API v3。
57
57
 
58
58
  npm 包提供龙虾杀接入、公共 SDK 和官方 Agent Skill,通过 `@myclaw163/game-agent-runtime` 提供通用运行机制。官方模块、第三方模块和玩家自己的线上模块由当前账号 Hub loadout 获取,纯本地模块由玩家自行创建。实际可用内容以本次 `ccl load` 和对应的 `list` 命令为准。保存或同步源码后,下次正常启动 Runtime 时加载生效。
59
59
 
@@ -388,10 +388,10 @@ ${commandName === "strategy" ? "Strategy" : "Behavior"} modules:
388
388
  }));
389
389
  fallback.addCommand(new Command("none").description("Use no fallback Behavior for a role").requiredOption("--role <role>", "Role binding", parseRole).allowExcessArguments(false).action((opts) => removeFallback(opts.role, "none")));
390
390
  behavior.addCommand(fallback);
391
- behavior.addCommand(new Command("watch").description("Re-enable automatic activation by equipped paired Perceptions in the current game (enabled by default)").argument("<id>", "Equipped Behavior operation name").option("--input <json>", "Optional execution parameter patch; perception parameters use perception update", (value) => parseJsonObject(value), {}).allowExcessArguments(false).action(async (id, opts) => {
391
+ behavior.addCommand(new Command("watch").description("Enable automatic reflection for this strategy in the current game").argument("<id>", "Equipped Behavior operation name").option("--input <json>", "Optional match-local strategy parameter patch", (value) => parseJsonObject(value), {}).allowExcessArguments(false).action(async (id, opts) => {
392
392
  await runOwnerCommand(`ccl ${commandName} watch`, "behavior_watch", { behavior: id, input: opts.input }, true, dependencies);
393
393
  }));
394
- behavior.addCommand(new Command("unwatch").description("Block automatic activation and cancel associated Reflex; perceptions keep observing and notifying").argument("<id>", "Equipped Behavior operation name").allowExcessArguments(false).action(async (id) => {
394
+ behavior.addCommand(new Command("unwatch").description("Block automatic activation and cancel the associated Reflex").argument("<id>", "Equipped Behavior operation name").allowExcessArguments(false).action(async (id) => {
395
395
  await runOwnerCommand(`ccl ${commandName} unwatch`, "behavior_unwatch", { behavior: id }, true, dependencies);
396
396
  }));
397
397
  behavior.addCommand(new Command("update").description("Patch this Behavior's match-local parameters and current executions; keep its watch switch").argument("<id>", "Behavior operation name; with --activation, one activation ID").option("--activation", "Update only the specified execution, without changing shared parameters").requiredOption("--input <json>", "Parameter patch JSON object", (value) => parseJsonObject(value)).allowExcessArguments(false).action(async (id, opts) => {
@@ -799,6 +799,7 @@ function createPrepareCommand(dependencies = {}) {
799
799
  description: source.description,
800
800
  source: entry.source,
801
801
  strategy_type: strategyLifecycle(source.sourcePath),
802
+ ...source.trigger ? { reflex: { available: true } } : source.triggerError ? { reflex: { available: false, reason: source.triggerError } } : {},
802
803
  ...source.management.versionNumber ? {
803
804
  version_number: source.management.versionNumber,
804
805
  version_description: source.management.versionDescription ?? ""
@@ -1,16 +1,18 @@
1
1
  import { normalizeBehaviorInput } from "./behavior-input-fields.js";
2
2
  const same = (a, b) => a.sessionId === b.sessionId && a.segmentId === b.segmentId;
3
3
  class BehaviorReflexControl {
4
- constructor(modules, behavior, catalog, scope) {
4
+ constructor(modules, behavior, catalog, scope, embedded = []) {
5
5
  this.modules = modules;
6
6
  this.behavior = behavior;
7
7
  this.catalog = catalog;
8
8
  this.scope = scope;
9
+ this.embedded = embedded;
9
10
  }
10
11
  modules;
11
12
  behavior;
12
13
  catalog;
13
14
  scope;
15
+ embedded;
14
16
  parameters = /* @__PURE__ */ new Map();
15
17
  currentScope;
16
18
  tail = Promise.resolve();
@@ -19,6 +21,7 @@ class BehaviorReflexControl {
19
21
  const active = this.behavior.status().stack.reflex;
20
22
  return (this.modules?.bindings(id) ?? []).map((binding) => ({
21
23
  ...binding,
24
+ ...this.embedded.some((source) => source.id === binding.perception_id) ? { source: "strategy", behavior_id: binding.id, config: this.modules?.status(binding.perception_id)[0]?.input } : {},
22
25
  active: active?.triggerId === binding.trigger_id,
23
26
  ...active?.triggerId === binding.trigger_id ? {
24
27
  activation_id: active.activationId,
@@ -52,17 +55,28 @@ class BehaviorReflexControl {
52
55
  }
53
56
  let input = this.parameters.get(id) ?? {}, updated = 0;
54
57
  if (operation === "update" || Object.keys(patch).length) {
55
- input = normalizeBehaviorInput({ ...input, ...patch }, entry.inputs);
56
- updated = await this.behavior.configureInput(
57
- id,
58
- input,
59
- patch,
60
- guard,
61
- () => {
58
+ const source = this.embedded.find((source2) => source2.embedded?.strategyId === id);
59
+ const fields = source?.module?.inputs ?? [];
60
+ const detectorPatch = {};
61
+ const executionPatch = {};
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();
62
74
  this.parameters.set(id, input);
63
75
  this.modules?.behaviorInputChanged(id);
64
- }
65
- );
76
+ });
77
+ } else {
78
+ configureDetector();
79
+ }
66
80
  }
67
81
  if (operation !== "update") {
68
82
  const triggerIds = this.modules?.setWatch(id, operation === "enable", guard);
@@ -0,0 +1,38 @@
1
+ import { normalizePerceptionModuleManifest } from "./perception-module-manifest.js";
2
+ function normalizeStrategyPerception(value, strategyId) {
3
+ const manifest = normalizePerceptionModuleManifest(value);
4
+ const bindings = Object.values(manifest.behaviors ?? {});
5
+ if (!bindings.length || bindings.some((binding) => binding.name !== strategyId || binding.resourceId !== void 0)) {
6
+ throw Error("strategy_perception_self_binding_required");
7
+ }
8
+ return manifest;
9
+ }
10
+ function strategyTriggerSource(source) {
11
+ if (!source.trigger) return void 0;
12
+ const { manifest, sha256 } = source.trigger;
13
+ const id = "strategy:" + source.id;
14
+ const name = manifest.name ?? manifest.id;
15
+ const behaviors = Object.fromEntries(Object.entries(manifest.behaviors).map(([key, binding]) => [key, { ...binding, name: source.id }]));
16
+ return {
17
+ id,
18
+ name,
19
+ description: manifest.description,
20
+ apiVersion: 3,
21
+ sourcePath: source.sourcePath,
22
+ sourceRoot: source.sourceRoot,
23
+ embedded: { strategyId: source.id, sha256, declaredManifest: manifest },
24
+ module: { ...manifest, behaviors },
25
+ manifest: {
26
+ apiVersion: 2,
27
+ id,
28
+ name,
29
+ description: manifest.description,
30
+ subjectScope: "self_and_others",
31
+ produces: manifest.produces ?? []
32
+ }
33
+ };
34
+ }
35
+ export {
36
+ normalizeStrategyPerception,
37
+ strategyTriggerSource
38
+ };
@@ -1,4 +1,5 @@
1
1
  import { startupMark, startupSpan, startupTraceEnabled, timeStartup } from "../../../bin/startup-trace.mjs";
2
+ import { strategyTriggerSource } from "./behavior-trigger.js";
2
3
  import { BUILTIN_PERCEPTION_NAMES } from "./plugins/system-perception/system-perceptions.js";
3
4
  import { BUILTIN_PERCEPTION_PREFIX } from "./notification-policy.js";
4
5
  import { isClawclawAgentNotification } from "./notification-policy.js";
@@ -476,7 +477,16 @@ async function runClawclawOwner(options) {
476
477
  behaviorCatalog,
477
478
  configurationWarning
478
479
  );
479
- const triggers = legacyTriggers;
480
+ const loadableStrategies = new Set(behaviorCatalog.list().filter((entry) => entry.loadable).map((entry) => entry.id));
481
+ const embeddedTriggers = behaviorSources.flatMap((source2) => {
482
+ if (!loadableStrategies.has(source2.id)) return [];
483
+ if (source2.triggerError) configurationWarning("strategy_trigger_unavailable", {
484
+ behavior_id: source2.id,
485
+ reason: source2.triggerError
486
+ });
487
+ const trigger = strategyTriggerSource(source2);
488
+ return trigger ? [trigger] : [];
489
+ });
480
490
  const disabledPerceptions = new Set(gameplayConfig.disabled_perception_modules);
481
491
  const agentPerceptionSources = agentWorkspace ? listAgentWorkspacePerceptionSources(workspaceDir, options.profile, agentWorkspace) : [];
482
492
  const localPerceptionSources = discoveredLocalCapabilities.perceptions.filter(({ source: source2, entry }) => entry.selection === "equipped" && !disabledPerceptions.has(source2.id) && !agentWorkspace?.items.perception.some((item) => item.resourceId === entry.hub?.resourceId)).map(({ source: source2 }) => source2);
@@ -502,7 +512,8 @@ async function runClawclawOwner(options) {
502
512
  triggerDiagnosticsEnabled: fullDiagnosticsEnabled,
503
513
  fallbackBehaviors,
504
514
  behaviorEventTypes,
505
- triggers
515
+ triggers: legacyTriggers,
516
+ embeddedPerceptions: embeddedTriggers
506
517
  });
507
518
  await assembly.behavior.setIdleMs(gameplayConfig.idle_ms);
508
519
  const epochPlugins = assembly.plugins;
@@ -516,7 +527,8 @@ async function runClawclawOwner(options) {
516
527
  assembly.modules,
517
528
  assembly.behavior,
518
529
  behaviorCatalog,
519
- () => runtime.publicScope()
530
+ () => runtime.publicScope(),
531
+ embeddedTriggers
520
532
  );
521
533
  const runtimeDone = startupSpan("owner.runtime_init");
522
534
  runtime = createClawclawRuntime(options.profile, {
@@ -583,7 +595,7 @@ async function runClawclawOwner(options) {
583
595
  } : null
584
596
  },
585
597
  perception: assembly.perception.diagnosticSnapshot(),
586
- trigger: assembly.trigger.diagnosticSnapshot()
598
+ trigger: assembly.trigger?.diagnosticSnapshot()
587
599
  }, {
588
600
  component: "runtime.diagnostics",
589
601
  scope: runtime?.publicScope()
@@ -599,7 +611,7 @@ async function runClawclawOwner(options) {
599
611
  throw new Error("The configured Runtime repository does not support durable Mailbox delivery.");
600
612
  }
601
613
  const mailboxRepository = runtime.repository;
602
- const perceptionSourceById = new Map(perceptionSources.map((source2) => [source2.id, source2]));
614
+ const perceptionSourceById = new Map([...perceptionSources, ...embeddedTriggers].map((source2) => [source2.id, source2]));
603
615
  const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
604
616
  producerPluginIds: [assembly.perception.id, assembly.reminders.id, ...assembly.modules ? [assembly.modules.id] : []],
605
617
  descriptor: (id) => {
@@ -1145,6 +1157,7 @@ async function runClawclawOwner(options) {
1145
1157
  if (!currentTriggerSources.some((source2) => source2.id === request.trigger)) {
1146
1158
  return { ok: false, type: "trigger_configure", error: "trigger_source_unavailable" };
1147
1159
  }
1160
+ if (!assembly.trigger) return { ok: false, type: request.type, error: "trigger_runtime_restart_required" };
1148
1161
  assembly.trigger.configure(triggerRegistrations(
1149
1162
  currentTriggerSources,
1150
1163
  latest,
@@ -79,14 +79,15 @@ function assembleClawclawPlugins(client, options = {}) {
79
79
  if (configuredTrigger && !(configuredTrigger instanceof ClawclawTriggerPlugin)) {
80
80
  throw new Error(`Runtime Plugin ${CLAWCLAW_TRIGGER_PLUGIN_ID} is not a ClawclawTriggerPlugin.`);
81
81
  }
82
- const trigger = configuredTrigger ?? new ClawclawTriggerPlugin({
82
+ const trigger = configuredTrigger ?? (options.triggers?.length ? new ClawclawTriggerPlugin({
83
83
  after: [],
84
84
  triggers: options.triggers,
85
85
  diagnosticsEnabled: options.triggerDiagnosticsEnabled
86
- });
87
- if (!configuredTrigger) plugins.push(trigger);
88
- const modules = moduleSources.length ? new ClawclawPerceptionModulePlugin({
89
- sources: moduleSources,
86
+ }) : void 0);
87
+ if (trigger && !configuredTrigger) plugins.push(trigger);
88
+ const sources = [...moduleSources, ...options.embeddedPerceptions ?? []];
89
+ const modules = sources.length ? new ClawclawPerceptionModulePlugin({
90
+ sources,
90
91
  after: [],
91
92
  behaviors: () => options.behaviorCatalog?.list?.() ?? []
92
93
  }) : void 0;
@@ -111,11 +112,11 @@ function assembleClawclawPlugins(client, options = {}) {
111
112
  });
112
113
  if (!configuredBehavior) plugins.push(behavior);
113
114
  const strategyMemory = new ClawclawStrategyMemory();
114
- trigger.attachMemory(strategyMemory);
115
+ trigger?.attachMemory(strategyMemory);
115
116
  behavior.attachMemory(strategyMemory);
116
117
  modules?.attachMemory(strategyMemory);
117
118
  modules?.attachDriver(behavior);
118
- trigger.attachDriver(behavior);
119
+ trigger?.attachDriver(behavior);
119
120
  action.attachAgentActivity(() => {
120
121
  void behavior.noteAgentActivity().catch(() => {
121
122
  });
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import {
2
3
  existsSync,
3
4
  readFileSync,
@@ -13,7 +14,8 @@ import {
13
14
  import {
14
15
  hasValidClawclawResourceLocalizations
15
16
  } from "../../../../sdk/behavior-plugin/index.js";
16
- import { parseLiteralBehaviorInputFields } from "../behavior-input-source.js";
17
+ import { parseLiteralBehaviorInputFields, parseLiteralModuleManifest } from "../behavior-input-source.js";
18
+ import { normalizeStrategyPerception } from "../../behavior-trigger.js";
17
19
  import {
18
20
  behaviorProducesDiagnostic,
19
21
  deepFreezeBehaviorValue,
@@ -23,6 +25,8 @@ const MAX_BEHAVIOR_FILES = 512;
23
25
  const MAX_BEHAVIOR_SOURCE_BYTES = 2 * 1024 * 1024;
24
26
  const SAFE_IMPORT = /(?:\bfrom\s*|\bimport\s*)["'](?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/(?:behavior|strategy)-plugin["']/;
25
27
  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*\{/;
28
+ const NAMED_TRIGGER = /export\s+class\s+Trigger\b/;
29
+ const TRIGGER_CLASS = /^export\s+class\s+Trigger\s+extends\s+ClawclawPerception(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
26
30
  const STATIC_MANIFEST = /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/;
27
31
  const BEHAVIOR_ID = /^[a-z0-9][a-z0-9._-]*$/;
28
32
  const MANIFEST_FIELDS = /* @__PURE__ */ new Set([
@@ -421,6 +425,14 @@ function behaviorSourceCompatibilityError(source) {
421
425
  const eventType = error.slice("behavior_produces_reserved:".length);
422
426
  return source.allowReservedProduces?.includes(eventType) ? void 0 : error;
423
427
  }
428
+ function classManifest(source, match) {
429
+ const body = balancedBlock(source, match.index + match[0].lastIndexOf("{"));
430
+ if (!body) return void 0;
431
+ const maskedBody = maskNonCode(body, true);
432
+ const manifest = STATIC_MANIFEST.exec(maskedBody);
433
+ if (!manifest || STATIC_MANIFEST.test(maskedBody.slice(manifest.index + manifest[0].length))) return void 0;
434
+ return balancedBlock(body, manifest.index + manifest[0].lastIndexOf("{")) ?? void 0;
435
+ }
424
436
  function inspectClawclawBehaviorSource(sourcePath, sourceRoot) {
425
437
  let root;
426
438
  let path;
@@ -436,30 +448,40 @@ function inspectClawclawBehaviorSource(sourcePath, sourceRoot) {
436
448
  if (Buffer.byteLength(source, "utf8") > MAX_BEHAVIOR_SOURCE_BYTES || !SAFE_IMPORT.test(maskNonCode(source, false))) {
437
449
  return null;
438
450
  }
439
- const classMatch = DEFAULT_CLASS.exec(maskNonCode(source, true));
440
- if (!classMatch) return null;
441
- const classOpen = classMatch.index + classMatch[0].lastIndexOf("{");
442
- const classBody = balancedBlock(source, classOpen);
443
- if (!classBody) return null;
444
- const maskedClassBody = maskNonCode(classBody, true);
445
- const manifestMatch = STATIC_MANIFEST.exec(maskedClassBody);
446
- if (!manifestMatch) return null;
447
- if (STATIC_MANIFEST.test(maskedClassBody.slice(manifestMatch.index + manifestMatch[0].length))) {
448
- return null;
449
- }
450
- const manifestOpen = manifestMatch.index + manifestMatch[0].lastIndexOf("{");
451
- const manifest = balancedBlock(classBody, manifestOpen);
451
+ const masked = maskNonCode(source, true);
452
+ const classMatch = DEFAULT_CLASS.exec(masked);
453
+ const manifest = classMatch && classManifest(source, classMatch);
452
454
  if (!manifest) return null;
453
455
  const compatible = sourceCompatibility(manifest);
454
456
  if (!compatible.id) return null;
455
457
  const apiVersionProperty = literalProperty(manifest, "apiVersion");
456
458
  const apiVersion = apiVersionProperty.status === "valid" && Number.isSafeInteger(apiVersionProperty.value) ? apiVersionProperty.value : void 0;
459
+ let trigger;
460
+ let triggerError;
461
+ const namedTrigger = NAMED_TRIGGER.exec(masked);
462
+ if (namedTrigger) {
463
+ try {
464
+ const match = TRIGGER_CLASS.exec(masked.slice(namedTrigger.index));
465
+ if (!match) throw Error("strategy_trigger_requires_perception_v3");
466
+ match.index = namedTrigger.index;
467
+ const literal = classManifest(source, match);
468
+ trigger = {
469
+ manifest: normalizeStrategyPerception(literal && parseLiteralModuleManifest(literal), compatible.id),
470
+ sha256: createHash("sha256").update(source).digest("hex")
471
+ };
472
+ } catch (error) {
473
+ triggerError = error instanceof Error ? error.message : "strategy_trigger_manifest_invalid";
474
+ }
475
+ }
457
476
  return deepFreezeBehaviorValue({
477
+ ...trigger ? { trigger } : {},
478
+ ...triggerError ? { triggerError } : {},
458
479
  ...apiVersion === void 0 ? {} : { apiVersion },
459
480
  ...compatible,
460
481
  id: compatible.id,
461
482
  sourcePath: path,
462
- sourceRoot: root
483
+ sourceRoot: root,
484
+ ...trigger ? { trustedSourceSha256: trigger.sha256 } : {}
463
485
  });
464
486
  }
465
487
  function listClawclawBehaviorSources(behaviorsDir) {
@@ -94,6 +94,8 @@ function createAdapter(options) {
94
94
  const { input, game, frame, facts, eventStates, boundary, common } = prepared.value;
95
95
  const events = facts.filter((event) => source.module.consumes?.includes(event.type));
96
96
  const comparison = comparePerceptionTasks(baseline, input, boundary);
97
+ const embedded = sourceValue(source).embedded;
98
+ const declaredTargets = embedded && bindings.availableBindings.length ? Object.values(embedded.declaredManifest.behaviors ?? {}).map((binding) => binding.name) : [];
97
99
  const moduleInput = {
98
100
  ...common,
99
101
  moduleId: source.id,
@@ -107,7 +109,7 @@ function createAdapter(options) {
107
109
  state,
108
110
  config,
109
111
  ...bindings,
110
- availableStrategies: bindings.availableBehaviors,
112
+ availableStrategies: [.../* @__PURE__ */ new Set([...bindings.availableBehaviors, ...declaredTargets])],
111
113
  taskChanges: comparison.changes,
112
114
  boundary
113
115
  };
@@ -134,7 +136,8 @@ class ClawclawPerceptionModulePlugin extends PerceptionHost {
134
136
  });
135
137
  }
136
138
  localizedModuleDescriptors(locale) {
137
- return super.localizedModuleDescriptors(locale);
139
+ const descriptors = super.localizedModuleDescriptors(locale);
140
+ return descriptors.filter((item) => !item.id.startsWith("strategy:"));
138
141
  }
139
142
  }
140
143
  export {
@@ -5,7 +5,8 @@ class PerceptionModuleRunner extends PerceptionWorker {
5
5
  constructor(source, bindMemory) {
6
6
  super({ compatibilityError: source.compatibilityError, workerData: {
7
7
  modulePath: source.sourcePath,
8
- expectedManifest: source.module,
8
+ expectedManifest: source.embedded?.declaredManifest ?? source.module,
9
+ embeddedSha256: source.embedded?.sha256,
9
10
  legacy: !!source.reaction,
10
11
  runtimeModuleBootstrap: {
11
12
  hostUrl: new URL("./perception-module-worker.ts", import.meta.url).href,
@@ -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";
@@ -5,7 +7,11 @@ import { normalizePerceptionModuleManifest } from "../../perception-module-manif
5
7
  import { normalizeReactionManifest } from "../../reaction-manifest.js";
6
8
  import { CLAWCLAW_PERCEPTION_SPATIAL_API } from "./spatial-facts.js";
7
9
  await runPerceptionWorker(async (data) => {
8
- const Module = (await import(pathToFileURL(data.modulePath).href)).default;
10
+ if (data.embeddedSha256 && createHash("sha256").update(readFileSync(data.modulePath)).digest("hex") !== data.embeddedSha256) {
11
+ throw Error("strategy_perception_source_changed");
12
+ }
13
+ const exports = await import(pathToFileURL(data.modulePath).href);
14
+ const Module = data.embeddedSha256 ? exports.Trigger : exports.default;
9
15
  if (!(Module?.prototype instanceof (data.legacy ? ClawclawReaction : ClawclawPerception)) || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw Error("PERCEPTION_MODULE_CLASS_INVALID");
10
16
  const legacy = data.legacy ? normalizeReactionManifest(Module.manifest) : void 0;
11
17
  const { kind: _kind, ...common } = legacy ?? {};
@@ -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;
@@ -142,6 +142,8 @@ class ClawclawTriggerPlugin {
142
142
  timeoutMs = DEFAULT_TRIGGER_PLUGIN_TIMEOUT_MS;
143
143
  failurePolicy = "failed_completion";
144
144
  registrations;
145
+ pendingActivations = /* @__PURE__ */ new Map();
146
+ invalidInputs = /* @__PURE__ */ new Map();
145
147
  loader;
146
148
  slots = /* @__PURE__ */ new Map();
147
149
  loadFailures = /* @__PURE__ */ new Set();
@@ -183,7 +185,6 @@ class ClawclawTriggerPlugin {
183
185
  if (this.driver && this.driver !== driver) throw new Error("trigger_activation_driver_already_attached");
184
186
  this.driver = driver;
185
187
  }
186
- /** Atomically replace effective config; newly enabled modules import on the next ordered boundary. */
187
188
  configure(triggers) {
188
189
  const next = normalizeRegistrations(triggers);
189
190
  for (const [id, config] of next) {
@@ -194,6 +195,8 @@ class ClawclawTriggerPlugin {
194
195
  }
195
196
  this.configGeneration += 1;
196
197
  this.registrations = next;
198
+ this.pendingActivations.clear();
199
+ this.invalidInputs.clear();
197
200
  this.slots.clear();
198
201
  this.loadFailures.clear();
199
202
  for (const id of this.states.keys()) if (!next.has(id)) this.states.delete(id);
@@ -499,6 +502,7 @@ class ClawclawTriggerPlugin {
499
502
  }
500
503
  for (const evaluation of computed.evaluations) {
501
504
  if (evaluation.outcome !== "clear") continue;
505
+ this.invalidInputs.delete(evaluation.triggerId);
502
506
  const config = this.registrations.get(evaluation.triggerId);
503
507
  if (config?.rearm !== "after_clear") continue;
504
508
  const state = this.stateFor(evaluation.triggerId);
@@ -507,11 +511,14 @@ class ClawclawTriggerPlugin {
507
511
  const candidates = computed.evaluations.flatMap((evaluation) => {
508
512
  if (evaluation.outcome !== "match" || !evaluation.match) return [];
509
513
  const config = this.registrations.get(evaluation.triggerId);
510
- if (!config || !this.isEnabled(config)) return [];
514
+ if (!config || !this.isEnabled(config) || this.pendingActivations.has(evaluation.triggerId)) return [];
515
+ const behaviorInput = { ...config.behaviorInput, ...evaluation.match.behaviorInput };
516
+ const inputKey = JSON.stringify(behaviorInput);
517
+ if (this.invalidInputs.get(evaluation.triggerId) === inputKey) return [];
511
518
  const state = this.stateFor(evaluation.triggerId);
512
519
  if (config.rearm === "after_clear" && !state.armed) return [];
513
520
  if (state.lastAcceptedAtMs !== void 0 && computed.nowMs - state.lastAcceptedAtMs < config.cooldownMs) return [];
514
- return [{ config, match: evaluation.match }];
521
+ return [{ config, match: evaluation.match, behaviorInput, inputKey }];
515
522
  }).sort((left, right) => {
516
523
  if (left.config.reflexPriority !== right.config.reflexPriority) {
517
524
  return left.config.reflexPriority > right.config.reflexPriority ? -1 : 1;
@@ -531,10 +538,7 @@ class ClawclawTriggerPlugin {
531
538
  epochId: computed.epochId,
532
539
  configGeneration: computed.configGeneration,
533
540
  behavior: selected.config.behavior,
534
- behaviorInput: Object.freeze({
535
- ...structuredClone(selected.config.behaviorInput),
536
- ...structuredClone(selected.match.behaviorInput ?? {})
537
- }),
541
+ behaviorInput: Object.freeze(structuredClone(selected.behaviorInput)),
538
542
  reflexPriority: selected.config.reflexPriority,
539
543
  maxRuntimeMs: selected.config.maxRuntimeMs,
540
544
  reason: selected.match.reason,
@@ -563,9 +567,23 @@ class ClawclawTriggerPlugin {
563
567
  }
564
568
  }
565
569
  if (activationResult.accepted) {
566
- const state = this.stateFor(request.triggerId);
567
- state.lastAcceptedAtMs = computed.nowMs;
568
- if (selected.config.rearm === "after_clear") state.armed = false;
570
+ const accept = () => {
571
+ const state = this.stateFor(request.triggerId);
572
+ state.lastAcceptedAtMs = computed.nowMs;
573
+ if (selected.config.rearm === "after_clear") state.armed = false;
574
+ };
575
+ if (activationResult.ready) {
576
+ const activationId = activationResult.activationId;
577
+ this.pendingActivations.set(request.triggerId, activationId);
578
+ void activationResult.ready.then((outcome) => {
579
+ if (this.pendingActivations.get(request.triggerId) !== activationId) return;
580
+ this.pendingActivations.delete(request.triggerId);
581
+ if (outcome === "ready") accept();
582
+ if (outcome === "invalid") this.invalidInputs.set(request.triggerId, selected.inputKey);
583
+ });
584
+ } else {
585
+ accept();
586
+ }
569
587
  context.diagnostic("trigger.activation.accepted", {
570
588
  trigger_id: request.triggerId,
571
589
  behavior_id: request.behavior,
@@ -576,6 +594,7 @@ class ClawclawTriggerPlugin {
576
594
  }
577
595
  });
578
596
  } else {
597
+ if (activationResult.reason === "binding_invalid") this.invalidInputs.set(request.triggerId, selected.inputKey);
579
598
  context.diagnostic("trigger.activation.rejected", {
580
599
  trigger_id: request.triggerId,
581
600
  behavior_id: request.behavior,
@@ -605,6 +624,8 @@ class ClawclawTriggerPlugin {
605
624
  this.slots.clear();
606
625
  this.loadFailures.clear();
607
626
  this.states.clear();
627
+ this.pendingActivations.clear();
628
+ this.invalidInputs.clear();
608
629
  this.observationMemory.clear();
609
630
  this.clearFrameBoundary();
610
631
  this.threadPool = void 0;
@@ -614,7 +635,7 @@ class ClawclawTriggerPlugin {
614
635
  this.loader.stop();
615
636
  }
616
637
  memoryNamespace(source) {
617
- return `trigger:${source.id}`;
638
+ return "trigger:" + source.id;
618
639
  }
619
640
  async ensureThreadPool(context) {
620
641
  if (!this.started || this.threadPool || this.threadPoolFailed) return;
@@ -72,6 +72,11 @@ export interface ClawclawTriggerManifest {
72
72
  readonly defaultMaxRuntimeMs: number;
73
73
  }
74
74
 
75
+ /** Static configuration of the named Trigger exported by a Strategy file. */
76
+ export type StrategyTriggerManifest = Pick<ClawclawTriggerManifest, 'apiVersion'>
77
+ & Partial<Pick<ClawclawTriggerManifest, 'consumes' | 'defaultReflexPriority' | 'defaultCooldownMs'
78
+ | 'defaultRearm' | 'defaultMaxRuntimeMs'>> & { readonly id?: never };
79
+
75
80
  /**
76
81
  * One immutable observation frame, backend-pushed Runtime Events, and configured rule
77
82
  * parameters. Perception and Trigger receive the same frame independently;
@@ -111,7 +116,7 @@ export interface TriggerMatch {
111
116
  export abstract class ClawclawTrigger<
112
117
  TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
113
118
  > {
114
- static readonly manifest?: ClawclawTriggerManifest;
119
+ static readonly manifest?: ClawclawTriggerManifest | StrategyTriggerManifest;
115
120
 
116
121
  abstract evaluate(
117
122
  input: Readonly<TriggerInput<TInput>>,
@@ -125,6 +130,6 @@ export abstract class ClawclawTrigger<
125
130
  export interface ClawclawTriggerClass<
126
131
  TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
127
132
  > {
128
- readonly manifest?: ClawclawTriggerManifest;
133
+ readonly manifest?: ClawclawTriggerManifest | StrategyTriggerManifest;
129
134
  new(): ClawclawTrigger<TInput>;
130
135
  }
@@ -672,6 +672,54 @@ var CLAWCLAW_VISUAL_EVENT_TYPES = [
672
672
  "visual.following",
673
673
  "visual.following_ended"
674
674
  ];
675
+ var CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES = [
676
+ "enter_room",
677
+ "move_start",
678
+ "move_end",
679
+ "move_interrupted",
680
+ "move",
681
+ "task_started",
682
+ "task_progress",
683
+ "task_completed",
684
+ "task_interrupted",
685
+ "task_sabotaged",
686
+ "task_assigned",
687
+ "kill",
688
+ "killed",
689
+ "murder_witnessed",
690
+ "body_dropped",
691
+ "warrior_shrimp_self_destruct",
692
+ "meeting_start",
693
+ "meeting_briefing",
694
+ "speech_turn",
695
+ "speech_your_turn",
696
+ "speech_next_turn",
697
+ "speech",
698
+ "speech_skipped",
699
+ "vote_phase_start",
700
+ "vote_cast",
701
+ "vote_speech",
702
+ "vote_speech_phase_ended",
703
+ "exile",
704
+ "no_exile",
705
+ "meeting_ended",
706
+ "meeting_result_pending",
707
+ "exile_game_over",
708
+ "game_started",
709
+ "game_over",
710
+ "role_assigned",
711
+ "emergency_started",
712
+ "emergency_resolved",
713
+ "emergency_interrupted",
714
+ "player_spotted",
715
+ "corpse_spotted",
716
+ "octopus_time_start",
717
+ "octopus_time_win",
718
+ "win_blocked_by_octopus",
719
+ "wandering_speech",
720
+ "death_speech",
721
+ "think"
722
+ ];
675
723
  var CLAWCLAW_BACKEND_AGENT_EVENT_TYPES = [
676
724
  "service_status",
677
725
  "move_interrupted",
@@ -1145,6 +1193,16 @@ function normalizeClawclawBehaviorManifest(value, options = {}) {
1145
1193
  });
1146
1194
  }
1147
1195
 
1196
+ // src/runtime/clawclaw/perception-module-manifest.ts
1197
+ var INPUT_TYPES = /* @__PURE__ */ new Set([
1198
+ ...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES,
1199
+ ...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES,
1200
+ ...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter((type) => !/^(behavior|reminder|perception)\./.test(type)),
1201
+ "tasks_changed",
1202
+ "meeting_state"
1203
+ ]);
1204
+ var PERCEPTION_OWNED_TYPES = /* @__PURE__ */ new Set([...CLAWCLAW_VISUAL_EVENT_TYPES, "reminder.task", "reminder.speech"]);
1205
+
1148
1206
  // src/runtime/clawclaw/plugins/behavior/behavior-source.ts
1149
1207
  var MAX_BEHAVIOR_SOURCE_BYTES = 2 * 1024 * 1024;
1150
1208