@myclaw163/clawclaw-cli 0.9.2 → 0.10.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.
- package/QUICKSTART.md +1 -1
- package/QUICKSTART_OTHER.md +13 -12
- package/README.md +7 -8
- package/bin/clawclaw-channel.mjs +2 -2
- package/bin/clawclaw-cli.mjs +2 -2
- package/docs/configuration.md +27 -101
- package/docs/custom-modules/README.md +23 -35
- package/docs/custom-modules/api-reference.md +95 -273
- package/docs/custom-modules/behavior.md +94 -78
- package/docs/custom-modules/examples/auto-escape.ts +5 -5
- package/docs/custom-modules/examples/go-to-point.ts +11 -11
- package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
- package/docs/custom-modules/examples/task-reminder.ts +4 -5
- package/docs/custom-modules/perception.md +42 -603
- package/docs/custom-modules/skill.md +12 -10
- package/docs/desktop-event-push.md +3 -3
- package/docs/runtime/README.md +16 -17
- package/docs/runtime/agent-notifications.md +42 -12
- package/docs/runtime/behavior-runtime.md +47 -46
- package/docs/runtime/components-and-boundaries.md +70 -28
- package/docs/runtime/events-and-state.md +41 -18
- package/docs/runtime/framework-package.md +73 -0
- package/docs/runtime/official-perception-modules.md +5 -5
- package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
- package/docs/runtime/short-commands-and-capabilities.md +8 -9
- package/docs/user-guide/README.md +10 -7
- package/docs/user-guide/api-reference.md +81 -164
- package/docs/user-guide/behavior.md +84 -68
- package/docs/user-guide/installation.md +7 -7
- package/docs/user-guide/perception.md +42 -586
- package/docs/user-guide/skill.md +12 -10
- package/package.json +24 -9
- package/scripts/check-framework-boundaries.mjs +27 -0
- package/scripts/check-skill-command-surface.mjs +20 -23
- package/scripts/enable_ccl_permissions.cjs +4 -0
- package/scripts/install-local-runtime.mjs +35 -0
- package/scripts/postinstall.mjs +1 -1
- package/scripts/qa-install.mjs +105 -0
- package/scripts/sync-bundled-skill.mjs +35 -28
- package/skills/clawclaw/SKILL.md +53 -57
- package/skills/clawclaw/references/BEHAVIORS.md +43 -83
- package/skills/clawclaw/references/CHANNELS.md +2 -2
- package/skills/clawclaw/references/COMMANDS.md +62 -103
- package/skills/clawclaw/references/HUB.md +2 -2
- package/skills/clawclaw/references/STREAM.md +8 -8
- package/skills/clawclaw/references/TACTICS.md +1 -1
- package/skills/clawclaw-creator/SKILL.md +82 -0
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
- package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
- package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
- package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
- package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
- package/src/channel/claude-channel-ipc-server.ts +1 -0
- package/src/cli.ts +4 -2
- package/src/commands/behavior.ts +26 -10
- package/src/commands/capability.ts +17 -14
- package/src/commands/load.ts +5 -3
- package/src/commands/perception.ts +5 -0
- package/src/commands/skill.ts +34 -29
- package/src/commands/strategy.ts +2 -0
- package/src/commands/upgrade.ts +2 -2
- package/src/lib/agent-workspace-skills.ts +20 -13
- package/src/lib/capability-cloud-sync.ts +2 -1
- package/src/lib/capability-discovery.ts +2 -1
- package/src/lib/capability-load-diagnostics.ts +3 -3
- package/src/lib/capability-workspace.ts +2 -1
- package/src/lib/game-client.ts +7 -1
- package/src/lib/package-skills.ts +4 -0
- package/src/lib/perception-config.ts +18 -6
- package/src/lib/runtime-cadence-config.ts +16 -0
- package/src/lib/skill-host.ts +1 -1
- package/src/lib/workspace-runtime-lock.ts +3 -46
- package/src/pipeline/canonical-event-presentation.ts +23 -124
- package/src/pipeline/event-format.ts +12 -21
- package/src/pipeline/event-hints.ts +6 -6
- package/src/pipeline/game-sync-event-normalization.ts +57 -63
- package/src/runtime/clawclaw/behavior-decision.ts +7 -3
- package/src/runtime/clawclaw/behavior-input.ts +8 -4
- package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
- package/src/runtime/clawclaw/notification-policy.ts +42 -0
- package/src/runtime/clawclaw/notification-turn.ts +19 -0
- package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
- package/src/runtime/clawclaw/owner.ts +47 -9
- package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
- package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
- package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
- package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
- package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
- package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
- package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
- package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
- package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
- package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
- package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
- package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
- package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
- package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
- package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
- package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
- package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
- package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
- package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
- package/src/runtime/clawclaw/runtime-state.ts +11 -0
- package/src/runtime/clawclaw/runtime.ts +8 -0
- package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
- package/src/runtime/clawclaw/strategy-memory.ts +1 -77
- package/src/runtime/clawclaw-event-catalog.ts +12 -12
- package/src/runtime/framework/action-diagnostics.ts +3 -83
- package/src/runtime/framework/capability-registry.ts +2 -395
- package/src/runtime/framework/contracts.ts +2 -144
- package/src/runtime/framework/control/control-scheduler.ts +2 -1268
- package/src/runtime/framework/control/domain-set.ts +2 -81
- package/src/runtime/framework/control/index.ts +1 -3
- package/src/runtime/framework/control/types.ts +2 -191
- package/src/runtime/framework/control-coordinator.ts +2 -11
- package/src/runtime/framework/events/event-catalog.ts +2 -74
- package/src/runtime/framework/events/event-delivery-service.ts +2 -200
- package/src/runtime/framework/events/event-ingress.ts +2 -99
- package/src/runtime/framework/events/event-repository.ts +2 -82
- package/src/runtime/framework/events/index.ts +2 -7
- package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
- package/src/runtime/framework/events/runtime-resume.ts +2 -20
- package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
- package/src/runtime/framework/events/test-helpers.ts +1 -1
- package/src/runtime/framework/events/types.ts +2 -312
- package/src/runtime/framework/index.ts +3 -7
- package/src/runtime/framework/load-node-sqlite.ts +2 -17
- package/src/runtime/framework/mailbox/coalescer.ts +2 -83
- package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
- package/src/runtime/framework/mailbox/identity.ts +2 -38
- package/src/runtime/framework/mailbox/index.ts +1 -7
- package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
- package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
- package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
- package/src/runtime/framework/mailbox/types.ts +2 -145
- package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
- package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
- package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
- package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
- package/src/runtime/framework/participation-manager.ts +2 -253
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
- package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
- package/src/runtime/framework/plugins/contracts.ts +2 -396
- package/src/runtime/framework/plugins/index.ts +1 -4
- package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
- package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
- package/src/runtime/framework/runtime.ts +5 -1843
- package/src/runtime/framework/serial-task-queue.ts +2 -14
- package/src/runtime/framework/state/contracts.ts +2 -49
- package/src/runtime/framework/state/current-state-store.ts +2 -184
- package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
- package/src/runtime/framework/state/freshness.ts +2 -72
- package/src/runtime/framework/state/history/contracts.ts +2 -158
- package/src/runtime/framework/state/history/history-writer.ts +2 -194
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
- package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
- package/src/runtime/framework/state/index.ts +1 -13
- package/src/runtime/framework/state/state-ingress.ts +2 -95
- package/src/runtime/framework/state/state-provider.ts +2 -62
- package/src/runtime/framework/state/types.ts +2 -155
- package/src/runtime/game-sync-ingress-protocol.ts +3 -2
- package/src/runtime/game-sync-ingress-worker.ts +7 -1
- package/src/runtime/game-sync-protocol.ts +64 -4
- package/src/runtime/host-monitor-rate-gate.ts +1 -123
- package/src/runtime/mailbox-host-relay.ts +1 -326
- package/src/runtime/observability/detail-capture.ts +4 -108
- package/src/runtime/observability/process-timing.ts +2 -59
- package/src/runtime/observability/recorder.ts +2 -238
- package/src/runtime/observability/redaction.ts +2 -181
- package/src/runtime/observability/reporter.ts +2 -154
- package/src/runtime/observability/sinks.ts +2 -135
- package/src/runtime/observability/types.ts +2 -92
- package/src/runtime/owner-control.ts +45 -320
- package/src/runtime/parent-process-watch.ts +1 -51
- package/src/runtime/process-identity.ts +1 -72
- package/src/runtime/threaded-ws-client.ts +11 -2
- package/src/runtime/ws-client.ts +6 -0
- package/src/sdk/behavior-plugin/index.ts +9 -3
- package/src/sdk/index.ts +40 -2
- package/src/sdk/module-input/index.ts +5 -0
- package/src/sdk/perception-plugin/index.ts +3 -1
- package/src/sdk/perception-plugin/module.ts +12 -2
- package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
- package/src/sdk/perception-plugin/reminder.ts +2 -1
- package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
- package/src/sdk/strategy-memory.ts +1 -12
- package/src/sdk/strategy-plugin/index.ts +36 -0
- package/src/sdk/trigger-plugin/index.ts +1 -0
- package/docs/custom-modules/trigger.md +0 -295
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
- package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
|
@@ -1,39 +1,17 @@
|
|
|
1
|
-
import { parentPort, workerData } from 'node:worker_threads';
|
|
2
1
|
import { pathToFileURL } from 'node:url';
|
|
2
|
+
import { runPerceptionWorker } from '@myclaw163/game-agent-runtime/perception/perception-worker-host.js';
|
|
3
3
|
import { ClawclawPerception, ClawclawReaction } from '../../../../sdk/perception-plugin/index.js';
|
|
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 { StrategyMemoryRpcClient } from '../../strategy-memory-rpc.js';
|
|
8
7
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const legacy = workerData.legacy ? normalizeReactionManifest(Module.manifest) : undefined;
|
|
20
|
-
const { kind: _kind, ...common } = legacy ?? {} as any;
|
|
21
|
-
const manifest = legacy ? { ...common, apiVersion: 3 } : normalizePerceptionModuleManifest(Module.manifest);
|
|
22
|
-
if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
|
|
23
|
-
parentPort!.postMessage({ type: 'ready' });
|
|
24
|
-
const memory = new StrategyMemoryRpcClient(message => parentPort!.postMessage(message));
|
|
25
|
-
let active: number | undefined;
|
|
26
|
-
parentPort!.on('message', async (message: any) => {
|
|
27
|
-
if (memory.receive(message)) return;
|
|
28
|
-
const { id, input }: { id: number; input: PerceptionModuleInput } = message;
|
|
29
|
-
active = id;
|
|
30
|
-
try {
|
|
31
|
-
const result = await new Module().evaluate(freeze({ ...input,
|
|
32
|
-
events: input.events.filter(event => manifest.consumes?.includes(event.type)) }),
|
|
33
|
-
Object.freeze({ memory: memory.bind(String(id), () => active === id) })) ?? {};
|
|
34
|
-
if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('PERCEPTION_MODULE_OUTPUT_TOO_LARGE');
|
|
35
|
-
parentPort!.postMessage({ type: 'result', id, result });
|
|
36
|
-
} catch { parentPort!.postMessage({ type: 'error', id }); }
|
|
37
|
-
finally { if (active === id) active = undefined; }
|
|
38
|
-
});
|
|
39
|
-
} catch { parentPort!.postMessage({ type: 'error' }); }
|
|
8
|
+
await runPerceptionWorker<PerceptionModuleInput>(async data => {
|
|
9
|
+
const Module = (await import(pathToFileURL(data.modulePath).href)).default;
|
|
10
|
+
if (!(Module?.prototype instanceof (data.legacy ? ClawclawReaction : ClawclawPerception))
|
|
11
|
+
|| Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw Error('PERCEPTION_MODULE_CLASS_INVALID');
|
|
12
|
+
const legacy = data.legacy ? normalizeReactionManifest(Module.manifest) : undefined;
|
|
13
|
+
const {kind: _kind, ...common} = legacy ?? {} as any;
|
|
14
|
+
const manifest = legacy ? {...common,apiVersion:3} : normalizePerceptionModuleManifest(Module.manifest);
|
|
15
|
+
if (JSON.stringify(manifest) !== JSON.stringify(data.expectedManifest)) throw Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
|
|
16
|
+
return { create: () => new Module(), prepareInput: input => ({...input,events:input.events.filter(event=>manifest.consumes?.includes(event.type))}) };
|
|
17
|
+
});
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { prepareNotificationContent } from './notification-content.js';
|
|
2
|
+
import { preparePerceptionNotification } from './report-content.js';
|
|
3
|
+
import { isNotificationTurn } from '../../notification-turn.js';
|
|
1
4
|
import type {
|
|
2
5
|
RuntimeEpochFlushReason,
|
|
3
6
|
RuntimeEpochPlugin,
|
|
@@ -362,6 +365,7 @@ function proposals(value: readonly PerceptionEventProposal[] | void): RuntimeEve
|
|
|
362
365
|
|
|
363
366
|
/** One Runtime plugin that projects each frame once and fans it out to perception modules. */
|
|
364
367
|
export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<string, any>> {
|
|
368
|
+
readonly agentNotificationProducer = true;
|
|
365
369
|
readonly kind = 'epoch' as const;
|
|
366
370
|
readonly id = CLAWCLAW_PERCEPTION_PLUGIN_ID;
|
|
367
371
|
readonly version = String(PERCEPTION_PLUGIN_API_VERSION);
|
|
@@ -480,6 +484,11 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
480
484
|
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
481
485
|
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
482
486
|
): Promise<RuntimeEpochPluginResult> {
|
|
487
|
+
if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' };
|
|
488
|
+
if (input.epoch.state.cycle && !input.epoch.state.cycle.hasNewState
|
|
489
|
+
&& input.epoch.state.connection === 'connected' && input.epoch.state.stage !== 'ended') {
|
|
490
|
+
return { outcome: 'noop', reason: 'unchanged_observation' };
|
|
491
|
+
}
|
|
483
492
|
const updateStartedAt = performance.now();
|
|
484
493
|
const projectionStartedAt = performance.now();
|
|
485
494
|
const visual = this.projector.project(input.frame);
|
|
@@ -513,6 +522,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
513
522
|
computation: Readonly<RuntimeEpochPluginResult>,
|
|
514
523
|
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
515
524
|
): Promise<RuntimeEpochPluginResult> {
|
|
525
|
+
if (isNotificationTurn(input.epoch.state) || computation.reason === 'unchanged_observation') return computation;
|
|
516
526
|
const proposal = this.computationProposal(computation.proposal);
|
|
517
527
|
const commitStartedAt = performance.now();
|
|
518
528
|
const previousFrameSeq = this.lastFrameSeq;
|
|
@@ -522,7 +532,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
522
532
|
analyses: proposal.analyses,
|
|
523
533
|
analysisTiming: proposal.timing ?? this.emptyAnalysisTiming(),
|
|
524
534
|
}, context.signal, context.diagnostic);
|
|
525
|
-
if (input.frame.frameSeq > previousFrameSeq + 1) {
|
|
535
|
+
if (!input.epoch.state.cycle && input.frame.frameSeq > previousFrameSeq + 1) {
|
|
526
536
|
context.diagnostic('perception.catchup_frames_dropped', {
|
|
527
537
|
target_epoch_seq: input.epoch.epochSeq,
|
|
528
538
|
max_backfill_visual_frames: this.maxBackfillVisualFrames,
|
|
@@ -546,7 +556,8 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
546
556
|
? {
|
|
547
557
|
outcome: 'processed',
|
|
548
558
|
...(inspected.reason ? { reason: inspected.reason } : {}),
|
|
549
|
-
events: inspected.proposals,
|
|
559
|
+
events: inspected.proposals.map(event => ({ ...event,
|
|
560
|
+
notificationContent: event.notificationContent ?? prepareNotificationContent(event.type, event.payload, input.currentState.state, 'custom') })),
|
|
550
561
|
checkpoint,
|
|
551
562
|
}
|
|
552
563
|
: { outcome: 'noop', reason: inspected.reason ?? 'not_visual_state', checkpoint };
|
|
@@ -585,7 +596,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
585
596
|
if (input.stored.frameSeq <= this.lastFrameSeq) {
|
|
586
597
|
return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() };
|
|
587
598
|
}
|
|
588
|
-
const stateFrameGap = this.lastFrameSeq > 0
|
|
599
|
+
const stateFrameGap = !input.stored.state.cycle && this.lastFrameSeq > 0
|
|
589
600
|
&& input.stored.frameSeq > this.lastFrameSeq + 1;
|
|
590
601
|
this.lastFrameSeq = input.stored.frameSeq;
|
|
591
602
|
const runtimeState = input.stored.state;
|
|
@@ -635,7 +646,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
635
646
|
reason: 'segment_ending',
|
|
636
647
|
};
|
|
637
648
|
}
|
|
638
|
-
if (runtimeState.game_snapshot.status !== 'fresh') {
|
|
649
|
+
if (runtimeState.game_snapshot.status !== 'fresh' && runtimeState.game_snapshot.status !== 'cached') {
|
|
639
650
|
return {
|
|
640
651
|
visual: null,
|
|
641
652
|
proposals: [],
|
|
@@ -1159,7 +1170,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
1159
1170
|
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
1160
1171
|
): PerceptionAnalysisInput {
|
|
1161
1172
|
this.rememberProjectedFrame(stored, currentVisual);
|
|
1162
|
-
const cached = [...this.projectedFrameCache.values()]
|
|
1173
|
+
const cached = (context.processingIntervalMs !== undefined ? [] : [...this.projectedFrameCache.values()])
|
|
1163
1174
|
.filter((value) => value.stored.frameSeq <= stored.frameSeq)
|
|
1164
1175
|
.sort((left, right) => left.stored.frameSeq - right.stored.frameSeq)
|
|
1165
1176
|
.slice(-(PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1));
|
|
@@ -1180,7 +1191,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
1180
1191
|
stored: StoredStateFrame<Record<string, any>>;
|
|
1181
1192
|
visual: PerceptionFrame;
|
|
1182
1193
|
}>();
|
|
1183
|
-
let beforeFrameSeq = stored.frameSeq + 1;
|
|
1194
|
+
let beforeFrameSeq = stored.state.cycle?.stateFrameSeq ?? stored.frameSeq + 1;
|
|
1184
1195
|
while (projected.size < PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1 && beforeFrameSeq > 1) {
|
|
1185
1196
|
context.signal.throwIfAborted();
|
|
1186
1197
|
const page = context.stateHistory.queryStateFrames({
|
|
@@ -1191,6 +1202,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
1191
1202
|
});
|
|
1192
1203
|
if (page.frames.length === 0) break;
|
|
1193
1204
|
for (const candidate of page.frames) {
|
|
1205
|
+
if (stored.state.cycle && candidate.state.cycle) continue;
|
|
1194
1206
|
if (candidate.frameSeq > stored.frameSeq) continue;
|
|
1195
1207
|
const visual = candidate.frameSeq === stored.frameSeq
|
|
1196
1208
|
? currentVisual
|
|
@@ -1276,7 +1288,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
1276
1288
|
if (!isClawclawRuntimeState(runtimeState)) return true;
|
|
1277
1289
|
return runtimeState.connection === 'connected'
|
|
1278
1290
|
&& runtimeState.stage !== 'ended'
|
|
1279
|
-
&& runtimeState.game_snapshot.status === 'fresh'
|
|
1291
|
+
&& (runtimeState.game_snapshot.status === 'fresh' || runtimeState.game_snapshot.status === 'cached')
|
|
1280
1292
|
&& !(
|
|
1281
1293
|
runtimeState.cause === 'agent_events_query'
|
|
1282
1294
|
&& runtimeState.control?.type === 'events_query'
|
|
@@ -1436,9 +1448,12 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
|
|
|
1436
1448
|
const values = proposals(result.value);
|
|
1437
1449
|
// Aliased copies may emit the same source-level dedupe key. Keep their
|
|
1438
1450
|
// outputs separate without renaming any public Event type or payload.
|
|
1439
|
-
return
|
|
1440
|
-
|
|
1441
|
-
|
|
1451
|
+
return values.map(value => ({ ...value,
|
|
1452
|
+
...(module.source?.declaredId && module.source.declaredId !== module.manifest.id
|
|
1453
|
+
? { dedupeKey: `ccl-alias:${JSON.stringify([module.manifest.id, value.dedupeKey])}` } : {}),
|
|
1454
|
+
notificationContent: preparePerceptionNotification(value.type, value.payload,
|
|
1455
|
+
this.lastVisualFrame?.gameState ?? null, module.manifest.id, this.lastVisualTick),
|
|
1456
|
+
}));
|
|
1442
1457
|
});
|
|
1443
1458
|
}
|
|
1444
1459
|
|
|
@@ -27,7 +27,7 @@ import { normalizeReactionManifest } from '../../reaction-manifest.js';
|
|
|
27
27
|
import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js';
|
|
28
28
|
import { normalizeReminderManifest } from '../../reminder-manifest.js';
|
|
29
29
|
import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js';
|
|
30
|
-
import { normalizePerceptionModuleManifest } from '../../perception-module-manifest.js';
|
|
30
|
+
import { normalizePerceptionModuleManifest, REMOVED_PERCEPTION_INPUT_TYPES } from '../../perception-module-manifest.js';
|
|
31
31
|
import type { PerceptionModuleManifest } from '../../../../sdk/perception-plugin/module.js';
|
|
32
32
|
|
|
33
33
|
export const MAX_PERCEPTION_FILES = 512;
|
|
@@ -39,6 +39,7 @@ const STATIC_MANIFEST = /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/;
|
|
|
39
39
|
export interface ResolvedClawclawPerceptionSource {
|
|
40
40
|
/** Literal source declaration; retained so the loader can diagnose unsupported modules. */
|
|
41
41
|
readonly apiVersion?: number;
|
|
42
|
+
readonly compatibilityError?: string;
|
|
42
43
|
readonly id: string;
|
|
43
44
|
readonly declaredId?: string;
|
|
44
45
|
readonly workingCopyPath?: string;
|
|
@@ -58,7 +59,7 @@ export function expectedPerceptionApiVersion(source: ResolvedClawclawPerceptionS
|
|
|
58
59
|
return source.reaction ? 2 : source.module ? 3 : 2;
|
|
59
60
|
}
|
|
60
61
|
export function isSupportedPerceptionSource(source: ResolvedClawclawPerceptionSource): boolean {
|
|
61
|
-
return source.apiVersion === expectedPerceptionApiVersion(source);
|
|
62
|
+
return !source.compatibilityError && source.apiVersion === expectedPerceptionApiVersion(source);
|
|
62
63
|
}
|
|
63
64
|
|
|
64
65
|
function pathInside(root: string, candidate: string): boolean {
|
|
@@ -364,9 +365,9 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
364
365
|
if (classMatch[1] === 'ClawclawPerception' && /\bevaluate\s*\(/.test(classBody)
|
|
365
366
|
&& literalPluginApiVersion(manifestBlock) !== 2) {
|
|
366
367
|
try {
|
|
367
|
-
const module = normalizePerceptionModuleManifest(parseLiteralModuleManifest(manifestBlock), false);
|
|
368
|
+
const module = normalizePerceptionModuleManifest(parseLiteralModuleManifest(manifestBlock), false, true);
|
|
368
369
|
const { id, description, localizations } = module;
|
|
369
|
-
return { apiVersion: module.apiVersion, id, name: module.name ?? id, description, module, sourcePath, sourceRoot,
|
|
370
|
+
return { ...removedInputDiagnosis(module.consumes ?? []), apiVersion: module.apiVersion, id, name: module.name ?? id, description, module, sourcePath, sourceRoot,
|
|
370
371
|
// Existing resource metadata consumers use this v2-shaped descriptor; executable v3 stays in module.
|
|
371
372
|
manifest: { apiVersion: PERCEPTION_PLUGIN_API_VERSION, id, name: module.name ?? id, description, localizations,
|
|
372
373
|
subjectScope: 'self_and_others', produces: module.produces ?? [] } };
|
|
@@ -386,10 +387,10 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
386
387
|
}
|
|
387
388
|
if (classMatch[1] === 'ClawclawReminder') {
|
|
388
389
|
try {
|
|
389
|
-
const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false);
|
|
390
|
+
const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false, true);
|
|
390
391
|
const { id, description, localizations } = reminder;
|
|
391
392
|
const name = reminder.name ?? id;
|
|
392
|
-
return { apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot,
|
|
393
|
+
return { ...removedInputDiagnosis(reminder.consumes), apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot,
|
|
393
394
|
manifest: { apiVersion: reminder.apiVersion, id, name, description, localizations,
|
|
394
395
|
subjectScope: 'self_and_others', produces: [] } };
|
|
395
396
|
} catch { return null; }
|
|
@@ -513,3 +514,8 @@ export function resolveClawclawPerceptionSource(
|
|
|
513
514
|
if (!source) throw new Error(`Unknown perception module '${id}'.`);
|
|
514
515
|
return source;
|
|
515
516
|
}
|
|
517
|
+
|
|
518
|
+
function removedInputDiagnosis(consumes: readonly string[]): { compatibilityError?: string } {
|
|
519
|
+
const removed = consumes.filter(type => REMOVED_PERCEPTION_INPUT_TYPES.has(type));
|
|
520
|
+
return removed.length ? { compatibilityError: `perception_input_removed:${removed.join(',')}:use gameState, frame or module-local taskChanges` } : {};
|
|
521
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { EventNotificationContent } from '../../../framework/events/types.js';
|
|
2
|
+
import type { GameSyncPerceptionTime } from '../../../game-sync-protocol.js';
|
|
3
|
+
import { timeRange } from '../../../../sdk/perception-plugin/math.js';
|
|
4
|
+
import { prepareNotificationContent } from './notification-content.js';
|
|
5
|
+
|
|
6
|
+
export const PERCEPTION_REPORT_VIEW = 'clawclaw.perception-report';
|
|
7
|
+
export type PerceptionReportContent = GameSyncPerceptionTime & {
|
|
8
|
+
readonly perceiver_id: string;
|
|
9
|
+
readonly output: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const isTick = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
|
|
13
|
+
|
|
14
|
+
/** Freeze the display projection at the producing module's accepted input boundary. */
|
|
15
|
+
export function preparePerceptionNotification(
|
|
16
|
+
type: string,
|
|
17
|
+
payload: Readonly<Record<string, unknown>>,
|
|
18
|
+
state: Record<string, any> | null,
|
|
19
|
+
perceiverId: string,
|
|
20
|
+
backendTick?: number | null,
|
|
21
|
+
): EventNotificationContent {
|
|
22
|
+
const notification = prepareNotificationContent(type, payload, state, 'custom');
|
|
23
|
+
let output = typeof payload.text === 'string' ? payload.text.trim() : '';
|
|
24
|
+
if (!output) return notification;
|
|
25
|
+
const from = payload.from_source_tick ?? payload.from_tick;
|
|
26
|
+
const to = payload.to_source_tick ?? payload.to_tick;
|
|
27
|
+
let time: GameSyncPerceptionTime;
|
|
28
|
+
if (from !== undefined || to !== undefined) {
|
|
29
|
+
if (!isTick(from) || !isTick(to) || from > to || payload.source_tick !== undefined) return notification;
|
|
30
|
+
time = from === to ? { source_tick: to } : { from_source_tick: from, to_source_tick: to };
|
|
31
|
+
// Existing visual modules use this exact SDK formatter. Do not parse arbitrary prose for times.
|
|
32
|
+
if (type.startsWith('visual.')) {
|
|
33
|
+
const prefix = timeRange(from, to);
|
|
34
|
+
for (const separator of [',', ', ']) {
|
|
35
|
+
if (output.startsWith(prefix + separator)) {
|
|
36
|
+
output = output.slice(prefix.length + separator.length).trim();
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
const tick = payload.source_tick ?? payload.tick ?? backendTick;
|
|
43
|
+
if (!isTick(tick)) return notification;
|
|
44
|
+
time = { source_tick: tick };
|
|
45
|
+
}
|
|
46
|
+
if (output) notification.views = { [PERCEPTION_REPORT_VIEW]: {
|
|
47
|
+
perceiver_id: perceiverId, output, ...time,
|
|
48
|
+
} satisfies PerceptionReportContent };
|
|
49
|
+
return notification;
|
|
50
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ReminderTaskChange } from '../../../../sdk/perception-plugin/reminder.js';
|
|
2
|
+
import { nextTaskProjection, type TaskSnapshot } from '../../../../sdk/perception-plugin/task-change-tracker.js';
|
|
3
|
+
import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
|
|
4
|
+
import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
|
|
5
|
+
|
|
6
|
+
/** Private to one perception/checkpoint. It does not subscribe to another perception. */
|
|
7
|
+
export interface PerceptionTaskBaseline { projection: TaskSnapshot[]; initialized: boolean }
|
|
8
|
+
export function comparePerceptionTasks(
|
|
9
|
+
baseline: PerceptionTaskBaseline | undefined,
|
|
10
|
+
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
11
|
+
boundary: 'initial' | 'recovery' | null,
|
|
12
|
+
): { baseline: PerceptionTaskBaseline; changes: ReminderTaskChange[] } {
|
|
13
|
+
const previous = boundary === 'initial' ? undefined : baseline;
|
|
14
|
+
const game = clawclawComputationGameState(input.frame.state);
|
|
15
|
+
if (!game) return { baseline: previous ?? { projection: [], initialized: false }, changes: [] };
|
|
16
|
+
const update = nextTaskProjection({ previous: previous?.projection ?? [], initialized: previous?.initialized ?? false,
|
|
17
|
+
summary: { ...game, ...(input.frame.backendTick === undefined ? {} : { tick: input.frame.backendTick }) },
|
|
18
|
+
events: (input.epoch.state.cycle ? input.pendingEvents.filter(event => !event.notificationOf && !event.producerPluginId)
|
|
19
|
+
: input.epoch.events).map(event => ({ ...event.payload, type: event.type })),
|
|
20
|
+
selfName: game.you?.player?.name ?? game.you?.name,
|
|
21
|
+
allowUntickedInitialRole: isClawclawRuntimeState(input.frame.state)
|
|
22
|
+
&& (input.frame.state.game_snapshot.status === 'fresh' || input.frame.state.game_snapshot.status === 'cached') && input.frame.state.game_snapshot.origin === 'update' });
|
|
23
|
+
// Stable local comparison identity; it is not an ID of a fabricated backend Event.
|
|
24
|
+
const eventId = `task-comparison:${input.epoch.scope.segmentId}:${input.epoch.epochSeq}`;
|
|
25
|
+
return { baseline: { projection: update.projection, initialized: update.initialized },
|
|
26
|
+
changes: (update.payload?.delta ?? []).map((change, index) => ({ ...change,
|
|
27
|
+
key: `${eventId}:${index}`, eventId, epochId: input.epoch.epochSeq,
|
|
28
|
+
baseline: !!boundary || update.payload!.baseline || update.payload!.reason === 'role_assigned' })) };
|
|
29
|
+
}
|
|
@@ -2063,6 +2063,12 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
2063
2063
|
): RuntimeSourceEvent<Record<string, unknown>>[] {
|
|
2064
2064
|
const events: RuntimeSourceEvent<Record<string, unknown>>[] = [];
|
|
2065
2065
|
const normalizedValues = normalizeGameSyncEventsSafely(values);
|
|
2066
|
+
for (const warning of normalizedValues.warnings ?? []) {
|
|
2067
|
+
this.diagnostic('runtime.source.event_field_preserved', {
|
|
2068
|
+
source_id: sourceId, source_seq: meta.sourceSeq, event_index: warning.index,
|
|
2069
|
+
field: warning.field, reason: warning.reason,
|
|
2070
|
+
}, 'warn');
|
|
2071
|
+
}
|
|
2066
2072
|
normalizedValues.rejected.forEach(({ index, error }) => {
|
|
2067
2073
|
const value = values[index];
|
|
2068
2074
|
const raw = value && typeof value === 'object' && !Array.isArray(value)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput,
|
|
2
|
+
RuntimeEpochPluginResult, RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js';
|
|
3
|
+
import type { StoredStateFrame } from '../../../framework/state/index.js';
|
|
4
|
+
import type { ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
|
|
5
|
+
|
|
6
|
+
export class PerceptionRuleRunner
|
|
7
|
+
implements RuntimeEpochPlugin<Record<string, any>> {
|
|
8
|
+
readonly kind = 'epoch' as const;
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly version = '2';
|
|
11
|
+
readonly produces: { events: readonly string[] };
|
|
12
|
+
readonly consumes: { events: readonly string[] };
|
|
13
|
+
// Never skip a computation boundary. Fixed-cadence boundaries may contain multiple Source inputs.
|
|
14
|
+
readonly catchUp = 'strict_ordered' as const;
|
|
15
|
+
readonly timeoutMs = 1_000;
|
|
16
|
+
|
|
17
|
+
private readonly rules: ClawclawDerivedEventRule[];
|
|
18
|
+
private lastFrameSeq = 0;
|
|
19
|
+
|
|
20
|
+
constructor(id: string, rules: readonly ClawclawDerivedEventRule[]) {
|
|
21
|
+
this.id = id;
|
|
22
|
+
this.rules = [...rules].sort((left, right) => left.id.localeCompare(right.id));
|
|
23
|
+
this.produces = { events: [...new Set(this.rules.flatMap(rule => rule.eventTypes))].sort() };
|
|
24
|
+
this.consumes = { events: [...new Set(this.rules.flatMap(rule => rule.consumes ?? []))].sort() };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
start(): void {
|
|
28
|
+
this.reset();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
|
|
32
|
+
const completedThrough = context.progress().completedThroughEpochSeq;
|
|
33
|
+
if (completedThrough <= 0) return;
|
|
34
|
+
if (context.processingIntervalMs !== undefined) {
|
|
35
|
+
const frame = context.stateHistory.queryStateFrames({ scope: context.scope, toEpochSeq: completedThrough, order: 'desc', limit: 1 }).frames[0];
|
|
36
|
+
if (frame) {
|
|
37
|
+
const sourceEpoch = frame.state.cycle?.stateVersion ?? frame.epochSeq;
|
|
38
|
+
this.inspectFrame(frame, sourceEpoch ? context.sourceEventsAt?.(sourceEpoch) ?? [] : []);
|
|
39
|
+
}
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
this.scanHistory(context, completedThrough, false);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
update(
|
|
46
|
+
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
47
|
+
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
48
|
+
): RuntimeEpochPluginResult {
|
|
49
|
+
const facts = input.pendingEvents.filter(event => !event.producerPluginId && !event.notificationOf)
|
|
50
|
+
.map(event => ({ type: event.type, payload: event.payload, producer: event.producer,
|
|
51
|
+
sourceEventId: event.sourceEventId, sourceSeq: event.sourceSequence, observedAt: event.occurredAt,
|
|
52
|
+
receivedAt: event.receivedAt, replayed: event.replayed }));
|
|
53
|
+
const events = context.processingIntervalMs !== undefined
|
|
54
|
+
? this.inspectFrame(input.frame, facts)
|
|
55
|
+
: this.scanHistory(context, input.epoch.epochSeq, true, input.frame.frameSeq, input);
|
|
56
|
+
return { ...(events.length > 0 ? { outcome: 'processed' as const, events }
|
|
57
|
+
: { outcome: 'noop' as const, reason: 'no_derived_event' }),
|
|
58
|
+
...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
stop(): void {
|
|
62
|
+
this.reset();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private scanHistory(
|
|
66
|
+
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
67
|
+
throughEpochSeq: number,
|
|
68
|
+
collect: boolean,
|
|
69
|
+
throughFrameSeq?: number,
|
|
70
|
+
currentInput?: RuntimeEpochPluginInput<Record<string, any>>,
|
|
71
|
+
): RuntimeEventProposal[] {
|
|
72
|
+
if (this.rules.length === 0) return [];
|
|
73
|
+
const proposals: RuntimeEventProposal[] = [];
|
|
74
|
+
let afterFrameSeq = this.lastFrameSeq;
|
|
75
|
+
while (true) {
|
|
76
|
+
const page = context.stateHistory.queryStateFrames({
|
|
77
|
+
scope: context.scope,
|
|
78
|
+
afterFrameSeq,
|
|
79
|
+
toEpochSeq: throughEpochSeq,
|
|
80
|
+
...(throughFrameSeq === undefined ? {} : { beforeFrameSeq: throughFrameSeq + 1 }),
|
|
81
|
+
order: 'asc',
|
|
82
|
+
limit: 500,
|
|
83
|
+
});
|
|
84
|
+
if (page.frames.length === 0) break;
|
|
85
|
+
for (const frame of page.frames) {
|
|
86
|
+
const facts = frame.epochSeq === undefined ? [] : context.sourceEventsAt?.(frame.epochSeq)
|
|
87
|
+
?? (frame.epochSeq === currentInput?.epoch.epochSeq ? currentInput.epoch.events : []);
|
|
88
|
+
const frameEvents = this.inspectFrame(frame, facts);
|
|
89
|
+
if (collect) proposals.push(...frameEvents);
|
|
90
|
+
afterFrameSeq = frame.frameSeq;
|
|
91
|
+
}
|
|
92
|
+
if (!page.page.hasMore) break;
|
|
93
|
+
}
|
|
94
|
+
return proposals;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
private inspectFrame(frame: StoredStateFrame<Record<string, any>>, facts: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] {
|
|
98
|
+
if (frame.frameSeq <= this.lastFrameSeq) return [];
|
|
99
|
+
this.lastFrameSeq = frame.frameSeq;
|
|
100
|
+
return this.rules.flatMap((rule) => rule.inspect(frame, facts));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private reset(): void {
|
|
104
|
+
this.lastFrameSeq = 0;
|
|
105
|
+
for (const rule of this.rules) rule.reset();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { prepareNotificationContent, notificationStateAt } from '../perception/notification-content.js';
|
|
2
|
+
import type { RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, RuntimeEventProposal } from '../../../framework/plugins/index.js';
|
|
3
|
+
import { CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, CLAWCLAW_LOCAL_AGENT_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
|
|
4
|
+
import { BUILTIN_PERCEPTION_PREFIX, CLAWCLAW_SYSTEM_CONTROL_EVENTS } from '../../notification-policy.js';
|
|
5
|
+
import { AbilityStateDerivedEventRule, EmergencyCountdownDerivedEventRule, RoomReadyDerivedEventRule,
|
|
6
|
+
type ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
|
|
7
|
+
import { PlayerChangesDerivedEventRule } from '../derived-event/state-change-rules.js';
|
|
8
|
+
import { PerceptionRuleRunner } from './rule-runner.js';
|
|
9
|
+
import { defaultReminder, TASK_LIFECYCLE_FACT_TYPES } from '../../../../sdk/perception-plugin/reminder-rules.js';
|
|
10
|
+
import { clawclawComputationGameState } from '../../runtime-state.js';
|
|
11
|
+
import { createCanonicalGameState } from '../../behavior-input.js';
|
|
12
|
+
import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
|
|
13
|
+
|
|
14
|
+
export const BUILTIN_PERCEPTION_NAMES = {
|
|
15
|
+
players: '玩家变化', tasks: '任务提醒', abilities: '能力变化', emergency: '紧急任务',
|
|
16
|
+
flow: '房间与游戏流程', meeting: '会议', behavior: '策略消息',
|
|
17
|
+
} as const;
|
|
18
|
+
type Domain = keyof typeof BUILTIN_PERCEPTION_NAMES;
|
|
19
|
+
interface TaskCheckpoint { gameId?: string; connectionId?: string }
|
|
20
|
+
|
|
21
|
+
/** Native mandatory perception. Public resource loadouts cannot replace or disable it. */
|
|
22
|
+
export class SystemPerceptionPlugin extends PerceptionRuleRunner {
|
|
23
|
+
readonly agentNotificationProducer = true;
|
|
24
|
+
override readonly consumes: { events: readonly string[] };
|
|
25
|
+
override readonly produces: { events: readonly string[] };
|
|
26
|
+
readonly notificationRelay: { sourceEvents?: boolean; producerPluginIds?: readonly string[]; previousEpochOnly?: boolean };
|
|
27
|
+
private taskState: TaskCheckpoint = {};
|
|
28
|
+
constructor(readonly domain: Domain, private readonly forwardedTypes: readonly string[], rules: readonly ClawclawDerivedEventRule[] = []) {
|
|
29
|
+
super(`${BUILTIN_PERCEPTION_PREFIX}${domain}`, rules);
|
|
30
|
+
this.notificationRelay = domain === 'behavior'
|
|
31
|
+
? { producerPluginIds: ['clawclaw.behavior'], previousEpochOnly: true } : { sourceEvents: true };
|
|
32
|
+
this.consumes = { events: [...new Set([...rules.flatMap(rule => rule.consumes ?? []), ...forwardedTypes,
|
|
33
|
+
...(domain === 'tasks' ? TASK_LIFECYCLE_FACT_TYPES : [])])] };
|
|
34
|
+
this.produces = { events: [...new Set([...rules.flatMap(rule => rule.eventTypes), ...forwardedTypes,
|
|
35
|
+
...(domain === 'tasks' ? ['reminder.task'] : [])])] };
|
|
36
|
+
}
|
|
37
|
+
override start(): void { super.start(); this.taskState = {}; }
|
|
38
|
+
override recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
|
|
39
|
+
super.recover(context);
|
|
40
|
+
if (this.domain === 'tasks') this.taskState = structuredClone(context.checkpoint() as TaskCheckpoint ?? {});
|
|
41
|
+
}
|
|
42
|
+
override update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): RuntimeEpochPluginResult {
|
|
43
|
+
const ruleResult = super.update(input, context);
|
|
44
|
+
const events: RuntimeEventProposal[] = [...(ruleResult.events ?? [])];
|
|
45
|
+
let cursor: number | undefined;
|
|
46
|
+
for (const event of input.pendingEvents) {
|
|
47
|
+
// A same-round Behavior output is deliberately held for the next round.
|
|
48
|
+
// Do not move the cursor past it, even if commit order overlaps epochs.
|
|
49
|
+
if (this.domain === 'behavior' && event.producerPluginId === 'clawclaw.behavior'
|
|
50
|
+
&& (event.epochSeq ?? input.epoch.epochSeq) >= input.epoch.epochSeq) break;
|
|
51
|
+
cursor = event.commitSeq;
|
|
52
|
+
if (event.notificationOf || !this.forwardedTypes.includes(event.type)) continue;
|
|
53
|
+
if (this.domain === 'behavior' ? event.producerPluginId !== 'clawclaw.behavior' : event.producerPluginId !== undefined) continue;
|
|
54
|
+
events.push({ type: event.type, forwardEventId: event.eventId, dedupeKey: event.eventId, payload: {},
|
|
55
|
+
notificationContent: prepareNotificationContent(event.type, event.payload, notificationStateAt(context, event.epochSeq), 'builtin', event) });
|
|
56
|
+
}
|
|
57
|
+
if (this.domain === 'tasks') {
|
|
58
|
+
const raw = clawclawComputationGameState(input.frame.state) ?? (input.epoch.state.cycle ? null : input.currentState.state);
|
|
59
|
+
const game = raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
|
|
60
|
+
const boundary = game && this.taskState.gameId !== game.game_id ? 'initial'
|
|
61
|
+
: this.taskState.connectionId !== undefined && this.taskState.connectionId !== input.epoch.connectionId ? 'recovery' : null;
|
|
62
|
+
this.taskState = { gameId: game?.game_id ?? this.taskState.gameId, connectionId: input.epoch.connectionId };
|
|
63
|
+
// Task facts have one notification owner. Do not recreate them from State differences.
|
|
64
|
+
const result = defaultReminder('tasks', { scope: input.epoch.scope, gameState: game, frame: null,
|
|
65
|
+
facts: input.pendingEvents.filter(event => !event.notificationOf && event.producerPluginId === undefined).map(event => ({
|
|
66
|
+
eventId: event.eventId, epochId: event.epochSeq, type: event.type, occurredAt: event.occurredAt,
|
|
67
|
+
producer: event.producer, replayed: event.replayed, payload: projectTaskChoiceEventPayload(game, event.type, event.payload),
|
|
68
|
+
})), taskChanges: [], boundary, config: {}, state: undefined,
|
|
69
|
+
nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs });
|
|
70
|
+
for (const event of result.events ?? []) events.push({ type: event.type, dedupeKey: event.key,
|
|
71
|
+
wakeAgent: event.wakeAgent, payload: { ...event.payload }, occurredAt: new Date(input.frame.receivedAtMs).toISOString() });
|
|
72
|
+
}
|
|
73
|
+
const notifications = events.map(event => event.notificationContent ? event : { ...event,
|
|
74
|
+
notificationContent: prepareNotificationContent(event.type, event.payload,
|
|
75
|
+
notificationStateAt(context, input.epoch.epochSeq), 'builtin', { producer: 'local_synth', producerPluginId: this.id }),
|
|
76
|
+
});
|
|
77
|
+
return { outcome: events.length ? 'processed' : 'noop', events: notifications,
|
|
78
|
+
...(this.domain === 'tasks' ? { checkpoint: structuredClone(this.taskState) } : {}),
|
|
79
|
+
...(cursor === undefined ? {} : { consumeEventsThroughCommitSeq: cursor }) };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Every currently public Source gameplay Event has exactly one builtin owner. */
|
|
84
|
+
export function createSystemPerceptions(behaviorEventTypes: readonly string[] = []): SystemPerceptionPlugin[] {
|
|
85
|
+
const groups: Record<Exclude<Domain, 'behavior'>, string[]> = {
|
|
86
|
+
players: ['kill', 'killed', 'murder_witnessed', 'body_dropped', 'corpse_spotted', 'warrior_shrimp_self_destruct', 'role_assigned'],
|
|
87
|
+
tasks: [], abilities: [],
|
|
88
|
+
emergency: ['emergency_started', 'emergency_resolved', 'emergency_interrupted'],
|
|
89
|
+
meeting: ['exile', 'no_exile', 'vote_speech_phase_ended', 'death_speech', 'meeting_briefing',
|
|
90
|
+
'speech', 'speech_skipped', 'speech_your_turn', 'speech_next_turn', 'vote_phase_start'],
|
|
91
|
+
flow: [],
|
|
92
|
+
};
|
|
93
|
+
const assigned = new Set(Object.values(groups).flat());
|
|
94
|
+
groups.flow = [...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, 'game_over_recovered', 'robot_speak_rule']
|
|
95
|
+
.filter(type => !assigned.has(type) && !CLAWCLAW_SYSTEM_CONTROL_EVENTS.has(type));
|
|
96
|
+
const behaviorTypes = [...new Set([...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter(type => type.startsWith('behavior.') || type === 'strategy_alert'),
|
|
97
|
+
...behaviorEventTypes])];
|
|
98
|
+
return [
|
|
99
|
+
new SystemPerceptionPlugin('players', groups.players, [new PlayerChangesDerivedEventRule()]),
|
|
100
|
+
new SystemPerceptionPlugin('tasks', groups.tasks),
|
|
101
|
+
new SystemPerceptionPlugin('abilities', groups.abilities, [new AbilityStateDerivedEventRule()]),
|
|
102
|
+
new SystemPerceptionPlugin('emergency', groups.emergency, [new EmergencyCountdownDerivedEventRule()]),
|
|
103
|
+
new SystemPerceptionPlugin('flow', groups.flow, [new RoomReadyDerivedEventRule()]),
|
|
104
|
+
new SystemPerceptionPlugin('meeting', groups.meeting),
|
|
105
|
+
new SystemPerceptionPlugin('behavior', behaviorTypes),
|
|
106
|
+
];
|
|
107
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isNotificationTurn } from '../../notification-turn.js';
|
|
1
2
|
import type {
|
|
2
3
|
ClawclawTrigger,
|
|
3
4
|
TriggerInput,
|
|
@@ -205,6 +206,7 @@ function triggerInputFor(
|
|
|
205
206
|
: semanticInput.events.filter((event) => consumes.has(event.type));
|
|
206
207
|
return Object.freeze({
|
|
207
208
|
frame,
|
|
209
|
+
...(semanticInput.cycle ? { cycle: semanticInput.cycle } : {}),
|
|
208
210
|
events: Object.freeze(events),
|
|
209
211
|
input: config.input,
|
|
210
212
|
});
|
|
@@ -218,7 +220,8 @@ function behaviorInputForTrigger(
|
|
|
218
220
|
return Object.freeze({
|
|
219
221
|
epochId: semanticInput.epochId,
|
|
220
222
|
scope: semanticInput.scope,
|
|
221
|
-
nowMs:
|
|
223
|
+
nowMs: semanticInput.nowMs,
|
|
224
|
+
...(semanticInput.cycle ? { cycle: semanticInput.cycle } : {}),
|
|
222
225
|
gameState: frame.gameState,
|
|
223
226
|
events: triggerInput.events,
|
|
224
227
|
input: triggerInput.input,
|
|
@@ -401,6 +404,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
|
|
|
401
404
|
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
402
405
|
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
403
406
|
): Promise<RuntimeEpochPluginResult> {
|
|
407
|
+
if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' };
|
|
404
408
|
this.currentScope = input.epoch.scope;
|
|
405
409
|
// Keep the live configure/enable entry point, but do no observation or Worker work while empty.
|
|
406
410
|
if (![...this.registrations.values()].some(config => this.isEnabled(config))) {
|
|
@@ -419,7 +423,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
|
|
|
419
423
|
// excluded so rule evaluation has no hidden computation-plugin dependency.
|
|
420
424
|
const triggerVisibleInput = {
|
|
421
425
|
...input,
|
|
422
|
-
pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push'),
|
|
426
|
+
pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push' && !event.notificationOf && event.producerPluginId === undefined),
|
|
423
427
|
} satisfies RuntimeEpochPluginInput<Record<string, any>>;
|
|
424
428
|
const emptyInput = createBehaviorInput(triggerVisibleInput, Object.freeze({}));
|
|
425
429
|
if (
|
|
@@ -556,7 +560,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
|
|
|
556
560
|
const eventCursor = input.pendingEvents.at(-1)?.commitSeq;
|
|
557
561
|
const triggerVisibleInput = {
|
|
558
562
|
...input,
|
|
559
|
-
pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push'),
|
|
563
|
+
pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push' && !event.notificationOf && event.producerPluginId === undefined),
|
|
560
564
|
} satisfies RuntimeEpochPluginInput<Record<string, any>>;
|
|
561
565
|
const emptyInput = createBehaviorInput(triggerVisibleInput, Object.freeze({}));
|
|
562
566
|
const baseProposal = (nowMs: number, evaluations: readonly ClawclawTriggerEvaluation[]) => ({
|
|
@@ -668,6 +672,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
|
|
|
668
672
|
computation: Readonly<RuntimeEpochPluginResult>,
|
|
669
673
|
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
670
674
|
): Promise<RuntimeEpochPluginResult> {
|
|
675
|
+
if (isNotificationTurn(input.epoch.state)) return computation;
|
|
671
676
|
const computed = proposal(computation.proposal);
|
|
672
677
|
if (computed.configGeneration !== this.configGeneration) {
|
|
673
678
|
return {
|
|
@@ -1,23 +1 @@
|
|
|
1
|
-
|
|
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
|
-
}
|
|
1
|
+
export * from '@myclaw163/game-agent-runtime/perception/binding-resolution.js';
|