@myclaw163/clawclaw-cli 0.10.6 → 0.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/strategy-worker/assets/clawclaw-spatial-facts.json +1383 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-3VLVCU6P.js +71 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ATQQZA4X.js +44 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-CF6IEQ4V.js +12 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-JMX6D6A3.js +260 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-QEPKDSLE.js +278 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ZQILO6OM.js +0 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/clawclaw-walkable.bin +0 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +1389 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-behavior-plugin.js +22 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-module-input.js +0 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-perception-plugin.js +72 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +3108 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-strategy-plugin.js +25 -0
- package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-trigger-plugin.js +16 -0
- package/docs/custom-modules/api-reference.md +10 -8
- package/docs/custom-modules/perception.md +26 -3
- package/docs/desktop-event-push.md +2 -1
- package/docs/runtime/behavior-runtime.md +3 -1
- package/docs/runtime/official-perception-modules.md +2 -2
- package/docs/user-guide/behavior.md +3 -1
- package/docs/user-guide/desktop-auth.md +33 -1
- package/package.json +5 -3
- package/scripts/build-strategy-worker.mjs +28 -0
- package/scripts/migrate-official-perceptions.mjs +157 -0
- package/skills/clawclaw/SKILL.md +3 -3
- package/skills/clawclaw/references/BEHAVIORS.md +2 -0
- package/skills/clawclaw/references/TACTICS.md +4 -0
- package/skills/clawclaw-creator/SKILL.md +3 -1
- package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +10 -8
- package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +26 -3
- package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
- package/src/commands/capability.ts +4 -2
- package/src/commands/load.ts +5 -2
- package/src/lib/agent-workspace-skills.ts +12 -7
- package/src/lib/capability-cloud-sync.ts +13 -7
- package/src/lib/capability-discovery.ts +10 -3
- package/src/lib/capability-selection.ts +7 -0
- package/src/lib/game-client.ts +33 -6
- package/src/lib/lobby-host-context.ts +74 -0
- package/src/lib/package-skills.ts +11 -1
- package/src/lib/participation-status.ts +5 -0
- package/src/pipeline/event-format.ts +2 -0
- package/src/pipeline/event-hints.ts +1 -0
- package/src/runtime/clawclaw/behavior-start-control.ts +114 -0
- package/src/runtime/clawclaw/notification-policy.ts +1 -0
- package/src/runtime/clawclaw/owner.ts +21 -4
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +1 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -6
- package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +48 -1
- package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +2 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +28 -6
- package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +25 -3
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +1 -1
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +9 -0
- package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -0
- package/src/runtime/clawclaw/plugins/perception/module-input-boundary.ts +64 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +37 -49
- package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +3 -1
- package/src/runtime/clawclaw/plugins/source/room-transport.ts +46 -9
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +18 -4
- package/src/runtime/clawclaw/plugins/source/types.ts +2 -0
- package/src/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.ts +2 -0
- package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +122 -61
- package/src/runtime/clawclaw-event-catalog.ts +1 -0
- package/src/sdk/perception-plugin/index.ts +1 -0
- package/src/sdk/perception-plugin/lifecycle.ts +15 -0
- package/src/sdk/perception-plugin/module.ts +15 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import WebSocket from 'ws';
|
|
3
|
+
import { lobbyHostHeaders, type LobbyHostContext } from '../../../../lib/lobby-host-context.js';
|
|
3
4
|
import {
|
|
4
5
|
normalizeRoomSnapshot,
|
|
5
6
|
type RoomSnapshot,
|
|
@@ -20,6 +21,7 @@ export type ClawclawRoomTransportStopReason =
|
|
|
20
21
|
| 'reconcile'
|
|
21
22
|
| 'replaced'
|
|
22
23
|
| 'fatal'
|
|
24
|
+
| 'normal'
|
|
23
25
|
| 'error'
|
|
24
26
|
| 'shutdown';
|
|
25
27
|
|
|
@@ -32,7 +34,7 @@ export interface ClawclawRoomCloseInfo {
|
|
|
32
34
|
reason: string;
|
|
33
35
|
}
|
|
34
36
|
|
|
35
|
-
export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'maintenance' | 'reconcile' | 'replaced' | 'fatal';
|
|
37
|
+
export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'maintenance' | 'reconcile' | 'replaced' | 'fatal' | 'normal';
|
|
36
38
|
|
|
37
39
|
export interface ClawclawRoomTransportFrameMeta {
|
|
38
40
|
connectionId: string;
|
|
@@ -45,6 +47,7 @@ export interface ClawclawRoomTransportFrameMeta {
|
|
|
45
47
|
export interface ClawclawRoomTransportOptions {
|
|
46
48
|
url: string;
|
|
47
49
|
apiKey: string;
|
|
50
|
+
hostContext?: LobbyHostContext;
|
|
48
51
|
onOpened(connectionId: string, reconnected: boolean): Promise<void> | void;
|
|
49
52
|
onLiveness(connectionId: string, atMs: number): void;
|
|
50
53
|
onConnectionChanged(connectionId: string, state: 'reconnecting' | 'disconnected'): Promise<void> | void;
|
|
@@ -67,6 +70,7 @@ export interface ClawclawRoomTransportOptions {
|
|
|
67
70
|
heartbeatIntervalMs?: number;
|
|
68
71
|
pongTimeoutMs?: number;
|
|
69
72
|
reconnectMs?: number;
|
|
73
|
+
maxHandshakeFailures?: number;
|
|
70
74
|
initialSnapshotTimeoutMs?: number;
|
|
71
75
|
/** Maximum time to attach or reattach before the aggregate Source reconciles through Lobby HTTP. */
|
|
72
76
|
reconcileAfterMs?: number;
|
|
@@ -132,11 +136,17 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
|
|
|
132
136
|
private openedConnections = 0;
|
|
133
137
|
private physicalFrameSeq = 0;
|
|
134
138
|
private gameStartedEmitted = false;
|
|
139
|
+
private replacementReceived = false;
|
|
140
|
+
private handshakeFailures = 0;
|
|
141
|
+
private socketOpened = false;
|
|
142
|
+
private reconnectAttempts = 0;
|
|
143
|
+
private readonly hostHeaders: Record<string, string>;
|
|
135
144
|
private stopped = false;
|
|
136
145
|
private resolveOutcome!: (outcome: ClawclawRoomTransportOutcome) => void;
|
|
137
146
|
private readonly outcomePromise: Promise<ClawclawRoomTransportOutcome>;
|
|
138
147
|
|
|
139
148
|
constructor(private readonly options: ClawclawRoomTransportOptions) {
|
|
149
|
+
this.hostHeaders = options.hostContext ? lobbyHostHeaders(options.hostContext) : {};
|
|
140
150
|
this.webSocketFactory = options.webSocketFactory ?? ((url, init) => new WebSocket(url, init));
|
|
141
151
|
this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? 15_000;
|
|
142
152
|
this.pongTimeoutMs = options.pongTimeoutMs ?? 10_000;
|
|
@@ -185,22 +195,25 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
|
|
|
185
195
|
const connectionId = randomUUID();
|
|
186
196
|
this.connectionId = connectionId;
|
|
187
197
|
this.physicalFrameSeq = 0;
|
|
198
|
+
this.socketOpened = false;
|
|
188
199
|
let ws: WebSocket;
|
|
189
200
|
try {
|
|
190
201
|
ws = this.webSocketFactory(this.options.url, {
|
|
191
|
-
headers: { Authorization: `Bearer ${this.options.apiKey}
|
|
202
|
+
headers: { Authorization: `Bearer ${this.options.apiKey}`, ...this.hostHeaders },
|
|
192
203
|
});
|
|
193
204
|
} catch (error) {
|
|
194
205
|
this.options.onDiagnostic('runtime.source.connect_failed', {
|
|
195
206
|
transport: 'room_ws',
|
|
196
207
|
error: error instanceof Error ? error.message : String(error),
|
|
197
208
|
});
|
|
198
|
-
this.scheduleReconnect();
|
|
209
|
+
if (!this.recordHandshakeFailure()) this.scheduleReconnect();
|
|
199
210
|
return;
|
|
200
211
|
}
|
|
201
212
|
this.ws = ws;
|
|
202
213
|
ws.once('open', () => {
|
|
203
214
|
if (this.stopped || this.ws !== ws) return;
|
|
215
|
+
this.socketOpened = true;
|
|
216
|
+
this.handshakeFailures = 0;
|
|
204
217
|
const reconnected = this.openedConnections > 0;
|
|
205
218
|
this.openedConnections += 1;
|
|
206
219
|
this.enqueue(() => this.options.onOpened(connectionId, reconnected));
|
|
@@ -246,6 +259,13 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
|
|
|
246
259
|
return;
|
|
247
260
|
}
|
|
248
261
|
const type = typeof message?.type === 'string' ? message.type : '';
|
|
262
|
+
if (type === 'replaced') {
|
|
263
|
+
this.handleClose(connectionId, ws, {
|
|
264
|
+
code: 4002,
|
|
265
|
+
reason: typeof message.message === 'string' ? message.message : 'Lobby connection replaced',
|
|
266
|
+
});
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
249
269
|
if (!type) {
|
|
250
270
|
this.options.onDiagnostic('runtime.input.rejected', { reason: 'room_ws_message_without_type' });
|
|
251
271
|
return;
|
|
@@ -264,8 +284,10 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
|
|
|
264
284
|
replay: type === 'room.snapshot',
|
|
265
285
|
};
|
|
266
286
|
this.enqueue(async () => {
|
|
287
|
+
if (this.replacementReceived) return;
|
|
267
288
|
let terminalPhase: 'room_left' | undefined;
|
|
268
289
|
if (type === 'room.snapshot') {
|
|
290
|
+
this.reconnectAttempts = 0;
|
|
269
291
|
this.clearSnapshotDeadline();
|
|
270
292
|
this.clearAttachDeadline();
|
|
271
293
|
this.latestSnapshot = normalizeRoomSnapshot(data);
|
|
@@ -283,6 +305,7 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
|
|
|
283
305
|
terminalPhase,
|
|
284
306
|
meta,
|
|
285
307
|
});
|
|
308
|
+
if (this.replacementReceived) return;
|
|
286
309
|
const started = gameStartedFromRoomSnapshot(this.latestSnapshot);
|
|
287
310
|
if (started && !this.gameStartedEmitted) {
|
|
288
311
|
this.gameStartedEmitted = true;
|
|
@@ -386,12 +409,16 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
|
|
|
386
409
|
info: ClawclawRoomCloseInfo,
|
|
387
410
|
): void {
|
|
388
411
|
if (this.stopped || this.ws !== ws || this.connectionId !== connectionId) return;
|
|
412
|
+
if (info.code === 4002) this.replacementReceived = true;
|
|
413
|
+
const handshakeFailed = !this.socketOpened;
|
|
389
414
|
this.clearTimers();
|
|
390
415
|
this.clearSocket();
|
|
391
416
|
this.enqueue(async () => {
|
|
392
|
-
await this.options.
|
|
393
|
-
const decision =
|
|
417
|
+
const classified = await this.options.onClosed(connectionId, info);
|
|
418
|
+
const decision = this.replacementReceived ? 'replaced' : classified;
|
|
419
|
+
await this.options.onConnectionChanged(connectionId, decision === 'retry' ? 'reconnecting' : 'disconnected');
|
|
394
420
|
if (decision === 'retry') {
|
|
421
|
+
if (handshakeFailed && this.recordHandshakeFailure()) return;
|
|
395
422
|
this.options.onDiagnostic('runtime.source.input_gap', {
|
|
396
423
|
reason: 'room_ws_disconnected',
|
|
397
424
|
connection_id: connectionId,
|
|
@@ -402,21 +429,29 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
|
|
|
402
429
|
this.scheduleReconnect();
|
|
403
430
|
return;
|
|
404
431
|
}
|
|
405
|
-
this.finish({ reason: decision
|
|
432
|
+
this.finish({ reason: decision, ...(decision === 'fatal'
|
|
433
|
+
? { error: new Error(`Lobby WebSocket closed (${info.code ?? 'unknown'}): ${info.reason}`) } : {}) });
|
|
406
434
|
});
|
|
407
435
|
}
|
|
408
436
|
|
|
409
437
|
private scheduleReconnect(): void {
|
|
410
|
-
if (this.stopped || this.reconnectTimer) return;
|
|
438
|
+
if (this.stopped || this.replacementReceived || this.reconnectTimer) return;
|
|
411
439
|
this.startAttachDeadline();
|
|
412
440
|
this.clearSocket();
|
|
441
|
+
const delay = Math.min(30_000, this.reconnectMs * 2 ** Math.min(this.reconnectAttempts++, 5));
|
|
413
442
|
this.reconnectTimer = setTimeout(() => {
|
|
414
443
|
this.reconnectTimer = undefined;
|
|
415
444
|
this.openSocket();
|
|
416
|
-
},
|
|
445
|
+
}, delay);
|
|
417
446
|
this.reconnectTimer.unref?.();
|
|
418
447
|
}
|
|
419
448
|
|
|
449
|
+
private recordHandshakeFailure(): boolean {
|
|
450
|
+
if (++this.handshakeFailures < (this.options.maxHandshakeFailures ?? 3)) return false;
|
|
451
|
+
this.finish({ reason: 'fatal', error: new Error('Lobby WebSocket handshake repeatedly failed; check credentials and host context before retrying.') });
|
|
452
|
+
return true;
|
|
453
|
+
}
|
|
454
|
+
|
|
420
455
|
private send(message: Record<string, unknown>, ws = this.ws): void {
|
|
421
456
|
if (!ws || ws !== this.ws || ws.readyState !== WebSocket.OPEN) return;
|
|
422
457
|
ws.send(JSON.stringify(message));
|
|
@@ -424,7 +459,9 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
|
|
|
424
459
|
|
|
425
460
|
private enqueue(operation: () => void | Promise<void>): void {
|
|
426
461
|
if (this.stopped) return;
|
|
427
|
-
this.operationTail = this.operationTail.then(
|
|
462
|
+
this.operationTail = this.operationTail.then(() => {
|
|
463
|
+
if (!this.stopped) return operation();
|
|
464
|
+
}).catch((error) => {
|
|
428
465
|
this.finish({ reason: 'error', error });
|
|
429
466
|
});
|
|
430
467
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { isInvalidHostContextError } from '../../../../lib/lobby-host-context.js';
|
|
2
3
|
import type { AuthProfile } from '../../../../lib/auth.js';
|
|
3
4
|
import { trainingCharacterId } from '../../../../lib/training-role.js';
|
|
4
5
|
import {
|
|
@@ -683,6 +684,8 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
683
684
|
lifecycleEvents: (queue: Record<string, any>) => Record<string, unknown>[],
|
|
684
685
|
): Promise<Record<string, any>> {
|
|
685
686
|
const maintenance = serverServiceStatusFromApiError(originalError);
|
|
687
|
+
// Invalid host declarations did not create a participation; do not adopt an unrelated one.
|
|
688
|
+
if (isInvalidHostContextError(originalError)) throw originalError;
|
|
686
689
|
if (maintenance) {
|
|
687
690
|
await this.acceptServiceStatus(maintenance);
|
|
688
691
|
throw originalError;
|
|
@@ -1007,6 +1010,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
1007
1010
|
const transport = this.createRoomTransport({
|
|
1008
1011
|
url: this.client.lobbyAgentWsUrl,
|
|
1009
1012
|
apiKey: this.profile.apiKey,
|
|
1013
|
+
hostContext: this.client.lobbyHostContext,
|
|
1010
1014
|
webSocketFactory: this.roomWebSocketFactory,
|
|
1011
1015
|
onOpened: async (connectionId, reconnected) => {
|
|
1012
1016
|
this.activeRoomConnectionId = connectionId;
|
|
@@ -1054,6 +1058,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
1054
1058
|
status: 'allocated',
|
|
1055
1059
|
mode: roomMode,
|
|
1056
1060
|
room_code: outcome.roomCode ?? roomCode,
|
|
1061
|
+
participation: queue.participation ?? null,
|
|
1057
1062
|
...outcome.event,
|
|
1058
1063
|
},
|
|
1059
1064
|
};
|
|
@@ -1066,7 +1071,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
1066
1071
|
return { kind: 'complete', completion: { reason: 'maintenance' } };
|
|
1067
1072
|
}
|
|
1068
1073
|
if (outcome.reason === 'replaced') return { kind: 'complete', completion: { reason: 'replaced' } };
|
|
1069
|
-
if (outcome.reason === 'shutdown' || outcome.reason === 'manual') {
|
|
1074
|
+
if (outcome.reason === 'shutdown' || outcome.reason === 'manual' || outcome.reason === 'normal') {
|
|
1070
1075
|
return { kind: 'complete', completion: { reason: 'stopped' } };
|
|
1071
1076
|
}
|
|
1072
1077
|
if (outcome.reason === 'fatal' || outcome.reason === 'error') {
|
|
@@ -1780,11 +1785,13 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
1780
1785
|
}
|
|
1781
1786
|
|
|
1782
1787
|
private classifyRoomClose(code: number | undefined, reason: string): ClawclawRoomCloseDecision {
|
|
1788
|
+
if (code === 4002) return 'replaced';
|
|
1789
|
+
if (code === 1000) return 'normal';
|
|
1783
1790
|
if (code === 4005) return 'room_destroyed';
|
|
1784
1791
|
if (code === 4006 || /service_maintenance/i.test(reason)) return 'maintenance';
|
|
1785
|
-
if (code === 4002) return 'replaced';
|
|
1786
1792
|
if (code === 4001) return 'fatal';
|
|
1787
|
-
if (code === 4003) return '
|
|
1793
|
+
if (code === 4003) return 'fatal';
|
|
1794
|
+
if (code === 4004) return 'reconcile';
|
|
1788
1795
|
if (/not in room|already left/i.test(reason)) return 'reconcile';
|
|
1789
1796
|
return 'retry';
|
|
1790
1797
|
}
|
|
@@ -1794,6 +1801,13 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
1794
1801
|
info: ClawclawRoomCloseInfo,
|
|
1795
1802
|
): Promise<ClawclawRoomCloseDecision> {
|
|
1796
1803
|
const decision = this.classifyRoomClose(info.code, info.reason);
|
|
1804
|
+
if (decision === 'replaced') {
|
|
1805
|
+
this.currentConnection = 'disconnected';
|
|
1806
|
+
await this.submitCurrentState('control', CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, [{
|
|
1807
|
+
type: 'lobby_connection_replaced', route: '/agent/ws', close_code: 4002,
|
|
1808
|
+
reason: info.reason, retryable: false,
|
|
1809
|
+
}]);
|
|
1810
|
+
}
|
|
1797
1811
|
if (decision === 'room_destroyed') {
|
|
1798
1812
|
this.requireRuntime().connectionChanged(
|
|
1799
1813
|
CLAWCLAW_ROOM_WS_SOURCE.sourceId,
|
|
@@ -2394,7 +2408,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
2394
2408
|
events: completion.reason === 'error'
|
|
2395
2409
|
? this.localEvents([{
|
|
2396
2410
|
type: 'error',
|
|
2397
|
-
code: 'SOURCE_FAILED',
|
|
2411
|
+
code: isInvalidHostContextError(completion.error) ? 'INVALID_HOST_CONTEXT' : 'SOURCE_FAILED',
|
|
2398
2412
|
phase: 'runtime',
|
|
2399
2413
|
message: errorMessage,
|
|
2400
2414
|
...(this.participationMode ? { game_mode: this.participationMode } : {}),
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { QueueMode } from '../../../../lib/competition.js';
|
|
2
|
+
import type { LobbyHostContext } from '../../../../lib/lobby-host-context.js';
|
|
2
3
|
import type { ClawclawRoleId } from '../../../../lib/gameplay-config.js';
|
|
3
4
|
import type {
|
|
4
5
|
CreateRoomOptions,
|
|
@@ -16,6 +17,7 @@ import type {
|
|
|
16
17
|
} from './room-transport.js';
|
|
17
18
|
|
|
18
19
|
export interface ClawclawSourceClient extends ClawclawGameTransportClient {
|
|
20
|
+
readonly lobbyHostContext?: LobbyHostContext;
|
|
19
21
|
readonly lobbyAgentWsUrl: string;
|
|
20
22
|
getQueueStatus(gameType?: string): Promise<any>;
|
|
21
23
|
getSettlement(): Promise<any>;
|
|
@@ -7,6 +7,8 @@ type SabotageStatus = 'ready' | 'cooldown_charged' | 'emergency_active';
|
|
|
7
7
|
|
|
8
8
|
/** Shared sabotage availability belongs to the game, not to a strategy instance. */
|
|
9
9
|
export class SabotageAvailabilityRule implements ClawclawDerivedEventRule {
|
|
10
|
+
save() { return { boundary: this.boundary, status: this.status }; }
|
|
11
|
+
restore(state: any) { this.boundary = state?.boundary; this.status = state?.status; }
|
|
10
12
|
readonly id = 'sabotage-availability';
|
|
11
13
|
readonly eventTypes = ['ability.ready', 'ability.unavailable'] as const;
|
|
12
14
|
private boundary?: string;
|
|
@@ -1,83 +1,144 @@
|
|
|
1
1
|
import { prepareNotificationContent, notificationStateAt } from '../perception/notification-content.js';
|
|
2
|
-
import type { RuntimeEpochPluginContext, RuntimeEpochPluginInput
|
|
2
|
+
import type { RuntimeEpochPluginContext, RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
|
|
3
3
|
import { CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, CLAWCLAW_LOCAL_AGENT_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
|
|
4
4
|
import { BUILTIN_PERCEPTION_PREFIX, CLAWCLAW_SYSTEM_CONTROL_EVENTS } from '../../notification-policy.js';
|
|
5
5
|
import { AbilityStateDerivedEventRule, EmergencyCountdownDerivedEventRule, RoomReadyDerivedEventRule,
|
|
6
6
|
type ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
|
|
7
7
|
import { PlayerChangesDerivedEventRule } from '../derived-event/state-change-rules.js';
|
|
8
|
-
import { PerceptionRuleRunner } from './rule-runner.js';
|
|
9
8
|
import { defaultReminder, TASK_LIFECYCLE_FACT_TYPES } from '../../../../sdk/perception-plugin/reminder-rules.js';
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
9
|
+
import { ClawclawPerception, type PerceptionModuleInput, type PerceptionModuleResult } from '../../../../sdk/perception-plugin/index.js';
|
|
10
|
+
import type { StoredStateFrame } from '../../../framework/state/index.js';
|
|
11
|
+
import type { CanonicalEvent } from '../../../framework/events/index.js';
|
|
13
12
|
import { SabotageAvailabilityRule } from './sabotage-availability-rule.js';
|
|
13
|
+
import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
|
|
14
|
+
import type { PerceptionAdapter, PerceptionBoundary } from '@myclaw163/game-agent-runtime/perception/contracts.js';
|
|
15
|
+
import { perceptionInputBoundary, type PerceptionInputBaseline } from '../perception/module-input-boundary.js';
|
|
16
|
+
import { comparePerceptionTasks, type PerceptionTaskBaseline } from '../perception/task-baseline.js';
|
|
17
|
+
import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
|
|
14
18
|
|
|
15
19
|
export const BUILTIN_PERCEPTION_NAMES = {
|
|
16
20
|
players: '玩家变化', tasks: '任务提醒', abilities: '能力变化', emergency: '紧急任务',
|
|
17
21
|
flow: '房间与游戏流程', meeting: '会议', behavior: '策略消息',
|
|
18
22
|
} as const;
|
|
19
23
|
type Domain = keyof typeof BUILTIN_PERCEPTION_NAMES;
|
|
20
|
-
interface
|
|
24
|
+
interface NativeState { rules: Record<string, unknown> }
|
|
21
25
|
|
|
22
|
-
/** Native
|
|
23
|
-
|
|
24
|
-
readonly
|
|
25
|
-
|
|
26
|
-
override
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
cursor = event.commitSeq;
|
|
53
|
-
if (event.notificationOf || !this.forwardedTypes.includes(event.type)) continue;
|
|
54
|
-
if (this.domain === 'behavior' ? event.producerPluginId !== 'clawclaw.behavior' : event.producerPluginId !== undefined) continue;
|
|
55
|
-
events.push({ type: event.type, forwardEventId: event.eventId, dedupeKey: event.eventId, payload: {},
|
|
56
|
-
notificationContent: prepareNotificationContent(event.type, event.payload, notificationStateAt(context, event.epochSeq), 'builtin', event) });
|
|
26
|
+
/** Native modules use the same evaluate/input/result contract as installed scripts. */
|
|
27
|
+
class NativePerceptionModule extends ClawclawPerception {
|
|
28
|
+
constructor(private readonly domain: Domain, private readonly forwarded: readonly string[],
|
|
29
|
+
private readonly rules: readonly ClawclawDerivedEventRule[]) { super(); }
|
|
30
|
+
override evaluate(input: Readonly<PerceptionModuleInput>): PerceptionModuleResult {
|
|
31
|
+
const prior = input.state as NativeState | undefined;
|
|
32
|
+
const source = input.source!;
|
|
33
|
+
const frame: StoredStateFrame<Record<string, any>> = {
|
|
34
|
+
frameSeq: source.frameSeq, epochSeq: source.epochId,
|
|
35
|
+
scope: { ...input.scope, adapterId: 'clawclaw', accountId: '' },
|
|
36
|
+
sourceId: 'clawclaw.perception-input', sourceKey: input.frame?.frameKey ?? `epoch:${source.epochId}`,
|
|
37
|
+
connectionId: source.connectionId, backendTick: source.backendTick,
|
|
38
|
+
receivedAtMs: source.receivedAtMs, observedAtMs: source.observedAtMs,
|
|
39
|
+
state: { schema: 'clawclaw.runtime-state.v1', stage: input.roomState ? 'room' : input.gameState?.phase === 'meeting' ? 'meeting' : 'game',
|
|
40
|
+
connection: 'connected', transport: 'none', cause: 'processing_cycle', room: input.roomState,
|
|
41
|
+
game_snapshot: input.gameState ? { status: 'cached', state: input.gameState } : { status: 'not_updated' } },
|
|
42
|
+
};
|
|
43
|
+
const facts = input.events.map(event => ({ type: event.type, payload: { ...event.payload }, producer: event.producer,
|
|
44
|
+
sourceEventId: event.eventId, observedAt: event.occurredAt, replayed: event.replayed }));
|
|
45
|
+
const events: NonNullable<PerceptionModuleResult['events']>[number][] = [];
|
|
46
|
+
const state: NativeState = { rules: {} };
|
|
47
|
+
for (const rule of this.rules) {
|
|
48
|
+
rule.reset();
|
|
49
|
+
if (input.boundary !== 'recovery') rule.restore?.(prior?.rules[rule.id]);
|
|
50
|
+
const proposals = rule.inspect(frame, facts);
|
|
51
|
+
state.rules[rule.id] = rule.save?.();
|
|
52
|
+
if (input.boundary !== 'recovery') for (const event of proposals) events.push({
|
|
53
|
+
type: event.type, key: event.dedupeKey ?? `${source.epochId}:${event.type}`,
|
|
54
|
+
payload: event.payload ?? {}, wakeAgent: event.wakeAgent, occurredAt: event.occurredAt,
|
|
55
|
+
});
|
|
57
56
|
}
|
|
58
57
|
if (this.domain === 'tasks') {
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
const boundary = game && this.taskState.gameId !== game.game_id ? 'initial'
|
|
62
|
-
: this.taskState.connectionId !== undefined && this.taskState.connectionId !== input.epoch.connectionId ? 'recovery' : null;
|
|
63
|
-
this.taskState = { gameId: game?.game_id ?? this.taskState.gameId, connectionId: input.epoch.connectionId };
|
|
64
|
-
// Task facts have one notification owner. Do not recreate them from State differences.
|
|
65
|
-
const result = defaultReminder('tasks', { scope: input.epoch.scope, gameState: game, frame: null,
|
|
66
|
-
facts: input.pendingEvents.filter(event => !event.notificationOf && event.producerPluginId === undefined).map(event => ({
|
|
67
|
-
eventId: event.eventId, epochId: event.epochSeq, type: event.type, occurredAt: event.occurredAt,
|
|
68
|
-
producer: event.producer, replayed: event.replayed, payload: projectTaskChoiceEventPayload(game, event.type, event.payload),
|
|
69
|
-
})), taskChanges: [], boundary, config: {}, state: undefined,
|
|
70
|
-
nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs });
|
|
71
|
-
for (const event of result.events ?? []) events.push({ type: event.type, dedupeKey: event.key,
|
|
72
|
-
wakeAgent: event.wakeAgent, payload: { ...event.payload }, occurredAt: new Date(input.frame.receivedAtMs).toISOString() });
|
|
58
|
+
const result = defaultReminder('tasks', { ...input, facts: input.events, taskChanges: [], config: {} });
|
|
59
|
+
events.push(...result.events ?? []);
|
|
73
60
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
61
|
+
return { state, events, forwards: input.events.filter(event => this.forwarded.includes(event.type))
|
|
62
|
+
.map(event => ({ eventId: event.eventId })) };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface PreparedNative {
|
|
67
|
+
input: RuntimeEpochPluginInput<Record<string, any>>;
|
|
68
|
+
common: ReturnType<typeof perceptionInputBoundary>['common'];
|
|
69
|
+
facts: CanonicalEvent[];
|
|
70
|
+
context: RuntimeEpochPluginContext<Record<string, any>>;
|
|
71
|
+
}
|
|
72
|
+
function nativeAdapter(domain: Domain, forwarded: readonly string[], rules: readonly ClawclawDerivedEventRule[]): PerceptionAdapter {
|
|
73
|
+
const module = new NativePerceptionModule(domain, forwarded, rules);
|
|
74
|
+
const prepared = (boundary: PerceptionBoundary) => boundary.value as PreparedNative;
|
|
75
|
+
return {
|
|
76
|
+
reset: () => {}, recover: checkpoint => (checkpoint as { adapterState?: unknown })?.adapterState,
|
|
77
|
+
prepare(input, previous, context) {
|
|
78
|
+
if (!context) throw Error('NATIVE_PERCEPTION_CONTEXT_MISSING');
|
|
79
|
+
const shared = perceptionInputBoundary(input, previous as PerceptionInputBaseline | undefined);
|
|
80
|
+
const eligible = [] as CanonicalEvent[];
|
|
81
|
+
let cursor = context.progress().eventCursor;
|
|
82
|
+
for (const event of input.pendingEvents) {
|
|
83
|
+
if (domain === 'behavior' && event.producerPluginId === 'clawclaw.behavior'
|
|
84
|
+
&& (event.epochSeq ?? input.epoch.epochSeq) >= input.epoch.epochSeq) break;
|
|
85
|
+
cursor = event.commitSeq;
|
|
86
|
+
if (event.notificationOf) continue;
|
|
87
|
+
if (domain === 'behavior' ? event.producerPluginId !== 'clawclaw.behavior' : event.producerPluginId !== undefined) continue;
|
|
88
|
+
eligible.push(event);
|
|
89
|
+
}
|
|
90
|
+
return { state: shared.state, identity: shared.state.scope, resetScope: shared.initial, resetModules: false,
|
|
91
|
+
notificationOnly: false, nowMs: shared.common.nowMs, reflexAllowed: false, consumeEventsThroughCommitSeq: cursor,
|
|
92
|
+
value: { input, common: shared.common, facts: eligible, context } satisfies PreparedNative };
|
|
93
|
+
},
|
|
94
|
+
configure: (_source, config) => config, describe: source => ({ id: source.id, name: source.name }),
|
|
95
|
+
createRunner: () => ({ start: async () => {}, stop: async () => {},
|
|
96
|
+
evaluate: async invocation => module.evaluate(invocation.value as PerceptionModuleInput) }),
|
|
97
|
+
input(source, boundary, inputState, state, config, bindings) {
|
|
98
|
+
const p = prepared(boundary);
|
|
99
|
+
const facts = p.facts.filter(e => source.module.consumes?.includes(e.type));
|
|
100
|
+
const eventStates = Object.fromEntries(facts.map(e => [e.eventId, notificationStateAt(p.context, e.epochSeq)]));
|
|
101
|
+
const comparison = comparePerceptionTasks(inputState as PerceptionTaskBaseline | undefined, p.input, p.common.boundary);
|
|
102
|
+
const value: PerceptionModuleInput = { ...p.common, moduleId: source.id, config, state, ...bindings,
|
|
103
|
+
availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes,
|
|
104
|
+
events: facts.map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type, occurredAt: e.occurredAt,
|
|
105
|
+
producer: e.producer, replayed: e.replayed, receivedAt: e.receivedAt, wakeAgent: e.wakeAgent,
|
|
106
|
+
payload: projectTaskChoiceEventPayload(eventStates[e.eventId], e.type, e.payload) })),
|
|
107
|
+
eventStates,
|
|
108
|
+
};
|
|
109
|
+
return { invocation: { scope: value.scope, value }, inputState: comparison.baseline, evaluate: true };
|
|
110
|
+
},
|
|
111
|
+
forward(eventId, boundary) {
|
|
112
|
+
const event = prepared(boundary).facts.find(e => e.eventId === eventId && forwarded.includes(e.type));
|
|
113
|
+
if (!event) throw Error('PERCEPTION_FORWARD_NOT_AUTHORIZED');
|
|
114
|
+
return { type: event.type, forwardEventId: eventId, dedupeKey: eventId, payload: {} };
|
|
115
|
+
},
|
|
116
|
+
notification(proposal, boundary) {
|
|
117
|
+
const p = prepared(boundary);
|
|
118
|
+
const original = proposal.forwardEventId ? p.facts.find(e => e.eventId === proposal.forwardEventId) : undefined;
|
|
119
|
+
return prepareNotificationContent(proposal.type, original?.payload ?? proposal.payload ?? {},
|
|
120
|
+
original ? notificationStateAt(p.context, original.epochSeq) : p.common.gameState,
|
|
121
|
+
'builtin', original ?? { producer: 'local_synth', producerPluginId: `${BUILTIN_PERCEPTION_PREFIX}${domain}` });
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Host registration, not module text, grants mandatory status and forwarding authority. */
|
|
127
|
+
export class SystemPerceptionPlugin extends PerceptionHost {
|
|
128
|
+
constructor(readonly domain: Domain, forwarded: readonly string[], rules: readonly ClawclawDerivedEventRule[] = []) {
|
|
129
|
+
const consumes = [...new Set([...rules.flatMap(rule => rule.consumes ?? []), ...forwarded,
|
|
130
|
+
...(domain === 'tasks' ? TASK_LIFECYCLE_FACT_TYPES : [])])];
|
|
131
|
+
const produces = [...new Set([...rules.flatMap(rule => rule.eventTypes), ...forwarded,
|
|
132
|
+
...(domain === 'tasks' ? ['reminder.task'] : [])])];
|
|
133
|
+
super({ id: `${BUILTIN_PERCEPTION_PREFIX}${domain}`, after: [],
|
|
134
|
+
sources: [{ id: domain, name: BUILTIN_PERCEPTION_NAMES[domain], module: { consumes, produces }, value: null }],
|
|
135
|
+
adapter: nativeAdapter(domain, forwarded, rules),
|
|
136
|
+
// Mandatory native rules must account for every accepted fact in a source batch.
|
|
137
|
+
// Custom workers retain the host's default per-result budgets.
|
|
138
|
+
resultLimits: { events: Infinity, bytes: Infinity },
|
|
139
|
+
notificationRelay: domain === 'behavior'
|
|
140
|
+
? { producerPluginIds: ['clawclaw.behavior'], previousEpochOnly: true } : { sourceEvents: true },
|
|
77
141
|
});
|
|
78
|
-
return { outcome: events.length ? 'processed' : 'noop', events: notifications,
|
|
79
|
-
...(this.domain === 'tasks' ? { checkpoint: structuredClone(this.taskState) } : {}),
|
|
80
|
-
...(cursor === undefined ? {} : { consumeEventsThroughCommitSeq: cursor }) };
|
|
81
142
|
}
|
|
82
143
|
}
|
|
83
144
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Frozen API v2 compatibility version; new modules use PERCEPTION_MODULE_API_VERSION (3). */
|
|
2
2
|
export const PERCEPTION_PLUGIN_API_VERSION = 2 as const;
|
|
3
3
|
export * from './module.js';
|
|
4
|
+
export * from './lifecycle.js';
|
|
4
5
|
import { Perception } from '@myclaw163/game-agent-runtime/sdk/perception.js';
|
|
5
6
|
import type { PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleApi } from './module.js';
|
|
6
7
|
export { ClawclawReaction } from './reaction.js';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { PerceptionModuleInput, PerceptionLifecycleChange } from './module.js';
|
|
2
|
+
|
|
3
|
+
export function hasPerceptionBoundary(input: Pick<PerceptionModuleInput, 'lifecycle'>, kind: PerceptionLifecycleChange['kind']): boolean {
|
|
4
|
+
return input.lifecycle?.some(change => change.kind === kind) ?? false;
|
|
5
|
+
}
|
|
6
|
+
export function enteredPhase(input: Pick<PerceptionModuleInput, 'lifecycle'>, phase: string): boolean {
|
|
7
|
+
return input.lifecycle?.some(change => change.kind === 'phase_changed' && change.to === phase) ?? false;
|
|
8
|
+
}
|
|
9
|
+
export function leftPhase(input: Pick<PerceptionModuleInput, 'lifecycle'>, phase: string): boolean {
|
|
10
|
+
return input.lifecycle?.some(change => change.kind === 'phase_changed' && change.from === phase) ?? false;
|
|
11
|
+
}
|
|
12
|
+
/** Return a new module state; never mutates the read-only input or another module. */
|
|
13
|
+
export function resetPerceptionState<T extends object>(state: Readonly<T>, replacement: Partial<T>): T {
|
|
14
|
+
return { ...state, ...replacement };
|
|
15
|
+
}
|
|
@@ -27,6 +27,13 @@ export interface PerceptionModuleManifest {
|
|
|
27
27
|
readonly behaviors?: Readonly<Record<string, ReactionBehaviorBinding>>;
|
|
28
28
|
}
|
|
29
29
|
export interface PerceptionModuleInput {
|
|
30
|
+
readonly source?: Readonly<{ epochId: number; frameSeq: number; connectionId: string; backendTick?: number; receivedAtMs: number; observedAtMs?: number }>;
|
|
31
|
+
/** Explicit boundaries; the host does not erase module state on a phase change. */
|
|
32
|
+
readonly lifecycle?: readonly PerceptionLifecycleChange[];
|
|
33
|
+
readonly roomState?: Readonly<Record<string, unknown>> | null;
|
|
34
|
+
readonly queueState?: Readonly<Record<string, unknown>> | null;
|
|
35
|
+
/** Source facts keep their own accepted State boundary, distinct from gameState. */
|
|
36
|
+
readonly eventStates?: Readonly<Record<string, Readonly<Record<string, unknown>> | null>>;
|
|
30
37
|
readonly cycle?: import('../module-input/index.js').ProcessingCycleInfo;
|
|
31
38
|
readonly moduleId: string;
|
|
32
39
|
readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
|
|
@@ -47,6 +54,7 @@ export interface PerceptionModuleInput {
|
|
|
47
54
|
readonly enabledBindings?: readonly string[];
|
|
48
55
|
}
|
|
49
56
|
export interface PerceptionModuleApi {
|
|
57
|
+
readonly spatial?: import('../behavior-plugin/index.js').SpatialApi;
|
|
50
58
|
/** Shared with a unique explicitly bound strategy; otherwise module-private. */
|
|
51
59
|
readonly memory: StrategyMemory;
|
|
52
60
|
}
|
|
@@ -56,10 +64,17 @@ export interface PerceptionModuleEvent {
|
|
|
56
64
|
/** false retains the event for a later wake; omit the event to produce no notification. */
|
|
57
65
|
readonly wakeAgent?: boolean;
|
|
58
66
|
readonly payload: Readonly<Record<string, unknown>>;
|
|
67
|
+
readonly occurredAt?: string;
|
|
59
68
|
}
|
|
60
69
|
export interface PerceptionModuleResult {
|
|
61
70
|
readonly state?: unknown;
|
|
62
71
|
readonly events?: readonly PerceptionModuleEvent[];
|
|
72
|
+
/** Requires host registration authority; user manifests cannot grant it. */
|
|
73
|
+
readonly forwards?: readonly { readonly eventId: string }[];
|
|
63
74
|
/** Keys in manifest.behaviors; never arbitrary strategy names or executable Actions. */
|
|
64
75
|
readonly activations?: readonly (PerceptionStrategyActivation | ReactionActivation)[];
|
|
65
76
|
}
|
|
77
|
+
|
|
78
|
+
export type PerceptionLifecycleChange =
|
|
79
|
+
| Readonly<{ kind: 'initial' | 'recovery' | 'observation_gap' | 'observer_died' | 'segment_ending' | 'snapshot_requested' }>
|
|
80
|
+
| Readonly<{ kind: 'phase_changed'; from: string; to: string }>;
|