@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
@@ -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';
@@ -630,7 +631,15 @@ export async function runClawclawOwner(
630
631
  behaviorCatalog,
631
632
  configurationWarning,
632
633
  );
633
- const triggers = legacyTriggers;
634
+ const loadableStrategies = new Set(behaviorCatalog.list().filter(entry => entry.loadable).map(entry => entry.id));
635
+ const embeddedTriggers = behaviorSources.flatMap(source => {
636
+ if (!loadableStrategies.has(source.id)) return [];
637
+ if (source.triggerError) configurationWarning('strategy_trigger_unavailable', {
638
+ behavior_id: source.id, reason: source.triggerError,
639
+ });
640
+ const trigger = strategyTriggerSource(source);
641
+ return trigger ? [trigger] : [];
642
+ });
634
643
  const disabledPerceptions = new Set(gameplayConfig.disabled_perception_modules);
635
644
  const agentPerceptionSources = agentWorkspace
636
645
  ? listAgentWorkspacePerceptionSources(workspaceDir, options.profile, agentWorkspace)
@@ -663,7 +672,8 @@ export async function runClawclawOwner(
663
672
  triggerDiagnosticsEnabled: fullDiagnosticsEnabled,
664
673
  fallbackBehaviors,
665
674
  behaviorEventTypes,
666
- triggers,
675
+ triggers: legacyTriggers,
676
+ embeddedPerceptions: embeddedTriggers,
667
677
  });
668
678
  await assembly.behavior.setIdleMs(gameplayConfig.idle_ms);
669
679
  const epochPlugins = assembly.plugins;
@@ -674,7 +684,7 @@ export async function runClawclawOwner(
674
684
  intent,
675
685
  );
676
686
  const reflexControl = new BehaviorReflexControl(assembly.modules,
677
- assembly.behavior, behaviorCatalog, () => runtime!.publicScope());
687
+ assembly.behavior, behaviorCatalog, () => runtime!.publicScope(), embeddedTriggers);
678
688
  const runtimeDone = startupSpan('owner.runtime_init');
679
689
  runtime = createClawclawRuntime(options.profile, {
680
690
  processingCadence: createClawclawProcessingCadence(readRuntimeCycleIntervalMs()),
@@ -746,7 +756,7 @@ export async function runClawclawOwner(
746
756
  : null,
747
757
  },
748
758
  perception: assembly.perception.diagnosticSnapshot(),
749
- trigger: assembly.trigger.diagnosticSnapshot(),
759
+ trigger: assembly.trigger?.diagnosticSnapshot(),
750
760
  }, {
751
761
  component: 'runtime.diagnostics',
752
762
  scope: runtime?.publicScope(),
@@ -763,7 +773,7 @@ export async function runClawclawOwner(
763
773
  throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
764
774
  }
765
775
  const mailboxRepository = runtime.repository;
766
- const perceptionSourceById = new Map(perceptionSources.map(source => [source.id, source]));
776
+ const perceptionSourceById = new Map([...perceptionSources, ...embeddedTriggers].map(source => [source.id, source]));
767
777
  const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
768
778
  producerPluginIds: [assembly.perception.id, assembly.reminders.id, ...(assembly.modules ? [assembly.modules.id] : [])],
769
779
  descriptor: id => {
@@ -1348,6 +1358,7 @@ export async function runClawclawOwner(
1348
1358
  if (!currentTriggerSources.some((source) => source.id === request.trigger)) {
1349
1359
  return { ok: false, type: 'trigger_configure', error: 'trigger_source_unavailable' };
1350
1360
  }
1361
+ if (!assembly.trigger) return { ok: false, type: request.type, error: 'trigger_runtime_restart_required' };
1351
1362
  assembly.trigger.configure(triggerRegistrations(
1352
1363
  currentTriggerSources,
1353
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.
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import {
2
3
  existsSync,
3
4
  readFileSync,
@@ -18,7 +19,8 @@ import type {
18
19
  import {
19
20
  hasValidClawclawResourceLocalizations,
20
21
  } from '../../../../sdk/behavior-plugin/index.js';
21
- import { parseLiteralBehaviorInputFields } from '../behavior-input-source.js';
22
+ import { parseLiteralBehaviorInputFields, parseLiteralModuleManifest } from '../behavior-input-source.js';
23
+ import { normalizeStrategyPerception } from '../../behavior-trigger.js';
22
24
  import {
23
25
  behaviorProducesDiagnostic,
24
26
  deepFreezeBehaviorValue,
@@ -29,6 +31,8 @@ const MAX_BEHAVIOR_FILES = 512;
29
31
  const MAX_BEHAVIOR_SOURCE_BYTES = 2 * 1024 * 1024;
30
32
  const SAFE_IMPORT = /(?:\bfrom\s*|\bimport\s*)["'](?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/(?:behavior|strategy)-plugin["']/;
31
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
+ const NAMED_TRIGGER = /export\s+class\s+Trigger\b/;
35
+ const TRIGGER_CLASS = /^export\s+class\s+Trigger\s+extends\s+ClawclawPerception(?:\s*<[\s\S]{0,4000}?>)?\s*\{/;
32
36
  const STATIC_MANIFEST = /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/;
33
37
  const BEHAVIOR_ID = /^[a-z0-9][a-z0-9._-]*$/;
34
38
  const MANIFEST_FIELDS = new Set([
@@ -76,6 +80,8 @@ export interface ResolvedClawclawBehaviorSource {
76
80
  readonly everyTicks: number;
77
81
  readonly produces?: readonly string[];
78
82
  readonly runtime?: Readonly<BehaviorRuntimeDefaults>;
83
+ readonly trigger?: Readonly<{ manifest: ReturnType<typeof normalizeStrategyPerception>; sha256: string }>;
84
+ readonly triggerError?: string;
79
85
  /** Host-authenticated origin. It is never parsed from module source. */
80
86
  readonly provenance?: Readonly<ClawclawBehaviorSourceProvenance>;
81
87
  /** Host-only trust grant. Static discovery never reads this from module source. */
@@ -542,6 +548,16 @@ export function behaviorSourceCompatibilityError(
542
548
  return source.allowReservedProduces?.includes(eventType) ? undefined : error;
543
549
  }
544
550
 
551
+ /** Finds the literal manifest owned by one exported class, without importing its code. */
552
+ function classManifest(source: string, match: RegExpExecArray): string | undefined {
553
+ const body = balancedBlock(source, match.index + match[0].lastIndexOf('{'));
554
+ if (!body) return undefined;
555
+ const maskedBody = maskNonCode(body, true);
556
+ const manifest = STATIC_MANIFEST.exec(maskedBody);
557
+ if (!manifest || STATIC_MANIFEST.test(maskedBody.slice(manifest.index + manifest[0].length))) return undefined;
558
+ return balancedBlock(body, manifest.index + manifest[0].lastIndexOf('{')) ?? undefined;
559
+ }
560
+
545
561
  /** Inspects one direct-child source using literal parsing only; it never imports player code. */
546
562
  export function inspectClawclawBehaviorSource(
547
563
  sourcePath: string,
@@ -564,19 +580,9 @@ export function inspectClawclawBehaviorSource(
564
580
  ) {
565
581
  return null;
566
582
  }
567
- const classMatch = DEFAULT_CLASS.exec(maskNonCode(source, true));
568
- if (!classMatch) return null;
569
- const classOpen = classMatch.index + classMatch[0].lastIndexOf('{');
570
- const classBody = balancedBlock(source, classOpen);
571
- if (!classBody) return null;
572
- const maskedClassBody = maskNonCode(classBody, true);
573
- const manifestMatch = STATIC_MANIFEST.exec(maskedClassBody);
574
- if (!manifestMatch) return null;
575
- if (STATIC_MANIFEST.test(maskedClassBody.slice(manifestMatch.index + manifestMatch[0].length))) {
576
- return null;
577
- }
578
- const manifestOpen = manifestMatch.index + manifestMatch[0].lastIndexOf('{');
579
- const manifest = balancedBlock(classBody, manifestOpen);
583
+ const masked = maskNonCode(source, true);
584
+ const classMatch = DEFAULT_CLASS.exec(masked);
585
+ const manifest = classMatch && classManifest(source, classMatch);
580
586
  if (!manifest) return null;
581
587
 
582
588
  const compatible = sourceCompatibility(manifest);
@@ -586,12 +592,32 @@ export function inspectClawclawBehaviorSource(
586
592
  && Number.isSafeInteger(apiVersionProperty.value)
587
593
  ? apiVersionProperty.value as number
588
594
  : undefined;
595
+ let trigger: ResolvedClawclawBehaviorSource['trigger'];
596
+ let triggerError: string | undefined;
597
+ const namedTrigger = NAMED_TRIGGER.exec(masked);
598
+ if (namedTrigger) {
599
+ try {
600
+ const match = TRIGGER_CLASS.exec(masked.slice(namedTrigger.index));
601
+ if (!match) throw Error('strategy_trigger_requires_perception_v3');
602
+ match.index = namedTrigger.index;
603
+ const literal = classManifest(source, match);
604
+ trigger = {
605
+ manifest: normalizeStrategyPerception(literal && parseLiteralModuleManifest(literal), compatible.id),
606
+ sha256: createHash('sha256').update(source).digest('hex'),
607
+ };
608
+ } catch (error) {
609
+ triggerError = error instanceof Error ? error.message : 'strategy_trigger_manifest_invalid';
610
+ }
611
+ }
589
612
  return deepFreezeBehaviorValue({
613
+ ...(trigger ? { trigger } : {}),
614
+ ...(triggerError ? { triggerError } : {}),
590
615
  ...(apiVersion === undefined ? {} : { apiVersion }),
591
616
  ...compatible,
592
617
  id: compatible.id,
593
618
  sourcePath: path,
594
619
  sourceRoot: root,
620
+ ...(trigger ? { trustedSourceSha256: trigger.sha256 } : {}),
595
621
  });
596
622
  }
597
623
 
@@ -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
  }
@@ -43,6 +43,7 @@ export type BehaviorReflexActivationResult =
43
43
  | Readonly<{
44
44
  accepted: true;
45
45
  activationId: string;
46
+ ready?: Promise<'ready' | 'invalid' | 'cancelled'>;
46
47
  replacedActivationId?: string;
47
48
  }>
48
49
  | Readonly<{
@@ -236,7 +236,7 @@ function triggerLifecycle(frame: Readonly<ObservationFrame>): string {
236
236
  }
237
237
 
238
238
  /**
239
- * Ordered Trigger host. Trigger and Perception project the same Source frame
239
+ * Compatibility host for previously installed standalone Trigger resources. Trigger and Perception project the same Source frame
240
240
  * independently and have no scheduler dependency on each other. Trigger
241
241
  * delegates at most one same-epoch Reflex request to the narrow Behavior
242
242
  * activation boundary.
@@ -257,6 +257,8 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
257
257
  readonly failurePolicy = 'failed_completion' as const;
258
258
 
259
259
  private registrations: Map<string, EffectiveTriggerConfig>;
260
+ private readonly pendingActivations = new Map<string, string>();
261
+ private readonly invalidInputs = new Map<string, string>();
260
262
  private readonly loader: TriggerModuleLoader;
261
263
  private readonly slots = new Map<string, TriggerSlot>();
262
264
  private readonly loadFailures = new Set<string>();
@@ -303,7 +305,6 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
303
305
  this.driver = driver;
304
306
  }
305
307
 
306
- /** Atomically replace effective config; newly enabled modules import on the next ordered boundary. */
307
308
  configure(triggers: readonly ClawclawTriggerRegistration[]): void {
308
309
  const next = normalizeRegistrations(triggers);
309
310
  for (const [id, config] of next) {
@@ -314,6 +315,8 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
314
315
  }
315
316
  this.configGeneration += 1;
316
317
  this.registrations = next;
318
+ this.pendingActivations.clear();
319
+ this.invalidInputs.clear();
317
320
  this.slots.clear();
318
321
  this.loadFailures.clear();
319
322
  for (const id of this.states.keys()) if (!next.has(id)) this.states.delete(id);
@@ -684,6 +687,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
684
687
 
685
688
  for (const evaluation of computed.evaluations) {
686
689
  if (evaluation.outcome !== 'clear') continue;
690
+ this.invalidInputs.delete(evaluation.triggerId);
687
691
  const config = this.registrations.get(evaluation.triggerId);
688
692
  if (config?.rearm !== 'after_clear') continue;
689
693
  const state = this.stateFor(evaluation.triggerId);
@@ -693,14 +697,17 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
693
697
  const candidates = computed.evaluations.flatMap((evaluation) => {
694
698
  if (evaluation.outcome !== 'match' || !evaluation.match) return [];
695
699
  const config = this.registrations.get(evaluation.triggerId);
696
- if (!config || !this.isEnabled(config)) return [];
700
+ if (!config || !this.isEnabled(config) || this.pendingActivations.has(evaluation.triggerId)) return [];
701
+ const behaviorInput = { ...config.behaviorInput, ...evaluation.match.behaviorInput };
702
+ const inputKey = JSON.stringify(behaviorInput);
703
+ if (this.invalidInputs.get(evaluation.triggerId) === inputKey) return [];
697
704
  const state = this.stateFor(evaluation.triggerId);
698
705
  if (config.rearm === 'after_clear' && !state.armed) return [];
699
706
  if (
700
707
  state.lastAcceptedAtMs !== undefined
701
708
  && computed.nowMs - state.lastAcceptedAtMs < config.cooldownMs
702
709
  ) return [];
703
- return [{ config, match: evaluation.match }];
710
+ return [{ config, match: evaluation.match, behaviorInput, inputKey }];
704
711
  }).sort((left, right) => {
705
712
  if (left.config.reflexPriority !== right.config.reflexPriority) {
706
713
  return left.config.reflexPriority > right.config.reflexPriority ? -1 : 1;
@@ -721,10 +728,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
721
728
  epochId: computed.epochId,
722
729
  configGeneration: computed.configGeneration,
723
730
  behavior: selected.config.behavior,
724
- behaviorInput: Object.freeze({
725
- ...structuredClone(selected.config.behaviorInput),
726
- ...structuredClone(selected.match.behaviorInput ?? {}),
727
- }),
731
+ behaviorInput: Object.freeze(structuredClone(selected.behaviorInput)),
728
732
  reflexPriority: selected.config.reflexPriority,
729
733
  maxRuntimeMs: selected.config.maxRuntimeMs,
730
734
  reason: selected.match.reason,
@@ -753,9 +757,23 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
753
757
  }
754
758
  }
755
759
  if (activationResult.accepted) {
756
- const state = this.stateFor(request.triggerId);
757
- state.lastAcceptedAtMs = computed.nowMs;
758
- if (selected.config.rearm === 'after_clear') state.armed = false;
760
+ const accept = () => {
761
+ const state = this.stateFor(request.triggerId);
762
+ state.lastAcceptedAtMs = computed.nowMs;
763
+ if (selected.config.rearm === 'after_clear') state.armed = false;
764
+ };
765
+ if (activationResult.ready) {
766
+ const activationId = activationResult.activationId;
767
+ this.pendingActivations.set(request.triggerId, activationId);
768
+ void activationResult.ready.then(outcome => {
769
+ if (this.pendingActivations.get(request.triggerId) !== activationId) return;
770
+ this.pendingActivations.delete(request.triggerId);
771
+ if (outcome === 'ready') accept();
772
+ if (outcome === 'invalid') this.invalidInputs.set(request.triggerId, selected.inputKey);
773
+ });
774
+ } else {
775
+ accept();
776
+ }
759
777
  context.diagnostic('trigger.activation.accepted', {
760
778
  trigger_id: request.triggerId,
761
779
  behavior_id: request.behavior,
@@ -766,6 +784,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
766
784
  }),
767
785
  });
768
786
  } else {
787
+ if (activationResult.reason === 'binding_invalid') this.invalidInputs.set(request.triggerId, selected.inputKey);
769
788
  context.diagnostic('trigger.activation.rejected', {
770
789
  trigger_id: request.triggerId,
771
790
  behavior_id: request.behavior,
@@ -799,6 +818,8 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
799
818
  this.slots.clear();
800
819
  this.loadFailures.clear();
801
820
  this.states.clear();
821
+ this.pendingActivations.clear();
822
+ this.invalidInputs.clear();
802
823
  this.observationMemory.clear();
803
824
  this.clearFrameBoundary();
804
825
  this.threadPool = undefined;
@@ -809,7 +830,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
809
830
  }
810
831
 
811
832
  private memoryNamespace(source: ResolvedClawclawTriggerSource): string {
812
- return `trigger:${source.id}`;
833
+ return 'trigger:' + source.id;
813
834
  }
814
835
 
815
836
  private async ensureThreadPool(
@@ -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
  }
@@ -1,22 +0,0 @@
1
- import { ClawclawPerception, type PerceptionModuleInput, type PerceptionModuleResult } from '@myclaw163/clawclaw-cli/perception-plugin';
2
-
3
- /** Equip this Perception and the separate auto-escape Behavior. */
4
- export default class NearbyReflex extends ClawclawPerception {
5
- static readonly manifest = {
6
- apiVersion: 3, id: 'community.nearby-reflex', description: '观察附近玩家,通知 Agent,并可请求撤离反射。',
7
- inputs: [{ id: 'triggerDistance', type: 'number', description: '观察距离', default: 160, min: 1, max: 1000 }],
8
- produces: ['perception.nearby'],
9
- strategies: { escape: { name: 'community.auto-escape', reflexPriority: 40, cooldownMs: 3000,
10
- rearm: 'after_clear', maxRuntimeMs: 10000 } },
11
- } as const;
12
- evaluate(input: PerceptionModuleInput): PerceptionModuleResult {
13
- const self = input.frame?.observation.players.find(player => player.observer);
14
- const nearby = self && input.frame?.observation.players.some(player => !player.observer
15
- && player.alive !== false && Math.hypot(player.x - self.x, player.y - self.y) <= Number(input.config.triggerDistance));
16
- const previous = input.state as { nearby?: boolean } | undefined;
17
- return { state: { nearby: !!nearby },
18
- events: nearby && !previous?.nearby ? [{ type: 'perception.nearby', key: String(input.nowMs),
19
- wakeAgent: true, payload: { text: '有玩家进入观察范围。' } }] : [],
20
- activations: nearby ? [{ strategy: 'escape', reason: 'player_nearby' }] : [] };
21
- }
22
- }