@myclaw163/clawclaw-cli 0.9.1 → 0.9.2

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 (82) hide show
  1. package/README.md +1 -1
  2. package/docs/custom-modules/README.md +14 -15
  3. package/docs/custom-modules/api-reference.md +73 -36
  4. package/docs/custom-modules/behavior.md +116 -22
  5. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  6. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  7. package/docs/custom-modules/perception.md +48 -247
  8. package/docs/custom-modules/trigger.md +5 -5
  9. package/docs/runtime/README.md +5 -5
  10. package/docs/runtime/agent-notifications.md +2 -2
  11. package/docs/runtime/behavior-runtime.md +34 -29
  12. package/docs/runtime/components-and-boundaries.md +55 -147
  13. package/docs/runtime/events-and-state.md +17 -5
  14. package/docs/runtime/owner-lifecycle-and-observability.md +2 -2
  15. package/docs/user-guide/README.md +6 -6
  16. package/docs/user-guide/api-reference.md +69 -34
  17. package/docs/user-guide/behavior.md +116 -22
  18. package/docs/user-guide/perception.md +48 -247
  19. package/package.json +1 -1
  20. package/scripts/check-skill-command-surface.mjs +2 -2
  21. package/skills/clawclaw/SKILL.md +8 -6
  22. package/skills/clawclaw/references/BEHAVIORS.md +18 -7
  23. package/skills/clawclaw/references/COMMANDS.md +19 -0
  24. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +116 -22
  25. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +70 -38
  26. package/skills/clawclaw/references/CUSTOM-MODULES.md +13 -14
  27. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +48 -247
  28. package/skills/clawclaw/references/STREAM.md +1 -1
  29. package/src/commands/behavior.ts +28 -99
  30. package/src/commands/load.ts +15 -23
  31. package/src/commands/module-runtime-control.ts +113 -0
  32. package/src/commands/perception.ts +18 -4
  33. package/src/commands/trigger.ts +1 -1
  34. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  35. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  36. package/src/runtime/clawclaw/owner.ts +50 -5
  37. package/src/runtime/clawclaw/perception-module-manifest.ts +16 -7
  38. package/src/runtime/clawclaw/plugins/assembly.ts +22 -32
  39. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +16 -3
  40. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +4 -0
  41. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +129 -57
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +7 -2
  45. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -1
  46. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +21 -18
  47. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +3 -2
  48. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +2 -0
  49. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  50. package/src/runtime/clawclaw/plugins/{source → derived-event}/task-change-tracker.ts +1 -1
  51. package/src/runtime/clawclaw/plugins/perception/{reaction-plugin.ts → perception-module-plugin.ts} +151 -70
  52. package/src/runtime/clawclaw/plugins/perception/{reaction-runner.ts → perception-module-runner.ts} +26 -13
  53. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +17 -6
  54. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  55. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +11 -9
  56. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2 -103
  57. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  58. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  59. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +61 -10
  60. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  61. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  62. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  63. package/src/runtime/clawclaw/runtime-state.ts +1 -1
  64. package/src/runtime/clawclaw/runtime.ts +3 -3
  65. package/src/runtime/clawclaw/strategy-memory-rpc.ts +63 -0
  66. package/src/runtime/clawclaw/strategy-memory.ts +77 -0
  67. package/src/runtime/clawclaw-event-catalog.ts +5 -5
  68. package/src/runtime/framework/plugins/contracts.ts +8 -0
  69. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +17 -6
  70. package/src/runtime/owner-control.ts +5 -0
  71. package/src/sdk/behavior-plugin/index.ts +4 -1
  72. package/src/sdk/index.ts +4 -1
  73. package/src/sdk/perception-plugin/index.ts +6 -4
  74. package/src/sdk/perception-plugin/module.ts +13 -4
  75. package/src/sdk/perception-plugin/reaction.ts +1 -1
  76. package/src/sdk/strategy-memory.ts +12 -0
  77. package/src/sdk/trigger-plugin/index.ts +3 -3
  78. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  79. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  80. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  81. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  82. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -0,0 +1,63 @@
1
+ import type { StrategyMemory, StrategyMemoryValue } from '../../sdk/strategy-memory.js';
2
+ import { validateStrategyMemoryValue } from './strategy-memory.js';
3
+
4
+ export interface StrategyMemoryRequest {
5
+ readonly type: 'strategy_memory';
6
+ readonly requestId: string;
7
+ readonly memoryRequestId: number;
8
+ readonly operation: 'get' | 'set' | 'delete';
9
+ readonly key: string;
10
+ readonly value?: StrategyMemoryValue;
11
+ }
12
+ export const unavailableStrategyMemory: StrategyMemory = {
13
+ get: async () => { throw Error('strategy_memory_unavailable'); },
14
+ set: async () => { throw Error('strategy_memory_unavailable'); },
15
+ delete: async () => { throw Error('strategy_memory_unavailable'); },
16
+ };
17
+
18
+ /** Replies are handled outside the computation queue, so an awaited memory call cannot deadlock it. */
19
+ export class StrategyMemoryRpcClient {
20
+ private sequence = 0;
21
+ private pending = new Map<number, { requestId: string; resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
22
+ constructor(private readonly send: (value: Readonly<Record<string, unknown>>) => void) {}
23
+ receive(message: any): boolean {
24
+ if (message?.type !== 'strategy_memory_result') return false;
25
+ const pending = this.pending.get(message.memoryRequestId);
26
+ if (!pending || pending.requestId !== message.requestId) return true;
27
+ this.pending.delete(message.memoryRequestId); clearTimeout(pending.timer);
28
+ if (message.error) pending.reject(Error(String(message.error))); else pending.resolve(message.value);
29
+ return true;
30
+ }
31
+ bind(requestId: string, isActive: () => boolean): StrategyMemory {
32
+ const call = (operation: StrategyMemoryRequest['operation'], key: string, value?: StrategyMemoryValue): Promise<any> => {
33
+ if (!isActive()) return Promise.reject(Error('strategy_memory_inactive'));
34
+ if (this.pending.size >= 64) return Promise.reject(Error('strategy_memory_request_limit'));
35
+ if (operation === 'set') { try { validateStrategyMemoryValue(value); } catch (error) { return Promise.reject(error); } }
36
+ const memoryRequestId = ++this.sequence;
37
+ return new Promise((resolve, reject) => {
38
+ const timer = setTimeout(() => { this.pending.delete(memoryRequestId); reject(Error('strategy_memory_timeout')); }, 5000);
39
+ timer.unref?.(); this.pending.set(memoryRequestId, {requestId, resolve, reject, timer});
40
+ try { this.send({type: 'strategy_memory', requestId, memoryRequestId, operation, key, ...(operation === 'set' ? {value} : {})}); }
41
+ catch (error) { this.pending.delete(memoryRequestId); clearTimeout(timer); reject(error); }
42
+ });
43
+ };
44
+ return Object.freeze({ get: <T extends StrategyMemoryValue>(key: string) => call('get', key) as Promise<T | undefined>,
45
+ set: (key: string, value: StrategyMemoryValue) => call('set', key, value), delete: (key: string) => call('delete', key) });
46
+ }
47
+ }
48
+
49
+ /** The parent supplies an already-bound capability; messages cannot choose another resource or scope. */
50
+ export async function serveStrategyMemoryRequest(message: StrategyMemoryRequest, binding: StrategyMemory | (() => StrategyMemory),
51
+ send: (value: Readonly<Record<string, unknown>>) => void): Promise<void> {
52
+ let value: unknown, error: string | undefined;
53
+ try {
54
+ const memory = typeof binding === 'function' ? binding() : binding;
55
+ if (!Number.isSafeInteger(message.memoryRequestId) || typeof message.key !== 'string') throw Error('strategy_memory_request_invalid');
56
+ if (message.operation === 'get') value = await memory.get(message.key);
57
+ else if (message.operation === 'set') await memory.set(message.key, message.value!);
58
+ else if (message.operation === 'delete') await memory.delete(message.key);
59
+ else throw Error('strategy_memory_request_invalid');
60
+ } catch (failure) { error = failure instanceof Error ? failure.message : 'strategy_memory_failed'; }
61
+ try { send({type: 'strategy_memory_result', requestId: message.requestId, memoryRequestId: message.memoryRequestId,
62
+ ...(error ? {error} : {value})}); } catch { /* the requesting Worker may have stopped */ }
63
+ }
@@ -0,0 +1,77 @@
1
+ import type { StrategyMemory, StrategyMemoryValue } from '../../sdk/strategy-memory.js';
2
+
3
+ export const STRATEGY_MEMORY_MAX_BYTES = 64 * 1024;
4
+ const MAX_KEYS = 256, MAX_SCOPE_BYTES = 4 * 1024 * 1024;
5
+ type Scope = Readonly<{ sessionId: string; segmentId: string }>;
6
+ interface Namespace { values: Map<string, { value: StrategyMemoryValue; bytes: number }>; bytes: number }
7
+ interface Segment { namespaces: Map<string, Namespace>; bytes: number }
8
+ const scopeKey = (scope: Scope) => JSON.stringify([scope.sessionId, scope.segmentId]);
9
+
10
+ function keySize(key: string): number {
11
+ if (typeof key !== 'string' || !key || Buffer.byteLength(key) > 256) throw Error('strategy_memory_key_invalid');
12
+ return Buffer.byteLength(key);
13
+ }
14
+ export function validateStrategyMemoryValue(value: unknown): asserts value is StrategyMemoryValue {
15
+ const seen = new Set<object>();
16
+ const visit = (entry: unknown, depth: number): void => {
17
+ if (depth > 32) throw Error('strategy_memory_value_invalid');
18
+ if (entry === null || typeof entry === 'boolean' || typeof entry === 'string') return;
19
+ if (typeof entry === 'number' && Number.isFinite(entry)) return;
20
+ if (!entry || typeof entry !== 'object' || seen.has(entry)) throw Error('strategy_memory_value_invalid');
21
+ const prototype = Object.getPrototypeOf(entry);
22
+ if (!Array.isArray(entry) && prototype !== Object.prototype && prototype !== null) throw Error('strategy_memory_value_invalid');
23
+ seen.add(entry);
24
+ for (const descriptor of Object.values(Object.getOwnPropertyDescriptors(entry))) {
25
+ if (!('value' in descriptor)) throw Error('strategy_memory_value_invalid');
26
+ // Array length is a finite number and is harmless to validate as well.
27
+ visit(descriptor.value, depth + 1);
28
+ }
29
+ if (Object.getOwnPropertySymbols(entry).length) throw Error('strategy_memory_value_invalid');
30
+ seen.delete(entry);
31
+ };
32
+ visit(value, 0);
33
+ if (Buffer.byteLength(JSON.stringify(value)) > STRATEGY_MEMORY_MAX_BYTES) throw Error('strategy_memory_limit_exceeded');
34
+ }
35
+
36
+ /** One explicitly assembled Owner-local store. Never persisted or shared with another account/Owner. */
37
+ export class ClawclawStrategyMemory {
38
+ private readonly segments = new Map<string, Segment>();
39
+ open(scope: Scope): void {
40
+ const key = scopeKey(scope);
41
+ if (!this.segments.has(key)) this.segments.set(key, { namespaces: new Map(), bytes: 0 });
42
+ }
43
+ close(scope: Scope): void {
44
+ const key = scopeKey(scope), segment = this.segments.get(key);
45
+ if (segment) { segment.namespaces.clear(); segment.bytes = 0; this.segments.delete(key); }
46
+ }
47
+ bind(scope: Scope, namespace: string, isActive: () => boolean): StrategyMemory {
48
+ const key = scopeKey(scope), segment = this.segments.get(key);
49
+ const check = () => {
50
+ if (!segment || this.segments.get(key) !== segment || !isActive()) throw Error('strategy_memory_inactive');
51
+ return segment;
52
+ };
53
+ return Object.freeze({
54
+ get: async <T extends StrategyMemoryValue>(name: string): Promise<T | undefined> => {
55
+ keySize(name); const current = check();
56
+ const value = current.namespaces.get(namespace)?.values.get(name)?.value;
57
+ return value === undefined ? undefined : structuredClone(value) as T;
58
+ },
59
+ set: async (name: string, value: StrategyMemoryValue): Promise<void> => {
60
+ const keyBytes = keySize(name); const current = check(); validateStrategyMemoryValue(value);
61
+ const size = keyBytes + Buffer.byteLength(JSON.stringify(value));
62
+ const target = current.namespaces.get(namespace) ?? { values: new Map(), bytes: 0 };
63
+ const old = target.values.get(name)?.bytes ?? 0, delta = size - old;
64
+ if ((!target.values.has(name) && target.values.size >= MAX_KEYS)
65
+ || target.bytes + delta > STRATEGY_MEMORY_MAX_BYTES || current.bytes + delta > MAX_SCOPE_BYTES) {
66
+ throw Error('strategy_memory_limit_exceeded');
67
+ }
68
+ target.values.set(name, { value: structuredClone(value), bytes: size });
69
+ target.bytes += delta; current.bytes += delta; current.namespaces.set(namespace, target);
70
+ },
71
+ delete: async (name: string): Promise<void> => {
72
+ keySize(name); const current = check(), target = current.namespaces.get(namespace), entry = target?.values.get(name);
73
+ if (target && entry) { target.values.delete(name); target.bytes -= entry.bytes; current.bytes -= entry.bytes; }
74
+ },
75
+ });
76
+ }
77
+ }
@@ -36,8 +36,8 @@ export interface ClawclawEventCatalogOptions {
36
36
  visualEventTypes?: readonly string[];
37
37
  /** Events declared by the enabled Intent and Strategy manifests at startup. */
38
38
  behaviorEventTypes?: readonly string[];
39
- /** Own notification types from equipped reaction perceptions. */
40
- reactionEventTypes?: readonly string[];
39
+ /** Own notification types from equipped unified perceptions. */
40
+ perceptionEventTypes?: readonly string[];
41
41
  }
42
42
 
43
43
  /**
@@ -183,8 +183,8 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
183
183
  'players_changed',
184
184
  'reminder.task',
185
185
  'reminder.speech',
186
+ 'perception.module_failed',
186
187
  'perception.behavior_unavailable',
187
- 'perception.reaction_failed',
188
188
  'emergency_countdown_warning',
189
189
  'ability.ready',
190
190
  'ability.remaining_uses_changed',
@@ -253,7 +253,7 @@ function visualDelivery(
253
253
  }
254
254
 
255
255
  function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[] {
256
- const perceptionOutputTypes = new Set(options.reactionEventTypes ?? []);
256
+ const perceptionOutputTypes = new Set(options.perceptionEventTypes ?? []);
257
257
  const ownOutputDelivery = (type: string) => perceptionOutputTypes.has(type)
258
258
  ? visualDelivery(options.visualEventDelivery, type) : 'monitor_and_events' as const;
259
259
  const visualEventTypes = [...new Set([
@@ -264,7 +264,7 @@ function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[]
264
264
  ...CLAWCLAW_FIXED_EVENT_TYPES,
265
265
  ...visualEventTypes,
266
266
  ]);
267
- const behaviorEventTypes = [...new Set([...(options.behaviorEventTypes ?? []), ...(options.reactionEventTypes ?? [])])]
267
+ const behaviorEventTypes = [...new Set([...(options.behaviorEventTypes ?? []), ...(options.perceptionEventTypes ?? [])])]
268
268
  .filter((type) => !fixedAndVisualTypes.has(type))
269
269
  .sort();
270
270
  return [
@@ -118,7 +118,11 @@ export interface RuntimeEventProposal {
118
118
  /** Whether this Event may initiate Agent delivery; omitted means true. */
119
119
  readonly wakeAgent?: boolean;
120
120
  readonly type: string;
121
+ /** Stable key for retrying this output at the same epoch and output position.
122
+ * Cross-epoch repetition is controlled by the producer's rule state, not this key.
123
+ */
121
124
  readonly dedupeKey: string;
125
+ /** Identity namespace only; epoch and output position remain part of the ID. */
122
126
  readonly dedupeScope?: 'segment' | 'session';
123
127
  readonly payload: Record<string, unknown>;
124
128
  readonly occurredAt?: string;
@@ -147,6 +151,10 @@ export interface RuntimeEpochPluginResult {
147
151
  export interface RuntimeEpochPluginContext<TState = Record<string, unknown>> {
148
152
  readonly scope: Readonly<RuntimeScope>;
149
153
  readonly stateHistory: StateFrameHistoryReader<TState>;
154
+ /** Declared Source facts in an accepted epoch, restricted to this scope and invocation boundary.
155
+ * Used to rebuild state rules with the same facts as live processing; never returns plugin outputs.
156
+ */
157
+ readonly sourceEventsAt?: (epochSeq: number) => readonly RuntimeSourceEvent[];
150
158
  /** Current logical segment without exposing Runtime internals. */
151
159
  readonly currentSegment: () => {
152
160
  readonly kind: string;
@@ -22,6 +22,7 @@ import type {
22
22
  RuntimeDiagnosticSeverity,
23
23
  RuntimeEventProposal,
24
24
  RuntimeInputJournal,
25
+ RuntimeSourceEvent,
25
26
  RuntimePluginCapabilityAccess,
26
27
  RuntimePluginFailurePolicy,
27
28
  RuntimePluginStore,
@@ -852,12 +853,15 @@ export class RuntimePluginScheduler<
852
853
  const catchUp = plugin.catchUp ?? 'every_epoch';
853
854
  const count = this.catchUpCounts.get(plugin.id) ?? 0;
854
855
  const requiredIndex = candidates.findIndex((candidate) => forbidsCoalescing(candidate.work));
855
- const shouldJump = requiredIndex > 0 || (
856
- requiredIndex < 0 && (
857
- catchUp === 'latest_only' || (
858
- catchUp === 'every_epoch'
859
- && count >= normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs)
860
- && candidates.length > 1
856
+ // A required boundary must not discard earlier strict-ordered inputs.
857
+ const shouldJump = catchUp !== 'strict_ordered' && (
858
+ requiredIndex > 0 || (
859
+ requiredIndex < 0 && (
860
+ catchUp === 'latest_only' || (
861
+ catchUp === 'every_epoch'
862
+ && count >= normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs)
863
+ && candidates.length > 1
864
+ )
861
865
  )
862
866
  )
863
867
  );
@@ -1677,6 +1681,13 @@ export class RuntimePluginScheduler<
1677
1681
  return Object.freeze({
1678
1682
  scope: cloneCanonical(scope),
1679
1683
  stateHistory: this.stateHistoryThrough(scope, epochSeq),
1684
+ sourceEventsAt: (requestedEpoch: number): readonly RuntimeSourceEvent[] => {
1685
+ if (!Number.isSafeInteger(requestedEpoch) || requestedEpoch < 1 || requestedEpoch > epochSeq) return [];
1686
+ const input = this.inputJournal.epoch(requestedEpoch);
1687
+ if (!input || runtimeScopeKey(input.scope) !== runtimeScopeKey(scope)) return [];
1688
+ const types = new Set(plugin.consumes?.events ?? []);
1689
+ return cloneCanonical(input.events.filter(event => types.has('*') || types.has(event.type))) as unknown as readonly RuntimeSourceEvent[];
1690
+ },
1680
1691
  currentSegment: segment
1681
1692
  ? () => cloneCanonical(segment)
1682
1693
  : this.currentSegment,
@@ -33,6 +33,11 @@ export type MasterOwnerControlType =
33
33
  | 'mailbox_events_prepare'
34
34
  | 'mailbox_events_ack'
35
35
  | 'mailbox_events_release'
36
+ | 'perception_update'
37
+ | 'perception_status'
38
+ | 'behavior_watch'
39
+ | 'behavior_unwatch'
40
+ | 'behavior_update'
36
41
  | 'behavior_start'
37
42
  | 'behavior_status'
38
43
  | 'behavior_cancel'
@@ -4,6 +4,8 @@ import type {
4
4
  Position,
5
5
  } from '../module-input/index.js';
6
6
  import type { ClawclawResourceLocalizations } from '../resource-metadata.js';
7
+ import type { StrategyMemory } from '../strategy-memory.js';
8
+ export type { StrategyMemory, StrategyMemoryValue } from '../strategy-memory.js';
7
9
 
8
10
  export const BEHAVIOR_PLUGIN_API_VERSION = 3 as const;
9
11
 
@@ -174,8 +176,9 @@ export interface ObservedCorpse extends Position {
174
176
  readonly ageMs: number;
175
177
  }
176
178
 
177
- /** Read-only, epoch-bound capabilities available while a Behavior computes a Decision. */
179
+ /** Epoch-bound game queries and resource-scoped private memory. */
178
180
  export interface BehaviorReadApi {
181
+ readonly memory: StrategyMemory;
179
182
  readonly spatial: SpatialApi;
180
183
  readonly navigation: {
181
184
  pathDistance(from: Readonly<Position>, to: Readonly<Position>): Promise<number | null>;
package/src/sdk/index.ts CHANGED
@@ -25,6 +25,7 @@
25
25
  */
26
26
 
27
27
  export { Action } from './action.js';
28
+ export type { StrategyMemory, StrategyMemoryValue } from './strategy-memory.js';
28
29
  export { getTaskAvailability, getAvailableTasks, isTaskAvailable, getTaskKind } from './task-availability.js';
29
30
  export type { GameTaskAvailability, GameTaskKind } from './module-input/index.js';
30
31
  export { GameClient } from '../lib/game-client.js';
@@ -57,7 +58,8 @@ export {
57
58
  TRIGGER_PLUGIN_API_VERSION,
58
59
  } from './trigger-plugin/index.js';
59
60
  export type {
60
- PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleEvent,
61
+ PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleEvent, PerceptionModuleApi,
62
+ ClawclawReactionManifest, ReactionBehaviorBinding, ReactionActivation, ReactionInput, ReactionResult,
61
63
  ClawclawPerceptionClass, ClawclawPerceptionEventMetadata,
62
64
  ClawclawPerceptionManifest, Direction, PerceptionAnalysisInput,
63
65
  PerceptionApi, PerceptionBoundary, PerceptionBoundaryKind,
@@ -65,6 +67,7 @@ export type {
65
67
  PerceptionSpatialApi, PerceptionSubjectScope, Vec,
66
68
  } from './perception-plugin/index.js';
67
69
  export {
70
+ ClawclawReaction,
68
71
  ClawclawParallelPerception,
69
72
  ClawclawPerception,
70
73
  MOVE_MIN_PX,
@@ -1,9 +1,10 @@
1
1
  /** Frozen API v2 compatibility version; new modules use PERCEPTION_MODULE_API_VERSION (3). */
2
2
  export const PERCEPTION_PLUGIN_API_VERSION = 2 as const;
3
3
  export * from './module.js';
4
- import type { PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult } from './module.js';
4
+ import type { PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleApi } from './module.js';
5
+ export { ClawclawReaction } from './reaction.js';
6
+ export type { ClawclawReactionManifest, ReactionBehaviorBinding, ReactionActivation, ReactionInput, ReactionResult, ReactionEvent, ReactionFact } from './reaction.js';
5
7
  export * from './reminder.js';
6
- export * from './reaction.js';
7
8
  import { defaultReminder } from './reminder-rules.js';
8
9
  import type { ReminderInput, ReminderResult, ReminderTopic } from './reminder.js';
9
10
  /** Optional task/speech helper accepts both the unified input and its v2 compatibility input. */
@@ -121,8 +122,9 @@ export interface PerceptionEventProposal {
121
122
  /** Whether this Event may initiate Agent delivery; omitted means true. */
122
123
  readonly wakeAgent?: boolean;
123
124
  readonly type: string;
124
- /** Stable identity of this semantic slice within the current segment. */
125
+ /** Stable semantic key for replaying the same epoch/output; not cross-frame suppression. */
125
126
  readonly dedupeKey: string;
127
+ /** Identity namespace; epoch and output position still participate in event identity. */
126
128
  readonly dedupeScope?: 'segment' | 'session';
127
129
  readonly payload: Readonly<Record<string, unknown>>;
128
130
  readonly occurredAt?: string;
@@ -171,7 +173,7 @@ export abstract class ClawclawPerception {
171
173
  static readonly manifest?: ClawclawPerceptionManifest | PerceptionModuleManifest;
172
174
 
173
175
  /** API v3 combines observation, notification and fixed Behavior activation. */
174
- evaluate(_input: Readonly<PerceptionModuleInput>): PerceptionModuleResult | Promise<PerceptionModuleResult> {
176
+ evaluate(_input: Readonly<PerceptionModuleInput>, _api?: PerceptionModuleApi): PerceptionModuleResult | Promise<PerceptionModuleResult> {
175
177
  throw new Error('PERCEPTION_EVALUATE_NOT_IMPLEMENTED');
176
178
  }
177
179
 
@@ -1,10 +1,11 @@
1
1
  import type { GameState, ObservationFrame } from '../module-input/index.js';
2
2
  import type { BehaviorInputFieldSpec } from '../behavior-plugin/index.js';
3
3
  import type { ClawclawResourceLocalizations } from '../resource-metadata.js';
4
- import type { ReactionBehaviorBinding, ReactionActivation } from './reaction.js';
5
4
  import type { ReminderFact, ReminderTaskChange } from './reminder.js';
5
+ import type { ReactionActivation, ReactionBehaviorBinding } from './reaction.js';
6
+ import type { StrategyMemory } from '../strategy-memory.js';
6
7
 
7
- /** Unified authoring contract; v2 visual/reminder/reaction scripts remain supported. */
8
+ /** Unified perception contract with optional fixed Reflex bindings. */
8
9
  export const PERCEPTION_MODULE_API_VERSION = 3 as const;
9
10
  export interface PerceptionModuleManifest {
10
11
  readonly apiVersion: typeof PERCEPTION_MODULE_API_VERSION;
@@ -14,9 +15,9 @@ export interface PerceptionModuleManifest {
14
15
  readonly localizations?: ClawclawResourceLocalizations;
15
16
  readonly consumes?: readonly string[];
16
17
  readonly produces?: readonly string[];
17
- readonly behaviors?: Readonly<Record<string, ReactionBehaviorBinding>>;
18
18
  readonly inputs?: readonly BehaviorInputFieldSpec[];
19
19
  readonly config?: Readonly<Record<string, unknown>>;
20
+ readonly behaviors?: Readonly<Record<string, ReactionBehaviorBinding>>;
20
21
  }
21
22
  export interface PerceptionModuleInput {
22
23
  readonly moduleId: string;
@@ -30,7 +31,14 @@ export interface PerceptionModuleInput {
30
31
  readonly nowMs: number;
31
32
  readonly config: Readonly<Record<string, unknown>>;
32
33
  readonly state: unknown;
33
- readonly availableBehaviors: readonly string[];
34
+ /** Equipped, loadable dependencies; independent of the automatic-activation switch. */
35
+ readonly availableBindings?: readonly string[];
36
+ readonly availableBehaviors?: readonly string[];
37
+ readonly enabledBindings?: readonly string[];
38
+ }
39
+ export interface PerceptionModuleApi {
40
+ /** Shared with a unique explicitly bound strategy; otherwise module-private. */
41
+ readonly memory: StrategyMemory;
34
42
  }
35
43
  export interface PerceptionModuleEvent {
36
44
  readonly type: string;
@@ -42,5 +50,6 @@ export interface PerceptionModuleEvent {
42
50
  export interface PerceptionModuleResult {
43
51
  readonly state?: unknown;
44
52
  readonly events?: readonly PerceptionModuleEvent[];
53
+ /** Keys in manifest.behaviors; never arbitrary strategy names or executable Actions. */
45
54
  readonly activations?: readonly ReactionActivation[];
46
55
  }
@@ -7,7 +7,7 @@ export interface ReactionBehaviorBinding {
7
7
  readonly name: string;
8
8
  /** Preferred Hub identity. A missing match falls back to name and its duplicate aliases. */
9
9
  readonly resourceId?: string;
10
- readonly layer?: 'reflex' | 'short' | 'long';
10
+ readonly layer?: 'reflex';
11
11
  readonly input?: Readonly<Record<string, unknown>>;
12
12
  readonly reflexPriority?: number;
13
13
  readonly cooldownMs?: number;
@@ -0,0 +1,12 @@
1
+ /** JSON data owned by one strategy resource in the current game and Owner process. */
2
+ export type StrategyMemoryValue = null | boolean | number | string
3
+ | readonly StrategyMemoryValue[] | { readonly [key: string]: StrategyMemoryValue };
4
+
5
+ /** Immediate, resource-scoped memory shared by a Behavior and its explicitly bound Perception.
6
+ * Values are detached copies; writes are independent of Decision or backend Action success.
7
+ */
8
+ export interface StrategyMemory {
9
+ get<T extends StrategyMemoryValue = StrategyMemoryValue>(key: string): Promise<T | undefined>;
10
+ set(key: string, value: StrategyMemoryValue): Promise<void>;
11
+ delete(key: string): Promise<void>;
12
+ }
@@ -2,6 +2,7 @@ import type {
2
2
  BehaviorInputFieldSpec,
3
3
  BehaviorReadApi,
4
4
  } from '../behavior-plugin/index.js';
5
+ export type { StrategyMemory, StrategyMemoryValue } from '../strategy-memory.js';
5
6
  import type {
6
7
  GameEvent,
7
8
  ObservationFrame,
@@ -90,7 +91,7 @@ export type TriggerResetReason =
90
91
  | 'segment_ending'
91
92
  | 'shutdown';
92
93
 
93
- /** Trigger rules receive only the common read-only module capabilities. */
94
+ /** Read-only game queries plus private memory shared with the same resource's Behavior. */
94
95
  export type TriggerReadApi = BehaviorReadApi;
95
96
 
96
97
  /**
@@ -105,8 +106,7 @@ export interface TriggerMatch {
105
106
  readonly behaviorInput?: Readonly<Record<string, unknown>>;
106
107
  }
107
108
 
108
- /** Public authoring surface for one read-only rule module. */
109
- /** @deprecated Compatibility API; may be unsupported in a future release. Use unified Perception API v3 for new rules. */
109
+ /** Public authoring surface for one rule; game writes remain Behavior Actions. */
110
110
  export abstract class ClawclawTrigger<
111
111
  TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
112
112
  > {
@@ -1,56 +0,0 @@
1
- import {
2
- ClawclawReaction,
3
- type ReactionInput,
4
- type ReactionResult,
5
- } from '@myclaw163/clawclaw-cli/perception-plugin';
6
-
7
- // 教学规则:靠近不代表敌意;撤离点需先在当前地图中验证。
8
- export default class NearbyEscape extends ClawclawReaction {
9
- static readonly manifest = {
10
- apiVersion: 2,
11
- kind: 'reaction',
12
- id: 'nearby_escape',
13
- description: '可见玩家靠近时记录通知,并请求前往已配置的撤离点。',
14
- consumes: [],
15
- produces: ['reaction.player_close'],
16
- behaviors: {
17
- escape: {
18
- name: 'community.go-to-point',
19
- layer: 'reflex',
20
- reflexPriority: 10,
21
- cooldownMs: 3000,
22
- rearm: 'after_clear',
23
- maxRuntimeMs: 10000,
24
- },
25
- },
26
- inputs: [
27
- { id: 'distance', type: 'number', description: '靠近阈值,单位像素。', default: 160 },
28
- { id: 'retreatX', type: 'number', description: '撤离点 X 坐标。', default: 640 },
29
- { id: 'retreatY', type: 'number', description: '撤离点 Y 坐标。', default: 360 },
30
- ],
31
- config: { distance: 160, retreatX: 640, retreatY: 360 },
32
- } as const;
33
-
34
- evaluate(input: Readonly<ReactionInput>): ReactionResult {
35
- const previous = input.state as { close?: boolean } | undefined;
36
- const players = input.frame?.observation.players ?? [];
37
- const self = players.find(player => player.observer);
38
- const close = input.gameState?.phase === 'wandering' && input.gameState.you?.is_alive === true
39
- && !!self && players.some(player => !player.observer && player.alive !== false
40
- && Math.hypot(player.x - self.x, player.y - self.y) < Number(input.config.distance));
41
- return {
42
- state: { close },
43
- events: close && !previous?.close ? [{
44
- type: 'reaction.player_close',
45
- key: `close:${input.gameState!.tick}`,
46
- wakeAgent: false,
47
- payload: { text: '有可见玩家靠近,触发撤离规则。' },
48
- }] : [],
49
- activations: close ? [{
50
- behavior: 'escape',
51
- input: { x: Number(input.config.retreatX), y: Number(input.config.retreatY) },
52
- reason: 'visible_player_close',
53
- }] : [],
54
- };
55
- }
56
- }
@@ -1,36 +0,0 @@
1
- import {
2
- ClawclawReaction,
3
- type ReactionInput,
4
- type ReactionResult,
5
- } from '@myclaw163/clawclaw-cli/perception-plugin';
6
-
7
- export default class NearbyNotice extends ClawclawReaction {
8
- static readonly manifest = {
9
- apiVersion: 2,
10
- kind: 'reaction',
11
- id: 'nearby_notice',
12
- description: '其他可见玩家靠近时记录一条通知。',
13
- consumes: [],
14
- produces: ['reaction.player_close'],
15
- inputs: [{ id: 'distance', type: 'number', description: '靠近阈值,单位像素。', default: 160 }],
16
- config: { distance: 160 },
17
- } as const;
18
-
19
- evaluate(input: Readonly<ReactionInput>): ReactionResult {
20
- const previous = input.state as { close?: boolean } | undefined;
21
- const players = input.frame?.observation.players ?? [];
22
- const self = players.find(player => player.observer);
23
- const close = input.gameState?.phase === 'wandering' && input.gameState.you?.is_alive === true
24
- && !!self && players.some(player => !player.observer && player.alive !== false
25
- && Math.hypot(player.x - self.x, player.y - self.y) < Number(input.config.distance));
26
- return {
27
- state: { close },
28
- events: close && !previous?.close ? [{
29
- type: 'reaction.player_close',
30
- key: `close:${input.gameState!.tick}`,
31
- wakeAgent: false,
32
- payload: { text: '有其他可见玩家靠近。' },
33
- }] : [],
34
- };
35
- }
36
- }
@@ -1,21 +0,0 @@
1
- import type { ReactionBehaviorBinding } from '../../sdk/perception-plugin/reaction.js';
2
-
3
- /** Generic module activation port. It is independent of model decision providers. */
4
- export const BEHAVIOR_ACTIVATION_CAPABILITY = 'clawclaw.behavior.activate';
5
- export interface PerceptionBehaviorActivation {
6
- readonly moduleId: string;
7
- readonly bindingKey: string;
8
- readonly behavior: string;
9
- readonly input: Readonly<Record<string, unknown>>;
10
- readonly layer: NonNullable<ReactionBehaviorBinding['layer']>;
11
- readonly reflexPriority: number;
12
- readonly maxRuntimeMs?: number;
13
- readonly reason: string;
14
- readonly epochId: number;
15
- readonly gameId: string;
16
- }
17
- export interface PerceptionBehaviorActivationResult {
18
- readonly accepted: boolean;
19
- readonly reason?: string;
20
- readonly activationId?: string;
21
- }
@@ -1,26 +0,0 @@
1
- import { parentPort, workerData } from 'node:worker_threads';
2
- import { pathToFileURL } from 'node:url';
3
- import { ClawclawReaction, type ReactionInput } from '../../../../sdk/perception-plugin/reaction.js';
4
- import { normalizeReactionManifest } from '../../reaction-manifest.js';
5
-
6
- function freeze<T>(value: T): T {
7
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
8
- for (const child of Object.values(value)) freeze(child); Object.freeze(value);
9
- }
10
- return value;
11
- }
12
- try {
13
- const Module = (await import(pathToFileURL(workerData.modulePath).href)).default;
14
- if (!(Module?.prototype instanceof ClawclawReaction)) throw new Error('REACTION_CLASS_INVALID');
15
- const manifest = normalizeReactionManifest(Module.manifest);
16
- if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('REACTION_MANIFEST_CHANGED');
17
- parentPort!.postMessage({ type: 'ready' });
18
- parentPort!.on('message', async ({ id, input }: { id: number; input: ReactionInput }) => {
19
- try {
20
- const result = await new Module().evaluate(freeze({ ...input, config: manifest.config ?? {},
21
- events: input.events.filter(e => manifest.consumes.includes(e.type)) }));
22
- if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('REACTION_OUTPUT_TOO_LARGE');
23
- parentPort!.postMessage({ type: 'result', id, result });
24
- } catch { parentPort!.postMessage({ type: 'error', id }); }
25
- });
26
- } catch { parentPort!.postMessage({ type: 'error' }); }