@myclaw163/clawclaw-cli 0.7.16 → 0.8.1
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_HERMES.md +1 -1
- package/QUICKSTART_OPENCLAW.md +3 -11
- package/QUICKSTART_OTHER.md +8 -8
- package/README.md +18 -9
- package/bin/clawclaw-channel.mjs +13 -0
- package/docs/configuration.md +86 -33
- package/docs/custom-modules/README.md +148 -0
- package/docs/custom-modules/api-reference.md +767 -0
- package/docs/custom-modules/behavior.md +318 -0
- package/docs/custom-modules/perception.md +305 -0
- package/docs/custom-modules/trigger.md +292 -0
- package/docs/desktop-event-push.md +6 -4
- package/docs/runtime/README.md +28 -10
- package/docs/runtime/agent-notifications.md +48 -29
- package/docs/runtime/behavior-runtime.md +139 -0
- package/docs/runtime/components-and-boundaries.md +89 -173
- package/docs/runtime/events-and-state.md +55 -66
- package/docs/runtime/official-perception-modules.md +17 -9
- package/docs/runtime/owner-lifecycle-and-observability.md +62 -39
- package/docs/runtime/perception-replay.md +6 -6
- package/docs/runtime/short-commands-and-capabilities.md +35 -37
- package/package.json +7 -4
- package/scripts/check-skill-command-surface.mjs +54 -10
- package/scripts/compare-perception-replays.test.ts +10 -10
- package/scripts/compare-perception-replays.ts +14 -10
- package/scripts/replay-perception.ts +3 -3
- package/scripts/watch-perception-events.test.ts +1 -1
- package/skills/clawclaw/SKILL.md +97 -59
- package/skills/clawclaw/references/BEHAVIORS.md +154 -0
- package/skills/clawclaw/references/CHANNELS.md +115 -0
- package/skills/clawclaw/references/CHATTERBOX.md +3 -2
- package/skills/clawclaw/references/COMMANDS.md +108 -58
- package/skills/clawclaw/references/GAME-MECHANICS.md +4 -3
- package/skills/clawclaw/references/HUB.md +27 -23
- package/skills/clawclaw/references/STREAM.md +18 -14
- package/skills/clawclaw/references/TACTICS.md +2 -2
- package/src/behaviors/official-finite/do-task.ts +141 -0
- package/src/behaviors/official-finite/evade.ts +78 -0
- package/src/behaviors/official-finite/find-player.ts +50 -0
- package/src/behaviors/official-finite/follow-player.ts +70 -0
- package/src/behaviors/official-finite/go-to.ts +69 -0
- package/src/behaviors/official-finite/hide-temporarily.ts +77 -0
- package/src/behaviors/official-finite/hold-position.ts +48 -0
- package/src/behaviors/official-finite/hunt-player.ts +47 -0
- package/src/behaviors/official-finite/index.test.ts +202 -0
- package/src/behaviors/official-finite/index.ts +47 -0
- package/src/behaviors/official-finite/inspect-corpse.ts +64 -0
- package/src/behaviors/official-finite/patrol-area.ts +80 -0
- package/src/behaviors/official-finite/report-corpse.ts +73 -0
- package/src/behaviors/official-finite/seek-kill-opportunity.ts +152 -0
- package/src/behaviors/official-finite/shared.ts +27 -0
- package/src/behaviors/official-finite/trigger-alarm.ts +53 -0
- package/src/channel/claude-channel-ipc-server.ts +295 -0
- package/src/channel/claude-channel-ipc.ts +152 -0
- package/src/channel/claude-channel-server.test.ts +202 -0
- package/src/channel/claude-channel-server.ts +221 -0
- package/src/cli.ts +4 -2
- package/src/commands/account.test.ts +17 -17
- package/src/commands/behavior.test.ts +158 -0
- package/src/commands/behavior.ts +443 -0
- package/src/commands/communication.test.ts +12 -0
- package/src/commands/communication.ts +6 -3
- package/src/commands/data.test.ts +1 -1
- package/src/commands/data.ts +1 -1
- package/src/commands/events-canonical-state.test.ts +221 -2
- package/src/commands/events.ts +205 -12
- package/src/commands/game/index.test.ts +172 -3
- package/src/commands/game/index.ts +69 -32
- package/src/commands/hub.test.ts +25 -14
- package/src/commands/hub.ts +15 -19
- package/src/commands/load.test.ts +228 -6
- package/src/commands/load.ts +102 -18
- package/src/commands/memory.ts +1 -1
- package/src/commands/peek.ts +1 -1
- package/src/commands/perception.test.ts +30 -1
- package/src/commands/perception.ts +15 -17
- package/src/commands/trigger.test.ts +140 -0
- package/src/commands/trigger.ts +314 -0
- package/src/lib/account-guidance.test.ts +4 -0
- package/src/lib/account-guidance.ts +1 -1
- package/src/lib/behavior-export.test.ts +282 -0
- package/src/lib/behavior-export.ts +514 -0
- package/src/lib/game-client.test.ts +4 -17
- package/src/lib/game-client.ts +1 -0
- package/src/lib/gameplay-config.test.ts +258 -37
- package/src/lib/gameplay-config.ts +175 -35
- package/src/lib/hub-install.test.ts +19 -41
- package/src/lib/hub-install.ts +10 -38
- package/src/lib/hub-reminder.ts +7 -9
- package/src/lib/init-command.ts +1 -1
- package/src/lib/official-resource-sync.test.ts +199 -0
- package/src/lib/official-resource-sync.ts +221 -0
- package/src/lib/perception-config.test.ts +9 -4
- package/src/lib/perception-config.ts +10 -13
- package/src/lib/perception-export.test.ts +145 -0
- package/src/lib/perception-export.ts +178 -0
- package/src/lib/trigger-config.test.ts +102 -0
- package/src/lib/trigger-config.ts +217 -0
- package/src/lib/user-data.test.ts +23 -6
- package/src/lib/user-data.ts +15 -123
- package/src/pipeline/canonical-event-presentation.test.ts +5 -5
- package/src/pipeline/canonical-event-presentation.ts +13 -5
- package/src/pipeline/event-format.test.ts +106 -3
- package/src/pipeline/event-format.ts +172 -4
- package/src/pipeline/event-hints.test.ts +57 -4
- package/src/pipeline/event-hints.ts +34 -8
- package/src/runtime/canonical-monitor.test.ts +2 -0
- package/src/runtime/canonical-monitor.ts +6 -2
- package/src/runtime/clawclaw/agent-event-policy.test.ts +23 -2
- package/src/runtime/clawclaw/agent-event-policy.ts +12 -5
- package/src/runtime/clawclaw/behavior-decision.test.ts +29 -0
- package/src/runtime/clawclaw/behavior-decision.ts +82 -0
- package/src/runtime/clawclaw/behavior-input-fields.test.ts +175 -0
- package/src/runtime/clawclaw/behavior-input-fields.ts +270 -0
- package/src/runtime/clawclaw/behavior-input.test.ts +151 -0
- package/src/runtime/clawclaw/behavior-input.ts +70 -0
- package/src/runtime/clawclaw/behavior-observation-memory.test.ts +59 -0
- package/src/runtime/clawclaw/behavior-observation-memory.ts +142 -0
- package/src/runtime/clawclaw/behavior-read-api.test.ts +123 -0
- package/src/runtime/clawclaw/behavior-read-api.ts +158 -0
- package/src/runtime/clawclaw/{plugins/perception/visual-state-projector.ts → observation-frame-projector.ts} +44 -25
- package/src/runtime/clawclaw/owner.test.ts +187 -0
- package/src/runtime/clawclaw/owner.ts +431 -69
- package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +304 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +285 -41
- package/src/runtime/clawclaw/plugins/action/automated-action-normalization.ts +82 -0
- package/src/runtime/clawclaw/plugins/assembly.test.ts +135 -29
- package/src/runtime/clawclaw/plugins/assembly.ts +54 -28
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.test.ts +180 -0
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +468 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +40 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +30 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +152 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.test.ts +156 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +104 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-manifest.ts +173 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.test.ts +182 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +223 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +157 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +848 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +1347 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +212 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.test.ts +174 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +621 -0
- package/src/runtime/clawclaw/plugins/behavior/control-driver.test.ts +195 -0
- package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +180 -0
- package/src/runtime/clawclaw/plugins/behavior/index.ts +11 -0
- package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +766 -0
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.test.ts +283 -0
- package/src/runtime/clawclaw/plugins/{strategy/thread-strategy-executor.ts → behavior/thread-behavior-executor.ts} +109 -121
- package/src/runtime/clawclaw/plugins/behavior-input-source.test.ts +80 -0
- package/src/runtime/clawclaw/plugins/behavior-input-source.ts +247 -0
- package/src/runtime/clawclaw/plugins/{strategy → game-query}/context-capabilities.ts +1 -1
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +13 -10
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +26 -14
- package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
- package/src/runtime/clawclaw/plugins/index.ts +3 -1
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.test.ts +239 -0
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +100 -0
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +346 -0
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +230 -12
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +118 -90
- package/src/runtime/clawclaw/plugins/mailbox/consumer-ids.ts +5 -0
- package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +1 -1
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +4 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.test.ts +87 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +70 -12
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +94 -11
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1229 -345
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +479 -35
- package/src/runtime/clawclaw/plugins/perception/contracts.ts +4 -3
- package/src/runtime/clawclaw/plugins/perception/index.ts +1 -1
- package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +23 -13
- package/src/runtime/clawclaw/plugins/perception/module-runner.ts +11 -9
- package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +39 -38
- package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.test.ts +92 -0
- package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.ts +248 -0
- package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +39 -37
- package/src/runtime/clawclaw/plugins/perception/modules/index.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +22 -21
- package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +15 -9
- package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +3 -3
- package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +33 -18
- package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +6 -7
- package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +22 -16
- package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +6 -7
- package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +18 -12
- package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +14 -10
- package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +20 -14
- package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +5 -6
- package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +5 -6
- package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +49 -34
- package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +126 -20
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +24 -3
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +59 -46
- package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +27 -5
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +381 -49
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +267 -245
- package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +98 -0
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +89 -16
- package/src/runtime/clawclaw/plugins/perception/perception-test-fixtures.ts +34 -0
- package/src/runtime/clawclaw/plugins/perception/replay.test.ts +27 -15
- package/src/runtime/clawclaw/plugins/perception/replay.ts +10 -5
- package/src/runtime/clawclaw/plugins/perception/shared/math.ts +1 -107
- package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +7 -10
- package/src/runtime/clawclaw/plugins/plugin-api-version.ts +112 -0
- package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +388 -559
- package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +56 -5
- package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +135 -26
- package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +249 -16
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +99 -2
- package/src/runtime/clawclaw/plugins/source/task-change-tracker.test.ts +212 -0
- package/src/runtime/clawclaw/plugins/source/task-change-tracker.ts +259 -0
- package/src/runtime/clawclaw/plugins/trigger/contracts.ts +97 -0
- package/src/runtime/clawclaw/plugins/trigger/index.ts +4 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +118 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.test.ts +548 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +655 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-source.test.ts +169 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-source.ts +457 -0
- package/src/runtime/clawclaw/runtime.ts +8 -0
- package/src/runtime/clawclaw/spatial-api.ts +76 -0
- package/src/runtime/clawclaw-event-catalog.test.ts +46 -1
- package/src/runtime/clawclaw-event-catalog.ts +40 -3
- package/src/runtime/framework/capability-registry.test.ts +196 -55
- package/src/runtime/framework/capability-registry.ts +99 -17
- package/src/runtime/framework/contracts.ts +30 -4
- package/src/runtime/framework/control/control-scheduler.ts +13 -5
- package/src/runtime/framework/control/types.ts +11 -4
- package/src/runtime/framework/control-coordinator.test.ts +95 -80
- package/src/runtime/framework/events/event-delivery-service.ts +4 -2
- package/src/runtime/framework/events/event-ingress.test.ts +25 -0
- package/src/runtime/framework/events/event-ingress.ts +2 -1
- package/src/runtime/framework/events/event-repository.ts +24 -2
- package/src/runtime/framework/events/mailbox-event-repositories.test.ts +124 -8
- package/src/runtime/framework/events/memory-event-repository.ts +92 -28
- package/src/runtime/framework/events/sqlite-event-repository.test.ts +604 -2
- package/src/runtime/framework/events/sqlite-event-repository.ts +531 -21
- package/src/runtime/framework/events/types.ts +24 -8
- package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +38 -1
- package/src/runtime/framework/modules/runtime-module-loader.test.ts +233 -7
- package/src/runtime/framework/modules/runtime-module-loader.ts +69 -4
- package/src/runtime/framework/plugins/contracts.ts +12 -18
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +81 -71
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +38 -20
- package/src/runtime/framework/runtime.ts +20 -23
- package/src/runtime/host-monitor-rate-gate.test.ts +73 -0
- package/src/runtime/host-monitor-rate-gate.ts +123 -0
- package/src/runtime/mailbox-host-relay.test.ts +45 -0
- package/src/runtime/mailbox-host-relay.ts +25 -0
- package/src/runtime/observability/factory.ts +4 -4
- package/src/runtime/observability/observability.test.ts +25 -3
- package/src/runtime/observability/reporter.ts +1 -1
- package/src/runtime/observability/types.ts +2 -2
- package/src/runtime/owner-control.ts +10 -2
- package/src/runtime/runtime-logger.test.ts +1 -1
- package/src/runtime/runtime-logger.ts +4 -6
- package/src/runtime/runtime.test.ts +88 -22
- package/src/sdk/action.ts +2 -2
- package/src/sdk/behavior-plugin/index.test.ts +74 -0
- package/src/sdk/behavior-plugin/index.ts +335 -0
- package/src/sdk/behavior-toolkit/corpse-search.ts +87 -0
- package/src/sdk/behavior-toolkit/escape.ts +40 -0
- package/src/sdk/behavior-toolkit/index.ts +7 -0
- package/src/sdk/behavior-toolkit/kill-flow.ts +299 -0
- package/src/sdk/behavior-toolkit/model.ts +263 -0
- package/src/sdk/behavior-toolkit/move-gate.ts +52 -0
- package/src/sdk/behavior-toolkit/patrol.ts +53 -0
- package/src/sdk/behavior-toolkit/search.ts +102 -0
- package/src/sdk/index.test.ts +45 -0
- package/src/sdk/index.ts +67 -73
- package/src/sdk/module-input/index.test.ts +49 -0
- package/src/sdk/module-input/index.ts +229 -0
- package/src/sdk/perception-plugin/index.test.ts +2 -2
- package/src/sdk/perception-plugin/index.ts +51 -142
- package/src/sdk/perception-plugin/math.ts +107 -0
- package/src/sdk/trigger-plugin/index.test.ts +41 -0
- package/src/sdk/trigger-plugin/index.ts +128 -0
- package/src/strategies/avoid-lone.ts +21 -10
- package/src/strategies/avoid-players.ts +26 -16
- package/src/strategies/corpse-patrol.ts +25 -14
- package/src/strategies/crab-sabotage.ts +20 -9
- package/src/strategies/find-player.ts +33 -21
- package/src/strategies/game-utils.ts +1 -1
- package/src/strategies/goals/crab-sabotage-top.test.ts +145 -0
- package/src/strategies/goals/crab-sabotage-top.ts +32 -69
- package/src/strategies/hide.ts +25 -15
- package/src/strategies/kill-frenzy.ts +21 -10
- package/src/strategies/kill-lone.ts +27 -17
- package/src/strategies/kill-target.ts +33 -22
- package/src/strategies/lone-kill-task.ts +20 -9
- package/src/strategies/move-room.ts +29 -18
- package/src/strategies/official-long-behavior.test.ts +89 -0
- package/src/strategies/paradise-fish.ts +29 -18
- package/src/strategies/pathfind/astar-path.test.ts +127 -2
- package/src/strategies/pathfind/astar-path.ts +136 -26
- package/src/strategies/patrol.ts +21 -10
- package/src/strategies/player-targets.test.ts +10 -0
- package/src/strategies/player-targets.ts +13 -0
- package/src/strategies/report-patrol.ts +21 -10
- package/src/strategies/shrimp-memory.ts +30 -19
- package/src/strategies/social-task.ts +34 -23
- package/src/strategies/task-kill-report.ts +33 -22
- package/src/strategies/task-only.test.ts +99 -85
- package/src/strategies/task-only.ts +23 -12
- package/src/strategies/task-report.ts +25 -14
- package/src/strategies/types.ts +8 -8
- package/src/strategies/warrior-memory.ts +29 -19
- package/docs/runtime/strategy-runtime.md +0 -111
- package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +0 -502
- package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +0 -395
- package/skills/clawclaw/references/STRATEGIES.md +0 -76
- package/src/commands/strategy.test.ts +0 -209
- package/src/commands/strategy.ts +0 -242
- package/src/lib/strategy-export.test.ts +0 -406
- package/src/lib/strategy-export.ts +0 -381
- package/src/runtime/clawclaw/plugins/perception/official-modules.ts +0 -31
- package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +0 -177
- package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +0 -191
- package/src/runtime/clawclaw/plugins/strategy/index.ts +0 -8
- package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +0 -412
- package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +0 -80
- package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +0 -183
- package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +0 -29
- package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +0 -693
- package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +0 -57
- package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +0 -168
- package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +0 -2175
- package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +0 -1774
- package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +0 -153
- package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +0 -443
- package/src/sdk/strategy-plugin/index.test.ts +0 -958
- package/src/sdk/strategy-plugin/index.ts +0 -1350
|
@@ -1,1774 +0,0 @@
|
|
|
1
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
-
import type {
|
|
3
|
-
ClawclawResolvedResourceMetadata,
|
|
4
|
-
StrategyActionAck,
|
|
5
|
-
StrategyControlSpec,
|
|
6
|
-
StrategyControlResult,
|
|
7
|
-
StrategyControlUpdate,
|
|
8
|
-
StrategyFrame,
|
|
9
|
-
StrategyResult,
|
|
10
|
-
} from '../../../../sdk/strategy-plugin/index.js';
|
|
11
|
-
import { resolveClawclawResourceMetadata } from '../../../../sdk/strategy-plugin/index.js';
|
|
12
|
-
import type {
|
|
13
|
-
RuntimeEpochCatchUp,
|
|
14
|
-
RuntimeDiagnosticSeverity,
|
|
15
|
-
RuntimeEpochPlugin,
|
|
16
|
-
RuntimeEpochPluginContext,
|
|
17
|
-
RuntimeEpochPluginInput,
|
|
18
|
-
RuntimeEpochPluginResult,
|
|
19
|
-
} from '../../../framework/plugins/index.js';
|
|
20
|
-
import { isClawclawRuntimeState } from '../../runtime-state.js';
|
|
21
|
-
import { CLAWCLAW_ACTION_CAPABILITY } from '../action/index.js';
|
|
22
|
-
import {
|
|
23
|
-
clawclawMapFromGameState,
|
|
24
|
-
clawclawTasksFromGameState,
|
|
25
|
-
type ClawclawPathDistanceRequest,
|
|
26
|
-
} from '../game-query/index.js';
|
|
27
|
-
import {
|
|
28
|
-
CLAWCLAW_MAP_CAPABILITY,
|
|
29
|
-
CLAWCLAW_PATH_DISTANCE_CAPABILITY,
|
|
30
|
-
CLAWCLAW_TASKS_CAPABILITY,
|
|
31
|
-
} from './context-capabilities.js';
|
|
32
|
-
import { normalizeClawclawStrategyAction } from './strategy-action.js';
|
|
33
|
-
import {
|
|
34
|
-
LocalStrategyExecutor,
|
|
35
|
-
type LocalStrategyExecutorOptions,
|
|
36
|
-
} from './local-strategy-executor.js';
|
|
37
|
-
import { ThreadStrategyExecutor } from './thread-strategy-executor.js';
|
|
38
|
-
import type {
|
|
39
|
-
StrategyGameQuery,
|
|
40
|
-
StrategyGameQueryResult,
|
|
41
|
-
StrategySource,
|
|
42
|
-
} from './strategy-executor-types.js';
|
|
43
|
-
|
|
44
|
-
export const CLAWCLAW_STRATEGY_PLUGIN_ID = 'clawclaw.strategy';
|
|
45
|
-
export const CLAWCLAW_STRATEGY_STATE_TOPIC = 'strategy.status';
|
|
46
|
-
export const CLAWCLAW_STRATEGY_EVENT_TYPES = ['strategy_alert', 'robot_speak_rule'] as const;
|
|
47
|
-
|
|
48
|
-
const STRATEGY_REPORT_LOCALE = 'zh-CN';
|
|
49
|
-
const STRATEGY_REPORT_RETRY_MS = 1_000;
|
|
50
|
-
|
|
51
|
-
interface StrategyReportTarget extends ClawclawResolvedResourceMetadata {
|
|
52
|
-
readonly fingerprint: string;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
interface StrategyReportAttempt {
|
|
56
|
-
readonly lifecycleGeneration: number;
|
|
57
|
-
readonly fingerprint: string;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export interface ClawclawStrategySelection extends StrategySource {
|
|
61
|
-
readonly parameters?: Readonly<Record<string, unknown>>;
|
|
62
|
-
readonly controls?: readonly StrategyControlSpec[];
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export interface ClawclawStrategyExecutor {
|
|
66
|
-
readonly runtimeInstanceId: string;
|
|
67
|
-
readonly isAlive: boolean;
|
|
68
|
-
start(parameters: Readonly<Record<string, unknown>>, signal: AbortSignal): Promise<void>;
|
|
69
|
-
applyControl?(
|
|
70
|
-
update: StrategyControlUpdate,
|
|
71
|
-
signal: AbortSignal,
|
|
72
|
-
): Promise<StrategyControlResult>;
|
|
73
|
-
reset(signal: AbortSignal): Promise<void>;
|
|
74
|
-
update(frame: StrategyFrame<Record<string, unknown>>, signal: AbortSignal): Promise<StrategyResult>;
|
|
75
|
-
analyze?(frame: StrategyFrame<Record<string, unknown>>, signal: AbortSignal): Promise<unknown>;
|
|
76
|
-
reduce?(
|
|
77
|
-
frame: StrategyFrame<Record<string, unknown>>,
|
|
78
|
-
analysis: unknown,
|
|
79
|
-
signal: AbortSignal,
|
|
80
|
-
): Promise<StrategyResult>;
|
|
81
|
-
stop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void>;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export interface ClawclawStrategyExecutorHost {
|
|
85
|
-
action(action: Record<string, unknown>): Promise<StrategyActionAck>;
|
|
86
|
-
gameQuery(
|
|
87
|
-
query: StrategyGameQuery,
|
|
88
|
-
frame?: StrategyFrame<Record<string, unknown>>,
|
|
89
|
-
): Promise<StrategyGameQueryResult>;
|
|
90
|
-
diagnostic(
|
|
91
|
-
name: string,
|
|
92
|
-
attributes?: Readonly<Record<string, unknown>>,
|
|
93
|
-
severity?: RuntimeDiagnosticSeverity,
|
|
94
|
-
): void;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export type ClawclawStrategyExecutorFactory = (
|
|
98
|
-
selection: ClawclawStrategySelection,
|
|
99
|
-
host: ClawclawStrategyExecutorHost,
|
|
100
|
-
purpose?: 'serial' | 'parallel',
|
|
101
|
-
) => ClawclawStrategyExecutor;
|
|
102
|
-
|
|
103
|
-
export interface ClawclawStrategyPluginOptions {
|
|
104
|
-
after?: readonly string[];
|
|
105
|
-
consumes?: RuntimeEpochPlugin<Record<string, any>>['consumes'];
|
|
106
|
-
produces?: RuntimeEpochPlugin<Record<string, any>>['produces'];
|
|
107
|
-
timeoutMs?: number;
|
|
108
|
-
catchUp?: RuntimeEpochCatchUp;
|
|
109
|
-
executorFactory?: ClawclawStrategyExecutorFactory;
|
|
110
|
-
defaultSelectionForRole?: (role: string) => ClawclawStrategySelection;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
export interface ClawclawStrategyStatus {
|
|
114
|
-
readonly selected?: string;
|
|
115
|
-
readonly pending?: string;
|
|
116
|
-
readonly running: boolean;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
export interface ClawclawStrategyControlAck extends StrategyControlResult {
|
|
120
|
-
readonly strategy: string;
|
|
121
|
-
readonly revision: number;
|
|
122
|
-
readonly appliedEpochId: number;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
interface PendingStrategyControl {
|
|
126
|
-
readonly strategyId: string;
|
|
127
|
-
readonly revision: number;
|
|
128
|
-
readonly values: Readonly<Record<string, unknown>>;
|
|
129
|
-
readonly preAppliedValues?: Readonly<Record<string, unknown>>;
|
|
130
|
-
readonly resolve: (ack: ClawclawStrategyControlAck) => void;
|
|
131
|
-
readonly reject: (error: Error) => void;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
interface StrategyComputationBase {
|
|
135
|
-
readonly generation: number;
|
|
136
|
-
/** Invalidates hybrid analyses computed with an older parameter snapshot. */
|
|
137
|
-
readonly parameterGeneration: number;
|
|
138
|
-
readonly actionBarrierGeneration: number;
|
|
139
|
-
readonly actionSafetyGeneration?: number;
|
|
140
|
-
readonly selection?: ClawclawStrategySelection;
|
|
141
|
-
readonly cursor?: number;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
type StrategyComputationProposal = StrategyComputationBase & (
|
|
145
|
-
| {
|
|
146
|
-
readonly kind: 'noop';
|
|
147
|
-
readonly reason: string;
|
|
148
|
-
readonly resetBeforeNextWandering: boolean;
|
|
149
|
-
}
|
|
150
|
-
| {
|
|
151
|
-
readonly kind: 'legacy';
|
|
152
|
-
readonly frame: StrategyFrame<Record<string, unknown>>;
|
|
153
|
-
}
|
|
154
|
-
| {
|
|
155
|
-
readonly kind: 'parallel_compute';
|
|
156
|
-
readonly frame: StrategyFrame<Record<string, unknown>>;
|
|
157
|
-
readonly result: StrategyResult;
|
|
158
|
-
}
|
|
159
|
-
| {
|
|
160
|
-
readonly kind: 'parallel_analyze';
|
|
161
|
-
readonly frame: StrategyFrame<Record<string, unknown>>;
|
|
162
|
-
readonly analysis: unknown;
|
|
163
|
-
}
|
|
164
|
-
);
|
|
165
|
-
|
|
166
|
-
function strategyProposal(value: unknown): StrategyComputationProposal {
|
|
167
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
168
|
-
throw new Error('strategy_computation_proposal_invalid');
|
|
169
|
-
}
|
|
170
|
-
const proposal = value as StrategyComputationProposal;
|
|
171
|
-
if (!['noop', 'legacy', 'parallel_compute', 'parallel_analyze'].includes(proposal.kind)) {
|
|
172
|
-
throw new Error('strategy_computation_proposal_invalid');
|
|
173
|
-
}
|
|
174
|
-
return proposal;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
function awaitWithAbort<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
178
|
-
if (signal.aborted) {
|
|
179
|
-
return Promise.reject(signal.reason instanceof Error
|
|
180
|
-
? signal.reason
|
|
181
|
-
: new Error('strategy_epoch_aborted'));
|
|
182
|
-
}
|
|
183
|
-
return new Promise<T>((resolve, reject) => {
|
|
184
|
-
const onAbort = (): void => reject(signal.reason instanceof Error
|
|
185
|
-
? signal.reason
|
|
186
|
-
: new Error('strategy_epoch_aborted'));
|
|
187
|
-
signal.addEventListener('abort', onAbort, { once: true });
|
|
188
|
-
void operation.then(resolve, reject).finally(() => {
|
|
189
|
-
signal.removeEventListener('abort', onAbort);
|
|
190
|
-
});
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
function validStrategyControlValue(spec: StrategyControlSpec, value: unknown): boolean {
|
|
195
|
-
if (spec.type === 'boolean') return typeof value === 'boolean';
|
|
196
|
-
if (spec.type === 'number') return typeof value === 'number' && Number.isFinite(value);
|
|
197
|
-
if (spec.type === 'string') return typeof value === 'string';
|
|
198
|
-
if (spec.type === 'enum') return typeof value === 'string' && !!spec.values?.includes(value);
|
|
199
|
-
if (spec.type === 'player_seats') {
|
|
200
|
-
return Array.isArray(value) && value.every((entry) => (
|
|
201
|
-
Number.isInteger(entry) && entry >= 1 && entry <= 10
|
|
202
|
-
));
|
|
203
|
-
}
|
|
204
|
-
return Array.isArray(value) && value.every((entry) => typeof entry === 'string');
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
function validateControlValues(
|
|
208
|
-
selection: ClawclawStrategySelection,
|
|
209
|
-
values: Readonly<Record<string, unknown>>,
|
|
210
|
-
requireDeclared: boolean,
|
|
211
|
-
): void {
|
|
212
|
-
const controls = new Map((selection.controls ?? []).map((control) => [control.id, control]));
|
|
213
|
-
if (requireDeclared && controls.size === 0) throw new Error('strategy_controls_not_supported');
|
|
214
|
-
for (const [key, value] of Object.entries(values)) {
|
|
215
|
-
const spec = controls.get(key);
|
|
216
|
-
if (!spec) {
|
|
217
|
-
if (requireDeclared) throw new Error(`unsupported_strategy_control:${key}`);
|
|
218
|
-
continue;
|
|
219
|
-
}
|
|
220
|
-
if (!validStrategyControlValue(spec, value)) {
|
|
221
|
-
throw new Error(`invalid_strategy_control:${key}`);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function diagnosticErrorCode(error: unknown, fallback: string): string {
|
|
227
|
-
const code = error && typeof error === 'object' && typeof (error as any).code === 'string'
|
|
228
|
-
? (error as any).code.trim()
|
|
229
|
-
: '';
|
|
230
|
-
if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code)) return code;
|
|
231
|
-
const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
|
|
232
|
-
return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1] ?? fallback;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
function isSuccessfulStrategyReportResponse(value: unknown): boolean {
|
|
236
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
237
|
-
const result = value as Record<string, unknown>;
|
|
238
|
-
if (
|
|
239
|
-
result.status !== 'success'
|
|
240
|
-
|| result.source !== 'backend'
|
|
241
|
-
|| result.actionOutcome !== 'confirmed'
|
|
242
|
-
) return false;
|
|
243
|
-
const response = result.value;
|
|
244
|
-
if (!response || typeof response !== 'object' || Array.isArray(response)) return false;
|
|
245
|
-
const root = response as Record<string, unknown>;
|
|
246
|
-
const data = root.data;
|
|
247
|
-
return root.success === true
|
|
248
|
-
&& !!data
|
|
249
|
-
&& typeof data === 'object'
|
|
250
|
-
&& !Array.isArray(data)
|
|
251
|
-
&& (data as Record<string, unknown>).ok === true;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
function strategyActionControllerId(strategyId: string, generation: number): string {
|
|
255
|
-
return `${strategyId}@activation-${generation}`;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
function isStaleStrategyActionResult(value: unknown): boolean {
|
|
259
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
260
|
-
const result = value as Record<string, unknown>;
|
|
261
|
-
if (
|
|
262
|
-
result.status !== 'failure'
|
|
263
|
-
|| result.source !== 'local'
|
|
264
|
-
|| result.actionOutcome !== 'not_submitted'
|
|
265
|
-
) return false;
|
|
266
|
-
const outer = result.error;
|
|
267
|
-
if (!outer || typeof outer !== 'object' || Array.isArray(outer)) return false;
|
|
268
|
-
const inner = (outer as Record<string, unknown>).error;
|
|
269
|
-
return !!inner
|
|
270
|
-
&& typeof inner === 'object'
|
|
271
|
-
&& !Array.isArray(inner)
|
|
272
|
-
&& (inner as Record<string, unknown>).code === 'STALE_STRATEGY_ACTION';
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
function strategyBackendTick(
|
|
276
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
277
|
-
): number | undefined {
|
|
278
|
-
if (input.epoch.domainTick === undefined) return undefined;
|
|
279
|
-
const tick = Number(input.epoch.domainTick);
|
|
280
|
-
return Number.isFinite(tick) ? tick : undefined;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
function strategyFrame(
|
|
284
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
285
|
-
parameters: Readonly<Record<string, unknown>>,
|
|
286
|
-
): StrategyFrame<Record<string, unknown>> {
|
|
287
|
-
const runtimeState = input.epoch.state;
|
|
288
|
-
const gameState = isClawclawRuntimeState(runtimeState)
|
|
289
|
-
&& runtimeState.game_snapshot.status === 'fresh'
|
|
290
|
-
? runtimeState.game_snapshot.state
|
|
291
|
-
: input.currentState.state;
|
|
292
|
-
const backendTick = strategyBackendTick(input);
|
|
293
|
-
const tick = backendTick ?? (gameState && Number.isFinite(gameState.tick)
|
|
294
|
-
? Number(gameState.tick)
|
|
295
|
-
: undefined);
|
|
296
|
-
const state = gameState ? structuredClone(gameState) : null;
|
|
297
|
-
if (state && backendTick !== undefined) state.tick = backendTick;
|
|
298
|
-
return {
|
|
299
|
-
epochId: input.epoch.epochSeq,
|
|
300
|
-
scope: {
|
|
301
|
-
sessionId: input.epoch.scope.sessionId,
|
|
302
|
-
segmentId: input.epoch.scope.segmentId,
|
|
303
|
-
},
|
|
304
|
-
stage: isClawclawRuntimeState(runtimeState) ? runtimeState.stage : String(gameState?.phase ?? 'unknown'),
|
|
305
|
-
...(tick === undefined ? {} : { tick }),
|
|
306
|
-
state,
|
|
307
|
-
upstreamStates: structuredClone(input.upstreamStates),
|
|
308
|
-
events: input.pendingEvents.map((event) => ({
|
|
309
|
-
eventId: event.eventId,
|
|
310
|
-
...(event.epochSeq === undefined ? {} : { epochId: event.epochSeq }),
|
|
311
|
-
type: event.type,
|
|
312
|
-
occurredAt: event.occurredAt,
|
|
313
|
-
payload: structuredClone(event.payload),
|
|
314
|
-
})),
|
|
315
|
-
parameters: structuredClone(parameters),
|
|
316
|
-
};
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
function gameEpochNeedsFreshState(
|
|
320
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
321
|
-
): boolean {
|
|
322
|
-
const state = input.epoch.state;
|
|
323
|
-
return isClawclawRuntimeState(state)
|
|
324
|
-
&& state.stage === 'game'
|
|
325
|
-
&& state.game_snapshot.status !== 'fresh';
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
function freshWanderingEpoch(
|
|
329
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
330
|
-
): boolean {
|
|
331
|
-
const state = input.epoch.state;
|
|
332
|
-
return isClawclawRuntimeState(state)
|
|
333
|
-
&& state.stage === 'game'
|
|
334
|
-
&& state.game_snapshot.status === 'fresh'
|
|
335
|
-
&& state.game_snapshot.state.phase === 'wandering';
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
function authoritativeActionDisposition(
|
|
339
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
340
|
-
): boolean | undefined {
|
|
341
|
-
const state = input.epoch.state;
|
|
342
|
-
if (!isClawclawRuntimeState(state)) return undefined;
|
|
343
|
-
if (state.connection !== 'connected') return false;
|
|
344
|
-
if (state.stage !== 'game') return false;
|
|
345
|
-
if (state.game_snapshot.status !== 'fresh') return undefined;
|
|
346
|
-
return state.game_snapshot.state.phase === 'wandering'
|
|
347
|
-
&& state.game_snapshot.state.you?.is_alive !== false;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
function inputActionSafetyGeneration(
|
|
351
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
352
|
-
): number | undefined {
|
|
353
|
-
const state = input.epoch.state;
|
|
354
|
-
if (!isClawclawRuntimeState(state)) return undefined;
|
|
355
|
-
const value = state.action_safety_generation;
|
|
356
|
-
return Number.isInteger(value) && (value as number) >= 0 ? value as number : undefined;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
function inputRequiresStrategyReset(
|
|
360
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
361
|
-
): boolean {
|
|
362
|
-
const state = input.epoch.state;
|
|
363
|
-
return isClawclawRuntimeState(state)
|
|
364
|
-
&& (state.connection !== 'connected' || state.stage !== 'game');
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
function hostedStrategyState(
|
|
368
|
-
topic: string,
|
|
369
|
-
value: unknown,
|
|
370
|
-
selection: ClawclawStrategySelection,
|
|
371
|
-
): unknown {
|
|
372
|
-
if (
|
|
373
|
-
topic !== CLAWCLAW_STRATEGY_STATE_TOPIC
|
|
374
|
-
|| !value
|
|
375
|
-
|| typeof value !== 'object'
|
|
376
|
-
|| Array.isArray(value)
|
|
377
|
-
) return value;
|
|
378
|
-
return {
|
|
379
|
-
...value,
|
|
380
|
-
strategy: selection.id,
|
|
381
|
-
parameters: structuredClone(selection.parameters ?? {}),
|
|
382
|
-
};
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
function defaultExecutorFactory(
|
|
386
|
-
selection: ClawclawStrategySelection,
|
|
387
|
-
host: ClawclawStrategyExecutorHost,
|
|
388
|
-
purpose: 'serial' | 'parallel' = 'serial',
|
|
389
|
-
): ClawclawStrategyExecutor {
|
|
390
|
-
const options: LocalStrategyExecutorOptions = {
|
|
391
|
-
source: selection,
|
|
392
|
-
onAction: host.action,
|
|
393
|
-
diagnostic: host.diagnostic,
|
|
394
|
-
};
|
|
395
|
-
return purpose === 'parallel'
|
|
396
|
-
? new ThreadStrategyExecutor({ source: selection, diagnostic: host.diagnostic })
|
|
397
|
-
: new LocalStrategyExecutor(options);
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
/** Trusted adapter between one Runtime epoch and one restricted strategy instance. */
|
|
401
|
-
export class ClawclawStrategyPlugin
|
|
402
|
-
implements RuntimeEpochPlugin<Record<string, any>> {
|
|
403
|
-
readonly kind = 'epoch' as const;
|
|
404
|
-
readonly id = CLAWCLAW_STRATEGY_PLUGIN_ID;
|
|
405
|
-
readonly version = '1';
|
|
406
|
-
readonly after: readonly string[];
|
|
407
|
-
readonly consumes: NonNullable<RuntimeEpochPlugin<Record<string, any>>['consumes']>;
|
|
408
|
-
readonly produces: NonNullable<RuntimeEpochPlugin<Record<string, any>>['produces']>;
|
|
409
|
-
readonly capabilities = {
|
|
410
|
-
uses: [
|
|
411
|
-
CLAWCLAW_ACTION_CAPABILITY,
|
|
412
|
-
CLAWCLAW_TASKS_CAPABILITY,
|
|
413
|
-
CLAWCLAW_MAP_CAPABILITY,
|
|
414
|
-
CLAWCLAW_PATH_DISTANCE_CAPABILITY,
|
|
415
|
-
],
|
|
416
|
-
} as const;
|
|
417
|
-
readonly timeoutMs: number;
|
|
418
|
-
readonly catchUp: RuntimeEpochCatchUp;
|
|
419
|
-
readonly failurePolicy = 'failed_completion' as const;
|
|
420
|
-
|
|
421
|
-
private readonly executorFactory: ClawclawStrategyExecutorFactory;
|
|
422
|
-
private readonly defaultSelectionForRole?: (role: string) => ClawclawStrategySelection;
|
|
423
|
-
private selected?: ClawclawStrategySelection;
|
|
424
|
-
private pendingSelection?: ClawclawStrategySelection;
|
|
425
|
-
private readonly pendingControls: PendingStrategyControl[] = [];
|
|
426
|
-
private controlRevision = 0;
|
|
427
|
-
private executor?: ClawclawStrategyExecutor;
|
|
428
|
-
private parallelExecutor?: ClawclawStrategyExecutor;
|
|
429
|
-
private parallelExecutorReady?: Promise<void>;
|
|
430
|
-
private parallelExecutorLifecycle?: AbortController;
|
|
431
|
-
private parallelExecutorGeneration = 0;
|
|
432
|
-
private readonly parallelContexts = new Map<
|
|
433
|
-
number,
|
|
434
|
-
RuntimeEpochPluginContext<Record<string, any>>
|
|
435
|
-
>();
|
|
436
|
-
private activeContext?: RuntimeEpochPluginContext<Record<string, any>>;
|
|
437
|
-
private activeActionOriginEpochSeq?: number;
|
|
438
|
-
private activeActionSafetyGeneration?: number;
|
|
439
|
-
private activeActionAllowed = false;
|
|
440
|
-
private selectedActionControllerId?: string;
|
|
441
|
-
private latestFrameAllowsActions = false;
|
|
442
|
-
private actionBarrierGeneration = 0;
|
|
443
|
-
private wanderingResetRequired = false;
|
|
444
|
-
private lastInvokedEpochSeq: number | null = null;
|
|
445
|
-
private lastDispatchedBackendTick: number | null = null;
|
|
446
|
-
private selectionGeneration = 0;
|
|
447
|
-
private pendingSelectionGeneration = 0;
|
|
448
|
-
private selectedGeneration = 0;
|
|
449
|
-
private parameterGeneration = 0;
|
|
450
|
-
private readonly committedActionDedupeKeys = new Map<string, number>();
|
|
451
|
-
private strategyReportTarget?: StrategyReportTarget;
|
|
452
|
-
private strategyReportAcknowledgedFingerprint?: string;
|
|
453
|
-
private strategyReportInFlight?: StrategyReportAttempt;
|
|
454
|
-
private strategyReportTimer?: ReturnType<typeof setTimeout>;
|
|
455
|
-
private strategyReportContext?: RuntimeEpochPluginContext<Record<string, any>>;
|
|
456
|
-
private strategyReportEligible = false;
|
|
457
|
-
private strategyReportLifecycleGeneration = 0;
|
|
458
|
-
|
|
459
|
-
constructor(options: ClawclawStrategyPluginOptions = {}) {
|
|
460
|
-
this.after = [...(options.after ?? [])];
|
|
461
|
-
this.consumes = options.consumes ?? { states: ['*'], events: ['*'] };
|
|
462
|
-
this.produces = options.produces ?? {
|
|
463
|
-
states: [CLAWCLAW_STRATEGY_STATE_TOPIC],
|
|
464
|
-
events: CLAWCLAW_STRATEGY_EVENT_TYPES,
|
|
465
|
-
};
|
|
466
|
-
this.timeoutMs = options.timeoutMs ?? 5_000;
|
|
467
|
-
this.catchUp = options.catchUp ?? 'every_epoch';
|
|
468
|
-
this.executorFactory = options.executorFactory ?? defaultExecutorFactory;
|
|
469
|
-
this.defaultSelectionForRole = options.defaultSelectionForRole;
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
get maxInFlight(): number {
|
|
473
|
-
const selection = this.pendingSelection ?? this.selected;
|
|
474
|
-
return selection?.execution === undefined ? 1 : 10;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
/** A control request changes configuration from the next actual epoch. */
|
|
478
|
-
select(selection: ClawclawStrategySelection): void {
|
|
479
|
-
if (!selection.id.trim()) throw new Error('strategy_id_invalid');
|
|
480
|
-
this.selectionGeneration += 1;
|
|
481
|
-
this.parameterGeneration += 1;
|
|
482
|
-
this.pendingSelectionGeneration = this.selectionGeneration;
|
|
483
|
-
this.pendingSelection = {
|
|
484
|
-
...selection,
|
|
485
|
-
parameters: structuredClone(selection.parameters ?? {}),
|
|
486
|
-
};
|
|
487
|
-
this.rejectAllPendingControls('strategy_switched_before_control_applied');
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
/** Queues controls for the selected strategy; they apply before its next update(). */
|
|
491
|
-
control(values: Readonly<Record<string, unknown>>): Promise<ClawclawStrategyControlAck> {
|
|
492
|
-
if (!values || typeof values !== 'object' || Array.isArray(values)) {
|
|
493
|
-
throw new Error('invalid_strategy_control');
|
|
494
|
-
}
|
|
495
|
-
const target = this.pendingSelection ?? this.selected;
|
|
496
|
-
if (!target) throw new Error('no_active_strategy');
|
|
497
|
-
const revision = ++this.controlRevision;
|
|
498
|
-
const cloned = structuredClone(values);
|
|
499
|
-
validateControlValues(target, cloned, target.execution === 'parallel_compute');
|
|
500
|
-
let preAppliedValues: Readonly<Record<string, unknown>> | undefined;
|
|
501
|
-
if (target.execution === 'parallel_compute') {
|
|
502
|
-
preAppliedValues = structuredClone({
|
|
503
|
-
...(target.parameters ?? {}),
|
|
504
|
-
...cloned,
|
|
505
|
-
});
|
|
506
|
-
this.selectionGeneration += 1;
|
|
507
|
-
this.pendingSelectionGeneration = this.selectionGeneration;
|
|
508
|
-
this.pendingSelection = {
|
|
509
|
-
...target,
|
|
510
|
-
parameters: preAppliedValues,
|
|
511
|
-
};
|
|
512
|
-
}
|
|
513
|
-
return new Promise<ClawclawStrategyControlAck>((resolve, reject) => {
|
|
514
|
-
this.pendingControls.push({
|
|
515
|
-
strategyId: target.id,
|
|
516
|
-
revision,
|
|
517
|
-
values: cloned,
|
|
518
|
-
...(preAppliedValues === undefined ? {} : { preAppliedValues }),
|
|
519
|
-
resolve,
|
|
520
|
-
reject,
|
|
521
|
-
});
|
|
522
|
-
});
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
status(): ClawclawStrategyStatus {
|
|
526
|
-
return {
|
|
527
|
-
...(this.selected ? { selected: this.selected.id } : {}),
|
|
528
|
-
...(this.pendingSelection ? { pending: this.pendingSelection.id } : {}),
|
|
529
|
-
running: (this.executor?.isAlive ?? false) || (this.parallelExecutor?.isAlive ?? false),
|
|
530
|
-
};
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
activeResourceDescriptor(locale: string): ClawclawResolvedResourceMetadata | null {
|
|
534
|
-
const selection = this.selected;
|
|
535
|
-
if (!selection?.name?.trim() || !selection.description?.trim()) return null;
|
|
536
|
-
return resolveClawclawResourceMetadata({
|
|
537
|
-
id: selection.id,
|
|
538
|
-
name: selection.name,
|
|
539
|
-
description: selection.description,
|
|
540
|
-
...(selection.localizations ? { localizations: selection.localizations } : {}),
|
|
541
|
-
}, locale);
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
private refreshStrategyReportRuntime(
|
|
545
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
546
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
547
|
-
): void {
|
|
548
|
-
const wasEligible = this.strategyReportEligible;
|
|
549
|
-
const state = input.epoch.state;
|
|
550
|
-
this.strategyReportContext = context;
|
|
551
|
-
this.strategyReportEligible = isClawclawRuntimeState(state)
|
|
552
|
-
&& state.connection === 'connected'
|
|
553
|
-
&& freshWanderingEpoch(input);
|
|
554
|
-
|
|
555
|
-
const descriptor = this.activeResourceDescriptor(STRATEGY_REPORT_LOCALE);
|
|
556
|
-
const nextTarget = descriptor
|
|
557
|
-
? {
|
|
558
|
-
...descriptor,
|
|
559
|
-
fingerprint: JSON.stringify([descriptor.id, descriptor.name, descriptor.description]),
|
|
560
|
-
}
|
|
561
|
-
: undefined;
|
|
562
|
-
const targetChanged = nextTarget?.fingerprint !== this.strategyReportTarget?.fingerprint;
|
|
563
|
-
if (targetChanged) {
|
|
564
|
-
this.strategyReportTarget = nextTarget;
|
|
565
|
-
this.clearStrategyReportTimer();
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
const target = this.strategyReportTarget;
|
|
569
|
-
if (!target || this.strategyReportAcknowledgedFingerprint === target.fingerprint) {
|
|
570
|
-
this.clearStrategyReportTimer();
|
|
571
|
-
return;
|
|
572
|
-
}
|
|
573
|
-
if (targetChanged || (!wasEligible && this.strategyReportEligible)) {
|
|
574
|
-
this.scheduleStrategyReport(0, true);
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
private clearStrategyReportTimer(): void {
|
|
579
|
-
if (!this.strategyReportTimer) return;
|
|
580
|
-
clearTimeout(this.strategyReportTimer);
|
|
581
|
-
this.strategyReportTimer = undefined;
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
private scheduleStrategyReport(delayMs: number, replace = false): void {
|
|
585
|
-
const target = this.strategyReportTarget;
|
|
586
|
-
if (
|
|
587
|
-
!target
|
|
588
|
-
|| this.strategyReportAcknowledgedFingerprint === target.fingerprint
|
|
589
|
-
|| this.strategyReportInFlight
|
|
590
|
-
) return;
|
|
591
|
-
if (this.strategyReportTimer) {
|
|
592
|
-
if (!replace) return;
|
|
593
|
-
this.clearStrategyReportTimer();
|
|
594
|
-
}
|
|
595
|
-
const lifecycleGeneration = this.strategyReportLifecycleGeneration;
|
|
596
|
-
this.strategyReportTimer = setTimeout(() => {
|
|
597
|
-
this.strategyReportTimer = undefined;
|
|
598
|
-
if (lifecycleGeneration !== this.strategyReportLifecycleGeneration) return;
|
|
599
|
-
this.startStrategyReportAttempt();
|
|
600
|
-
}, delayMs);
|
|
601
|
-
this.strategyReportTimer.unref?.();
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
/** Starts one host-owned report without extending the ordered Strategy commit. */
|
|
605
|
-
private startStrategyReportAttempt(): void {
|
|
606
|
-
const target = this.strategyReportTarget;
|
|
607
|
-
const context = this.strategyReportContext;
|
|
608
|
-
if (
|
|
609
|
-
!target
|
|
610
|
-
|| this.strategyReportAcknowledgedFingerprint === target.fingerprint
|
|
611
|
-
|| this.strategyReportInFlight
|
|
612
|
-
) return;
|
|
613
|
-
if (!this.strategyReportEligible || !context || context.signal.aborted) {
|
|
614
|
-
this.scheduleStrategyReport(STRATEGY_REPORT_RETRY_MS);
|
|
615
|
-
return;
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
const attempt: StrategyReportAttempt = {
|
|
619
|
-
lifecycleGeneration: this.strategyReportLifecycleGeneration,
|
|
620
|
-
fingerprint: target.fingerprint,
|
|
621
|
-
};
|
|
622
|
-
this.strategyReportInFlight = attempt;
|
|
623
|
-
context.diagnostic('strategy.report.started', {
|
|
624
|
-
strategy_id: target.id,
|
|
625
|
-
}, 'debug');
|
|
626
|
-
|
|
627
|
-
let pending: Promise<unknown>;
|
|
628
|
-
try {
|
|
629
|
-
pending = context.capabilities.performAction(
|
|
630
|
-
CLAWCLAW_ACTION_CAPABILITY,
|
|
631
|
-
{
|
|
632
|
-
route: 'game',
|
|
633
|
-
action: {
|
|
634
|
-
action: 'strategy',
|
|
635
|
-
name: target.name,
|
|
636
|
-
description: target.description,
|
|
637
|
-
},
|
|
638
|
-
},
|
|
639
|
-
);
|
|
640
|
-
} catch (error) {
|
|
641
|
-
this.finishStrategyReportAttempt(attempt, false, error);
|
|
642
|
-
return;
|
|
643
|
-
}
|
|
644
|
-
void pending.then(
|
|
645
|
-
(result) => this.finishStrategyReportAttempt(
|
|
646
|
-
attempt,
|
|
647
|
-
isSuccessfulStrategyReportResponse(result),
|
|
648
|
-
result,
|
|
649
|
-
),
|
|
650
|
-
(error) => this.finishStrategyReportAttempt(attempt, false, error),
|
|
651
|
-
);
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
private finishStrategyReportAttempt(
|
|
655
|
-
attempt: StrategyReportAttempt,
|
|
656
|
-
successful: boolean,
|
|
657
|
-
result: unknown,
|
|
658
|
-
): void {
|
|
659
|
-
if (
|
|
660
|
-
attempt.lifecycleGeneration !== this.strategyReportLifecycleGeneration
|
|
661
|
-
|| this.strategyReportInFlight?.fingerprint !== attempt.fingerprint
|
|
662
|
-
) return;
|
|
663
|
-
this.strategyReportInFlight = undefined;
|
|
664
|
-
const target = this.strategyReportTarget;
|
|
665
|
-
if (successful && target?.fingerprint === attempt.fingerprint) {
|
|
666
|
-
this.strategyReportAcknowledgedFingerprint = attempt.fingerprint;
|
|
667
|
-
this.clearStrategyReportTimer();
|
|
668
|
-
this.strategyReportContext?.diagnostic('strategy.report.completed', {
|
|
669
|
-
strategy_id: target.id,
|
|
670
|
-
}, 'info');
|
|
671
|
-
return;
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
if (target?.fingerprint === attempt.fingerprint) {
|
|
675
|
-
this.strategyReportContext?.diagnostic('strategy.report.retry_scheduled', {
|
|
676
|
-
strategy_id: target.id,
|
|
677
|
-
retry_ms: STRATEGY_REPORT_RETRY_MS,
|
|
678
|
-
error_code: diagnosticErrorCode(result, 'STRATEGY_REPORT_RESPONSE_INVALID'),
|
|
679
|
-
}, 'warn');
|
|
680
|
-
this.scheduleStrategyReport(STRATEGY_REPORT_RETRY_MS);
|
|
681
|
-
return;
|
|
682
|
-
}
|
|
683
|
-
if (target && this.strategyReportAcknowledgedFingerprint !== target.fingerprint) {
|
|
684
|
-
this.scheduleStrategyReport(0);
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
private resetStrategyReporting(): void {
|
|
689
|
-
this.strategyReportLifecycleGeneration += 1;
|
|
690
|
-
this.clearStrategyReportTimer();
|
|
691
|
-
this.strategyReportTarget = undefined;
|
|
692
|
-
this.strategyReportAcknowledgedFingerprint = undefined;
|
|
693
|
-
this.strategyReportInFlight = undefined;
|
|
694
|
-
this.strategyReportContext = undefined;
|
|
695
|
-
this.strategyReportEligible = false;
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
async update(
|
|
699
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
700
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
701
|
-
): Promise<RuntimeEpochPluginResult> {
|
|
702
|
-
this.selectDefaultForAssignedRole(input);
|
|
703
|
-
const actionDisposition = authoritativeActionDisposition(input);
|
|
704
|
-
if (actionDisposition !== undefined) {
|
|
705
|
-
if (this.latestFrameAllowsActions && !actionDisposition) {
|
|
706
|
-
this.actionBarrierGeneration += 1;
|
|
707
|
-
}
|
|
708
|
-
this.latestFrameAllowsActions = actionDisposition;
|
|
709
|
-
}
|
|
710
|
-
const actionBarrierGeneration = this.actionBarrierGeneration;
|
|
711
|
-
const actionSafetyGeneration = inputActionSafetyGeneration(input);
|
|
712
|
-
const cursor = input.pendingEvents.at(-1)?.commitSeq;
|
|
713
|
-
const selection = this.pendingSelection ?? this.selected;
|
|
714
|
-
const generation = this.pendingSelection
|
|
715
|
-
? this.pendingSelectionGeneration
|
|
716
|
-
: this.selectedGeneration;
|
|
717
|
-
const parameterGeneration = this.parameterGeneration;
|
|
718
|
-
if (gameEpochNeedsFreshState(input)) {
|
|
719
|
-
return {
|
|
720
|
-
outcome: 'processed',
|
|
721
|
-
proposal: {
|
|
722
|
-
kind: 'noop',
|
|
723
|
-
reason: selection ? 'strategy_waiting_for_current_state' : 'strategy_not_selected',
|
|
724
|
-
resetBeforeNextWandering: inputRequiresStrategyReset(input),
|
|
725
|
-
generation,
|
|
726
|
-
parameterGeneration,
|
|
727
|
-
actionBarrierGeneration,
|
|
728
|
-
...(selection ? { selection: structuredClone(selection) } : {}),
|
|
729
|
-
...(!selection && cursor !== undefined ? { cursor } : {}),
|
|
730
|
-
} satisfies StrategyComputationProposal,
|
|
731
|
-
};
|
|
732
|
-
}
|
|
733
|
-
if (!freshWanderingEpoch(input)) {
|
|
734
|
-
return {
|
|
735
|
-
outcome: 'processed',
|
|
736
|
-
proposal: {
|
|
737
|
-
kind: 'noop',
|
|
738
|
-
reason: 'strategy_inactive_stage',
|
|
739
|
-
resetBeforeNextWandering: true,
|
|
740
|
-
generation,
|
|
741
|
-
parameterGeneration,
|
|
742
|
-
actionBarrierGeneration,
|
|
743
|
-
...(selection ? { selection: structuredClone(selection) } : {}),
|
|
744
|
-
...(cursor === undefined ? {} : { cursor }),
|
|
745
|
-
} satisfies StrategyComputationProposal,
|
|
746
|
-
};
|
|
747
|
-
}
|
|
748
|
-
if (!selection) {
|
|
749
|
-
return {
|
|
750
|
-
outcome: 'processed',
|
|
751
|
-
proposal: {
|
|
752
|
-
kind: 'noop',
|
|
753
|
-
reason: 'strategy_not_selected',
|
|
754
|
-
resetBeforeNextWandering: false,
|
|
755
|
-
generation,
|
|
756
|
-
parameterGeneration,
|
|
757
|
-
actionBarrierGeneration,
|
|
758
|
-
...(cursor === undefined ? {} : { cursor }),
|
|
759
|
-
} satisfies StrategyComputationProposal,
|
|
760
|
-
};
|
|
761
|
-
}
|
|
762
|
-
const backendTick = strategyBackendTick(input);
|
|
763
|
-
if (
|
|
764
|
-
backendTick !== undefined
|
|
765
|
-
&& this.lastDispatchedBackendTick !== null
|
|
766
|
-
&& backendTick <= this.lastDispatchedBackendTick
|
|
767
|
-
) {
|
|
768
|
-
return {
|
|
769
|
-
outcome: 'processed',
|
|
770
|
-
proposal: {
|
|
771
|
-
kind: 'noop',
|
|
772
|
-
reason: 'strategy_update_interval',
|
|
773
|
-
resetBeforeNextWandering: false,
|
|
774
|
-
generation,
|
|
775
|
-
parameterGeneration,
|
|
776
|
-
actionBarrierGeneration,
|
|
777
|
-
...(actionSafetyGeneration === undefined ? {} : { actionSafetyGeneration }),
|
|
778
|
-
selection: structuredClone(selection),
|
|
779
|
-
} satisfies StrategyComputationProposal,
|
|
780
|
-
};
|
|
781
|
-
}
|
|
782
|
-
if (backendTick !== undefined) this.lastDispatchedBackendTick = backendTick;
|
|
783
|
-
const frame = strategyFrame(input, selection.parameters ?? {});
|
|
784
|
-
if (selection.execution === undefined) {
|
|
785
|
-
return {
|
|
786
|
-
outcome: 'processed',
|
|
787
|
-
proposal: {
|
|
788
|
-
kind: 'legacy',
|
|
789
|
-
generation,
|
|
790
|
-
parameterGeneration,
|
|
791
|
-
actionBarrierGeneration,
|
|
792
|
-
...(actionSafetyGeneration === undefined ? {} : { actionSafetyGeneration }),
|
|
793
|
-
selection: structuredClone(selection),
|
|
794
|
-
frame,
|
|
795
|
-
...(cursor === undefined ? {} : { cursor }),
|
|
796
|
-
} satisfies StrategyComputationProposal,
|
|
797
|
-
};
|
|
798
|
-
}
|
|
799
|
-
|
|
800
|
-
const executor = await this.ensureParallelExecutor(selection, generation, context);
|
|
801
|
-
this.parallelContexts.set(frame.epochId, context);
|
|
802
|
-
try {
|
|
803
|
-
if (selection.execution === 'parallel_analyze') {
|
|
804
|
-
if (!executor.analyze) throw new Error('strategy_parallel_analyze_handler_missing');
|
|
805
|
-
const analysis = structuredClone(await executor.analyze(frame, context.signal));
|
|
806
|
-
return {
|
|
807
|
-
outcome: 'processed',
|
|
808
|
-
proposal: {
|
|
809
|
-
kind: 'parallel_analyze',
|
|
810
|
-
generation,
|
|
811
|
-
parameterGeneration,
|
|
812
|
-
actionBarrierGeneration,
|
|
813
|
-
...(actionSafetyGeneration === undefined ? {} : { actionSafetyGeneration }),
|
|
814
|
-
selection: structuredClone(selection),
|
|
815
|
-
frame,
|
|
816
|
-
analysis,
|
|
817
|
-
...(cursor === undefined ? {} : { cursor }),
|
|
818
|
-
} satisfies StrategyComputationProposal,
|
|
819
|
-
};
|
|
820
|
-
}
|
|
821
|
-
const result = await executor.update(frame, context.signal);
|
|
822
|
-
return {
|
|
823
|
-
outcome: 'processed',
|
|
824
|
-
proposal: {
|
|
825
|
-
kind: 'parallel_compute',
|
|
826
|
-
generation,
|
|
827
|
-
parameterGeneration,
|
|
828
|
-
actionBarrierGeneration,
|
|
829
|
-
...(actionSafetyGeneration === undefined ? {} : { actionSafetyGeneration }),
|
|
830
|
-
selection: structuredClone(selection),
|
|
831
|
-
frame,
|
|
832
|
-
result: structuredClone(result),
|
|
833
|
-
...(cursor === undefined ? {} : { cursor }),
|
|
834
|
-
} satisfies StrategyComputationProposal,
|
|
835
|
-
};
|
|
836
|
-
} finally {
|
|
837
|
-
this.parallelContexts.delete(frame.epochId);
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
async commit(
|
|
842
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
843
|
-
computation: Readonly<RuntimeEpochPluginResult>,
|
|
844
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
845
|
-
): Promise<RuntimeEpochPluginResult> {
|
|
846
|
-
const proposal = strategyProposal(computation.proposal);
|
|
847
|
-
this.refreshStrategyReportRuntime(input, context);
|
|
848
|
-
const previousInvokedEpochSeq = this.lastInvokedEpochSeq;
|
|
849
|
-
this.lastInvokedEpochSeq = input.epoch.epochSeq;
|
|
850
|
-
if (previousInvokedEpochSeq !== null && input.epoch.epochSeq > previousInvokedEpochSeq + 1) {
|
|
851
|
-
this.wanderingResetRequired = true;
|
|
852
|
-
context.diagnostic('strategy.catchup_gap', {
|
|
853
|
-
previous_invoked_epoch_seq: previousInvokedEpochSeq,
|
|
854
|
-
current_epoch_seq: input.epoch.epochSeq,
|
|
855
|
-
skipped_from_epoch_seq: previousInvokedEpochSeq + 1,
|
|
856
|
-
skipped_through_epoch_seq: input.epoch.epochSeq - 1,
|
|
857
|
-
skipped_epoch_count: input.epoch.epochSeq - previousInvokedEpochSeq - 1,
|
|
858
|
-
}, 'debug');
|
|
859
|
-
}
|
|
860
|
-
if (proposal.kind === 'noop') {
|
|
861
|
-
if (proposal.selection && proposal.generation !== this.selectionGeneration) {
|
|
862
|
-
return { outcome: 'noop', reason: 'strategy_computation_superseded' };
|
|
863
|
-
}
|
|
864
|
-
if (proposal.resetBeforeNextWandering) this.wanderingResetRequired = true;
|
|
865
|
-
return {
|
|
866
|
-
outcome: 'noop',
|
|
867
|
-
reason: proposal.reason,
|
|
868
|
-
...(proposal.cursor === undefined ? {} : { consumeEventsThroughCommitSeq: proposal.cursor }),
|
|
869
|
-
};
|
|
870
|
-
}
|
|
871
|
-
if (!proposal.selection || proposal.generation !== this.selectionGeneration) {
|
|
872
|
-
return { outcome: 'noop', reason: 'strategy_computation_superseded' };
|
|
873
|
-
}
|
|
874
|
-
await this.applyPendingSelection(context);
|
|
875
|
-
this.refreshStrategyReportRuntime(input, context);
|
|
876
|
-
if (!this.selected || this.selectedGeneration !== proposal.generation) {
|
|
877
|
-
return { outcome: 'noop', reason: 'strategy_computation_superseded' };
|
|
878
|
-
}
|
|
879
|
-
await this.applyPendingControls(input, context);
|
|
880
|
-
if (
|
|
881
|
-
proposal.kind === 'parallel_analyze'
|
|
882
|
-
&& proposal.parameterGeneration !== this.parameterGeneration
|
|
883
|
-
) {
|
|
884
|
-
context.diagnostic('strategy.result.discarded', {
|
|
885
|
-
strategy_id: this.selected.id,
|
|
886
|
-
epoch_id: proposal.frame.epochId,
|
|
887
|
-
reason: 'strategy_parameters_changed_before_reduce',
|
|
888
|
-
}, 'debug');
|
|
889
|
-
return { outcome: 'noop', reason: 'strategy_parameters_changed_before_reduce' };
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
if (proposal.kind === 'legacy') {
|
|
893
|
-
if (!this.executor) this.executor = this.createExecutor(this.selected, context);
|
|
894
|
-
if (!this.executor.isAlive) {
|
|
895
|
-
await this.executor.start(this.selected.parameters ?? {}, context.signal);
|
|
896
|
-
}
|
|
897
|
-
if (this.wanderingResetRequired) {
|
|
898
|
-
await this.executor.reset(context.signal);
|
|
899
|
-
this.wanderingResetRequired = false;
|
|
900
|
-
}
|
|
901
|
-
this.activeContext = context;
|
|
902
|
-
this.activeActionOriginEpochSeq = proposal.frame.epochId;
|
|
903
|
-
this.activeActionSafetyGeneration = proposal.actionSafetyGeneration;
|
|
904
|
-
this.activeActionAllowed = this.latestFrameAllowsActions;
|
|
905
|
-
try {
|
|
906
|
-
const result = await this.executor.update(proposal.frame, context.signal);
|
|
907
|
-
return this.commitResult(proposal, result, context);
|
|
908
|
-
} finally {
|
|
909
|
-
this.activeContext = undefined;
|
|
910
|
-
this.activeActionOriginEpochSeq = undefined;
|
|
911
|
-
this.activeActionSafetyGeneration = undefined;
|
|
912
|
-
this.activeActionAllowed = false;
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
if (proposal.kind === 'parallel_analyze') {
|
|
916
|
-
if (
|
|
917
|
-
!this.latestFrameAllowsActions
|
|
918
|
-
|| proposal.actionBarrierGeneration !== this.actionBarrierGeneration
|
|
919
|
-
) {
|
|
920
|
-
context.diagnostic('strategy.result.discarded', {
|
|
921
|
-
strategy_id: this.selected.id,
|
|
922
|
-
epoch_id: proposal.frame.epochId,
|
|
923
|
-
reason: 'strategy_action_barrier_advanced',
|
|
924
|
-
}, 'debug');
|
|
925
|
-
return { outcome: 'noop', reason: 'strategy_action_barrier_advanced' };
|
|
926
|
-
}
|
|
927
|
-
const commitFrame = strategyFrame(input, this.selected.parameters ?? {});
|
|
928
|
-
const commitCursor = input.pendingEvents.at(-1)?.commitSeq;
|
|
929
|
-
const {
|
|
930
|
-
frame: _analysisFrame,
|
|
931
|
-
cursor: _analysisCursor,
|
|
932
|
-
...proposalWithoutStaleFrame
|
|
933
|
-
} = proposal;
|
|
934
|
-
const committedProposal = {
|
|
935
|
-
...proposalWithoutStaleFrame,
|
|
936
|
-
frame: commitFrame,
|
|
937
|
-
...(commitCursor === undefined ? {} : { cursor: commitCursor }),
|
|
938
|
-
} satisfies Extract<StrategyComputationProposal, { kind: 'parallel_analyze' }>;
|
|
939
|
-
if (!this.executor) this.executor = this.createExecutor(this.selected, context);
|
|
940
|
-
if (!this.executor.isAlive) {
|
|
941
|
-
await this.executor.start(this.selected.parameters ?? {}, context.signal);
|
|
942
|
-
}
|
|
943
|
-
if (this.wanderingResetRequired) {
|
|
944
|
-
await this.executor.reset(context.signal);
|
|
945
|
-
this.wanderingResetRequired = false;
|
|
946
|
-
}
|
|
947
|
-
if (!this.executor.reduce) throw new Error('strategy_ordered_reduce_handler_missing');
|
|
948
|
-
this.activeContext = context;
|
|
949
|
-
this.activeActionOriginEpochSeq = commitFrame.epochId;
|
|
950
|
-
this.activeActionSafetyGeneration = proposal.actionSafetyGeneration;
|
|
951
|
-
this.activeActionAllowed = this.latestFrameAllowsActions
|
|
952
|
-
&& proposal.actionBarrierGeneration === this.actionBarrierGeneration;
|
|
953
|
-
const reducer = this.executor;
|
|
954
|
-
try {
|
|
955
|
-
const result = await reducer.reduce!(
|
|
956
|
-
commitFrame,
|
|
957
|
-
structuredClone(proposal.analysis),
|
|
958
|
-
context.signal,
|
|
959
|
-
);
|
|
960
|
-
return await this.commitResult(committedProposal, result, context);
|
|
961
|
-
} catch (error) {
|
|
962
|
-
// reduce() owns persistent Goal state. Once it throws (including after
|
|
963
|
-
// mutating state but before returning a valid result), that state can no
|
|
964
|
-
// longer be trusted. Replace the worker instead of leaking a half-applied
|
|
965
|
-
// tick into the next ordered commit.
|
|
966
|
-
if (this.executor === reducer) this.executor = undefined;
|
|
967
|
-
try {
|
|
968
|
-
await reducer.stop('switched');
|
|
969
|
-
} catch (stopError) {
|
|
970
|
-
context.diagnostic('strategy.executor.stop_failed', {
|
|
971
|
-
strategy_id: this.selected.id,
|
|
972
|
-
execution: 'parallel_analyze',
|
|
973
|
-
error_code: diagnosticErrorCode(stopError, 'STRATEGY_EXECUTOR_STOP_FAILED'),
|
|
974
|
-
}, 'warn');
|
|
975
|
-
}
|
|
976
|
-
context.diagnostic('strategy.reducer.discarded', {
|
|
977
|
-
strategy_id: this.selected.id,
|
|
978
|
-
epoch_id: commitFrame.epochId,
|
|
979
|
-
error_code: diagnosticErrorCode(error, 'STRATEGY_REDUCER_FAILED'),
|
|
980
|
-
}, 'error');
|
|
981
|
-
throw error;
|
|
982
|
-
} finally {
|
|
983
|
-
this.activeContext = undefined;
|
|
984
|
-
this.activeActionOriginEpochSeq = undefined;
|
|
985
|
-
this.activeActionSafetyGeneration = undefined;
|
|
986
|
-
this.activeActionAllowed = false;
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
this.wanderingResetRequired = false;
|
|
990
|
-
return this.commitResult(proposal, proposal.result, context);
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
|
|
994
|
-
this.resetStrategyReporting();
|
|
995
|
-
const executor = this.executor;
|
|
996
|
-
this.executor = undefined;
|
|
997
|
-
const parallelExecutor = this.parallelExecutor;
|
|
998
|
-
const parallelExecutorReady = this.parallelExecutorReady;
|
|
999
|
-
this.parallelExecutor = undefined;
|
|
1000
|
-
this.parallelExecutorReady = undefined;
|
|
1001
|
-
this.parallelExecutorLifecycle?.abort(new Error(`strategy_parallel_executor_stopped:${reason}`));
|
|
1002
|
-
this.parallelExecutorLifecycle = undefined;
|
|
1003
|
-
this.parallelExecutorGeneration = 0;
|
|
1004
|
-
this.parallelContexts.clear();
|
|
1005
|
-
this.activeContext = undefined;
|
|
1006
|
-
this.activeActionOriginEpochSeq = undefined;
|
|
1007
|
-
this.activeActionSafetyGeneration = undefined;
|
|
1008
|
-
this.activeActionAllowed = false;
|
|
1009
|
-
this.selectedActionControllerId = undefined;
|
|
1010
|
-
this.latestFrameAllowsActions = false;
|
|
1011
|
-
this.actionBarrierGeneration = 0;
|
|
1012
|
-
this.wanderingResetRequired = false;
|
|
1013
|
-
this.lastInvokedEpochSeq = null;
|
|
1014
|
-
this.lastDispatchedBackendTick = null;
|
|
1015
|
-
this.committedActionDedupeKeys.clear();
|
|
1016
|
-
this.rejectAllPendingControls(
|
|
1017
|
-
reason === 'shutdown' ? 'strategy_runtime_shutdown' : 'strategy_scope_ended',
|
|
1018
|
-
);
|
|
1019
|
-
if (parallelExecutor) {
|
|
1020
|
-
try {
|
|
1021
|
-
await parallelExecutor.stop(reason === 'shutdown' ? 'shutdown' : 'scope_ended');
|
|
1022
|
-
} finally {
|
|
1023
|
-
await parallelExecutorReady?.catch(() => {});
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
if (executor) await executor.stop(reason === 'shutdown' ? 'shutdown' : 'scope_ended');
|
|
1027
|
-
if (reason === 'segment_ending' && this.selected && !this.defaultSelectionForRole) {
|
|
1028
|
-
this.pendingSelection = this.selected;
|
|
1029
|
-
this.pendingSelectionGeneration = this.selectedGeneration;
|
|
1030
|
-
} else {
|
|
1031
|
-
this.selected = undefined;
|
|
1032
|
-
this.pendingSelection = undefined;
|
|
1033
|
-
this.selectedGeneration = 0;
|
|
1034
|
-
this.pendingSelectionGeneration = 0;
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
private selectDefaultForAssignedRole(
|
|
1039
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
1040
|
-
): void {
|
|
1041
|
-
if (this.selected || this.pendingSelection || !this.defaultSelectionForRole) return;
|
|
1042
|
-
const runtimeState = input.epoch.state;
|
|
1043
|
-
const stateRole = isClawclawRuntimeState(runtimeState)
|
|
1044
|
-
&& runtimeState.game_snapshot.status === 'fresh'
|
|
1045
|
-
&& typeof runtimeState.game_snapshot.state.you?.role === 'string'
|
|
1046
|
-
? runtimeState.game_snapshot.state.you.role.trim()
|
|
1047
|
-
: '';
|
|
1048
|
-
const assignment = [...input.pendingEvents].reverse().find((event) => (
|
|
1049
|
-
event.type === 'role_assigned'
|
|
1050
|
-
&& typeof event.payload?.role === 'string'
|
|
1051
|
-
&& event.payload.role.trim().length > 0
|
|
1052
|
-
));
|
|
1053
|
-
const role = stateRole || (typeof assignment?.payload.role === 'string'
|
|
1054
|
-
? assignment.payload.role.trim()
|
|
1055
|
-
: '');
|
|
1056
|
-
if (!role) return;
|
|
1057
|
-
this.select(this.defaultSelectionForRole(role));
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
private async applyPendingSelection(
|
|
1061
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
1062
|
-
): Promise<void> {
|
|
1063
|
-
const pending = this.pendingSelection;
|
|
1064
|
-
if (!pending) return;
|
|
1065
|
-
this.pendingSelection = undefined;
|
|
1066
|
-
const previousStrategyId = this.selected?.id;
|
|
1067
|
-
const previousActionControllerId = this.selectedActionControllerId;
|
|
1068
|
-
const previous = this.executor;
|
|
1069
|
-
const previousParallel = this.parallelExecutor;
|
|
1070
|
-
const previousParallelReady = this.parallelExecutorReady;
|
|
1071
|
-
const previousParallelLifecycle = this.parallelExecutorLifecycle;
|
|
1072
|
-
const keepParallel = pending.execution !== undefined
|
|
1073
|
-
&& previousParallel !== undefined
|
|
1074
|
-
&& this.parallelExecutorGeneration === this.pendingSelectionGeneration;
|
|
1075
|
-
this.executor = undefined;
|
|
1076
|
-
if (!keepParallel) {
|
|
1077
|
-
this.parallelExecutor = undefined;
|
|
1078
|
-
this.parallelExecutorReady = undefined;
|
|
1079
|
-
this.parallelExecutorLifecycle = undefined;
|
|
1080
|
-
this.parallelExecutorGeneration = 0;
|
|
1081
|
-
this.parallelContexts.clear();
|
|
1082
|
-
}
|
|
1083
|
-
if (previous) await previous.stop('switched');
|
|
1084
|
-
if (previousParallel && !keepParallel) {
|
|
1085
|
-
previousParallelLifecycle?.abort(new Error('strategy_parallel_executor_switched'));
|
|
1086
|
-
try {
|
|
1087
|
-
await previousParallel.stop('switched');
|
|
1088
|
-
} finally {
|
|
1089
|
-
await previousParallelReady?.catch(() => {});
|
|
1090
|
-
}
|
|
1091
|
-
}
|
|
1092
|
-
if (previousActionControllerId) {
|
|
1093
|
-
context.capabilities.releaseActionCaller(
|
|
1094
|
-
CLAWCLAW_ACTION_CAPABILITY,
|
|
1095
|
-
{ kind: 'strategy', id: previousActionControllerId },
|
|
1096
|
-
'strategy_switched',
|
|
1097
|
-
);
|
|
1098
|
-
}
|
|
1099
|
-
this.selected = pending;
|
|
1100
|
-
this.selectedGeneration = this.pendingSelectionGeneration;
|
|
1101
|
-
this.selectedActionControllerId = strategyActionControllerId(
|
|
1102
|
-
pending.id,
|
|
1103
|
-
this.selectedGeneration,
|
|
1104
|
-
);
|
|
1105
|
-
if (pending.execution !== 'parallel_compute') {
|
|
1106
|
-
this.executor = this.createExecutor(pending, context);
|
|
1107
|
-
}
|
|
1108
|
-
this.wanderingResetRequired = false;
|
|
1109
|
-
this.committedActionDedupeKeys.clear();
|
|
1110
|
-
context.diagnostic('strategy.selection.applied', {
|
|
1111
|
-
strategy_id: pending.id,
|
|
1112
|
-
...(previousStrategyId ? { previous_strategy_id: previousStrategyId } : {}),
|
|
1113
|
-
parameter_count: Object.keys(pending.parameters ?? {}).length,
|
|
1114
|
-
}, 'info');
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
private async applyPendingControls(
|
|
1118
|
-
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
1119
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
1120
|
-
): Promise<void> {
|
|
1121
|
-
const controls = this.pendingControls.splice(0);
|
|
1122
|
-
for (const control of controls) {
|
|
1123
|
-
const selected = this.selected;
|
|
1124
|
-
const executor = this.executor;
|
|
1125
|
-
context.diagnostic('strategy.control.started', {
|
|
1126
|
-
strategy_id: control.strategyId,
|
|
1127
|
-
revision: control.revision,
|
|
1128
|
-
parameter_count: Object.keys(control.values).length,
|
|
1129
|
-
}, 'info');
|
|
1130
|
-
if (!selected || selected.id !== control.strategyId) {
|
|
1131
|
-
context.diagnostic('strategy.control.rejected', {
|
|
1132
|
-
strategy_id: control.strategyId,
|
|
1133
|
-
revision: control.revision,
|
|
1134
|
-
reason: 'strategy_switched_before_control_applied',
|
|
1135
|
-
}, 'warn');
|
|
1136
|
-
control.reject(new Error('strategy_switched_before_control_applied'));
|
|
1137
|
-
continue;
|
|
1138
|
-
}
|
|
1139
|
-
if (control.preAppliedValues !== undefined) {
|
|
1140
|
-
control.resolve({
|
|
1141
|
-
accepted: true,
|
|
1142
|
-
appliedRevision: control.revision,
|
|
1143
|
-
effectiveValues: structuredClone(control.preAppliedValues),
|
|
1144
|
-
strategy: selected.id,
|
|
1145
|
-
revision: control.revision,
|
|
1146
|
-
appliedEpochId: input.epoch.epochSeq,
|
|
1147
|
-
});
|
|
1148
|
-
context.diagnostic('strategy.control.completed', {
|
|
1149
|
-
strategy_id: selected.id,
|
|
1150
|
-
revision: control.revision,
|
|
1151
|
-
accepted: true,
|
|
1152
|
-
effective_parameter_count: Object.keys(control.preAppliedValues).length,
|
|
1153
|
-
}, 'info');
|
|
1154
|
-
continue;
|
|
1155
|
-
}
|
|
1156
|
-
if (selected.execution === 'parallel_compute') {
|
|
1157
|
-
try {
|
|
1158
|
-
validateControlValues(selected, control.values, true);
|
|
1159
|
-
const result = this.parallelExecutor?.applyControl
|
|
1160
|
-
? await this.parallelExecutor.applyControl({
|
|
1161
|
-
epochId: input.epoch.epochSeq,
|
|
1162
|
-
scope: {
|
|
1163
|
-
sessionId: input.epoch.scope.sessionId,
|
|
1164
|
-
segmentId: input.epoch.scope.segmentId,
|
|
1165
|
-
},
|
|
1166
|
-
revision: control.revision,
|
|
1167
|
-
values: control.values,
|
|
1168
|
-
}, context.signal)
|
|
1169
|
-
: {
|
|
1170
|
-
accepted: true,
|
|
1171
|
-
appliedRevision: control.revision,
|
|
1172
|
-
effectiveValues: {
|
|
1173
|
-
...(selected.parameters ?? {}),
|
|
1174
|
-
...control.values,
|
|
1175
|
-
},
|
|
1176
|
-
};
|
|
1177
|
-
if (!result.accepted) {
|
|
1178
|
-
control.resolve({
|
|
1179
|
-
...result,
|
|
1180
|
-
strategy: selected.id,
|
|
1181
|
-
revision: control.revision,
|
|
1182
|
-
appliedEpochId: input.epoch.epochSeq,
|
|
1183
|
-
});
|
|
1184
|
-
continue;
|
|
1185
|
-
}
|
|
1186
|
-
const effectiveValues = result.effectiveValues ?? {
|
|
1187
|
-
...(selected.parameters ?? {}),
|
|
1188
|
-
...control.values,
|
|
1189
|
-
};
|
|
1190
|
-
this.selected = {
|
|
1191
|
-
...selected,
|
|
1192
|
-
parameters: structuredClone(effectiveValues),
|
|
1193
|
-
};
|
|
1194
|
-
control.resolve({
|
|
1195
|
-
accepted: true,
|
|
1196
|
-
appliedRevision: result.appliedRevision ?? control.revision,
|
|
1197
|
-
effectiveValues: structuredClone(effectiveValues),
|
|
1198
|
-
strategy: selected.id,
|
|
1199
|
-
revision: control.revision,
|
|
1200
|
-
appliedEpochId: input.epoch.epochSeq,
|
|
1201
|
-
});
|
|
1202
|
-
context.diagnostic('strategy.control.completed', {
|
|
1203
|
-
strategy_id: selected.id,
|
|
1204
|
-
revision: control.revision,
|
|
1205
|
-
accepted: true,
|
|
1206
|
-
effective_parameter_count: Object.keys(effectiveValues).length,
|
|
1207
|
-
}, 'info');
|
|
1208
|
-
} catch (error) {
|
|
1209
|
-
const failure = error instanceof Error ? error : new Error(String(error));
|
|
1210
|
-
control.reject(failure);
|
|
1211
|
-
context.diagnostic('strategy.control.rejected', {
|
|
1212
|
-
strategy_id: selected.id,
|
|
1213
|
-
revision: control.revision,
|
|
1214
|
-
reason: diagnosticErrorCode(failure, 'INVALID_STRATEGY_CONTROL'),
|
|
1215
|
-
}, 'warn');
|
|
1216
|
-
}
|
|
1217
|
-
continue;
|
|
1218
|
-
}
|
|
1219
|
-
if (selected.execution === 'parallel_analyze') {
|
|
1220
|
-
if (!executor?.applyControl) {
|
|
1221
|
-
context.diagnostic('strategy.control.rejected', {
|
|
1222
|
-
strategy_id: selected.id,
|
|
1223
|
-
revision: control.revision,
|
|
1224
|
-
reason: 'strategy_controls_not_supported',
|
|
1225
|
-
}, 'warn');
|
|
1226
|
-
control.reject(new Error('strategy_controls_not_supported'));
|
|
1227
|
-
continue;
|
|
1228
|
-
}
|
|
1229
|
-
try {
|
|
1230
|
-
const result = await executor.applyControl({
|
|
1231
|
-
epochId: input.epoch.epochSeq,
|
|
1232
|
-
scope: {
|
|
1233
|
-
sessionId: input.epoch.scope.sessionId,
|
|
1234
|
-
segmentId: input.epoch.scope.segmentId,
|
|
1235
|
-
},
|
|
1236
|
-
revision: control.revision,
|
|
1237
|
-
values: control.values,
|
|
1238
|
-
}, context.signal);
|
|
1239
|
-
if (result.accepted) {
|
|
1240
|
-
const previousValues = selected.parameters ?? {};
|
|
1241
|
-
const effectiveValues = {
|
|
1242
|
-
...previousValues,
|
|
1243
|
-
...control.values,
|
|
1244
|
-
...(result.effectiveValues ?? {}),
|
|
1245
|
-
};
|
|
1246
|
-
const parametersChanged = !isDeepStrictEqual(previousValues, effectiveValues);
|
|
1247
|
-
this.selected = {
|
|
1248
|
-
...selected,
|
|
1249
|
-
parameters: structuredClone(effectiveValues),
|
|
1250
|
-
};
|
|
1251
|
-
if (parametersChanged) {
|
|
1252
|
-
this.parameterGeneration += 1;
|
|
1253
|
-
await this.retireParallelAnalyzerPool(context, 'strategy_parameters_changed');
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
const effectiveValues = result.accepted
|
|
1257
|
-
? this.selected?.parameters ?? selected.parameters ?? {}
|
|
1258
|
-
: result.effectiveValues;
|
|
1259
|
-
control.resolve({
|
|
1260
|
-
...result,
|
|
1261
|
-
...(effectiveValues === undefined
|
|
1262
|
-
? {}
|
|
1263
|
-
: { effectiveValues: structuredClone(effectiveValues) }),
|
|
1264
|
-
strategy: selected.id,
|
|
1265
|
-
revision: control.revision,
|
|
1266
|
-
appliedEpochId: input.epoch.epochSeq,
|
|
1267
|
-
});
|
|
1268
|
-
context.diagnostic('strategy.control.completed', {
|
|
1269
|
-
strategy_id: selected.id,
|
|
1270
|
-
revision: control.revision,
|
|
1271
|
-
accepted: result.accepted,
|
|
1272
|
-
effective_parameter_count: Object.keys(effectiveValues ?? control.values).length,
|
|
1273
|
-
}, result.accepted ? 'info' : 'warn');
|
|
1274
|
-
} catch (error) {
|
|
1275
|
-
const failure = error instanceof Error ? error : new Error(String(error));
|
|
1276
|
-
control.reject(failure);
|
|
1277
|
-
context.diagnostic('strategy.control.failed', {
|
|
1278
|
-
strategy_id: selected.id,
|
|
1279
|
-
revision: control.revision,
|
|
1280
|
-
error_code: diagnosticErrorCode(failure, 'STRATEGY_CONTROL_FAILED'),
|
|
1281
|
-
}, 'error');
|
|
1282
|
-
}
|
|
1283
|
-
continue;
|
|
1284
|
-
}
|
|
1285
|
-
if (!executor?.applyControl) {
|
|
1286
|
-
context.diagnostic('strategy.control.rejected', {
|
|
1287
|
-
strategy_id: selected.id,
|
|
1288
|
-
revision: control.revision,
|
|
1289
|
-
reason: 'strategy_controls_not_supported',
|
|
1290
|
-
}, 'warn');
|
|
1291
|
-
control.reject(new Error('strategy_controls_not_supported'));
|
|
1292
|
-
continue;
|
|
1293
|
-
}
|
|
1294
|
-
try {
|
|
1295
|
-
const result = await executor.applyControl({
|
|
1296
|
-
epochId: input.epoch.epochSeq,
|
|
1297
|
-
scope: {
|
|
1298
|
-
sessionId: input.epoch.scope.sessionId,
|
|
1299
|
-
segmentId: input.epoch.scope.segmentId,
|
|
1300
|
-
},
|
|
1301
|
-
revision: control.revision,
|
|
1302
|
-
values: control.values,
|
|
1303
|
-
}, context.signal);
|
|
1304
|
-
if (result.accepted) {
|
|
1305
|
-
const effectiveValues = result.effectiveValues ?? control.values;
|
|
1306
|
-
this.selected = {
|
|
1307
|
-
...selected,
|
|
1308
|
-
parameters: structuredClone({
|
|
1309
|
-
...(selected.parameters ?? {}),
|
|
1310
|
-
...effectiveValues,
|
|
1311
|
-
}),
|
|
1312
|
-
};
|
|
1313
|
-
}
|
|
1314
|
-
control.resolve({
|
|
1315
|
-
...result,
|
|
1316
|
-
strategy: selected.id,
|
|
1317
|
-
revision: control.revision,
|
|
1318
|
-
appliedEpochId: input.epoch.epochSeq,
|
|
1319
|
-
});
|
|
1320
|
-
context.diagnostic('strategy.control.completed', {
|
|
1321
|
-
strategy_id: selected.id,
|
|
1322
|
-
revision: control.revision,
|
|
1323
|
-
accepted: result.accepted,
|
|
1324
|
-
effective_parameter_count: Object.keys(result.effectiveValues ?? control.values).length,
|
|
1325
|
-
}, result.accepted ? 'info' : 'warn');
|
|
1326
|
-
} catch (error) {
|
|
1327
|
-
const failure = error instanceof Error ? error : new Error(String(error));
|
|
1328
|
-
control.reject(failure);
|
|
1329
|
-
context.diagnostic('strategy.control.failed', {
|
|
1330
|
-
strategy_id: selected.id,
|
|
1331
|
-
revision: control.revision,
|
|
1332
|
-
error_code: diagnosticErrorCode(failure, 'STRATEGY_CONTROL_FAILED'),
|
|
1333
|
-
}, 'error');
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
}
|
|
1337
|
-
|
|
1338
|
-
private rejectAllPendingControls(reason: string): void {
|
|
1339
|
-
const pending = this.pendingControls.splice(0);
|
|
1340
|
-
for (const control of pending) control.reject(new Error(reason));
|
|
1341
|
-
}
|
|
1342
|
-
|
|
1343
|
-
private async retireParallelAnalyzerPool(
|
|
1344
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
1345
|
-
reason: string,
|
|
1346
|
-
): Promise<void> {
|
|
1347
|
-
const executor = this.parallelExecutor;
|
|
1348
|
-
const ready = this.parallelExecutorReady;
|
|
1349
|
-
const lifecycle = this.parallelExecutorLifecycle;
|
|
1350
|
-
this.parallelExecutor = undefined;
|
|
1351
|
-
this.parallelExecutorReady = undefined;
|
|
1352
|
-
this.parallelExecutorLifecycle = undefined;
|
|
1353
|
-
this.parallelExecutorGeneration = 0;
|
|
1354
|
-
this.parallelContexts.clear();
|
|
1355
|
-
if (!executor) return;
|
|
1356
|
-
lifecycle?.abort(new Error(reason));
|
|
1357
|
-
try {
|
|
1358
|
-
await executor.stop('switched');
|
|
1359
|
-
} catch (error) {
|
|
1360
|
-
context.diagnostic('strategy.executor.stop_failed', {
|
|
1361
|
-
strategy_id: this.selected?.id ?? 'unknown',
|
|
1362
|
-
execution: 'parallel_analyze',
|
|
1363
|
-
error_code: diagnosticErrorCode(error, 'STRATEGY_EXECUTOR_STOP_FAILED'),
|
|
1364
|
-
}, 'warn');
|
|
1365
|
-
} finally {
|
|
1366
|
-
await ready?.catch(() => {});
|
|
1367
|
-
}
|
|
1368
|
-
}
|
|
1369
|
-
|
|
1370
|
-
private createExecutor(
|
|
1371
|
-
selection: ClawclawStrategySelection,
|
|
1372
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
1373
|
-
): ClawclawStrategyExecutor {
|
|
1374
|
-
const selectionGeneration = this.selectedGeneration;
|
|
1375
|
-
const actionControllerId = this.selectedActionControllerId;
|
|
1376
|
-
if (!actionControllerId) throw new Error('strategy_action_controller_not_active');
|
|
1377
|
-
return this.executorFactory(selection, {
|
|
1378
|
-
action: (action) => this.performAction(
|
|
1379
|
-
selection.id,
|
|
1380
|
-
selectionGeneration,
|
|
1381
|
-
actionControllerId,
|
|
1382
|
-
action,
|
|
1383
|
-
),
|
|
1384
|
-
gameQuery: (query, frame) => this.performGameQuery(this.activeContext, query, frame),
|
|
1385
|
-
diagnostic: (name, attributes = {}, severity = 'debug') => {
|
|
1386
|
-
const diagnosticContext = this.activeContext ?? context;
|
|
1387
|
-
diagnosticContext.diagnostic(name, {
|
|
1388
|
-
strategy_id: selection.id,
|
|
1389
|
-
...attributes,
|
|
1390
|
-
}, severity);
|
|
1391
|
-
},
|
|
1392
|
-
}, 'serial');
|
|
1393
|
-
}
|
|
1394
|
-
|
|
1395
|
-
private createParallelExecutor(
|
|
1396
|
-
selection: ClawclawStrategySelection,
|
|
1397
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
1398
|
-
): ClawclawStrategyExecutor {
|
|
1399
|
-
return this.executorFactory(selection, {
|
|
1400
|
-
action: async () => ({
|
|
1401
|
-
status: 'failure',
|
|
1402
|
-
source: 'local',
|
|
1403
|
-
actionOutcome: 'not_submitted',
|
|
1404
|
-
error: {
|
|
1405
|
-
code: 'STRATEGY_PARALLEL_ACTION_MUST_BE_PROPOSED',
|
|
1406
|
-
message: 'Parallel strategy compute cannot submit Actions directly.',
|
|
1407
|
-
},
|
|
1408
|
-
}),
|
|
1409
|
-
gameQuery: (query, frame) => frame
|
|
1410
|
-
? this.performGameQuery(this.parallelContexts.get(frame.epochId), query, frame)
|
|
1411
|
-
: Promise.resolve({
|
|
1412
|
-
status: 'failure' as const,
|
|
1413
|
-
error: {
|
|
1414
|
-
code: 'STRATEGY_QUERY_FRAME_MISSING',
|
|
1415
|
-
message: 'Parallel strategy query is missing its bound frame.',
|
|
1416
|
-
},
|
|
1417
|
-
}),
|
|
1418
|
-
diagnostic: (name, attributes = {}, severity = 'debug') => {
|
|
1419
|
-
const epochId = attributes.epoch_id;
|
|
1420
|
-
const diagnosticContext = typeof epochId === 'number'
|
|
1421
|
-
? this.parallelContexts.get(epochId) ?? context
|
|
1422
|
-
: context;
|
|
1423
|
-
diagnosticContext.diagnostic(name, {
|
|
1424
|
-
strategy_id: selection.id,
|
|
1425
|
-
execution: selection.execution,
|
|
1426
|
-
...attributes,
|
|
1427
|
-
}, severity);
|
|
1428
|
-
},
|
|
1429
|
-
}, 'parallel');
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
private async ensureParallelExecutor(
|
|
1433
|
-
selection: ClawclawStrategySelection,
|
|
1434
|
-
generation: number,
|
|
1435
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
1436
|
-
): Promise<ClawclawStrategyExecutor> {
|
|
1437
|
-
if (
|
|
1438
|
-
!this.parallelExecutor
|
|
1439
|
-
|| (!this.parallelExecutor.isAlive && !this.parallelExecutorReady)
|
|
1440
|
-
|| this.parallelExecutorGeneration !== generation
|
|
1441
|
-
) {
|
|
1442
|
-
const previous = this.parallelExecutor;
|
|
1443
|
-
const previousReady = this.parallelExecutorReady;
|
|
1444
|
-
const previousLifecycle = this.parallelExecutorLifecycle;
|
|
1445
|
-
const executor = this.createParallelExecutor(selection, context);
|
|
1446
|
-
const lifecycle = new AbortController();
|
|
1447
|
-
this.parallelExecutor = executor;
|
|
1448
|
-
this.parallelExecutorLifecycle = lifecycle;
|
|
1449
|
-
this.parallelExecutorGeneration = generation;
|
|
1450
|
-
const ready = (async () => {
|
|
1451
|
-
if (previous) {
|
|
1452
|
-
previousLifecycle?.abort(new Error('strategy_parallel_executor_replaced'));
|
|
1453
|
-
let stopFailure: unknown;
|
|
1454
|
-
try {
|
|
1455
|
-
await previous.stop('switched');
|
|
1456
|
-
} catch (error) {
|
|
1457
|
-
stopFailure = error;
|
|
1458
|
-
}
|
|
1459
|
-
// A superseded transition can own an even older pool. Its ready task
|
|
1460
|
-
// does not settle until that older pool is fully retired.
|
|
1461
|
-
await previousReady?.catch(() => {});
|
|
1462
|
-
if (stopFailure !== undefined) throw stopFailure;
|
|
1463
|
-
}
|
|
1464
|
-
await executor.start(selection.parameters ?? {}, lifecycle.signal);
|
|
1465
|
-
})();
|
|
1466
|
-
this.parallelExecutorReady = ready;
|
|
1467
|
-
void ready.then(
|
|
1468
|
-
() => {
|
|
1469
|
-
if (this.parallelExecutor === executor && this.parallelExecutorReady === ready) {
|
|
1470
|
-
this.parallelExecutorReady = undefined;
|
|
1471
|
-
}
|
|
1472
|
-
},
|
|
1473
|
-
() => {
|
|
1474
|
-
if (this.parallelExecutor === executor && this.parallelExecutorReady === ready) {
|
|
1475
|
-
this.parallelExecutorReady = undefined;
|
|
1476
|
-
}
|
|
1477
|
-
},
|
|
1478
|
-
);
|
|
1479
|
-
}
|
|
1480
|
-
const expected = this.parallelExecutor;
|
|
1481
|
-
const ready = this.parallelExecutorReady;
|
|
1482
|
-
try {
|
|
1483
|
-
if (ready) await awaitWithAbort(ready, context.signal);
|
|
1484
|
-
} catch (error) {
|
|
1485
|
-
if (context.signal.aborted) throw error;
|
|
1486
|
-
if (this.parallelExecutor === expected) {
|
|
1487
|
-
this.parallelExecutorLifecycle?.abort(new Error('strategy_parallel_executor_start_failed'));
|
|
1488
|
-
this.parallelExecutor = undefined;
|
|
1489
|
-
this.parallelExecutorReady = undefined;
|
|
1490
|
-
this.parallelExecutorLifecycle = undefined;
|
|
1491
|
-
this.parallelExecutorGeneration = 0;
|
|
1492
|
-
try {
|
|
1493
|
-
await expected.stop('switched');
|
|
1494
|
-
} catch (stopError) {
|
|
1495
|
-
context.diagnostic('strategy.executor.stop_failed', {
|
|
1496
|
-
strategy_id: selection.id,
|
|
1497
|
-
execution: selection.execution,
|
|
1498
|
-
error_code: diagnosticErrorCode(stopError, 'STRATEGY_EXECUTOR_STOP_FAILED'),
|
|
1499
|
-
}, 'warn');
|
|
1500
|
-
}
|
|
1501
|
-
}
|
|
1502
|
-
throw error;
|
|
1503
|
-
}
|
|
1504
|
-
if (
|
|
1505
|
-
!this.parallelExecutor
|
|
1506
|
-
|| !this.parallelExecutor.isAlive
|
|
1507
|
-
|| this.parallelExecutorGeneration !== generation
|
|
1508
|
-
) {
|
|
1509
|
-
throw new Error('strategy_parallel_executor_superseded');
|
|
1510
|
-
}
|
|
1511
|
-
return this.parallelExecutor;
|
|
1512
|
-
}
|
|
1513
|
-
|
|
1514
|
-
private async commitResult(
|
|
1515
|
-
proposal: Extract<StrategyComputationProposal, {
|
|
1516
|
-
kind: 'legacy' | 'parallel_compute' | 'parallel_analyze';
|
|
1517
|
-
}>,
|
|
1518
|
-
result: StrategyResult,
|
|
1519
|
-
context: RuntimeEpochPluginContext<Record<string, any>>,
|
|
1520
|
-
): Promise<RuntimeEpochPluginResult> {
|
|
1521
|
-
const selection = this.selected!;
|
|
1522
|
-
const validated = structuredClone(result);
|
|
1523
|
-
if (validated.states !== undefined && !Array.isArray(validated.states)) {
|
|
1524
|
-
throw new Error('strategy_states_invalid');
|
|
1525
|
-
}
|
|
1526
|
-
for (const state of validated.states ?? []) {
|
|
1527
|
-
if (
|
|
1528
|
-
!state
|
|
1529
|
-
|| typeof state !== 'object'
|
|
1530
|
-
|| typeof state.topic !== 'string'
|
|
1531
|
-
|| !this.produces.states?.includes(state.topic)
|
|
1532
|
-
) throw new Error('strategy_state_output_invalid');
|
|
1533
|
-
}
|
|
1534
|
-
if (validated.events !== undefined && !Array.isArray(validated.events)) {
|
|
1535
|
-
throw new Error('strategy_events_invalid');
|
|
1536
|
-
}
|
|
1537
|
-
for (const event of validated.events ?? []) {
|
|
1538
|
-
if (
|
|
1539
|
-
!event
|
|
1540
|
-
|| typeof event !== 'object'
|
|
1541
|
-
|| typeof event.type !== 'string'
|
|
1542
|
-
|| !this.produces.events?.includes(event.type)
|
|
1543
|
-
|| !event.payload
|
|
1544
|
-
|| typeof event.payload !== 'object'
|
|
1545
|
-
|| Array.isArray(event.payload)
|
|
1546
|
-
|| (event.dedupeKey !== undefined && typeof event.dedupeKey !== 'string')
|
|
1547
|
-
|| (event.occurredAt !== undefined && typeof event.occurredAt !== 'string')
|
|
1548
|
-
) throw new Error('strategy_event_output_invalid');
|
|
1549
|
-
}
|
|
1550
|
-
if (validated.actions !== undefined && !Array.isArray(validated.actions)) {
|
|
1551
|
-
throw new Error('strategy_actions_invalid');
|
|
1552
|
-
}
|
|
1553
|
-
const actions = (validated.actions ?? []).map((candidate) => {
|
|
1554
|
-
if (
|
|
1555
|
-
!candidate
|
|
1556
|
-
|| typeof candidate !== 'object'
|
|
1557
|
-
|| !candidate.action
|
|
1558
|
-
|| typeof candidate.action !== 'object'
|
|
1559
|
-
|| Array.isArray(candidate.action)
|
|
1560
|
-
|| (candidate.dedupeKey !== undefined && typeof candidate.dedupeKey !== 'string')
|
|
1561
|
-
) throw new Error('strategy_action_proposal_invalid');
|
|
1562
|
-
return {
|
|
1563
|
-
candidate,
|
|
1564
|
-
request: normalizeClawclawStrategyAction(
|
|
1565
|
-
candidate.action,
|
|
1566
|
-
proposal.frame.epochId,
|
|
1567
|
-
proposal.actionSafetyGeneration,
|
|
1568
|
-
),
|
|
1569
|
-
};
|
|
1570
|
-
});
|
|
1571
|
-
const actionControllerId = this.selectedActionControllerId;
|
|
1572
|
-
if (actions.length > 0 && !actionControllerId) {
|
|
1573
|
-
throw new Error('strategy_action_controller_not_active');
|
|
1574
|
-
}
|
|
1575
|
-
if (
|
|
1576
|
-
actions.length > 0
|
|
1577
|
-
&& (
|
|
1578
|
-
!this.latestFrameAllowsActions
|
|
1579
|
-
|| proposal.generation !== this.selectionGeneration
|
|
1580
|
-
|| proposal.actionBarrierGeneration !== this.actionBarrierGeneration
|
|
1581
|
-
)
|
|
1582
|
-
) {
|
|
1583
|
-
context.diagnostic('strategy.result.discarded', {
|
|
1584
|
-
strategy_id: selection.id,
|
|
1585
|
-
epoch_id: proposal.frame.epochId,
|
|
1586
|
-
reason: 'strategy_action_barrier_advanced',
|
|
1587
|
-
}, 'debug');
|
|
1588
|
-
return { outcome: 'noop', reason: 'strategy_action_barrier_advanced' };
|
|
1589
|
-
}
|
|
1590
|
-
let anEarlierActionMayHaveBeenSubmitted = false;
|
|
1591
|
-
for (const [actionIndex, { candidate, request }] of actions.entries()) {
|
|
1592
|
-
if (candidate.dedupeKey && this.committedActionDedupeKeys.has(candidate.dedupeKey)) {
|
|
1593
|
-
context.diagnostic('strategy.action.deduplicated', {
|
|
1594
|
-
strategy_id: selection.id,
|
|
1595
|
-
epoch_id: proposal.frame.epochId,
|
|
1596
|
-
dedupe_key: candidate.dedupeKey,
|
|
1597
|
-
}, 'debug');
|
|
1598
|
-
continue;
|
|
1599
|
-
}
|
|
1600
|
-
try {
|
|
1601
|
-
const actionResult = await context.capabilities.performAction(
|
|
1602
|
-
CLAWCLAW_ACTION_CAPABILITY,
|
|
1603
|
-
request,
|
|
1604
|
-
{ kind: 'strategy', id: actionControllerId! },
|
|
1605
|
-
);
|
|
1606
|
-
if (isStaleStrategyActionResult(actionResult)) {
|
|
1607
|
-
if (!anEarlierActionMayHaveBeenSubmitted) {
|
|
1608
|
-
context.diagnostic('strategy.result.discarded', {
|
|
1609
|
-
strategy_id: selection.id,
|
|
1610
|
-
epoch_id: proposal.frame.epochId,
|
|
1611
|
-
reason: 'strategy_action_safety_superseded',
|
|
1612
|
-
}, 'debug');
|
|
1613
|
-
return { outcome: 'noop', reason: 'strategy_action_safety_superseded' };
|
|
1614
|
-
}
|
|
1615
|
-
context.diagnostic('strategy.action.batch_truncated', {
|
|
1616
|
-
strategy_id: selection.id,
|
|
1617
|
-
epoch_id: proposal.frame.epochId,
|
|
1618
|
-
reason: 'strategy_action_safety_superseded',
|
|
1619
|
-
rejected_action_index: actionIndex,
|
|
1620
|
-
skipped_action_count: actions.length - actionIndex - 1,
|
|
1621
|
-
}, 'debug');
|
|
1622
|
-
break;
|
|
1623
|
-
}
|
|
1624
|
-
if (actionResult.actionOutcome !== 'not_submitted') {
|
|
1625
|
-
anEarlierActionMayHaveBeenSubmitted = true;
|
|
1626
|
-
}
|
|
1627
|
-
if (
|
|
1628
|
-
candidate.dedupeKey
|
|
1629
|
-
&& (actionResult.status === 'success' || actionResult.status === 'partial')
|
|
1630
|
-
) {
|
|
1631
|
-
this.committedActionDedupeKeys.set(candidate.dedupeKey, proposal.frame.epochId);
|
|
1632
|
-
while (this.committedActionDedupeKeys.size > 2_048) {
|
|
1633
|
-
const oldest = this.committedActionDedupeKeys.keys().next().value as string | undefined;
|
|
1634
|
-
if (oldest === undefined) break;
|
|
1635
|
-
this.committedActionDedupeKeys.delete(oldest);
|
|
1636
|
-
}
|
|
1637
|
-
}
|
|
1638
|
-
} catch (error) {
|
|
1639
|
-
// A throwing capability cannot prove that submission never started. Keep
|
|
1640
|
-
// the rest of this commit observable instead of hiding a possible effect.
|
|
1641
|
-
anEarlierActionMayHaveBeenSubmitted = true;
|
|
1642
|
-
context.diagnostic('strategy.action.failed', {
|
|
1643
|
-
strategy_id: selection.id,
|
|
1644
|
-
epoch_id: proposal.frame.epochId,
|
|
1645
|
-
error_code: diagnosticErrorCode(error, 'STRATEGY_ACTION_FAILED'),
|
|
1646
|
-
}, 'error');
|
|
1647
|
-
}
|
|
1648
|
-
}
|
|
1649
|
-
return {
|
|
1650
|
-
outcome: 'processed',
|
|
1651
|
-
states: validated.states?.map((state) => ({
|
|
1652
|
-
topic: state.topic,
|
|
1653
|
-
value: hostedStrategyState(state.topic, state.value, selection),
|
|
1654
|
-
})),
|
|
1655
|
-
events: validated.events?.map((event, index) => ({
|
|
1656
|
-
type: event.type,
|
|
1657
|
-
dedupeKey: event.dedupeKey
|
|
1658
|
-
?? `${selection.id}:${proposal.frame.tick ?? proposal.frame.epochId}:${event.type}:${index}`,
|
|
1659
|
-
payload: { ...event.payload },
|
|
1660
|
-
...(event.occurredAt ? { occurredAt: event.occurredAt } : {}),
|
|
1661
|
-
})),
|
|
1662
|
-
...(proposal.cursor === undefined ? {} : { consumeEventsThroughCommitSeq: proposal.cursor }),
|
|
1663
|
-
};
|
|
1664
|
-
}
|
|
1665
|
-
|
|
1666
|
-
private async performAction(
|
|
1667
|
-
strategyId: string,
|
|
1668
|
-
selectionGeneration: number,
|
|
1669
|
-
actionControllerId: string,
|
|
1670
|
-
action: Record<string, unknown>,
|
|
1671
|
-
): Promise<StrategyActionAck> {
|
|
1672
|
-
const context = this.activeContext;
|
|
1673
|
-
if (
|
|
1674
|
-
this.selected?.id !== strategyId
|
|
1675
|
-
|| this.selectedGeneration !== selectionGeneration
|
|
1676
|
-
|| this.selectedActionControllerId !== actionControllerId
|
|
1677
|
-
) {
|
|
1678
|
-
return {
|
|
1679
|
-
status: 'deferred',
|
|
1680
|
-
source: 'local',
|
|
1681
|
-
actionOutcome: 'not_submitted',
|
|
1682
|
-
error: {
|
|
1683
|
-
code: 'STRATEGY_GENERATION_SUPERSEDED',
|
|
1684
|
-
message: 'The Strategy Action belongs to a replaced strategy generation.',
|
|
1685
|
-
},
|
|
1686
|
-
};
|
|
1687
|
-
}
|
|
1688
|
-
if (!context || context.signal.aborted || !this.activeActionAllowed) {
|
|
1689
|
-
return {
|
|
1690
|
-
status: 'deferred',
|
|
1691
|
-
error: {
|
|
1692
|
-
code: this.activeActionAllowed ? 'STRATEGY_UPDATE_NOT_ACTIVE' : 'STRATEGY_NOT_WANDERING',
|
|
1693
|
-
message: this.activeActionAllowed
|
|
1694
|
-
? 'The strategy update is no longer active.'
|
|
1695
|
-
: 'Strategy Actions are only available during the wandering phase.',
|
|
1696
|
-
},
|
|
1697
|
-
};
|
|
1698
|
-
}
|
|
1699
|
-
const result = await context.capabilities.performAction(
|
|
1700
|
-
CLAWCLAW_ACTION_CAPABILITY,
|
|
1701
|
-
normalizeClawclawStrategyAction(
|
|
1702
|
-
action,
|
|
1703
|
-
this.activeActionOriginEpochSeq!,
|
|
1704
|
-
this.activeActionSafetyGeneration,
|
|
1705
|
-
),
|
|
1706
|
-
{ kind: 'strategy', id: actionControllerId },
|
|
1707
|
-
);
|
|
1708
|
-
const ack = {
|
|
1709
|
-
status: result.status,
|
|
1710
|
-
actionId: result.actionId,
|
|
1711
|
-
...(result.source === undefined ? {} : { source: result.source }),
|
|
1712
|
-
...(result.actionOutcome === undefined ? {} : { actionOutcome: result.actionOutcome }),
|
|
1713
|
-
...(result.value === undefined ? {} : { value: result.value }),
|
|
1714
|
-
...(result.error === undefined ? {} : { error: result.error }),
|
|
1715
|
-
};
|
|
1716
|
-
return ack;
|
|
1717
|
-
}
|
|
1718
|
-
|
|
1719
|
-
private async performGameQuery(
|
|
1720
|
-
context: RuntimeEpochPluginContext<Record<string, any>> | undefined,
|
|
1721
|
-
query: StrategyGameQuery,
|
|
1722
|
-
frame?: StrategyFrame<Record<string, unknown>>,
|
|
1723
|
-
): Promise<StrategyGameQueryResult> {
|
|
1724
|
-
if (!context || context.signal.aborted) {
|
|
1725
|
-
return {
|
|
1726
|
-
status: 'failure',
|
|
1727
|
-
error: {
|
|
1728
|
-
code: 'STRATEGY_UPDATE_NOT_ACTIVE',
|
|
1729
|
-
message: 'The strategy update is no longer active.',
|
|
1730
|
-
},
|
|
1731
|
-
};
|
|
1732
|
-
}
|
|
1733
|
-
try {
|
|
1734
|
-
if (query.kind === 'tasks') {
|
|
1735
|
-
if (frame) {
|
|
1736
|
-
const tasks = clawclawTasksFromGameState(frame.state);
|
|
1737
|
-
if (tasks === null) throw new Error('authoritative_tasks_unavailable');
|
|
1738
|
-
return { status: 'success', value: tasks };
|
|
1739
|
-
}
|
|
1740
|
-
const observed = await context.capabilities.queryObservation<unknown, unknown>(
|
|
1741
|
-
CLAWCLAW_TASKS_CAPABILITY,
|
|
1742
|
-
{},
|
|
1743
|
-
);
|
|
1744
|
-
return { status: 'success', value: observed.value };
|
|
1745
|
-
}
|
|
1746
|
-
if (query.kind === 'map') {
|
|
1747
|
-
if (frame) {
|
|
1748
|
-
return { status: 'success', value: clawclawMapFromGameState(frame.state) };
|
|
1749
|
-
}
|
|
1750
|
-
const observed = await context.capabilities.queryObservation<unknown, unknown>(
|
|
1751
|
-
CLAWCLAW_MAP_CAPABILITY,
|
|
1752
|
-
{},
|
|
1753
|
-
);
|
|
1754
|
-
return { status: 'success', value: observed.value };
|
|
1755
|
-
}
|
|
1756
|
-
const observed = await context.capabilities.queryObservation<
|
|
1757
|
-
ClawclawPathDistanceRequest,
|
|
1758
|
-
number | null
|
|
1759
|
-
>(CLAWCLAW_PATH_DISTANCE_CAPABILITY, {
|
|
1760
|
-
from: query.from,
|
|
1761
|
-
to: query.to,
|
|
1762
|
-
});
|
|
1763
|
-
return { status: 'success', value: observed.value };
|
|
1764
|
-
} catch (error) {
|
|
1765
|
-
return {
|
|
1766
|
-
status: 'failure',
|
|
1767
|
-
error: {
|
|
1768
|
-
code: 'STRATEGY_GAME_QUERY_FAILED',
|
|
1769
|
-
message: error instanceof Error ? error.message : String(error),
|
|
1770
|
-
},
|
|
1771
|
-
};
|
|
1772
|
-
}
|
|
1773
|
-
}
|
|
1774
|
-
}
|