@myclaw163/clawclaw-cli 0.10.6 → 0.10.8
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/dist/strategy-worker/assets/clawclaw-spatial-facts.json +1383 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-3VLVCU6P.js +71 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ATQQZA4X.js +44 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-CF6IEQ4V.js +12 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-JMX6D6A3.js +260 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-QEPKDSLE.js +278 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ZQILO6OM.js +0 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/clawclaw-walkable.bin +0 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +1389 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-behavior-plugin.js +22 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-module-input.js +0 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-perception-plugin.js +72 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +3108 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-strategy-plugin.js +25 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-trigger-plugin.js +16 -0
- package/docs/custom-modules/api-reference.md +10 -8
- package/docs/custom-modules/perception.md +26 -3
- package/docs/desktop-event-push.md +2 -1
- package/docs/runtime/behavior-runtime.md +3 -1
- package/docs/runtime/official-perception-modules.md +2 -2
- package/docs/user-guide/behavior.md +3 -1
- package/docs/user-guide/desktop-auth.md +33 -1
- package/package.json +5 -3
- package/scripts/build-strategy-worker.mjs +28 -0
- package/scripts/migrate-official-perceptions.mjs +157 -0
- package/skills/clawclaw/SKILL.md +3 -3
- package/skills/clawclaw/references/BEHAVIORS.md +2 -0
- package/skills/clawclaw/references/TACTICS.md +4 -0
- package/skills/clawclaw-creator/SKILL.md +3 -1
- package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +10 -8
- package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +26 -3
- package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
- package/src/commands/capability.ts +4 -2
- package/src/commands/load.ts +5 -2
- package/src/lib/agent-workspace-skills.ts +12 -7
- package/src/lib/capability-cloud-sync.ts +13 -7
- package/src/lib/capability-discovery.ts +10 -3
- package/src/lib/capability-selection.ts +7 -0
- package/src/lib/game-client.ts +33 -6
- package/src/lib/lobby-host-context.ts +74 -0
- package/src/lib/package-skills.ts +11 -1
- package/src/lib/participation-status.ts +5 -0
- package/src/pipeline/event-format.ts +2 -0
- package/src/pipeline/event-hints.ts +1 -0
- package/src/runtime/clawclaw/behavior-start-control.ts +114 -0
- package/src/runtime/clawclaw/notification-policy.ts +1 -0
- package/src/runtime/clawclaw/owner.ts +21 -4
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +1 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -6
- package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +48 -1
- package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +2 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +28 -6
- package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +25 -3
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +1 -1
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +9 -0
- package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -0
- package/src/runtime/clawclaw/plugins/perception/module-input-boundary.ts +64 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +37 -49
- package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +3 -1
- package/src/runtime/clawclaw/plugins/source/room-transport.ts +46 -9
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +18 -4
- package/src/runtime/clawclaw/plugins/source/types.ts +2 -0
- package/src/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.ts +2 -0
- package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +122 -61
- package/src/runtime/clawclaw-event-catalog.ts +1 -0
- package/src/sdk/perception-plugin/index.ts +1 -0
- package/src/sdk/perception-plugin/lifecycle.ts +15 -0
- package/src/sdk/perception-plugin/module.ts +15 -0
|
@@ -5,7 +5,8 @@ import { createClawclawProcessingCadence } from './runtime-cadence.js';
|
|
|
5
5
|
import { readRuntimeCycleIntervalMs } from '../../lib/runtime-cadence-config.js';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import { BehaviorReflexControl } from './behavior-reflex-control.js';
|
|
8
|
-
import {
|
|
8
|
+
import { DeferredMeetingShortStrategy } from './behavior-start-control.js';
|
|
9
|
+
import { normalizeBehaviorInput } from './behavior-input-fields.js';
|
|
9
10
|
import { acquireOwnerLock, type OwnerLock } from './owner-lock.js';
|
|
10
11
|
import { createStartingOwnerControl } from './starting-owner-control.js';
|
|
11
12
|
export { acquireOwnerLock, type OwnerLock, type OwnerLockOperations } from './owner-lock.js';
|
|
@@ -561,6 +562,8 @@ export async function runClawclawOwner(
|
|
|
561
562
|
},
|
|
562
563
|
});
|
|
563
564
|
closeGameSyncTransports = () => client.closeGameSyncTransports();
|
|
565
|
+
// Validate before starting a participation or attaching any game transport.
|
|
566
|
+
void client.lobbyHostContext;
|
|
564
567
|
const workspaceDir = getWorkspaceDir();
|
|
565
568
|
ensureAccountUserDataLayout(workspaceDir, options.profile);
|
|
566
569
|
const perceptionConfig = readWorkspacePerceptionConfig();
|
|
@@ -671,6 +674,13 @@ export async function runClawclawOwner(
|
|
|
671
674
|
behaviorEventTypes: assembly.behavior.produces?.events ?? [],
|
|
672
675
|
perceptionEventTypes: assembly.modules?.produces.events,
|
|
673
676
|
});
|
|
677
|
+
const deferredShort = new DeferredMeetingShortStrategy(runtime, assembly.behavior, request => {
|
|
678
|
+
const source = behaviorSourceById.get(request.behavior);
|
|
679
|
+
if (!source) return undefined;
|
|
680
|
+
normalizeBehaviorInput(request.input, source.inputs, { allowedKeys: ['timeout_ms', 'duration_ms'] });
|
|
681
|
+
return resolveClawclawResourceMetadata(source, 'zh-CN');
|
|
682
|
+
});
|
|
683
|
+
assembly.behavior.attachDeferredShortControl(deferredShort);
|
|
674
684
|
if (fullDiagnosticsEnabled) {
|
|
675
685
|
processTimingSampler = new RuntimeProcessTimingSampler();
|
|
676
686
|
const sample = (): void => {
|
|
@@ -1225,7 +1235,7 @@ export async function runClawclawOwner(
|
|
|
1225
1235
|
|| maxRuntimeMs > 120_000
|
|
1226
1236
|
))
|
|
1227
1237
|
) return { ok: false, type: 'behavior_start', error: 'invalid_behavior_start_request' };
|
|
1228
|
-
return
|
|
1238
|
+
return deferredShort.start({
|
|
1229
1239
|
expectedScope: expected,
|
|
1230
1240
|
behavior,
|
|
1231
1241
|
layer,
|
|
@@ -1234,7 +1244,11 @@ export async function runClawclawOwner(
|
|
|
1234
1244
|
});
|
|
1235
1245
|
}
|
|
1236
1246
|
if (request.type === 'behavior_status') {
|
|
1237
|
-
|
|
1247
|
+
const id = typeof request.behavior === 'string' ? request.behavior : undefined;
|
|
1248
|
+
const pending = deferredShort.status(id);
|
|
1249
|
+
return { ok: true, type: 'behavior_status', status: {
|
|
1250
|
+
...reflexControl.view(id), ...(pending ? { pending_short: pending } : {}),
|
|
1251
|
+
} };
|
|
1238
1252
|
}
|
|
1239
1253
|
if (request.type === 'behavior_cancel') {
|
|
1240
1254
|
const expected = ownerExpectedScope(request.expected_scope);
|
|
@@ -1244,7 +1258,10 @@ export async function runClawclawOwner(
|
|
|
1244
1258
|
}
|
|
1245
1259
|
const requestedId = typeof request.activation_id === 'string'
|
|
1246
1260
|
? request.activation_id.trim()
|
|
1247
|
-
: assembly.behavior.status().current?.activationId;
|
|
1261
|
+
: assembly.behavior.status().current?.activationId ?? deferredShort.status()?.request_id;
|
|
1262
|
+
if (requestedId && deferredShort.cancel(requestedId)) {
|
|
1263
|
+
return { ok: true, type: 'behavior_cancel', cancelled: true, request_id: requestedId };
|
|
1264
|
+
}
|
|
1248
1265
|
if (!requestedId) {
|
|
1249
1266
|
return { ok: true, type: 'behavior_cancel', cancelled: false };
|
|
1250
1267
|
}
|
|
@@ -11,6 +11,7 @@ import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observa
|
|
|
11
11
|
// This entry point only adapts the game SDK and verifies the pinned source.
|
|
12
12
|
await runStrategyWorker<ResolvedClawclawBehaviorSource, BehaviorInput, BehaviorDecision, BehaviorReadApi, ClawclawBehaviorObservationSnapshot>({
|
|
13
13
|
async load(data) {
|
|
14
|
+
resolveBehaviorSource(data.source);
|
|
14
15
|
const module = await import(data.sourceUrl) as Record<string, unknown>;
|
|
15
16
|
resolveBehaviorSource(data.source);
|
|
16
17
|
const loaded = validateClawclawBehaviorModule(module, data.source);
|
|
@@ -98,17 +98,22 @@ export class ClawclawBehaviorCatalog {
|
|
|
98
98
|
return loading;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
|
|
101
|
+
prepareForActivation(id: string, input: unknown, diagnosticsEnabled = false): Promise<PreparedClawclawBehavior> {
|
|
102
|
+
return this.prepare(id, input, true, diagnosticsEnabled);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async prepare(id: string, input: unknown, retainWorker = false, diagnosticsEnabled = false): Promise<PreparedClawclawBehavior> {
|
|
102
106
|
const source = this.sources.get(id);
|
|
103
107
|
if (!source) throw new Error(`Unknown behavior module '${id}'.`);
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
);
|
|
108
|
+
const rawInput = deepFreezeBehaviorValue(normalizeBehaviorInput(input, source.inputs, { allowedKeys: ['timeout_ms', 'duration_ms'] }));
|
|
109
|
+
const prepared = await prepareBehaviorInWorker(source, input as Readonly<Record<string, unknown>>, {
|
|
110
|
+
retainWorker, diagnosticsEnabled,
|
|
111
|
+
});
|
|
108
112
|
return Object.freeze({
|
|
109
113
|
manifest: deepFreezeBehaviorValue(structuredClone(prepared.manifest)),
|
|
110
114
|
input: deepFreezeBehaviorValue(structuredClone(prepared.input)),
|
|
111
|
-
rawInput
|
|
115
|
+
rawInput,
|
|
116
|
+
...(prepared.worker ? { worker: prepared.worker } : {}),
|
|
112
117
|
source: prepared.source,
|
|
113
118
|
display: source.display,
|
|
114
119
|
...(prepared.timing === undefined ? {} : { timing: prepared.timing }),
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import * as asyncFs from 'node:fs/promises';
|
|
3
4
|
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
5
|
import { pathToFileURL } from 'node:url';
|
|
5
6
|
import {
|
|
@@ -197,9 +198,55 @@ export function pinBehaviorSource(
|
|
|
197
198
|
});
|
|
198
199
|
}
|
|
199
200
|
|
|
201
|
+
/** Pin source before dispatch without making the Owner wait on synchronous disk reads. */
|
|
202
|
+
export async function pinBehaviorSourceAsync(source: ResolvedClawclawBehaviorSource): Promise<ResolvedClawclawBehaviorSource> {
|
|
203
|
+
const sourceRoot = await asyncFs.realpath(source.sourceRoot);
|
|
204
|
+
const sourcePath = await asyncFs.realpath(source.sourcePath);
|
|
205
|
+
if (!pathInside(sourceRoot, sourcePath) || dirname(sourcePath) !== sourceRoot
|
|
206
|
+
|| !(await asyncFs.stat(sourcePath)).isFile()) {
|
|
207
|
+
throw new Error(`Behavior '${source.id}' source is outside its root.`);
|
|
208
|
+
}
|
|
209
|
+
const files: Array<{ path: string; relativePath: string }> = [];
|
|
210
|
+
const visit = async (directory: string): Promise<void> => {
|
|
211
|
+
for (const entry of await asyncFs.readdir(directory, { withFileTypes: true })) {
|
|
212
|
+
const path = join(directory, entry.name);
|
|
213
|
+
if (entry.isSymbolicLink()) throw new Error('behavior_source_tree_symlink_unsupported');
|
|
214
|
+
if (entry.isDirectory()) await visit(path);
|
|
215
|
+
else if (entry.isFile() && RUNTIME_SOURCE_FILE.test(entry.name)) {
|
|
216
|
+
if (files.length >= MAX_BEHAVIOR_SOURCE_TREE_FILES) throw new Error('behavior_source_tree_file_limit_exceeded');
|
|
217
|
+
const physical = await asyncFs.realpath(path);
|
|
218
|
+
if (!pathInside(sourceRoot, physical)) throw new Error('behavior_source_tree_outside_root');
|
|
219
|
+
files.push({ path: physical, relativePath: relative(sourceRoot, physical).replaceAll('\\', '/') });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
await visit(sourceRoot);
|
|
224
|
+
files.sort((left, right) => left.relativePath.localeCompare(right.relativePath));
|
|
225
|
+
const hash = createHash('sha256');
|
|
226
|
+
let totalBytes = 0;
|
|
227
|
+
for (const file of files) {
|
|
228
|
+
if (totalBytes + (await asyncFs.stat(file.path)).size > MAX_BEHAVIOR_SOURCE_TREE_BYTES) {
|
|
229
|
+
throw new Error('behavior_source_tree_byte_limit_exceeded');
|
|
230
|
+
}
|
|
231
|
+
const content = await asyncFs.readFile(file.path);
|
|
232
|
+
totalBytes += content.length;
|
|
233
|
+
if (totalBytes > MAX_BEHAVIOR_SOURCE_TREE_BYTES) throw new Error('behavior_source_tree_byte_limit_exceeded');
|
|
234
|
+
if (file.path === sourcePath && source.trustedSourceSha256 !== undefined
|
|
235
|
+
&& createHash('sha256').update(content).digest('hex') !== source.trustedSourceSha256) {
|
|
236
|
+
throw new Error('behavior_trusted_source_changed');
|
|
237
|
+
}
|
|
238
|
+
hash.update(file.relativePath).update('\0').update(content).update('\0');
|
|
239
|
+
}
|
|
240
|
+
const digest = hash.digest('hex');
|
|
241
|
+
if (source.trustedSourceTreeSha256 !== undefined && source.trustedSourceTreeSha256 !== digest) {
|
|
242
|
+
throw new Error('behavior_source_tree_changed');
|
|
243
|
+
}
|
|
244
|
+
return Object.freeze({ ...source, sourceRoot, sourcePath, trustedSourceTreeSha256: digest });
|
|
245
|
+
}
|
|
246
|
+
|
|
200
247
|
/** Resolves one already-scanned source to the URL imported inside each Worker slot. */
|
|
201
248
|
export function behaviorSourceUrl(source: ResolvedClawclawBehaviorSource): string {
|
|
202
|
-
const resolved =
|
|
249
|
+
const resolved = source;
|
|
203
250
|
assertPluginApiVersion(
|
|
204
251
|
'behavior_api_version_unsupported',
|
|
205
252
|
BEHAVIOR_PLUGIN_API_VERSION,
|
|
@@ -5,6 +5,7 @@ import type {
|
|
|
5
5
|
ClawclawBehaviorClass,
|
|
6
6
|
ClawclawBehaviorManifest,
|
|
7
7
|
} from '../../../../sdk/behavior-plugin/index.js';
|
|
8
|
+
import type { StrategyWorkerLease } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
|
|
8
9
|
import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
|
|
9
10
|
import { deepFreezeBehaviorValue } from './behavior-manifest.js';
|
|
10
11
|
import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
|
|
@@ -24,6 +25,7 @@ export interface PreparedClawclawBehavior {
|
|
|
24
25
|
readonly rawInput?: Readonly<Record<string, unknown>>;
|
|
25
26
|
/** Static source identity required only by isolated parallel execution. */
|
|
26
27
|
readonly source?: ResolvedClawclawBehaviorSource;
|
|
28
|
+
readonly worker?: StrategyWorkerLease;
|
|
27
29
|
/** Present only when the request/module materialized a finite budget. */
|
|
28
30
|
readonly timing?: Readonly<BehaviorTiming>;
|
|
29
31
|
}
|
|
@@ -59,7 +59,7 @@ function isSuccessfulBackendStrategyReport(value: unknown): boolean {
|
|
|
59
59
|
}
|
|
60
60
|
export interface ClawclawBehaviorPluginOptions {
|
|
61
61
|
readonly memory?: ClawclawStrategyMemory;
|
|
62
|
-
readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'
|
|
62
|
+
readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'> & Partial<Pick<ClawclawBehaviorCatalog, 'prepareForActivation'>>;
|
|
63
63
|
readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
|
|
64
64
|
readonly manager?: BehaviorActivationManager;
|
|
65
65
|
readonly driver?: ClawclawBehaviorControlDriver;
|
|
@@ -87,7 +87,7 @@ function sdkFrame(frame: StrategyFrame): Readonly<BehaviorInput> { return frame.
|
|
|
87
87
|
function preparedValue(prepared: PreparedStrategy): PreparedClawclawBehavior {
|
|
88
88
|
return { ...(prepared.value as PreparedClawclawBehavior), ...(prepared.module ? { module: prepared.module as PreparedClawclawBehavior['module'] } : {}) };
|
|
89
89
|
}
|
|
90
|
-
function createAdapter(): StrategyAdapter {
|
|
90
|
+
function createAdapter(deferredDisplay: () => ClawclawResolvedResourceMetadata | undefined, useAdaptiveWorkers: boolean): StrategyAdapter {
|
|
91
91
|
const observations = new ClawclawBehaviorObservationMemory();
|
|
92
92
|
return {
|
|
93
93
|
input: (input, parameters, continuation, history) => {
|
|
@@ -116,6 +116,7 @@ function createAdapter(): StrategyAdapter {
|
|
|
116
116
|
observations: { capture: frame => observations.capture(sdkFrame(frame)), snapshot: id => observations.snapshot(id), clear: () => observations.clear() },
|
|
117
117
|
createRunner: options => {
|
|
118
118
|
const runner = new ClawclawBehaviorRunner({ ...options, prepared: preparedValue(options.prepared),
|
|
119
|
+
initialWorkers: useAdaptiveWorkers ? 1 : undefined,
|
|
119
120
|
memory: options.memory && ((input, active) => options.memory!({ value: input, epochId: input.epochId, scope: input.scope,
|
|
120
121
|
nowMs: input.nowMs, tick: Number(input.gameState.tick ?? input.epochId), cycle: input.cycle, events: input.events }, active)) });
|
|
121
122
|
return { execution: runner.execution, everyTicks: runner.everyTicks, prepare: () => runner.prepare(),
|
|
@@ -124,8 +125,9 @@ function createAdapter(): StrategyAdapter {
|
|
|
124
125
|
decideParallel: (frame, signal, observation) => runner.decideParallel(sdkFrame(frame), signal, observation as ClawclawBehaviorObservationSnapshot) };
|
|
125
126
|
},
|
|
126
127
|
action: (action, epoch, safety, generation, tick) => ({ ...normalizeClawclawBehaviorAction(action as GameAction, epoch, safety, generation, tick) }),
|
|
127
|
-
display: prepared =>
|
|
128
|
-
|
|
128
|
+
display: prepared => deferredDisplay() ?? (prepared
|
|
129
|
+
? resolveClawclawResourceMetadata({ ...preparedValue(prepared).manifest, display: prepared.display }, BACKEND_STRATEGY_REPORT_LOCALE)
|
|
130
|
+
: { id: 'clawclaw:no-active-behavior', name: '无策略在运行', description: '当前没有活跃的策略。' }),
|
|
129
131
|
reportEligible: input => {
|
|
130
132
|
const state = input.epoch.state;
|
|
131
133
|
return isClawclawRuntimeState(state)
|
|
@@ -147,13 +149,33 @@ function createAdapter(): StrategyAdapter {
|
|
|
147
149
|
};
|
|
148
150
|
}
|
|
149
151
|
/** Game policy and SDK adapter; activation/control/decision execution belongs to the shared runtime. */
|
|
152
|
+
interface DeferredShortControl {
|
|
153
|
+
display(): ClawclawResolvedResourceMetadata | undefined;
|
|
154
|
+
afterReady(): void;
|
|
155
|
+
}
|
|
156
|
+
|
|
150
157
|
export class ClawclawBehaviorPlugin extends StrategyHost {
|
|
158
|
+
private readonly deferredShort: { control?: DeferredShortControl };
|
|
159
|
+
|
|
151
160
|
constructor(options: ClawclawBehaviorPluginOptions) {
|
|
161
|
+
const deferredShort: { control?: DeferredShortControl } = {};
|
|
152
162
|
super({ ...options, id: CLAWCLAW_BEHAVIOR_PLUGIN_ID, stateTopic: CLAWCLAW_BEHAVIOR_STATE_TOPIC,
|
|
153
|
-
actionCapability: CLAWCLAW_ACTION_CAPABILITY, adapter: createAdapter(), captureActions: resolveDetailCapture().actions,
|
|
163
|
+
actionCapability: CLAWCLAW_ACTION_CAPABILITY, adapter: createAdapter(() => deferredShort.control?.display(), !!options.catalog.prepareForActivation), captureActions: resolveDetailCapture().actions,
|
|
154
164
|
catalog: { has: id => options.catalog.has(id), prepare: async (id, input) => {
|
|
155
165
|
const prepared = await options.catalog.prepare(id, input);
|
|
156
166
|
return { ...prepared, value: prepared };
|
|
157
|
-
}
|
|
167
|
+
}, ...(options.catalog.prepareForActivation ? { prepareForActivation: async (id: string, input: Readonly<Record<string, unknown>>) => {
|
|
168
|
+
const prepared = await options.catalog.prepareForActivation!(id, input, options.diagnosticsEnabled);
|
|
169
|
+
return { ...prepared, value: prepared, discardWorker: () => prepared.worker?.dispose() };
|
|
170
|
+
} } : {}) }, after: options.after ?? [CLAWCLAW_ACTION_PLUGIN_ID, CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID] });
|
|
171
|
+
this.deferredShort = deferredShort;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
attachDeferredShortControl(control: DeferredShortControl): void {
|
|
175
|
+
this.deferredShort.control = control;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
afterReady(): void {
|
|
179
|
+
this.deferredShort.control?.afterReady();
|
|
158
180
|
}
|
|
159
181
|
}
|
|
@@ -1,8 +1,30 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
1
2
|
import type { StrategyThreadBridge } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
|
|
2
|
-
import { behaviorSourceUrl, behaviorThreadLoaderConfig, pinBehaviorSource,
|
|
3
|
+
import { behaviorSourceUrl, behaviorThreadLoaderConfig, pinBehaviorSource, pinBehaviorSourceAsync } from './behavior-module-loader.js';
|
|
3
4
|
import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
|
|
5
|
+
const compiled = new URL('../../../../../dist/strategy-worker/runtime/clawclaw/plugins/behavior/', import.meta.url);
|
|
6
|
+
const compiledHost = new URL('host.js', compiled);
|
|
7
|
+
const useCompiledWorker = existsSync(compiledHost);
|
|
8
|
+
|
|
9
|
+
function workerLoader() {
|
|
10
|
+
const loader = behaviorThreadLoaderConfig();
|
|
11
|
+
if (!useCompiledWorker) return loader;
|
|
12
|
+
const sdkAliases = Object.fromEntries(Object.entries(loader.sdkAliases).map(([specifier, target]) => {
|
|
13
|
+
if (!specifier.startsWith('clawclaw-cli') && !specifier.startsWith('@myclaw163/clawclaw-cli')) {
|
|
14
|
+
return [specifier, target];
|
|
15
|
+
}
|
|
16
|
+
const entry = /\/sdk\/([^/]+)\/index\.ts$/.exec(target)?.[1] ?? 'sdk';
|
|
17
|
+
return [specifier, new URL(`sdk-${entry}.js`, compiled).href];
|
|
18
|
+
}));
|
|
19
|
+
return { ...loader, sdkAliases };
|
|
20
|
+
}
|
|
21
|
+
|
|
4
22
|
/** Game SDK and source validation; pool scheduling belongs to the framework. */
|
|
5
23
|
export const CLAWCLAW_STRATEGY_WORKER_BRIDGE: StrategyThreadBridge<ResolvedClawclawBehaviorSource> = {
|
|
6
|
-
hostUrl: new URL('./behavior-analysis-thread-host.ts', import.meta.url).href,
|
|
7
|
-
pin:
|
|
24
|
+
hostUrl: useCompiledWorker ? compiledHost.href : new URL('./behavior-analysis-thread-host.ts', import.meta.url).href,
|
|
25
|
+
pin: source => source.trustedSourceTreeSha256 ? source : pinBehaviorSource(source),
|
|
26
|
+
pinAsync: pinBehaviorSourceAsync,
|
|
27
|
+
resolve: source => source,
|
|
28
|
+
sourceUrl: behaviorSourceUrl,
|
|
29
|
+
loader: workerLoader,
|
|
8
30
|
};
|
|
@@ -7,7 +7,7 @@ export { PARALLEL_STRATEGY_THREAD_POOL_SIZE as PARALLEL_BEHAVIOR_THREAD_POOL_SIZ
|
|
|
7
7
|
export type { ThreadStrategyExecutorSnapshot as ThreadBehaviorExecutorSnapshot } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
|
|
8
8
|
export type ThreadBehaviorExecutorOptions = Omit<ThreadStrategyExecutorOptions<ResolvedClawclawBehaviorSource, BehaviorInput, ClawclawBehaviorObservationSnapshot>, 'bridge' | 'inputMetadata'>;
|
|
9
9
|
export type BehaviorThreadPreparation = StrategyThreadPreparation<ResolvedClawclawBehaviorSource, ClawclawBehaviorManifest>;
|
|
10
|
-
export const prepareBehaviorInWorker = (source: ResolvedClawclawBehaviorSource, input: Readonly<Record<string,unknown>>, options: {maxOldGenerationSizeMb?: number; diagnosticsEnabled?: boolean} = {}): Promise<BehaviorThreadPreparation> =>
|
|
10
|
+
export const prepareBehaviorInWorker = (source: ResolvedClawclawBehaviorSource, input: Readonly<Record<string,unknown>>, options: {maxOldGenerationSizeMb?: number; diagnosticsEnabled?: boolean; retainWorker?: boolean} = {}): Promise<BehaviorThreadPreparation> =>
|
|
11
11
|
prepareStrategyInWorker<ResolvedClawclawBehaviorSource, ClawclawBehaviorManifest>(source, input, {...options, bridge: CLAWCLAW_STRATEGY_WORKER_BRIDGE});
|
|
12
12
|
export class ThreadBehaviorExecutor extends ThreadStrategyExecutor<ResolvedClawclawBehaviorSource, BehaviorInput, BehaviorDecision, ClawclawBehaviorObservationSnapshot> {
|
|
13
13
|
constructor(options: ThreadBehaviorExecutorOptions) { super({...options, bridge: CLAWCLAW_STRATEGY_WORKER_BRIDGE,
|
|
@@ -14,6 +14,8 @@ export interface ClawclawDerivedEventRule {
|
|
|
14
14
|
readonly eventTypes: readonly string[];
|
|
15
15
|
readonly consumes?: readonly string[];
|
|
16
16
|
reset(): void;
|
|
17
|
+
save?(): unknown;
|
|
18
|
+
restore?(state: any): void;
|
|
17
19
|
inspect(frame: StoredStateFrame<Record<string, any>>, events?: readonly RuntimeSourceEvent[]): RuntimeEventProposal[];
|
|
18
20
|
}
|
|
19
21
|
|
|
@@ -66,6 +68,8 @@ function roomReadyPayload(room: UnknownRecord): UnknownRecord {
|
|
|
66
68
|
}
|
|
67
69
|
|
|
68
70
|
export class RoomReadyDerivedEventRule implements ClawclawDerivedEventRule {
|
|
71
|
+
save() { return { ready: this.ready }; }
|
|
72
|
+
restore(state: any) { this.ready = state?.ready === true; }
|
|
69
73
|
readonly id = 'room-ready';
|
|
70
74
|
readonly eventTypes = ['room_ready_to_start'] as const;
|
|
71
75
|
private ready = false;
|
|
@@ -123,6 +127,9 @@ function freshGameSnapshot(
|
|
|
123
127
|
const EMERGENCY_WARNING_THRESHOLDS = [30, 20] as const;
|
|
124
128
|
|
|
125
129
|
export class EmergencyCountdownDerivedEventRule implements ClawclawDerivedEventRule {
|
|
130
|
+
save() { return { emergencyKey: this.emergencyKey, remainingSecs: this.remainingSecs, emittedThresholds: [...this.emittedThresholds] }; }
|
|
131
|
+
restore(state: any) { if (!state) return; this.emergencyKey = state.emergencyKey; this.remainingSecs = state.remainingSecs;
|
|
132
|
+
this.emittedThresholds.clear(); for (const value of state.emittedThresholds ?? []) this.emittedThresholds.add(value); }
|
|
126
133
|
readonly id = 'emergency-countdown';
|
|
127
134
|
readonly eventTypes = ['emergency_countdown_warning'] as const;
|
|
128
135
|
private emergencyKey = '';
|
|
@@ -198,6 +205,8 @@ export class EmergencyCountdownDerivedEventRule implements ClawclawDerivedEventR
|
|
|
198
205
|
}
|
|
199
206
|
|
|
200
207
|
export class AbilityStateDerivedEventRule implements ClawclawDerivedEventRule {
|
|
208
|
+
save() { return { initialized: this.initialized, abilities: structuredClone(this.abilities) }; }
|
|
209
|
+
restore(state: any) { if (!state) return; this.initialized = state.initialized; this.abilities = structuredClone(state.abilities); }
|
|
201
210
|
readonly id = 'ability-state';
|
|
202
211
|
readonly eventTypes = [
|
|
203
212
|
'ability.ready',
|
|
@@ -45,6 +45,9 @@ function proposal(type: string, frame: StoredStateFrame<Record<string, any>>, pa
|
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
export class PlayerChangesDerivedEventRule implements ClawclawDerivedEventRule {
|
|
48
|
+
save() { return { initialized: this.initialized, projection: structuredClone(this.projection), snapshots: structuredClone(this.snapshots) }; }
|
|
49
|
+
restore(state: any) { if (!state) return; this.initialized = state.initialized;
|
|
50
|
+
this.projection = structuredClone(state.projection); this.snapshots = structuredClone(state.snapshots); }
|
|
48
51
|
readonly id = 'player-changes';
|
|
49
52
|
readonly eventTypes = ['players_changed'] as const;
|
|
50
53
|
readonly consumes = [...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, 'players_changed'];
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { PerceptionLifecycleChange, PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
|
|
2
|
+
import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
|
|
3
|
+
import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
|
|
4
|
+
import { createCanonicalGameState } from '../../behavior-input.js';
|
|
5
|
+
import { ObservationFrameProjector } from '../../observation-frame-projector.js';
|
|
6
|
+
|
|
7
|
+
export interface PerceptionInputBaseline {
|
|
8
|
+
scope?: string;
|
|
9
|
+
gameId?: string;
|
|
10
|
+
phase?: string;
|
|
11
|
+
connectionId?: string;
|
|
12
|
+
connected?: boolean;
|
|
13
|
+
tick?: number;
|
|
14
|
+
alive?: boolean;
|
|
15
|
+
ended?: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Shared, game-owned input projection for mandatory and installed perceptions. */
|
|
19
|
+
export function perceptionInputBoundary(
|
|
20
|
+
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
21
|
+
previous: PerceptionInputBaseline = {},
|
|
22
|
+
) {
|
|
23
|
+
const rawState = input.epoch.state;
|
|
24
|
+
const runtime = isClawclawRuntimeState(rawState) ? rawState : undefined;
|
|
25
|
+
const raw = clawclawComputationGameState(input.frame.state) ?? (rawState.cycle ? null : input.currentState.state);
|
|
26
|
+
const connected = !runtime || runtime.connection === 'connected';
|
|
27
|
+
const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
|
|
28
|
+
const frame = new ObservationFrameProjector().project(input.frame);
|
|
29
|
+
const scope = `${input.epoch.scope.sessionId}:${input.epoch.scope.segmentId}`;
|
|
30
|
+
const initial = previous.scope !== scope || !!game && previous.gameId !== game.game_id;
|
|
31
|
+
const recovery = !initial && connected && (previous.connected === false || previous.connectionId !== input.epoch.connectionId);
|
|
32
|
+
const lifecycle: PerceptionLifecycleChange[] = [];
|
|
33
|
+
if (initial) lifecycle.push({ kind: 'initial' });
|
|
34
|
+
else if (recovery) lifecycle.push({ kind: 'recovery' });
|
|
35
|
+
else {
|
|
36
|
+
if (game?.phase && previous.phase && previous.phase !== game.phase) {
|
|
37
|
+
lifecycle.push({ kind: 'phase_changed', from: previous.phase, to: game.phase });
|
|
38
|
+
}
|
|
39
|
+
if (previous.alive === true && game?.you?.is_alive === false) lifecycle.push({ kind: 'observer_died' });
|
|
40
|
+
if (!connected && previous.connected !== false) lifecycle.push({ kind: 'observation_gap' });
|
|
41
|
+
}
|
|
42
|
+
const delta = frame && previous.tick !== undefined && !initial && !recovery ? frame.tick - previous.tick : null;
|
|
43
|
+
// Repeated local cycles and same-tick revisions are valid; missing visual samples are explicit.
|
|
44
|
+
const continuous = connected && lifecycle.length === 0 && delta !== null && delta >= 0 && delta <= 3;
|
|
45
|
+
if (frame && !continuous && !initial && !recovery && lifecycle.length === 0) lifecycle.push({ kind: 'observation_gap' });
|
|
46
|
+
if (frame) Object.assign(frame, { tickDelta: delta, continuousFromPrevious: continuous });
|
|
47
|
+
const ended = runtime?.stage === 'ended' || game?.phase === 'game_over';
|
|
48
|
+
const state: PerceptionInputBaseline = { scope, connectionId: input.epoch.connectionId, connected, ended,
|
|
49
|
+
gameId: game?.game_id ?? previous.gameId, phase: game?.phase ?? previous.phase,
|
|
50
|
+
tick: frame?.tick ?? previous.tick, alive: game?.you?.is_alive ?? previous.alive };
|
|
51
|
+
if (runtime?.cause === 'agent_events_query') lifecycle.push({ kind: 'snapshot_requested' });
|
|
52
|
+
if (ended && !previous.ended) lifecycle.push({ kind: 'segment_ending' });
|
|
53
|
+
const common: Pick<PerceptionModuleInput, 'source' | 'scope' | 'gameState' | 'frame' | 'cycle' | 'boundary' | 'lifecycle' | 'roomState' | 'queueState' | 'nowMs'> = {
|
|
54
|
+
source: { epochId: input.epoch.epochSeq, frameSeq: input.frame.frameSeq, connectionId: input.epoch.connectionId,
|
|
55
|
+
backendTick: input.frame.backendTick, receivedAtMs: input.frame.receivedAtMs, observedAtMs: input.frame.observedAtMs },
|
|
56
|
+
scope: { sessionId: input.epoch.scope.sessionId, segmentId: input.epoch.scope.segmentId },
|
|
57
|
+
gameState: game, frame: connected ? frame : null,
|
|
58
|
+
...(runtime?.cycle ? { cycle: runtime.cycle } : {}),
|
|
59
|
+
boundary: initial ? 'initial' : recovery ? 'recovery' : null, lifecycle,
|
|
60
|
+
roomState: runtime?.room ?? null, queueState: runtime?.queue ?? null,
|
|
61
|
+
nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
|
|
62
|
+
};
|
|
63
|
+
return { state, common, initial, recovery };
|
|
64
|
+
}
|
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
import { normalizePerceptionStrategyNames } from '../../perception-strategy-names.js';
|
|
2
|
-
import { prepareNotificationContent } from './notification-content.js';
|
|
2
|
+
import { prepareNotificationContent, notificationStateAt } from './notification-content.js';
|
|
3
3
|
import { preparePerceptionNotification } from './report-content.js';
|
|
4
4
|
import { isNotificationTurn } from '../../notification-turn.js';
|
|
5
|
-
import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
|
|
5
|
+
import type { RuntimeEpochPluginInput, RuntimeEpochPluginContext } from '../../../framework/plugins/index.js';
|
|
6
6
|
import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
|
|
7
7
|
import { type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
|
|
8
|
-
import { ObservationFrameProjector } from '../../observation-frame-projector.js';
|
|
9
8
|
import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
|
|
10
|
-
import { createCanonicalGameState } from '../../behavior-input.js';
|
|
11
9
|
import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
|
|
12
10
|
import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
|
|
13
11
|
import { PerceptionModuleRunner } from './perception-module-runner.js';
|
|
@@ -17,6 +15,7 @@ import { comparePerceptionTasks, type PerceptionTaskBaseline } from './task-base
|
|
|
17
15
|
import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
|
|
18
16
|
import type { PerceptionAdapter, PerceptionSource } from '@myclaw163/game-agent-runtime/perception/contracts.js';
|
|
19
17
|
import type { ClawclawResolvedResourceMetadata } from '../../../../sdk/resource-metadata.js';
|
|
18
|
+
import { perceptionInputBoundary, type PerceptionInputBaseline } from './module-input-boundary.js';
|
|
20
19
|
export const CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID = 'clawclaw.perception.modules';
|
|
21
20
|
export { REACTION_HOST_EVENT_TYPES } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
|
|
22
21
|
export interface PerceptionModulePluginOptions {
|
|
@@ -27,6 +26,7 @@ export interface PerceptionModulePluginOptions {
|
|
|
27
26
|
runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>;
|
|
28
27
|
}
|
|
29
28
|
interface GameCheckpoint {
|
|
29
|
+
inputBoundary?: PerceptionInputBaseline;
|
|
30
30
|
gameId?: string;
|
|
31
31
|
phase?: string;
|
|
32
32
|
connectionId?: string;
|
|
@@ -42,55 +42,41 @@ interface GameCheckpoint {
|
|
|
42
42
|
}
|
|
43
43
|
function sourceValue(source: PerceptionSource): ResolvedClawclawPerceptionSource { return source.value as ResolvedClawclawPerceptionSource; }
|
|
44
44
|
function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapter {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
45
|
+
function prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown, context?: RuntimeEpochPluginContext<Record<string, any>>) {
|
|
46
|
+
const checkpoint = structuredClone(previous ?? { modules: {} }) as GameCheckpoint;
|
|
47
|
+
// The shipped host checkpoint already has this baseline under flat names.
|
|
48
|
+
// Recover it without pretending a running game has just been initialized.
|
|
49
|
+
const oldBoundary = checkpoint.gameId ? { scope: `${input.epoch.scope.sessionId}:${input.epoch.scope.segmentId}`,
|
|
50
|
+
gameId: checkpoint.gameId, phase: checkpoint.phase, connectionId: checkpoint.connectionId,
|
|
51
|
+
tick: checkpoint.previousTick, connected: true } : undefined;
|
|
52
|
+
const shared = perceptionInputBoundary(input, checkpoint.inputBoundary ?? oldBoundary);
|
|
49
53
|
const oldGame = checkpoint.gameId, oldPhase = checkpoint.phase;
|
|
50
|
-
const
|
|
51
|
-
const connected =
|
|
52
|
-
const
|
|
53
|
-
const
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|| (game && checkpoint.phase !== game.phase)) {
|
|
60
|
-
checkpoint.previousTick = undefined;
|
|
61
|
-
for (const state of Object.values(checkpoint.modules)) {
|
|
62
|
-
state.value = undefined;
|
|
63
|
-
for (const binding of Object.values(state.bindings)) {
|
|
64
|
-
binding.armed = true;
|
|
65
|
-
binding.lastAcceptedAt = undefined;
|
|
66
|
-
binding.failedAttempt = undefined;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
checkpoint.phase = game?.phase;
|
|
70
|
-
}
|
|
71
|
-
const frame = projector.project(input.frame);
|
|
72
|
-
if (frame) {
|
|
73
|
-
const delta = checkpoint.previousTick === undefined ? null : frame.tick - checkpoint.previousTick;
|
|
74
|
-
Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
|
|
75
|
-
&& checkpoint.connectionId === input.epoch.connectionId });
|
|
76
|
-
checkpoint.previousTick = frame.tick;
|
|
77
|
-
}
|
|
78
|
-
const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
|
|
79
|
-
const facts = input.pendingEvents.filter(event => !event.replayed && !event.notificationOf && event.producerPluginId === undefined).map(event => ({
|
|
54
|
+
const game = shared.common.gameState;
|
|
55
|
+
const connected = shared.state.connected === true;
|
|
56
|
+
const boundary = shared.common.boundary;
|
|
57
|
+
const frame = shared.common.frame;
|
|
58
|
+
const nowMs = shared.common.nowMs;
|
|
59
|
+
const originalFacts = input.pendingEvents.filter(event => !event.replayed && !event.notificationOf && event.producerPluginId === undefined);
|
|
60
|
+
const eventStates = Object.fromEntries(originalFacts.map(event => [event.eventId,
|
|
61
|
+
context ? notificationStateAt(context, event.epochSeq) : null]));
|
|
62
|
+
const facts = originalFacts.map(event => ({
|
|
80
63
|
eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
|
|
81
64
|
type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
|
|
82
|
-
payload: projectTaskChoiceEventPayload(
|
|
65
|
+
payload: projectTaskChoiceEventPayload(eventStates[event.eventId], event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
|
|
83
66
|
}));
|
|
84
67
|
const resetScope = !!game && oldGame !== game.game_id;
|
|
85
|
-
const
|
|
68
|
+
const resetBindings = (!game && oldPhase !== undefined) || (!!game && (resetScope ? undefined : oldPhase) !== game.phase);
|
|
86
69
|
checkpoint.connectionId = input.epoch.connectionId;
|
|
87
|
-
|
|
70
|
+
checkpoint.inputBoundary = shared.state;
|
|
71
|
+
checkpoint.gameId = game?.game_id ?? oldGame;
|
|
72
|
+
checkpoint.phase = game?.phase;
|
|
73
|
+
return { state: checkpoint, identity: game?.game_id, resetScope, resetModules: false, resetBindings, notificationOnly: false, nowMs,
|
|
88
74
|
reflexAllowed: !!game && game.phase === 'wandering' && game.you?.is_alive === true && connected,
|
|
89
|
-
value: { input, game, frame, facts, boundary } };
|
|
75
|
+
value: { input, game, frame, facts, eventStates, boundary, common: shared.common } };
|
|
90
76
|
}
|
|
91
77
|
type Prepared = ReturnType<typeof prepare>['value'];
|
|
92
78
|
return {
|
|
93
|
-
reset: () =>
|
|
79
|
+
reset: () => {},
|
|
94
80
|
recover: saved => {
|
|
95
81
|
const value = saved as {
|
|
96
82
|
adapterState?: unknown;
|
|
@@ -103,9 +89,9 @@ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapte
|
|
|
103
89
|
}
|
|
104
90
|
return value.adapterState ?? { gameId: value.gameId, phase: value.phase, connectionId: value.connectionId, previousTick: value.previousTick, modules: {} };
|
|
105
91
|
},
|
|
106
|
-
prepare: (input, previous) => isNotificationTurn(input.epoch.state)
|
|
92
|
+
prepare: (input, previous, context) => isNotificationTurn(input.epoch.state)
|
|
107
93
|
? { state: previous, resetScope: false, resetModules: false, notificationOnly: true, nowMs: 0, reflexAllowed: false, value: null }
|
|
108
|
-
: prepare(input, previous),
|
|
94
|
+
: prepare(input, previous, context),
|
|
109
95
|
configure: (source, value) => normalizeBehaviorInput(value, sourceValue(source).module!.inputs ?? []),
|
|
110
96
|
describe: (source, locale) => { const value = sourceValue(source); return resolveClawclawResourceMetadata({ ...value.manifest, display: value.display }, locale); },
|
|
111
97
|
createRunner: (source, bindMemory) => {
|
|
@@ -114,14 +100,16 @@ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapte
|
|
|
114
100
|
return { start: () => runner.start(), stop: () => runner.stop(), evaluate: async (input) => normalizePerceptionStrategyNames(await runner.evaluate(input.value as PerceptionModuleInput)) };
|
|
115
101
|
},
|
|
116
102
|
input: (source, prepared, baseline, state, config, bindings) => {
|
|
117
|
-
const { input, game, frame, facts, boundary } = prepared.value as Prepared;
|
|
103
|
+
const { input, game, frame, facts, eventStates, boundary, common } = prepared.value as Prepared;
|
|
104
|
+
const events = facts.filter(event => source.module.consumes?.includes(event.type));
|
|
118
105
|
const comparison = comparePerceptionTasks(baseline as PerceptionTaskBaseline | undefined, input, boundary);
|
|
119
|
-
const moduleInput: PerceptionModuleInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
|
|
106
|
+
const moduleInput: PerceptionModuleInput = { ...common, moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
|
|
120
107
|
...(isClawclawRuntimeState(input.epoch.state) && input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
|
|
121
|
-
events:
|
|
108
|
+
events, eventStates: Object.fromEntries(events.map(event => [event.eventId, eventStates[event.eventId]])), nowMs: prepared.nowMs,
|
|
122
109
|
state, config, ...bindings, availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes, boundary };
|
|
123
110
|
return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline,
|
|
124
|
-
evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) ||
|
|
111
|
+
evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || !!common.roomState || !!common.queueState
|
|
112
|
+
|| moduleInput.events.length > 0 || !!moduleInput.lifecycle?.length };
|
|
125
113
|
},
|
|
126
114
|
notification: (event, prepared, source) => {
|
|
127
115
|
const { game, input } = prepared.value as Prepared;
|
|
@@ -4,6 +4,7 @@ import { ClawclawPerception, ClawclawReaction } from '../../../../sdk/perception
|
|
|
4
4
|
import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
|
|
5
5
|
import { normalizePerceptionModuleManifest } from '../../perception-module-manifest.js';
|
|
6
6
|
import { normalizeReactionManifest } from '../../reaction-manifest.js';
|
|
7
|
+
import { CLAWCLAW_PERCEPTION_SPATIAL_API } from './spatial-facts.js';
|
|
7
8
|
|
|
8
9
|
await runPerceptionWorker<PerceptionModuleInput>(async data => {
|
|
9
10
|
const Module = (await import(pathToFileURL(data.modulePath).href)).default;
|
|
@@ -13,5 +14,6 @@ await runPerceptionWorker<PerceptionModuleInput>(async data => {
|
|
|
13
14
|
const {kind: _kind, ...common} = legacy ?? {} as any;
|
|
14
15
|
const manifest = legacy ? {...common,apiVersion:3} : normalizePerceptionModuleManifest(Module.manifest);
|
|
15
16
|
if (JSON.stringify(manifest) !== JSON.stringify(data.expectedManifest)) throw Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
|
|
16
|
-
return { create: () =>
|
|
17
|
+
return { create: () => ({ evaluate: (input, api) => new Module().evaluate(input, { ...api, spatial: CLAWCLAW_PERCEPTION_SPATIAL_API }) }),
|
|
18
|
+
prepareInput: input => ({...input,events:input.events.filter(event=>manifest.consumes?.includes(event.type))}) };
|
|
17
19
|
});
|