@myclaw163/clawclaw-cli 0.8.38 → 0.8.39
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.
- package/docs/custom-modules/README.md +6 -4
- package/docs/custom-modules/api-reference.md +10 -0
- package/docs/custom-modules/examples/nearby-escape.ts +49 -0
- package/docs/custom-modules/perception.md +114 -5
- package/docs/custom-modules/trigger.md +2 -0
- package/docs/runtime/components-and-boundaries.md +2 -2
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +10 -4
- package/skills/clawclaw/references/BEHAVIORS.md +6 -2
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +13 -0
- package/skills/clawclaw/references/CUSTOM-MODULES.md +3 -1
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +114 -5
- package/src/commands/load.ts +25 -1
- package/src/commands/perception.ts +1 -0
- package/src/lib/agent-workspace-runtime.ts +11 -5
- package/src/lib/capability-load-diagnostics.ts +1 -1
- package/src/lib/capability-operation-name.ts +1 -0
- package/src/runtime/clawclaw/behavior-activation-capability.ts +21 -0
- package/src/runtime/clawclaw/owner.ts +8 -3
- package/src/runtime/clawclaw/plugins/assembly.ts +20 -3
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -1
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +4 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +72 -9
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +14 -1
- package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +198 -0
- package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +49 -0
- package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +26 -0
- package/src/runtime/clawclaw/reaction-behavior-resolution.ts +23 -0
- package/src/runtime/clawclaw/reaction-manifest.ts +50 -0
- package/src/runtime/clawclaw/runtime.ts +3 -0
- package/src/runtime/clawclaw-event-catalog.ts +5 -1
- package/src/sdk/perception-plugin/index.ts +1 -0
- package/src/sdk/perception-plugin/reaction.ts +78 -0
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult,
|
|
2
|
+
RuntimeEventProposal } from '../../../framework/plugins/index.js';
|
|
3
|
+
import type { ReactionActivation, ReactionInput, ReactionResult } from '../../../../sdk/perception-plugin/reaction.js';
|
|
4
|
+
import { normalizeReactionManifest } from '../../reaction-manifest.js';
|
|
5
|
+
import { resolveReactionBehavior, type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
|
|
6
|
+
import { BEHAVIOR_ACTIVATION_CAPABILITY, type PerceptionBehaviorActivation,
|
|
7
|
+
type PerceptionBehaviorActivationResult } from '../../behavior-activation-capability.js';
|
|
8
|
+
import { ObservationFrameProjector } from '../../observation-frame-projector.js';
|
|
9
|
+
import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
|
|
10
|
+
import { createCanonicalGameState } from '../../behavior-input.js';
|
|
11
|
+
import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
|
|
12
|
+
import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
|
|
13
|
+
import { ReactionRunner } from './reaction-runner.js';
|
|
14
|
+
import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
|
|
15
|
+
|
|
16
|
+
export const CLAWCLAW_REACTION_PLUGIN_ID = 'clawclaw.perception.reactions';
|
|
17
|
+
export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.reaction_failed'] as const;
|
|
18
|
+
interface BindingState { armed: boolean; lastAcceptedAt?: number; warning?: string; warningSequence: number; failedAttempt?: string }
|
|
19
|
+
interface ModuleState { value?: unknown; bindings: Record<string, BindingState> }
|
|
20
|
+
interface Checkpoint { gameId?: string; phase?: string; modules: Record<string, ModuleState>; failures: string[] }
|
|
21
|
+
export interface ReactionPluginOptions {
|
|
22
|
+
sources: readonly ResolvedClawclawPerceptionSource[];
|
|
23
|
+
after: readonly string[];
|
|
24
|
+
behaviors: () => readonly ReactionBehaviorCandidate[];
|
|
25
|
+
runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<ReactionRunner, 'start' | 'evaluate' | 'stop'>;
|
|
26
|
+
}
|
|
27
|
+
const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
28
|
+
|
|
29
|
+
/** All modules observe their subscribed facts independently. Only own outputs are produced. */
|
|
30
|
+
export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string, any>> {
|
|
31
|
+
readonly kind = 'epoch' as const;
|
|
32
|
+
readonly id = CLAWCLAW_REACTION_PLUGIN_ID;
|
|
33
|
+
readonly version = '1';
|
|
34
|
+
readonly catchUp = 'strict_ordered' as const;
|
|
35
|
+
readonly timeoutMs = 10_000;
|
|
36
|
+
readonly after: readonly string[];
|
|
37
|
+
readonly consumes: { events: readonly string[] };
|
|
38
|
+
readonly produces: { events: readonly string[] };
|
|
39
|
+
readonly capabilities = { uses: [BEHAVIOR_ACTIVATION_CAPABILITY] };
|
|
40
|
+
private readonly sources: readonly ResolvedClawclawPerceptionSource[];
|
|
41
|
+
private readonly runners = new Map<string, Pick<ReactionRunner, 'start' | 'evaluate' | 'stop'>>();
|
|
42
|
+
private readonly failed = new Set<string>();
|
|
43
|
+
private checkpoint: Checkpoint = { modules: {}, failures: [] };
|
|
44
|
+
private readonly projector = new ObservationFrameProjector();
|
|
45
|
+
constructor(private readonly options: ReactionPluginOptions) {
|
|
46
|
+
this.sources = options.sources.filter(source => source.reaction).map(source => ({
|
|
47
|
+
...source, reaction: normalizeReactionManifest(source.reaction),
|
|
48
|
+
})).sort((a, b) => a.id.localeCompare(b.id));
|
|
49
|
+
this.after = options.after;
|
|
50
|
+
this.consumes = { events: [...new Set(this.sources.flatMap(source => [...source.reaction!.consumes]))] };
|
|
51
|
+
this.produces = { events: [...new Set([...REACTION_HOST_EVENT_TYPES,
|
|
52
|
+
...this.sources.flatMap(source => [...source.reaction!.produces])])] };
|
|
53
|
+
}
|
|
54
|
+
async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
|
|
55
|
+
this.checkpoint = { modules: {}, failures: [] }; this.failed.clear(); this.projector.reset();
|
|
56
|
+
await Promise.all(this.sources.map(async (source, index) => {
|
|
57
|
+
try {
|
|
58
|
+
if (index >= 32) throw new Error('REACTION_MODULE_LIMIT');
|
|
59
|
+
const runner = this.options.runnerFactory?.(source) ?? new ReactionRunner(source);
|
|
60
|
+
this.runners.set(source.id, runner); await runner.start();
|
|
61
|
+
} catch {
|
|
62
|
+
this.failed.add(source.id); await this.runners.get(source.id)?.stop();
|
|
63
|
+
context.diagnostic('reaction.module_failed', { module_id: source.id }, 'warn');
|
|
64
|
+
}
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
|
|
68
|
+
const saved = context.checkpoint() as Checkpoint | undefined;
|
|
69
|
+
if (saved?.modules && Array.isArray(saved.failures)) this.checkpoint = structuredClone(saved);
|
|
70
|
+
this.projector.reset();
|
|
71
|
+
}
|
|
72
|
+
async stop(): Promise<void> { await Promise.all([...this.runners.values()].map(runner => runner.stop())); this.runners.clear(); }
|
|
73
|
+
localizedModuleDescriptors(locale: string) {
|
|
74
|
+
return this.sources.filter(source => !this.failed.has(source.id)).map(source =>
|
|
75
|
+
resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, locale));
|
|
76
|
+
}
|
|
77
|
+
async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
|
|
78
|
+
const raw = freshClawclawGameState(input.frame.state) ?? input.currentState.state;
|
|
79
|
+
const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
|
|
80
|
+
const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
|
|
81
|
+
if (game && this.checkpoint.gameId !== game.game_id) this.checkpoint = { gameId: game.game_id, modules: {}, failures: [] };
|
|
82
|
+
if (!game || this.checkpoint.phase !== game.phase) {
|
|
83
|
+
for (const state of Object.values(this.checkpoint.modules)) {
|
|
84
|
+
state.value = undefined;
|
|
85
|
+
for (const binding of Object.values(state.bindings)) {
|
|
86
|
+
binding.armed = true; binding.lastAcceptedAt = undefined; binding.failedAttempt = undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
this.checkpoint.phase = game?.phase;
|
|
90
|
+
}
|
|
91
|
+
const frame = this.projector.project(input.frame);
|
|
92
|
+
const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
|
|
93
|
+
const candidates = this.options.behaviors();
|
|
94
|
+
const facts = input.pendingEvents.filter(event => !event.replayed).map(event => ({
|
|
95
|
+
eventId: event.eventId, type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
|
|
96
|
+
payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
|
|
97
|
+
}));
|
|
98
|
+
const events: RuntimeEventProposal[] = [];
|
|
99
|
+
const requests: Array<{ source: ResolvedClawclawPerceptionSource; activation: ReactionActivation; state: BindingState }> = [];
|
|
100
|
+
for (const source of this.sources) {
|
|
101
|
+
if (!this.failed.has(source.id)) {
|
|
102
|
+
try {
|
|
103
|
+
const state = Object.hasOwn(this.checkpoint.modules, source.id)
|
|
104
|
+
? this.checkpoint.modules[source.id] : (this.checkpoint.modules[source.id] = { bindings: {} });
|
|
105
|
+
const moduleInput: ReactionInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
|
|
106
|
+
events: facts.filter(event => source.reaction!.consumes.includes(event.type)), nowMs,
|
|
107
|
+
state: state.value, config: source.reaction!.config ?? {}, availableBehaviors: candidates.filter(c => c.loadable).map(c => c.id) };
|
|
108
|
+
// A control-only epoch is not an observation that clears a visual condition.
|
|
109
|
+
if (!frame && moduleInput.events.length === 0) continue;
|
|
110
|
+
const result = await this.runners.get(source.id)!.evaluate(moduleInput);
|
|
111
|
+
this.validate(result, source);
|
|
112
|
+
state.value = structuredClone(result.state);
|
|
113
|
+
for (const event of result.events ?? []) events.push({ type: event.type,
|
|
114
|
+
dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
|
|
115
|
+
payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() });
|
|
116
|
+
const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
|
|
117
|
+
for (const [key, binding] of Object.entries(source.reaction!.behaviors ?? {})) {
|
|
118
|
+
const current = state.bindings[key] ??= { armed: true, warningSequence: 0 };
|
|
119
|
+
if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) current.warning = undefined;
|
|
120
|
+
if (!matched.has(key)) { current.armed = true; current.failedAttempt = undefined; continue; }
|
|
121
|
+
if (!game || game.phase !== 'wandering' || game.you?.is_alive !== true || !connected) continue;
|
|
122
|
+
if ((binding.rearm ?? 'after_clear') === 'after_clear' && !current.armed) continue;
|
|
123
|
+
if (current.lastAcceptedAt !== undefined && nowMs - current.lastAcceptedAt < (binding.cooldownMs ?? 1_000)) continue;
|
|
124
|
+
requests.push({ source, activation: matched.get(key)!, state: current });
|
|
125
|
+
}
|
|
126
|
+
} catch {
|
|
127
|
+
this.failed.add(source.id); await this.runners.get(source.id)?.stop();
|
|
128
|
+
context.diagnostic('reaction.module_failed', { module_id: source.id }, 'warn');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (this.failed.has(source.id) && !this.checkpoint.failures.includes(source.id)) {
|
|
132
|
+
this.checkpoint.failures.push(source.id);
|
|
133
|
+
events.push({ type: 'perception.reaction_failed', wakeAgent: true, dedupeKey: `module:${source.id}`,
|
|
134
|
+
payload: { module_id: source.id, text: `感知“${source.name}”的反应脚本不可用,已停止该模块;其他感知和策略继续运行。` } });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
requests.sort((a, b) => (b.source.reaction!.behaviors![b.activation.behavior].reflexPriority ?? 0)
|
|
138
|
+
- (a.source.reaction!.behaviors![a.activation.behavior].reflexPriority ?? 0));
|
|
139
|
+
for (const { source, activation, state } of requests) {
|
|
140
|
+
if (context.signal.aborted) break;
|
|
141
|
+
const binding = source.reaction!.behaviors![activation.behavior];
|
|
142
|
+
const behavior = resolveReactionBehavior(binding, this.options.behaviors());
|
|
143
|
+
const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
|
|
144
|
+
if (state.failedAttempt === attempt) continue;
|
|
145
|
+
let result: PerceptionBehaviorActivationResult = { accepted: false, reason: 'behavior_not_loaded' };
|
|
146
|
+
if (behavior) {
|
|
147
|
+
try {
|
|
148
|
+
const response = await context.capabilities.performAction<PerceptionBehaviorActivation, PerceptionBehaviorActivationResult>(
|
|
149
|
+
BEHAVIOR_ACTIVATION_CAPABILITY, { moduleId: source.id, bindingKey: activation.behavior, behavior,
|
|
150
|
+
input: { ...binding.input, ...activation.input }, layer: binding.layer ?? 'reflex',
|
|
151
|
+
reflexPriority: binding.reflexPriority ?? 0,
|
|
152
|
+
maxRuntimeMs: binding.maxRuntimeMs ?? ((binding.layer ?? 'reflex') === 'long' ? undefined : 10_000),
|
|
153
|
+
epochId: input.epoch.epochSeq, gameId: game!.game_id,
|
|
154
|
+
reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` });
|
|
155
|
+
result = response.value ?? { accepted: false, reason: 'activation_unavailable' };
|
|
156
|
+
} catch { result = { accepted: false, reason: 'activation_unavailable' }; }
|
|
157
|
+
}
|
|
158
|
+
if (result.accepted) {
|
|
159
|
+
state.armed = false; state.lastAcceptedAt = nowMs; state.warning = undefined; state.failedAttempt = undefined;
|
|
160
|
+
} else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason ?? '')) {
|
|
161
|
+
const reason = result.reason ?? 'activation_unavailable';
|
|
162
|
+
state.failedAttempt = attempt;
|
|
163
|
+
if (state.warning !== reason) {
|
|
164
|
+
state.warning = reason; state.warningSequence++;
|
|
165
|
+
events.push({ type: 'perception.behavior_unavailable', wakeAgent: true,
|
|
166
|
+
dedupeKey: JSON.stringify([game?.game_id, source.id, activation.behavior, state.warningSequence]),
|
|
167
|
+
payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
|
|
168
|
+
...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
|
|
169
|
+
...(behavior ? { behavior_id: behavior } : {}), reason,
|
|
170
|
+
text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { outcome: 'processed', events, checkpoint: structuredClone(this.checkpoint),
|
|
175
|
+
...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
|
|
176
|
+
}
|
|
177
|
+
private validate(result: ReactionResult, source: ResolvedClawclawPerceptionSource): void {
|
|
178
|
+
if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
|
|
179
|
+
|| result.events !== undefined && !Array.isArray(result.events)
|
|
180
|
+
|| result.activations !== undefined && !Array.isArray(result.activations)
|
|
181
|
+
|| (result.events?.length ?? 0) > 32 || (result.activations?.length ?? 0) > 16
|
|
182
|
+
|| Buffer.byteLength(JSON.stringify(result)) > 128_000) throw new Error('REACTION_OUTPUT_INVALID');
|
|
183
|
+
for (const event of result.events ?? []) {
|
|
184
|
+
if (!record(event) || !source.reaction!.produces.includes(event.type)
|
|
185
|
+
|| typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
|
|
186
|
+
|| event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
|
|
187
|
+
|| !record(event.payload) || typeof event.payload.text !== 'string' || !event.payload.text.trim()) throw new Error('REACTION_EVENT_INVALID');
|
|
188
|
+
}
|
|
189
|
+
const bindings = new Set<string>();
|
|
190
|
+
for (const activation of result.activations ?? []) {
|
|
191
|
+
if (!record(activation) || !Object.hasOwn(source.reaction!.behaviors ?? {}, activation.behavior)
|
|
192
|
+
|| bindings.has(activation.behavior) || activation.input !== undefined && !record(activation.input)
|
|
193
|
+
|| activation.reason !== undefined && (typeof activation.reason !== 'string' || activation.reason.length > 512)
|
|
194
|
+
|| Object.keys(activation).some(key => !['behavior', 'input', 'reason'].includes(key))) throw new Error('REACTION_ACTIVATION_INVALID');
|
|
195
|
+
bindings.add(activation.behavior);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import type { ReactionInput, ReactionResult } from '../../../../sdk/perception-plugin/reaction.js';
|
|
4
|
+
import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
|
|
5
|
+
import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runtime-module-loader.js';
|
|
6
|
+
|
|
7
|
+
/** Generic reaction execution; no model service, exclusive event routing or delivery rewriting. */
|
|
8
|
+
export class ReactionRunner {
|
|
9
|
+
private worker?: Worker;
|
|
10
|
+
private sequence = 0;
|
|
11
|
+
private failure?: Error;
|
|
12
|
+
private pending?: { id?: number; resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> };
|
|
13
|
+
constructor(readonly source: ResolvedClawclawPerceptionSource) {}
|
|
14
|
+
async start(): Promise<void> {
|
|
15
|
+
const ready = this.wait(8_000);
|
|
16
|
+
this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
|
|
17
|
+
execArgv: [], stdout: true, stderr: true, resourceLimits: { maxOldGenerationSizeMb: 64 },
|
|
18
|
+
workerData: { modulePath: this.source.sourcePath, expectedManifest: this.source.reaction,
|
|
19
|
+
runtimeModuleBootstrap: { hostUrl: new URL('./reaction-worker.ts', import.meta.url).href,
|
|
20
|
+
...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(this.source.sourcePath)).href] } },
|
|
21
|
+
});
|
|
22
|
+
this.worker.stdout?.on('data', () => {}); this.worker.stderr?.on('data', () => {});
|
|
23
|
+
this.worker.on('error', error => this.fail(error));
|
|
24
|
+
this.worker.on('exit', () => this.fail(new Error('REACTION_WORKER_EXITED')));
|
|
25
|
+
this.worker.on('message', message => {
|
|
26
|
+
if (!this.pending || (message.id !== undefined && message.id !== this.pending.id)) return;
|
|
27
|
+
if (message.type === 'error') { this.fail(new Error('REACTION_MODULE_FAILED')); return; }
|
|
28
|
+
const pending = this.pending; this.pending = undefined; clearTimeout(pending.timer); pending.resolve(message.result);
|
|
29
|
+
});
|
|
30
|
+
await ready;
|
|
31
|
+
}
|
|
32
|
+
async evaluate(input: ReactionInput): Promise<ReactionResult> {
|
|
33
|
+
if (this.failure) throw this.failure;
|
|
34
|
+
if (!this.worker) throw new Error('REACTION_WORKER_NOT_STARTED');
|
|
35
|
+
const id = ++this.sequence; const result = this.wait(500, id);
|
|
36
|
+
this.worker.postMessage({ id, input }); return result;
|
|
37
|
+
}
|
|
38
|
+
async stop(): Promise<void> { this.fail(new Error('REACTION_STOPPED')); await this.worker?.terminate(); this.worker = undefined; }
|
|
39
|
+
private wait(ms: number, id?: number): Promise<any> {
|
|
40
|
+
if (this.pending) throw new Error('REACTION_CONCURRENT_CALL');
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
this.pending = { id, resolve, reject, timer: setTimeout(() => { this.fail(new Error('REACTION_TIMEOUT')); void this.stop(); }, ms) };
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
private fail(error: Error): void {
|
|
46
|
+
this.failure = error;
|
|
47
|
+
if (this.pending) { const pending = this.pending; this.pending = undefined; clearTimeout(pending.timer); pending.reject(error); }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
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' }); }
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ReactionBehaviorBinding } from '../../sdk/perception-plugin/reaction.js';
|
|
2
|
+
|
|
3
|
+
export interface ReactionBehaviorCandidate {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly declaredId?: string;
|
|
6
|
+
readonly resourceId?: string;
|
|
7
|
+
readonly loadable: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Shared by load diagnostics and the live activation path. Never selects disabled/unloaded entries. */
|
|
11
|
+
export function resolveReactionBehavior(binding: ReactionBehaviorBinding, candidates: readonly ReactionBehaviorCandidate[]): string | undefined {
|
|
12
|
+
const available = candidates.filter(candidate => candidate.loadable);
|
|
13
|
+
const compare = (a: ReactionBehaviorCandidate, b: ReactionBehaviorCandidate) =>
|
|
14
|
+
Number(b.id === binding.name) - Number(a.id === binding.name)
|
|
15
|
+
|| a.id.localeCompare(b.id, 'en', { numeric: true }) || String(a.resourceId).localeCompare(String(b.resourceId));
|
|
16
|
+
const preferred = binding.resourceId && available.filter(candidate => candidate.resourceId === binding.resourceId).sort(compare)[0];
|
|
17
|
+
if (preferred) return preferred.id;
|
|
18
|
+
// Declared source identity distinguishes real duplicate aliases from an unrelated literal escape_1.
|
|
19
|
+
const named = available.filter(candidate => candidate.id === binding.name || candidate.declaredId === binding.name
|
|
20
|
+
|| candidate.declaredId === undefined && candidate.id.startsWith(`${binding.name}_`)
|
|
21
|
+
&& /^[1-9][0-9]*$/.test(candidate.id.slice(binding.name.length + 1))).sort(compare);
|
|
22
|
+
return named[0]?.id;
|
|
23
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { ClawclawReactionManifest, ReactionBehaviorBinding } from '../../sdk/perception-plugin/reaction.js';
|
|
2
|
+
import { hasValidClawclawResourceLocalizations } from '../../sdk/resource-metadata.js';
|
|
3
|
+
import { normalizeBehaviorInput, normalizeBehaviorInputFields } from './behavior-input-fields.js';
|
|
4
|
+
import { isClawclawFixedEventType } from '../clawclaw-event-catalog.js';
|
|
5
|
+
|
|
6
|
+
const ID = /^[a-z0-9][a-z0-9._-]*$/;
|
|
7
|
+
const OPERATION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;
|
|
8
|
+
const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
9
|
+
const integer = (value: unknown, minimum: number, maximum: number) =>
|
|
10
|
+
Number.isSafeInteger(value) && Number(value) >= minimum && Number(value) <= maximum;
|
|
11
|
+
|
|
12
|
+
export function normalizeReactionManifest(value: unknown, requireCurrentVersion = true): ClawclawReactionManifest {
|
|
13
|
+
const m = value as ClawclawReactionManifest;
|
|
14
|
+
if (!record(value) || m.kind !== 'reaction' || !Number.isInteger(m.apiVersion)
|
|
15
|
+
|| requireCurrentVersion && m.apiVersion !== 2 || typeof m.id !== 'string' || !ID.test(m.id)
|
|
16
|
+
|| typeof m.description !== 'string' || !m.description.trim()
|
|
17
|
+
|| m.name !== undefined && (typeof m.name !== 'string' || !m.name.trim())
|
|
18
|
+
|| !hasValidClawclawResourceLocalizations(m.localizations)
|
|
19
|
+
|| !Array.isArray(m.consumes) || m.consumes.some(type => typeof type !== 'string' || !ID.test(type)
|
|
20
|
+
|| /^(reaction|perception|behavior|decision)\./.test(type))
|
|
21
|
+
|| !Array.isArray(m.produces) || m.produces.some(type => typeof type !== 'string'
|
|
22
|
+
|| !/^reaction\.[a-z0-9][a-z0-9._-]*$/.test(type) || isClawclawFixedEventType(type))
|
|
23
|
+
|| m.behaviors !== undefined && !record(m.behaviors)
|
|
24
|
+
|| m.config !== undefined && !record(m.config)
|
|
25
|
+
|| Object.keys(m).some(key => !['apiVersion', 'kind', 'id', 'name', 'description', 'localizations',
|
|
26
|
+
'consumes', 'produces', 'behaviors', 'inputs', 'config'].includes(key))) throw new Error('reaction_manifest_invalid');
|
|
27
|
+
const behaviors: Record<string, ReactionBehaviorBinding> = {};
|
|
28
|
+
if (Object.keys(m.behaviors ?? {}).length > 16) throw new Error('reaction_behavior_limit');
|
|
29
|
+
for (const [key, binding] of Object.entries(m.behaviors ?? {})) {
|
|
30
|
+
if (!ID.test(key) || ['__proto__', 'constructor', 'prototype'].includes(key) || !record(binding)
|
|
31
|
+
|| typeof binding.name !== 'string' || !OPERATION.test(binding.name)
|
|
32
|
+
|| binding.resourceId !== undefined && (typeof binding.resourceId !== 'string' || !binding.resourceId.trim() || binding.resourceId.length > 255)
|
|
33
|
+
|| binding.layer !== undefined && !['reflex', 'short', 'long'].includes(binding.layer)
|
|
34
|
+
|| binding.input !== undefined && !record(binding.input)
|
|
35
|
+
|| binding.reflexPriority !== undefined && !integer(binding.reflexPriority, -1_000_000, 1_000_000)
|
|
36
|
+
|| binding.cooldownMs !== undefined && !integer(binding.cooldownMs, 0, 86_400_000)
|
|
37
|
+
|| binding.maxRuntimeMs !== undefined && !integer(binding.maxRuntimeMs, 1, 120_000)
|
|
38
|
+
|| binding.rearm !== undefined && !['after_clear', 'after_cooldown'].includes(binding.rearm)
|
|
39
|
+
|| Object.keys(binding).some(field => !['name', 'resourceId', 'layer', 'input', 'reflexPriority',
|
|
40
|
+
'cooldownMs', 'maxRuntimeMs', 'rearm'].includes(field))) throw new Error(`reaction_behavior_invalid:${key}`);
|
|
41
|
+
behaviors[key] = structuredClone(binding);
|
|
42
|
+
}
|
|
43
|
+
const inputs = m.inputs ? normalizeBehaviorInputFields(m.inputs) : undefined;
|
|
44
|
+
const config = inputs ? normalizeBehaviorInput(m.config ?? {}, inputs) : structuredClone(m.config ?? {});
|
|
45
|
+
return { apiVersion: m.apiVersion, kind: 'reaction', id: m.id, description: m.description,
|
|
46
|
+
...(m.name === undefined ? {} : { name: m.name }),
|
|
47
|
+
...(m.localizations === undefined ? {} : { localizations: structuredClone(m.localizations) }),
|
|
48
|
+
consumes: [...new Set(m.consumes)], produces: [...new Set(m.produces)], behaviors,
|
|
49
|
+
...(inputs ? { inputs } : {}), config };
|
|
50
|
+
}
|
|
@@ -48,6 +48,7 @@ export type ClawclawRuntimeOptions = Omit<
|
|
|
48
48
|
visualEventDelivery?: ClawclawVisualEventDelivery;
|
|
49
49
|
/** Visual Event types declared by the selected perception modules. */
|
|
50
50
|
visualEventTypes?: readonly string[];
|
|
51
|
+
reactionEventTypes?: readonly string[];
|
|
51
52
|
/** Event types declared by enabled Intent and Strategy modules at startup. */
|
|
52
53
|
behaviorEventTypes?: readonly string[];
|
|
53
54
|
};
|
|
@@ -96,6 +97,7 @@ export function createClawclawRuntime(
|
|
|
96
97
|
stateFreshnessPolicyResolver: configuredResolver,
|
|
97
98
|
visualEventDelivery,
|
|
98
99
|
visualEventTypes,
|
|
100
|
+
reactionEventTypes,
|
|
99
101
|
behaviorEventTypes,
|
|
100
102
|
...runtimeOptions
|
|
101
103
|
} = options;
|
|
@@ -144,6 +146,7 @@ export function createClawclawRuntime(
|
|
|
144
146
|
eventCatalog: createClawclawEventCatalog({
|
|
145
147
|
visualEventDelivery,
|
|
146
148
|
visualEventTypes,
|
|
149
|
+
reactionEventTypes,
|
|
147
150
|
behaviorEventTypes,
|
|
148
151
|
}),
|
|
149
152
|
// Mailbox ACK adapters own independent durable lanes. Disabled and
|
|
@@ -36,6 +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
41
|
}
|
|
40
42
|
|
|
41
43
|
/**
|
|
@@ -181,6 +183,8 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
|
|
|
181
183
|
'players_changed',
|
|
182
184
|
'reminder.task',
|
|
183
185
|
'reminder.speech',
|
|
186
|
+
'perception.behavior_unavailable',
|
|
187
|
+
'perception.reaction_failed',
|
|
184
188
|
'emergency_countdown_warning',
|
|
185
189
|
'ability.ready',
|
|
186
190
|
'ability.remaining_uses_changed',
|
|
@@ -257,7 +261,7 @@ function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[]
|
|
|
257
261
|
...CLAWCLAW_FIXED_EVENT_TYPES,
|
|
258
262
|
...visualEventTypes,
|
|
259
263
|
]);
|
|
260
|
-
const behaviorEventTypes = [...new Set(options.behaviorEventTypes ?? [])]
|
|
264
|
+
const behaviorEventTypes = [...new Set([...(options.behaviorEventTypes ?? []), ...(options.reactionEventTypes ?? [])])]
|
|
261
265
|
.filter((type) => !fixedAndVisualTypes.has(type))
|
|
262
266
|
.sort();
|
|
263
267
|
return [
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { GameEvent, GameState, ObservationFrame } from '../module-input/index.js';
|
|
2
|
+
import type { BehaviorInputFieldSpec } from '../behavior-plugin/index.js';
|
|
3
|
+
import type { ClawclawResourceLocalizations } from '../resource-metadata.js';
|
|
4
|
+
|
|
5
|
+
/** A fixed dependency, resolved against this account's equipped, loadable Behaviors. */
|
|
6
|
+
export interface ReactionBehaviorBinding {
|
|
7
|
+
readonly name: string;
|
|
8
|
+
/** Preferred Hub identity. A missing match falls back to name and its duplicate aliases. */
|
|
9
|
+
readonly resourceId?: string;
|
|
10
|
+
readonly layer?: 'reflex' | 'short' | 'long';
|
|
11
|
+
readonly input?: Readonly<Record<string, unknown>>;
|
|
12
|
+
readonly reflexPriority?: number;
|
|
13
|
+
readonly cooldownMs?: number;
|
|
14
|
+
readonly rearm?: 'after_clear' | 'after_cooldown';
|
|
15
|
+
readonly maxRuntimeMs?: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ClawclawReactionManifest {
|
|
19
|
+
readonly apiVersion: 2;
|
|
20
|
+
readonly kind: 'reaction';
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly name?: string;
|
|
23
|
+
readonly description: string;
|
|
24
|
+
readonly localizations?: ClawclawResourceLocalizations;
|
|
25
|
+
/** Backend, derived and visual Events. Reaction outputs cannot feed reactions. */
|
|
26
|
+
readonly consumes: readonly string[];
|
|
27
|
+
/** Own Agent-visible notices, named reaction.<name>. */
|
|
28
|
+
readonly produces: readonly string[];
|
|
29
|
+
readonly behaviors?: Readonly<Record<string, ReactionBehaviorBinding>>;
|
|
30
|
+
readonly inputs?: readonly BehaviorInputFieldSpec[];
|
|
31
|
+
readonly config?: Readonly<Record<string, unknown>>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ReactionFact extends GameEvent {
|
|
35
|
+
readonly wakeAgent?: boolean;
|
|
36
|
+
readonly replayed: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ReactionInput {
|
|
40
|
+
readonly moduleId: string;
|
|
41
|
+
readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
|
|
42
|
+
readonly gameState: Readonly<GameState> | null;
|
|
43
|
+
readonly frame: Readonly<ObservationFrame> | null;
|
|
44
|
+
readonly events: readonly ReactionFact[];
|
|
45
|
+
readonly nowMs: number;
|
|
46
|
+
/** JSON data returned by the previous evaluate; do not keep state in class fields. */
|
|
47
|
+
readonly state: unknown;
|
|
48
|
+
readonly config: Readonly<Record<string, unknown>>;
|
|
49
|
+
readonly availableBehaviors: readonly string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ReactionEvent {
|
|
53
|
+
readonly type: string;
|
|
54
|
+
/** Stable identity for this occurrence, not a new key on every frame. */
|
|
55
|
+
readonly key: string;
|
|
56
|
+
readonly wakeAgent?: boolean;
|
|
57
|
+
readonly payload: Readonly<Record<string, unknown>> & { readonly text: string };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface ReactionActivation {
|
|
61
|
+
/** Key in manifest.behaviors; never an arbitrary executable command. */
|
|
62
|
+
readonly behavior: string;
|
|
63
|
+
readonly input?: Readonly<Record<string, unknown>>;
|
|
64
|
+
readonly reason?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ReactionResult {
|
|
68
|
+
readonly state?: unknown;
|
|
69
|
+
readonly events?: readonly ReactionEvent[];
|
|
70
|
+
/** Return while the condition holds. Omitting a binding clears its after_clear latch. */
|
|
71
|
+
readonly activations?: readonly ReactionActivation[];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A perception resource that can notify the Agent and request fixed Behaviors. */
|
|
75
|
+
export abstract class ClawclawReaction {
|
|
76
|
+
static readonly manifest?: ClawclawReactionManifest;
|
|
77
|
+
abstract evaluate(input: Readonly<ReactionInput>): ReactionResult | Promise<ReactionResult>;
|
|
78
|
+
}
|