@myclaw163/clawclaw-cli 0.8.2 → 0.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/configuration.md +1 -1
- package/docs/custom-modules/README.md +2 -2
- package/docs/custom-modules/api-reference.md +17 -3
- package/docs/custom-modules/behavior.md +7 -3
- package/docs/custom-modules/perception.md +26 -3
- package/docs/custom-modules/trigger.md +1 -1
- package/docs/runtime/README.md +1 -1
- package/docs/runtime/behavior-runtime.md +6 -2
- package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +27 -34
- package/skills/clawclaw/references/COMMANDS.md +1 -1
- package/skills/clawclaw/references/STREAM.md +20 -3
- package/src/commands/load.ts +8 -3
- package/src/commands/trigger.ts +12 -5
- package/src/lib/clawclaw-skill-spectate-guidance.test.ts +21 -0
- package/src/lib/trigger-export.test.ts +80 -0
- package/src/lib/trigger-export.ts +210 -0
- package/src/lib/user-data.test.ts +4 -0
- package/src/lib/user-data.ts +4 -0
- package/src/pipeline/event-format.test.ts +62 -0
- package/src/pipeline/event-format.ts +31 -1
- package/src/pipeline/event-hints.test.ts +4 -0
- package/src/runtime/clawclaw/agent-ability-state.ts +89 -0
- package/src/runtime/clawclaw/agent-event-policy.test.ts +4 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +4 -0
- package/src/runtime/clawclaw/behavior-decision.test.ts +14 -0
- package/src/runtime/clawclaw/behavior-decision.ts +8 -1
- package/src/runtime/clawclaw/behavior-input.test.ts +22 -0
- package/src/runtime/clawclaw/behavior-input.ts +3 -0
- package/src/runtime/clawclaw/owner.test.ts +16 -0
- package/src/runtime/clawclaw/owner.ts +21 -8
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -1
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +246 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +135 -6
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +118 -1
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +13 -2
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +156 -0
- package/src/runtime/clawclaw-event-catalog.test.ts +4 -0
- package/src/runtime/clawclaw-event-catalog.ts +4 -0
- package/src/sdk/behavior-plugin/index.ts +10 -0
- package/src/sdk/module-input/index.ts +16 -0
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import type {
|
|
3
|
+
BehaviorContinuation,
|
|
3
4
|
BehaviorDecision,
|
|
5
|
+
BehaviorDelegation,
|
|
4
6
|
BehaviorFinish,
|
|
5
7
|
BehaviorInput,
|
|
6
8
|
BehaviorStatus,
|
|
@@ -135,9 +137,14 @@ interface ActivationRuntime {
|
|
|
135
137
|
instanceGeneration?: number;
|
|
136
138
|
lastCommittedBackendTick?: number;
|
|
137
139
|
lastStatus?: Readonly<BehaviorStatus>;
|
|
140
|
+
pendingContinuation?: Readonly<BehaviorContinuation>;
|
|
138
141
|
committedActionDedupeKeys: Map<string, number>;
|
|
139
142
|
}
|
|
140
143
|
|
|
144
|
+
interface DelegatedShort {
|
|
145
|
+
readonly parentActivationId: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
141
148
|
interface BehaviorComputationProposal {
|
|
142
149
|
readonly schema: typeof BEHAVIOR_COMPUTATION_SCHEMA;
|
|
143
150
|
readonly kind:
|
|
@@ -279,6 +286,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
279
286
|
private readonly decisionTimeoutMs: number;
|
|
280
287
|
private readonly observationMemory = new ClawclawBehaviorObservationMemory();
|
|
281
288
|
private readonly runtimes = new Map<string, ActivationRuntime>();
|
|
289
|
+
private readonly delegatedShorts = new Map<string, Readonly<DelegatedShort>>();
|
|
290
|
+
private readonly finishSummaries = new Map<string, string>();
|
|
282
291
|
private readonly controls = new Map<string, ClawclawBehaviorControlHandle>();
|
|
283
292
|
private readonly pendingLifecycleEvents: RuntimeEventProposal[] = [];
|
|
284
293
|
private readonly decisionControllers = new Map<string, Set<AbortController>>();
|
|
@@ -509,7 +518,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
509
518
|
if (!current) {
|
|
510
519
|
return { outcome: 'processed', proposal: { ...base, kind: 'inactive' } satisfies BehaviorComputationProposal };
|
|
511
520
|
}
|
|
512
|
-
const
|
|
521
|
+
const runtime = this.runtimes.get(current.activationId);
|
|
522
|
+
const frame = createBehaviorInput(input, current.input, runtime?.pendingContinuation);
|
|
513
523
|
if (!frame) {
|
|
514
524
|
return { outcome: 'processed', proposal: { ...base, kind: 'waiting_for_state' } satisfies BehaviorComputationProposal };
|
|
515
525
|
}
|
|
@@ -523,7 +533,6 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
523
533
|
if (frame.gameState.phase !== 'wandering' && !meetingShort) {
|
|
524
534
|
return { outcome: 'processed', proposal: { ...base, kind: 'boundary' } satisfies BehaviorComputationProposal };
|
|
525
535
|
}
|
|
526
|
-
const runtime = this.runtimes.get(current.activationId);
|
|
527
536
|
const control = this.controls.get(current.activationId);
|
|
528
537
|
if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration) {
|
|
529
538
|
return { outcome: 'processed', proposal: { ...base, kind: 'control_held' } satisfies BehaviorComputationProposal };
|
|
@@ -604,6 +613,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
604
613
|
await Promise.all(runners.map((runner) => runner.stop(runnerReason)));
|
|
605
614
|
await this.applyTransitions(this.manager.clearScope(reason, this.now()));
|
|
606
615
|
this.runtimes.clear();
|
|
616
|
+
this.delegatedShorts.clear();
|
|
617
|
+
this.finishSummaries.clear();
|
|
607
618
|
for (const handle of this.controls.values()) handle.release(reason);
|
|
608
619
|
this.controls.clear();
|
|
609
620
|
this.observationMemory.clear();
|
|
@@ -675,8 +686,13 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
675
686
|
this.refreshBackendStrategyReport(input, context);
|
|
676
687
|
|
|
677
688
|
await this.applyTransitions(this.manager.advance(now));
|
|
678
|
-
const
|
|
679
|
-
|
|
689
|
+
const currentForFrame = this.manager.current();
|
|
690
|
+
const frame = currentForFrame
|
|
691
|
+
? createBehaviorInput(
|
|
692
|
+
input,
|
|
693
|
+
currentForFrame.input,
|
|
694
|
+
this.runtimes.get(currentForFrame.activationId)?.pendingContinuation,
|
|
695
|
+
)
|
|
680
696
|
: frameForClock;
|
|
681
697
|
if (frame?.gameState.phase === 'game_over' || computed.kind === 'game_over') {
|
|
682
698
|
await this.applyTransitions(this.manager.clearScope('game_over', now));
|
|
@@ -800,10 +816,25 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
800
816
|
if (decision.finish && (decision.actions?.length ?? 0) > 0) {
|
|
801
817
|
throw new Error('behavior_finish_with_actions_invalid');
|
|
802
818
|
}
|
|
819
|
+
if (decision.delegate && (decision.actions?.length ?? 0) > 0) {
|
|
820
|
+
throw new Error('behavior_delegate_with_actions_invalid');
|
|
821
|
+
}
|
|
822
|
+
if (decision.delegate && decision.finish) {
|
|
823
|
+
throw new Error('behavior_delegate_with_finish_invalid');
|
|
824
|
+
}
|
|
825
|
+
if (decision.delegate && activation.layer !== 'long') {
|
|
826
|
+
throw new Error('behavior_delegate_layer_invalid');
|
|
827
|
+
}
|
|
828
|
+
const delegated = decision.delegate === undefined
|
|
829
|
+
? undefined
|
|
830
|
+
: await this.prepareDelegatedShort(decision.delegate);
|
|
803
831
|
const declaredEvents = new Set(runtime.prepared.manifest.produces ?? []);
|
|
804
832
|
for (const event of decision.events ?? []) {
|
|
805
833
|
if (!declaredEvents.has(event.type)) throw new Error('behavior_event_output_invalid');
|
|
806
834
|
}
|
|
835
|
+
// A continuation belongs to the first Decision that actually reaches the
|
|
836
|
+
// ordered effect queue. Stale proposals and cadence skips never consume it.
|
|
837
|
+
runtime.pendingContinuation = undefined;
|
|
807
838
|
const state = input.epoch.state;
|
|
808
839
|
const safetyGeneration = isClawclawRuntimeState(state)
|
|
809
840
|
? state.action_safety_generation
|
|
@@ -855,21 +886,79 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
855
886
|
payload: { ...event.payload },
|
|
856
887
|
...(event.occurredAt === undefined ? {} : { occurredAt: event.occurredAt }),
|
|
857
888
|
}));
|
|
858
|
-
if (
|
|
889
|
+
if (delegated) {
|
|
890
|
+
// Keep the status on the suspended parent. Publishing it as the current
|
|
891
|
+
// semantic status would incorrectly attach it to the newly started child.
|
|
892
|
+
runtime.lastStatus = decision.status ?? runtime.lastStatus;
|
|
893
|
+
await this.startDelegatedShort(activation, delegated, frame.nowMs);
|
|
894
|
+
} else if (decision.finish) {
|
|
859
895
|
await this.finishCurrent(activation, decision.finish, frame.nowMs);
|
|
860
896
|
}
|
|
861
897
|
return {
|
|
862
|
-
...(decision.status === undefined ? {} : { status: decision.status }),
|
|
898
|
+
...(decision.status === undefined || delegated ? {} : { status: decision.status }),
|
|
863
899
|
events,
|
|
864
900
|
};
|
|
865
901
|
}
|
|
866
902
|
|
|
903
|
+
private async prepareDelegatedShort(
|
|
904
|
+
delegation: Readonly<BehaviorDelegation>,
|
|
905
|
+
): Promise<Readonly<{
|
|
906
|
+
behaviorId: string;
|
|
907
|
+
rawInput: Readonly<Record<string, unknown>>;
|
|
908
|
+
prepared: PreparedClawclawBehavior;
|
|
909
|
+
}>> {
|
|
910
|
+
const rawInput = delegation.input ?? Object.freeze({});
|
|
911
|
+
const prepared = await this.catalog.prepare(delegation.behavior, rawInput);
|
|
912
|
+
return Object.freeze({
|
|
913
|
+
behaviorId: delegation.behavior,
|
|
914
|
+
rawInput: Object.freeze(structuredClone(rawInput)),
|
|
915
|
+
prepared,
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
private async startDelegatedShort(
|
|
920
|
+
parent: Readonly<BehaviorActivationSnapshot>,
|
|
921
|
+
delegated: Readonly<{
|
|
922
|
+
behaviorId: string;
|
|
923
|
+
rawInput: Readonly<Record<string, unknown>>;
|
|
924
|
+
prepared: PreparedClawclawBehavior;
|
|
925
|
+
}>,
|
|
926
|
+
now: number,
|
|
927
|
+
): Promise<void> {
|
|
928
|
+
if (!this.manager.isCurrent(parent.activationId, parent.instanceGeneration)) return;
|
|
929
|
+
const activationId = this.createActivationId();
|
|
930
|
+
const maxRuntimeMs = runtimeMs(delegated.prepared, delegated.rawInput)
|
|
931
|
+
?? DEFAULT_SHORT_MAX_RUNTIME_MS;
|
|
932
|
+
const transitions = this.manager.startShort({
|
|
933
|
+
activationId,
|
|
934
|
+
behaviorId: delegated.behaviorId,
|
|
935
|
+
source: 'behavior',
|
|
936
|
+
input: delegated.prepared.input,
|
|
937
|
+
requestedAt: now,
|
|
938
|
+
maxRuntimeMs,
|
|
939
|
+
deadlineOutcome: deadlineOutcome(delegated.prepared, delegated.rawInput) ?? 'failed',
|
|
940
|
+
}, now);
|
|
941
|
+
this.runtimes.set(activationId, {
|
|
942
|
+
activationId,
|
|
943
|
+
behaviorId: delegated.behaviorId,
|
|
944
|
+
prepared: delegated.prepared,
|
|
945
|
+
committedActionDedupeKeys: new Map(),
|
|
946
|
+
});
|
|
947
|
+
this.delegatedShorts.set(activationId, Object.freeze({
|
|
948
|
+
parentActivationId: parent.activationId,
|
|
949
|
+
}));
|
|
950
|
+
await this.applyTransitions(transitions);
|
|
951
|
+
}
|
|
952
|
+
|
|
867
953
|
private async finishCurrent(
|
|
868
954
|
activation: Readonly<BehaviorActivationSnapshot>,
|
|
869
955
|
finish: Readonly<BehaviorFinish>,
|
|
870
956
|
now: number,
|
|
871
957
|
): Promise<void> {
|
|
872
958
|
if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) return;
|
|
959
|
+
if (finish.summary !== undefined) {
|
|
960
|
+
this.finishSummaries.set(activation.activationId, finish.summary);
|
|
961
|
+
}
|
|
873
962
|
await this.applyTransitions(this.manager.finish(
|
|
874
963
|
activation.activationId,
|
|
875
964
|
finish.outcome,
|
|
@@ -890,6 +979,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
890
979
|
private async applyTransitions(
|
|
891
980
|
transitions: readonly BehaviorActivationTransition[],
|
|
892
981
|
): Promise<void> {
|
|
982
|
+
this.captureDelegationResults(transitions);
|
|
893
983
|
for (const transition of transitions) {
|
|
894
984
|
const event = lifecycleEvent(transition);
|
|
895
985
|
if (event) this.pendingLifecycleEvents.push(event);
|
|
@@ -950,6 +1040,45 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
950
1040
|
if (failures.length > 0) await this.applyTransitions(failures);
|
|
951
1041
|
}
|
|
952
1042
|
|
|
1043
|
+
private captureDelegationResults(
|
|
1044
|
+
transitions: readonly BehaviorActivationTransition[],
|
|
1045
|
+
): void {
|
|
1046
|
+
for (const transition of transitions) {
|
|
1047
|
+
if (
|
|
1048
|
+
transition.type !== 'completed'
|
|
1049
|
+
&& transition.type !== 'failed'
|
|
1050
|
+
&& transition.type !== 'cancelled'
|
|
1051
|
+
&& transition.type !== 'replaced'
|
|
1052
|
+
) continue;
|
|
1053
|
+
const delegated = this.delegatedShorts.get(transition.activationId);
|
|
1054
|
+
const summary = this.finishSummaries.get(transition.activationId);
|
|
1055
|
+
if (delegated) {
|
|
1056
|
+
const parent = currentRuntimeSnapshot(this.manager, delegated.parentActivationId);
|
|
1057
|
+
const parentRuntime = this.runtimes.get(delegated.parentActivationId);
|
|
1058
|
+
if (parent?.layer === 'long' && parentRuntime) {
|
|
1059
|
+
parentRuntime.pendingContinuation = Object.freeze({
|
|
1060
|
+
delegatedBehavior: Object.freeze({
|
|
1061
|
+
activationId: transition.activationId,
|
|
1062
|
+
behavior: transition.behaviorId,
|
|
1063
|
+
outcome: transition.type,
|
|
1064
|
+
reason: transition.reason,
|
|
1065
|
+
...(summary === undefined ? {} : { summary }),
|
|
1066
|
+
}),
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
this.delegatedShorts.delete(transition.activationId);
|
|
1070
|
+
}
|
|
1071
|
+
this.finishSummaries.delete(transition.activationId);
|
|
1072
|
+
if (transition.layer === 'long') {
|
|
1073
|
+
for (const [childActivationId, relation] of this.delegatedShorts) {
|
|
1074
|
+
if (relation.parentActivationId === transition.activationId) {
|
|
1075
|
+
this.delegatedShorts.delete(childActivationId);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
|
|
953
1082
|
private async ensureRuntime(
|
|
954
1083
|
activation: Readonly<BehaviorActivationSnapshot>,
|
|
955
1084
|
): Promise<ActivationRuntime> {
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
ClawclawDerivedEventPlugin,
|
|
9
9
|
CLAWCLAW_DERIVED_EVENT_PLUGIN_ID,
|
|
10
10
|
} from './derived-event-plugin.js';
|
|
11
|
+
import { EmergencyCountdownDerivedEventRule } from './derived-event-rules.js';
|
|
11
12
|
|
|
12
13
|
function roomState(ready: boolean, roomType = 'casual'): Record<string, any> {
|
|
13
14
|
return {
|
|
@@ -31,7 +32,11 @@ function roomState(ready: boolean, roomType = 'casual'): Record<string, any> {
|
|
|
31
32
|
};
|
|
32
33
|
}
|
|
33
34
|
|
|
34
|
-
function gameState(
|
|
35
|
+
function gameState(
|
|
36
|
+
tick: number,
|
|
37
|
+
meeting?: Record<string, any>,
|
|
38
|
+
state: Record<string, any> = {},
|
|
39
|
+
): Record<string, any> {
|
|
35
40
|
return {
|
|
36
41
|
schema: 'clawclaw.runtime-state.v1',
|
|
37
42
|
stage: meeting ? 'meeting' : 'game',
|
|
@@ -43,12 +48,23 @@ function gameState(tick: number, meeting?: Record<string, any>): Record<string,
|
|
|
43
48
|
state: {
|
|
44
49
|
tick,
|
|
45
50
|
phase: meeting ? 'meeting' : 'wandering',
|
|
51
|
+
...state,
|
|
46
52
|
...(meeting ? { meeting } : {}),
|
|
47
53
|
},
|
|
48
54
|
},
|
|
49
55
|
};
|
|
50
56
|
}
|
|
51
57
|
|
|
58
|
+
function storedGameFrame(tick: number, state: Record<string, any>): any {
|
|
59
|
+
return {
|
|
60
|
+
frameSeq: tick,
|
|
61
|
+
epochSeq: tick,
|
|
62
|
+
state: gameState(tick, undefined, state),
|
|
63
|
+
observedAtMs: tick * 1_000,
|
|
64
|
+
receivedAtMs: tick * 1_000,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
52
68
|
async function fixture(kind: 'room' | 'game') {
|
|
53
69
|
const events = new MemoryEventRepository();
|
|
54
70
|
const runtime = new Runtime({
|
|
@@ -141,10 +157,111 @@ describe('ClawclawDerivedEventPlugin', () => {
|
|
|
141
157
|
await runtime.close();
|
|
142
158
|
});
|
|
143
159
|
|
|
160
|
+
it('emits emergency countdown warnings once at 30s and 20s', async () => {
|
|
161
|
+
const { runtime, events, submit } = await fixture('game');
|
|
162
|
+
const emergency = (remainingSecs: number) => ({
|
|
163
|
+
emergency: {
|
|
164
|
+
active: true,
|
|
165
|
+
task_name: '修复供氧',
|
|
166
|
+
room: '制氧舱',
|
|
167
|
+
remaining_secs: remainingSecs,
|
|
168
|
+
},
|
|
169
|
+
you: { is_alive: true },
|
|
170
|
+
});
|
|
171
|
+
await submit(gameState(1, undefined, emergency(31)));
|
|
172
|
+
await submit(gameState(2, undefined, emergency(29.8)));
|
|
173
|
+
await submit(gameState(3, undefined, emergency(25)));
|
|
174
|
+
await submit(gameState(4, undefined, emergency(19.7)));
|
|
175
|
+
await submit(gameState(5, undefined, emergency(18)));
|
|
176
|
+
await runtime.flush();
|
|
177
|
+
|
|
178
|
+
const warnings = events.listCommittedEvents({
|
|
179
|
+
sessionId: runtime.scope().sessionId,
|
|
180
|
+
types: ['emergency_countdown_warning'],
|
|
181
|
+
order: 'asc',
|
|
182
|
+
});
|
|
183
|
+
expect(warnings.map((event) => event.payload)).toMatchObject([{
|
|
184
|
+
tick: 2,
|
|
185
|
+
threshold_secs: 30,
|
|
186
|
+
remaining_secs: 29.8,
|
|
187
|
+
}, {
|
|
188
|
+
tick: 4,
|
|
189
|
+
threshold_secs: 20,
|
|
190
|
+
remaining_secs: 19.7,
|
|
191
|
+
}]);
|
|
192
|
+
expect(warnings.every((event) => (
|
|
193
|
+
event.producerPluginId === CLAWCLAW_DERIVED_EVENT_PLUGIN_ID
|
|
194
|
+
))).toBe(true);
|
|
195
|
+
await runtime.close();
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it('rebuilds countdown rule state without replay and preserves a two-threshold leap', () => {
|
|
199
|
+
const emergency = (remainingSecs: number) => ({
|
|
200
|
+
emergency: { active: true, task_name: '维修', remaining_secs: remainingSecs },
|
|
201
|
+
you: { is_alive: true },
|
|
202
|
+
});
|
|
203
|
+
const recovered = new EmergencyCountdownDerivedEventRule();
|
|
204
|
+
recovered.inspect(storedGameFrame(1, emergency(31)));
|
|
205
|
+
recovered.inspect(storedGameFrame(2, emergency(29)));
|
|
206
|
+
expect(recovered.inspect(storedGameFrame(3, emergency(25)))).toEqual([]);
|
|
207
|
+
expect(recovered.inspect(storedGameFrame(4, emergency(19))).map((event) => (
|
|
208
|
+
event.payload.threshold_secs
|
|
209
|
+
))).toEqual([20]);
|
|
210
|
+
|
|
211
|
+
const skipped = new EmergencyCountdownDerivedEventRule();
|
|
212
|
+
skipped.inspect(storedGameFrame(1, emergency(31)));
|
|
213
|
+
expect(skipped.inspect(storedGameFrame(2, emergency(19))).map((event) => (
|
|
214
|
+
event.payload.threshold_secs
|
|
215
|
+
))).toEqual([30, 20]);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
it('emits ability readiness and finite-use changes from authoritative State transitions', async () => {
|
|
219
|
+
const { runtime, events, submit } = await fixture('game');
|
|
220
|
+
const pistol = (cooldown: number, remaining: number) => ({
|
|
221
|
+
you: {
|
|
222
|
+
role: 'shrimp_pistol',
|
|
223
|
+
is_alive: true,
|
|
224
|
+
kill_cooldown_secs: cooldown,
|
|
225
|
+
kills_remaining: remaining,
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
await submit(gameState(1, undefined, pistol(1, 1)));
|
|
229
|
+
await submit(gameState(2, undefined, pistol(0, 1)));
|
|
230
|
+
await submit(gameState(3, undefined, pistol(20, 0)));
|
|
231
|
+
await runtime.flush();
|
|
232
|
+
|
|
233
|
+
const abilityEvents = events.listCommittedEvents({
|
|
234
|
+
sessionId: runtime.scope().sessionId,
|
|
235
|
+
types: ['ability.ready', 'ability.exhausted'],
|
|
236
|
+
order: 'asc',
|
|
237
|
+
});
|
|
238
|
+
expect(abilityEvents.map((event) => ({ type: event.type, payload: event.payload })))
|
|
239
|
+
.toMatchObject([{
|
|
240
|
+
type: 'ability.ready',
|
|
241
|
+
payload: { tick: 2, ability_id: 'kill', remaining_uses: 1 },
|
|
242
|
+
}, {
|
|
243
|
+
type: 'ability.exhausted',
|
|
244
|
+
payload: {
|
|
245
|
+
tick: 3,
|
|
246
|
+
ability_id: 'kill',
|
|
247
|
+
previous_remaining_uses: 1,
|
|
248
|
+
remaining_uses: 0,
|
|
249
|
+
},
|
|
250
|
+
}]);
|
|
251
|
+
expect(abilityEvents.every((event) => (
|
|
252
|
+
event.producerPluginId === CLAWCLAW_DERIVED_EVENT_PLUGIN_ID
|
|
253
|
+
))).toBe(true);
|
|
254
|
+
await runtime.close();
|
|
255
|
+
});
|
|
256
|
+
|
|
144
257
|
it('does not claim backend-owned terminal or turn Events', () => {
|
|
145
258
|
expect(new ClawclawDerivedEventPlugin().produces.events).toEqual([
|
|
146
259
|
'room_ready_to_start',
|
|
147
260
|
'meeting_state',
|
|
261
|
+
'emergency_countdown_warning',
|
|
262
|
+
'ability.ready',
|
|
263
|
+
'ability.remaining_uses_changed',
|
|
264
|
+
'ability.exhausted',
|
|
148
265
|
]);
|
|
149
266
|
});
|
|
150
267
|
});
|
|
@@ -7,6 +7,8 @@ import type {
|
|
|
7
7
|
} from '../../../framework/plugins/index.js';
|
|
8
8
|
import type { StoredStateFrame } from '../../../framework/state/index.js';
|
|
9
9
|
import {
|
|
10
|
+
AbilityStateDerivedEventRule,
|
|
11
|
+
EmergencyCountdownDerivedEventRule,
|
|
10
12
|
MeetingStateDerivedEventRule,
|
|
11
13
|
RoomReadyDerivedEventRule,
|
|
12
14
|
type ClawclawDerivedEventRule,
|
|
@@ -18,9 +20,16 @@ export class ClawclawDerivedEventPlugin
|
|
|
18
20
|
implements RuntimeEpochPlugin<Record<string, any>> {
|
|
19
21
|
readonly kind = 'epoch' as const;
|
|
20
22
|
readonly id = CLAWCLAW_DERIVED_EVENT_PLUGIN_ID;
|
|
21
|
-
readonly version = '
|
|
23
|
+
readonly version = '2';
|
|
22
24
|
readonly produces = {
|
|
23
|
-
events: [
|
|
25
|
+
events: [
|
|
26
|
+
'room_ready_to_start',
|
|
27
|
+
'meeting_state',
|
|
28
|
+
'emergency_countdown_warning',
|
|
29
|
+
'ability.ready',
|
|
30
|
+
'ability.remaining_uses_changed',
|
|
31
|
+
'ability.exhausted',
|
|
32
|
+
],
|
|
24
33
|
} as const;
|
|
25
34
|
readonly catchUp = 'every_epoch' as const;
|
|
26
35
|
readonly timeoutMs = 1_000;
|
|
@@ -30,6 +39,8 @@ implements RuntimeEpochPlugin<Record<string, any>> {
|
|
|
30
39
|
|
|
31
40
|
constructor(rules?: readonly ClawclawDerivedEventRule[]) {
|
|
32
41
|
this.rules = [...(rules ?? [
|
|
42
|
+
new AbilityStateDerivedEventRule(),
|
|
43
|
+
new EmergencyCountdownDerivedEventRule(),
|
|
33
44
|
new RoomReadyDerivedEventRule(),
|
|
34
45
|
new MeetingStateDerivedEventRule(),
|
|
35
46
|
])].sort((left, right) => left.id.localeCompare(right.id));
|
|
@@ -2,6 +2,10 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import type { RuntimeEventProposal } from '../../../framework/plugins/index.js';
|
|
3
3
|
import type { StoredStateFrame } from '../../../framework/state/index.js';
|
|
4
4
|
import { isClawclawRuntimeState } from '../../runtime-state.js';
|
|
5
|
+
import {
|
|
6
|
+
projectAgentAbilities,
|
|
7
|
+
type AgentAbilityState,
|
|
8
|
+
} from '../../agent-ability-state.js';
|
|
5
9
|
|
|
6
10
|
type UnknownRecord = Record<string, unknown>;
|
|
7
11
|
|
|
@@ -30,6 +34,10 @@ function sourceIdentity(frame: StoredStateFrame<Record<string, any>>): number {
|
|
|
30
34
|
return frame.epochSeq ?? frame.frameSeq;
|
|
31
35
|
}
|
|
32
36
|
|
|
37
|
+
function finiteNumber(value: unknown): number | undefined {
|
|
38
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
33
41
|
function roomSnapshot(
|
|
34
42
|
frame: StoredStateFrame<Record<string, any>>,
|
|
35
43
|
): UnknownRecord | null | undefined {
|
|
@@ -111,6 +119,154 @@ function freshGameSnapshot(
|
|
|
111
119
|
return record(state.game_snapshot.state);
|
|
112
120
|
}
|
|
113
121
|
|
|
122
|
+
const EMERGENCY_WARNING_THRESHOLDS = [30, 20] as const;
|
|
123
|
+
|
|
124
|
+
export class EmergencyCountdownDerivedEventRule implements ClawclawDerivedEventRule {
|
|
125
|
+
readonly id = 'emergency-countdown';
|
|
126
|
+
readonly eventTypes = ['emergency_countdown_warning'] as const;
|
|
127
|
+
private emergencyKey = '';
|
|
128
|
+
private remainingSecs?: number;
|
|
129
|
+
private readonly emittedThresholds = new Set<number>();
|
|
130
|
+
|
|
131
|
+
reset(): void {
|
|
132
|
+
this.emergencyKey = '';
|
|
133
|
+
this.remainingSecs = undefined;
|
|
134
|
+
this.emittedThresholds.clear();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
inspect(frame: StoredStateFrame<Record<string, any>>): RuntimeEventProposal[] {
|
|
138
|
+
const game = freshGameSnapshot(frame);
|
|
139
|
+
if (game === undefined) return [];
|
|
140
|
+
const emergency = record(game?.emergency);
|
|
141
|
+
if (emergency?.active !== true) {
|
|
142
|
+
this.reset();
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const key = JSON.stringify([
|
|
147
|
+
emergency.task_name ?? null,
|
|
148
|
+
emergency.room ?? null,
|
|
149
|
+
finiteNumber(emergency.x) ?? null,
|
|
150
|
+
finiteNumber(emergency.y) ?? null,
|
|
151
|
+
]);
|
|
152
|
+
const remainingSecs = finiteNumber(emergency.remaining_secs);
|
|
153
|
+
const sameEmergency = this.emergencyKey === key;
|
|
154
|
+
let crossed: number[] = [];
|
|
155
|
+
if (!sameEmergency) {
|
|
156
|
+
this.emergencyKey = key;
|
|
157
|
+
this.remainingSecs = undefined;
|
|
158
|
+
this.emittedThresholds.clear();
|
|
159
|
+
if (remainingSecs !== undefined) {
|
|
160
|
+
// A recovered Runtime may first observe an incident after one or more
|
|
161
|
+
// thresholds. Wake only for the nearest still-relevant threshold.
|
|
162
|
+
const nearest = [...EMERGENCY_WARNING_THRESHOLDS]
|
|
163
|
+
.reverse()
|
|
164
|
+
.find((threshold) => remainingSecs <= threshold);
|
|
165
|
+
if (nearest !== undefined) crossed = [nearest];
|
|
166
|
+
}
|
|
167
|
+
} else if (remainingSecs !== undefined && this.remainingSecs !== undefined) {
|
|
168
|
+
crossed = EMERGENCY_WARNING_THRESHOLDS.filter((threshold) => (
|
|
169
|
+
this.remainingSecs! > threshold
|
|
170
|
+
&& remainingSecs <= threshold
|
|
171
|
+
&& !this.emittedThresholds.has(threshold)
|
|
172
|
+
));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
this.remainingSecs = remainingSecs;
|
|
176
|
+
for (const threshold of crossed) this.emittedThresholds.add(threshold);
|
|
177
|
+
if (game?.you && record(game.you)?.is_alive === false) return [];
|
|
178
|
+
|
|
179
|
+
return crossed.map((threshold) => {
|
|
180
|
+
const payload: UnknownRecord = {
|
|
181
|
+
threshold_secs: threshold,
|
|
182
|
+
remaining_secs: remainingSecs,
|
|
183
|
+
};
|
|
184
|
+
for (const field of ['task_name', 'room'] as const) {
|
|
185
|
+
if (typeof emergency[field] === 'string') payload[field] = emergency[field];
|
|
186
|
+
}
|
|
187
|
+
if (typeof game?.tick === 'number' || typeof game?.tick === 'string') payload.tick = game.tick;
|
|
188
|
+
return {
|
|
189
|
+
type: 'emergency_countdown_warning',
|
|
190
|
+
dedupeKey: `emergency-countdown:${sourceIdentity(frame)}:${threshold}:${stableHash(key)}`,
|
|
191
|
+
dedupeScope: 'segment' as const,
|
|
192
|
+
payload,
|
|
193
|
+
occurredAt: occurredAt(frame),
|
|
194
|
+
};
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export class AbilityStateDerivedEventRule implements ClawclawDerivedEventRule {
|
|
200
|
+
readonly id = 'ability-state';
|
|
201
|
+
readonly eventTypes = [
|
|
202
|
+
'ability.ready',
|
|
203
|
+
'ability.remaining_uses_changed',
|
|
204
|
+
'ability.exhausted',
|
|
205
|
+
] as const;
|
|
206
|
+
private initialized = false;
|
|
207
|
+
private abilities: AgentAbilityState[] = [];
|
|
208
|
+
|
|
209
|
+
reset(): void {
|
|
210
|
+
this.initialized = false;
|
|
211
|
+
this.abilities = [];
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
inspect(frame: StoredStateFrame<Record<string, any>>): RuntimeEventProposal[] {
|
|
215
|
+
const game = freshGameSnapshot(frame);
|
|
216
|
+
if (game === undefined) return [];
|
|
217
|
+
const current = projectAgentAbilities(game as Record<string, any>) ?? [];
|
|
218
|
+
if (!this.initialized) {
|
|
219
|
+
this.initialized = true;
|
|
220
|
+
this.abilities = structuredClone(current);
|
|
221
|
+
return [];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const previousById = new Map(this.abilities.map((ability) => [ability.id, ability]));
|
|
225
|
+
const proposals: RuntimeEventProposal[] = [];
|
|
226
|
+
for (const ability of current) {
|
|
227
|
+
const previous = previousById.get(ability.id);
|
|
228
|
+
if (!previous) continue;
|
|
229
|
+
const base: UnknownRecord = {
|
|
230
|
+
ability_id: ability.id,
|
|
231
|
+
ability_name: ability.name,
|
|
232
|
+
};
|
|
233
|
+
if (typeof game?.tick === 'number' || typeof game?.tick === 'string') base.tick = game.tick;
|
|
234
|
+
if (ability.effective_range_px !== undefined) {
|
|
235
|
+
base.effective_range_px = ability.effective_range_px;
|
|
236
|
+
}
|
|
237
|
+
if (!previous.ready && ability.ready) {
|
|
238
|
+
proposals.push({
|
|
239
|
+
type: 'ability.ready',
|
|
240
|
+
dedupeKey: `ability-ready:${sourceIdentity(frame)}:${ability.id}`,
|
|
241
|
+
dedupeScope: 'segment',
|
|
242
|
+
payload: { ...base, remaining_uses: ability.remaining_uses },
|
|
243
|
+
occurredAt: occurredAt(frame),
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
if (
|
|
247
|
+
typeof previous.remaining_uses === 'number'
|
|
248
|
+
&& typeof ability.remaining_uses === 'number'
|
|
249
|
+
&& previous.remaining_uses !== ability.remaining_uses
|
|
250
|
+
) {
|
|
251
|
+
const exhausted = ability.remaining_uses === 0;
|
|
252
|
+
proposals.push({
|
|
253
|
+
type: exhausted ? 'ability.exhausted' : 'ability.remaining_uses_changed',
|
|
254
|
+
dedupeKey: `ability-uses:${sourceIdentity(frame)}:${ability.id}:${ability.remaining_uses}`,
|
|
255
|
+
dedupeScope: 'segment',
|
|
256
|
+
payload: {
|
|
257
|
+
...base,
|
|
258
|
+
previous_remaining_uses: previous.remaining_uses,
|
|
259
|
+
remaining_uses: ability.remaining_uses,
|
|
260
|
+
},
|
|
261
|
+
occurredAt: occurredAt(frame),
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
this.abilities = structuredClone(current);
|
|
266
|
+
return proposals;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
114
270
|
export class MeetingStateDerivedEventRule implements ClawclawDerivedEventRule {
|
|
115
271
|
readonly id = 'meeting-state';
|
|
116
272
|
readonly eventTypes = ['meeting_state'] as const;
|
|
@@ -40,6 +40,10 @@ describe('ClawClaw Event Catalog', () => {
|
|
|
40
40
|
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('room_destroyed');
|
|
41
41
|
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('players_changed');
|
|
42
42
|
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('tasks_changed');
|
|
43
|
+
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('emergency_countdown_warning');
|
|
44
|
+
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('ability.ready');
|
|
45
|
+
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('ability.remaining_uses_changed');
|
|
46
|
+
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('ability.exhausted');
|
|
43
47
|
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).not.toContain('task_assigned');
|
|
44
48
|
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).not.toContain('heartbeat');
|
|
45
49
|
expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).not.toContain('room.snapshot');
|
|
@@ -179,6 +179,10 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
|
|
|
179
179
|
'behavior.replaced',
|
|
180
180
|
'players_changed',
|
|
181
181
|
'tasks_changed',
|
|
182
|
+
'emergency_countdown_warning',
|
|
183
|
+
'ability.ready',
|
|
184
|
+
'ability.remaining_uses_changed',
|
|
185
|
+
'ability.exhausted',
|
|
182
186
|
] as const;
|
|
183
187
|
|
|
184
188
|
/** Durable inputs used by projectors, but never sent directly to the Agent. */
|
|
@@ -18,6 +18,8 @@ export type {
|
|
|
18
18
|
} from '../resource-metadata.js';
|
|
19
19
|
|
|
20
20
|
export type {
|
|
21
|
+
BehaviorContinuation,
|
|
22
|
+
BehaviorDelegatedBehaviorResult,
|
|
21
23
|
BehaviorInput,
|
|
22
24
|
BehaviorScope,
|
|
23
25
|
GameEvent,
|
|
@@ -222,11 +224,19 @@ export interface BehaviorEventProposal {
|
|
|
222
224
|
readonly occurredAt?: string;
|
|
223
225
|
}
|
|
224
226
|
|
|
227
|
+
/** Starts one finite short Behavior from the currently running long Behavior. */
|
|
228
|
+
export interface BehaviorDelegation {
|
|
229
|
+
readonly behavior: string;
|
|
230
|
+
readonly input?: Readonly<Record<string, unknown>>;
|
|
231
|
+
}
|
|
232
|
+
|
|
225
233
|
/** All semantic effects of one Behavior decision. */
|
|
226
234
|
export interface BehaviorDecision {
|
|
227
235
|
readonly actions?: readonly Readonly<GameAction>[];
|
|
228
236
|
readonly status?: Readonly<BehaviorStatus>;
|
|
229
237
|
readonly events?: readonly Readonly<BehaviorEventProposal>[];
|
|
238
|
+
/** Suspends this long Activation and starts one validated short Activation. */
|
|
239
|
+
readonly delegate?: Readonly<BehaviorDelegation>;
|
|
230
240
|
/** Ends this Activation after the Decision's preceding effects are committed. */
|
|
231
241
|
readonly finish?: Readonly<BehaviorFinish>;
|
|
232
242
|
}
|
|
@@ -215,6 +215,20 @@ export interface BehaviorScope {
|
|
|
215
215
|
readonly segmentId: string;
|
|
216
216
|
}
|
|
217
217
|
|
|
218
|
+
/** Runtime-owned terminal result of a short Behavior delegated by a long Behavior. */
|
|
219
|
+
export interface BehaviorDelegatedBehaviorResult {
|
|
220
|
+
readonly activationId: string;
|
|
221
|
+
readonly behavior: string;
|
|
222
|
+
readonly outcome: 'completed' | 'failed' | 'cancelled' | 'replaced';
|
|
223
|
+
readonly reason: string;
|
|
224
|
+
readonly summary?: string;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** One-shot input delivered when a long Behavior resumes after delegated work. */
|
|
228
|
+
export interface BehaviorContinuation {
|
|
229
|
+
readonly delegatedBehavior: Readonly<BehaviorDelegatedBehaviorResult>;
|
|
230
|
+
}
|
|
231
|
+
|
|
218
232
|
/** The input envelope shared by finite and continuous Behaviors. */
|
|
219
233
|
export interface BehaviorInput<
|
|
220
234
|
TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
|
|
@@ -226,4 +240,6 @@ export interface BehaviorInput<
|
|
|
226
240
|
readonly gameState: Readonly<GameState>;
|
|
227
241
|
readonly events: readonly Readonly<GameEvent>[];
|
|
228
242
|
readonly input: Readonly<TInput>;
|
|
243
|
+
/** Present for the first committed decision after delegated short work ends. */
|
|
244
|
+
readonly continuation?: Readonly<BehaviorContinuation>;
|
|
229
245
|
}
|