@myclaw163/clawclaw-cli 0.8.13 → 0.8.15
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/custom-modules/perception.md +4 -4
- package/docs/runtime/README.md +1 -1
- package/docs/runtime/behavior-runtime.md +1 -1
- package/docs/runtime/official-perception-modules.md +23 -30
- package/docs/runtime/perception-replay.md +1 -1
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +8 -4
- package/skills/clawclaw/references/BEHAVIORS.md +16 -1
- package/skills/clawclaw/references/CHANNELS.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +2 -2
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
- package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
- package/skills/clawclaw/references/STREAM.md +4 -2
- package/src/lib/game-client.ts +12 -4
- package/src/pipeline/event-format.ts +5 -0
- package/src/pipeline/event-hints.ts +10 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
- package/src/runtime/clawclaw/behavior-decision.ts +4 -1
- package/src/runtime/clawclaw/behavior-input.ts +5 -0
- package/src/runtime/clawclaw/owner.ts +64 -1
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
- package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
- package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +201 -43
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +45 -9
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +170 -8
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
- package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +33 -9
- package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
- package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +327 -23
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
- package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
- package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
- package/src/runtime/clawclaw/runtime.ts +31 -3
- package/src/runtime/clawclaw-event-catalog.ts +3 -0
- package/src/runtime/framework/events/event-repository.ts +1 -1
- package/src/runtime/framework/events/memory-event-repository.ts +71 -1
- package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
- package/src/runtime/framework/mailbox/types.ts +2 -0
- package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +383 -0
- package/src/runtime/framework/plugins/contracts.ts +5 -2
- package/src/runtime/framework/plugins/runtime-input-journal.ts +185 -17
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +173 -34
- package/src/runtime/framework/runtime.ts +75 -4
- package/src/runtime/framework/state/history/contracts.ts +9 -1
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +59 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
- package/src/runtime/observability/redaction.ts +28 -1
- package/src/sdk/behavior-plugin/index.ts +5 -24
- package/src/sdk/module-input/index.ts +47 -0
- package/src/sdk/perception-plugin/index.ts +13 -8
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
2
|
+
import {
|
|
3
|
+
PERCEPTION_PLUGIN_API_VERSION,
|
|
4
|
+
type ClawclawPerception,
|
|
5
|
+
type ClawclawPerceptionClass,
|
|
6
|
+
type PerceptionAnalysisInput,
|
|
7
|
+
type PerceptionBoundary,
|
|
8
|
+
type PerceptionFrame,
|
|
9
|
+
} from '../../../../sdk/perception-plugin/index.js';
|
|
10
|
+
import { createSpatialApi, type SpatialFacts } from '../../spatial-api.js';
|
|
11
|
+
import type { PerceptionThreadModuleSpec } from './perception-module-loader.js';
|
|
12
|
+
import { normalizePerceptionEvents } from './perception-module-output.js';
|
|
13
|
+
import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
|
|
14
|
+
|
|
15
|
+
type ResetReason = Exclude<PerceptionBoundary['kind'], 'events_requested'> | 'replay';
|
|
16
|
+
type ReducerOperation = 'update' | 'commit' | 'flush' | 'reset';
|
|
17
|
+
|
|
18
|
+
interface PerceptionReducerWorkerData {
|
|
19
|
+
readonly poolId: string;
|
|
20
|
+
readonly laneId: number;
|
|
21
|
+
readonly modules: readonly PerceptionThreadModuleSpec[];
|
|
22
|
+
readonly spatialFacts: SpatialFacts;
|
|
23
|
+
readonly diagnosticsEnabled?: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface PerceptionReducerRequest {
|
|
27
|
+
readonly type: 'operate';
|
|
28
|
+
readonly poolId: string;
|
|
29
|
+
readonly requestId: string;
|
|
30
|
+
readonly moduleId: string;
|
|
31
|
+
readonly operation: ReducerOperation;
|
|
32
|
+
readonly frame?: PerceptionFrame;
|
|
33
|
+
readonly analysis?: unknown;
|
|
34
|
+
readonly boundary?: PerceptionBoundary;
|
|
35
|
+
readonly reason?: ResetReason;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
|
|
39
|
+
if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
|
|
40
|
+
const object = value as object;
|
|
41
|
+
if (seen.has(object)) return value;
|
|
42
|
+
seen.add(object);
|
|
43
|
+
for (const child of Object.values(object)) deepFreeze(child, seen);
|
|
44
|
+
return Object.freeze(value);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function errorMessage(error: unknown): string {
|
|
48
|
+
return error instanceof Error ? error.message : String(error);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function errorCode(error: unknown): string {
|
|
52
|
+
const message = errorMessage(error).trim();
|
|
53
|
+
return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message)?.[1]
|
|
54
|
+
?? 'PERCEPTION_REDUCER_OPERATION_FAILED';
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const port = parentPort;
|
|
58
|
+
if (!port) throw new Error('perception_reducer_worker_parent_missing');
|
|
59
|
+
const data = workerData as Partial<PerceptionReducerWorkerData> | undefined;
|
|
60
|
+
if (
|
|
61
|
+
!data
|
|
62
|
+
|| typeof data.poolId !== 'string'
|
|
63
|
+
|| !data.poolId
|
|
64
|
+
|| typeof data.laneId !== 'number'
|
|
65
|
+
|| !Array.isArray(data.modules)
|
|
66
|
+
|| data.modules.length === 0
|
|
67
|
+
|| !data.spatialFacts
|
|
68
|
+
|| typeof data.spatialFacts !== 'object'
|
|
69
|
+
) throw new Error('perception_reducer_worker_data_invalid');
|
|
70
|
+
|
|
71
|
+
function diagnosticMemory(): Readonly<Record<string, number>> {
|
|
72
|
+
return data?.diagnosticsEnabled === true
|
|
73
|
+
? { heapUsedBytes: process.memoryUsage().heapUsed }
|
|
74
|
+
: {};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function send(value: Readonly<Record<string, unknown>>): void {
|
|
78
|
+
port!.postMessage({
|
|
79
|
+
...value,
|
|
80
|
+
poolId: data!.poolId!,
|
|
81
|
+
laneId: data!.laneId!,
|
|
82
|
+
...diagnosticMemory(),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function validateClass(
|
|
87
|
+
spec: PerceptionThreadModuleSpec,
|
|
88
|
+
loaded: Record<string, unknown>,
|
|
89
|
+
): ClawclawPerceptionClass {
|
|
90
|
+
if (typeof loaded.default !== 'function') {
|
|
91
|
+
throw new Error('perception_reducer_worker_class_missing');
|
|
92
|
+
}
|
|
93
|
+
const ModuleClass = loaded.default as unknown as ClawclawPerceptionClass;
|
|
94
|
+
const manifest = ModuleClass.manifest;
|
|
95
|
+
if (
|
|
96
|
+
!manifest
|
|
97
|
+
|| manifest.apiVersion !== PERCEPTION_PLUGIN_API_VERSION
|
|
98
|
+
|| manifest.id !== spec.moduleId
|
|
99
|
+
|| (manifest.execution ?? 'ordered_update')
|
|
100
|
+
!== (spec.manifest.execution ?? 'ordered_update')
|
|
101
|
+
|| JSON.stringify(manifest.produces) !== JSON.stringify(spec.manifest.produces)
|
|
102
|
+
) throw new Error('perception_reducer_worker_manifest_mismatch');
|
|
103
|
+
return ModuleClass;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function validateInstance(
|
|
107
|
+
spec: PerceptionThreadModuleSpec,
|
|
108
|
+
instance: ClawclawPerception,
|
|
109
|
+
): void {
|
|
110
|
+
const execution = spec.manifest.execution ?? 'ordered_update';
|
|
111
|
+
if (
|
|
112
|
+
!instance
|
|
113
|
+
|| typeof instance !== 'object'
|
|
114
|
+
|| (execution === 'ordered_update' && typeof instance.update !== 'function')
|
|
115
|
+
|| (execution === 'parallel_analysis' && (
|
|
116
|
+
typeof (instance as any).analyze !== 'function'
|
|
117
|
+
|| typeof (instance as any).commit !== 'function'
|
|
118
|
+
))
|
|
119
|
+
) throw new Error('perception_reducer_worker_contract_invalid');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const api = Object.freeze({ spatial: createSpatialApi(data.spatialFacts) });
|
|
123
|
+
const specs = new Map<string, PerceptionThreadModuleSpec>();
|
|
124
|
+
const classes = new Map<string, ClawclawPerceptionClass>();
|
|
125
|
+
const modules = new Map<string, ClawclawPerception>();
|
|
126
|
+
const startupFailures: Array<Readonly<Record<string, unknown>>> = [];
|
|
127
|
+
|
|
128
|
+
for (const spec of data.modules) {
|
|
129
|
+
try {
|
|
130
|
+
if (
|
|
131
|
+
!spec
|
|
132
|
+
|| typeof spec.moduleId !== 'string'
|
|
133
|
+
|| !spec.moduleId
|
|
134
|
+
|| typeof spec.sourceUrl !== 'string'
|
|
135
|
+
|| !spec.sourceUrl
|
|
136
|
+
|| specs.has(spec.moduleId)
|
|
137
|
+
) throw new Error('perception_reducer_worker_module_invalid');
|
|
138
|
+
const ModuleClass = validateClass(
|
|
139
|
+
spec,
|
|
140
|
+
await import(spec.sourceUrl) as Record<string, unknown>,
|
|
141
|
+
);
|
|
142
|
+
const instance = new ModuleClass();
|
|
143
|
+
validateInstance(spec, instance);
|
|
144
|
+
specs.set(spec.moduleId, spec);
|
|
145
|
+
classes.set(spec.moduleId, ModuleClass);
|
|
146
|
+
modules.set(spec.moduleId, instance);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
startupFailures.push({
|
|
149
|
+
moduleId: typeof spec?.moduleId === 'string' ? spec.moduleId : '',
|
|
150
|
+
code: errorCode(error),
|
|
151
|
+
messagePresent: errorMessage(error).length > 0,
|
|
152
|
+
messageLength: errorMessage(error).length,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function safeDebugSnapshot(module: ClawclawPerception): unknown {
|
|
158
|
+
try {
|
|
159
|
+
const snapshot = structuredClone(module.debugSnapshot?.() ?? null);
|
|
160
|
+
assertRuntimeModuleOutputSize(snapshot, 'perception_debug_snapshot');
|
|
161
|
+
return snapshot;
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function operate(request: PerceptionReducerRequest): Promise<void> {
|
|
168
|
+
if (
|
|
169
|
+
request.poolId !== data!.poolId
|
|
170
|
+
|| typeof request.requestId !== 'string'
|
|
171
|
+
|| !request.requestId
|
|
172
|
+
|| typeof request.moduleId !== 'string'
|
|
173
|
+
|| !['update', 'commit', 'flush', 'reset'].includes(request.operation)
|
|
174
|
+
) throw new Error('perception_reducer_worker_request_invalid');
|
|
175
|
+
const spec = specs.get(request.moduleId);
|
|
176
|
+
const ModuleClass = classes.get(request.moduleId);
|
|
177
|
+
const module = modules.get(request.moduleId);
|
|
178
|
+
if (!spec || !ModuleClass || !module) throw new Error('perception_reducer_worker_module_unknown');
|
|
179
|
+
|
|
180
|
+
try {
|
|
181
|
+
let value;
|
|
182
|
+
if (request.operation === 'update') {
|
|
183
|
+
if ((spec.manifest.execution ?? 'ordered_update') !== 'ordered_update' || !request.frame) {
|
|
184
|
+
throw new Error('perception_reducer_update_invalid');
|
|
185
|
+
}
|
|
186
|
+
value = await module.update(deepFreeze(request.frame), api);
|
|
187
|
+
} else if (request.operation === 'commit') {
|
|
188
|
+
if (spec.manifest.execution !== 'parallel_analysis' || !request.frame) {
|
|
189
|
+
throw new Error('perception_reducer_commit_invalid');
|
|
190
|
+
}
|
|
191
|
+
value = await (module as ClawclawPerception & {
|
|
192
|
+
commit(
|
|
193
|
+
frame: Readonly<PerceptionFrame>,
|
|
194
|
+
analysis: unknown,
|
|
195
|
+
capability: typeof api,
|
|
196
|
+
): unknown | Promise<unknown>;
|
|
197
|
+
}).commit(
|
|
198
|
+
deepFreeze(request.frame),
|
|
199
|
+
deepFreeze(request.analysis),
|
|
200
|
+
api,
|
|
201
|
+
);
|
|
202
|
+
} else if (request.operation === 'flush') {
|
|
203
|
+
if (!request.boundary) throw new Error('perception_reducer_flush_invalid');
|
|
204
|
+
value = await module.flush?.(deepFreeze(request.boundary), api);
|
|
205
|
+
} else {
|
|
206
|
+
if (typeof request.reason !== 'string') throw new Error('perception_reducer_reset_invalid');
|
|
207
|
+
await module.reset?.(request.reason);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const events = request.operation === 'reset'
|
|
211
|
+
? []
|
|
212
|
+
: normalizePerceptionEvents(
|
|
213
|
+
value as Parameters<typeof normalizePerceptionEvents>[0],
|
|
214
|
+
spec.manifest,
|
|
215
|
+
);
|
|
216
|
+
send({
|
|
217
|
+
type: 'result',
|
|
218
|
+
requestId: request.requestId,
|
|
219
|
+
moduleId: request.moduleId,
|
|
220
|
+
events,
|
|
221
|
+
debugSnapshot: safeDebugSnapshot(module),
|
|
222
|
+
});
|
|
223
|
+
} catch (error) {
|
|
224
|
+
// commit/reset may have partially mutated private reducer state. Match the
|
|
225
|
+
// direct runner contract by replacing that instance before the next frame.
|
|
226
|
+
if (request.operation === 'commit' || request.operation === 'reset') {
|
|
227
|
+
const replacement = new ModuleClass();
|
|
228
|
+
validateInstance(spec, replacement);
|
|
229
|
+
modules.set(request.moduleId, replacement);
|
|
230
|
+
}
|
|
231
|
+
send({
|
|
232
|
+
type: 'request_error',
|
|
233
|
+
requestId: request.requestId,
|
|
234
|
+
moduleId: request.moduleId,
|
|
235
|
+
code: errorCode(error),
|
|
236
|
+
messagePresent: errorMessage(error).length > 0,
|
|
237
|
+
messageLength: errorMessage(error).length,
|
|
238
|
+
debugSnapshot: safeDebugSnapshot(modules.get(request.moduleId)!),
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
let operationTail = Promise.resolve();
|
|
244
|
+
port.on('message', (request: PerceptionReducerRequest) => {
|
|
245
|
+
operationTail = operationTail.then(() => operate(request)).catch((error) => {
|
|
246
|
+
send({
|
|
247
|
+
type: 'error',
|
|
248
|
+
requestId: typeof request?.requestId === 'string' ? request.requestId : undefined,
|
|
249
|
+
moduleId: typeof request?.moduleId === 'string' ? request.moduleId : undefined,
|
|
250
|
+
code: errorCode(error),
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
send({
|
|
256
|
+
type: 'ready',
|
|
257
|
+
moduleIds: [...modules.keys()],
|
|
258
|
+
startupFailures,
|
|
259
|
+
debugSnapshots: Object.fromEntries(
|
|
260
|
+
[...modules].map(([moduleId, module]) => [moduleId, safeDebugSnapshot(module)]),
|
|
261
|
+
),
|
|
262
|
+
});
|
|
@@ -17,13 +17,19 @@ export type ClawclawGameTransportStopReason =
|
|
|
17
17
|
export interface ClawclawGameTransportOutcome {
|
|
18
18
|
reason: ClawclawGameTransportStopReason;
|
|
19
19
|
error?: unknown;
|
|
20
|
+
queueState?: Record<string, any>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ClawclawGameServerDiscoveryResult {
|
|
24
|
+
readonly routeChanged: boolean;
|
|
25
|
+
readonly queue?: Record<string, any>;
|
|
20
26
|
}
|
|
21
27
|
|
|
22
28
|
export interface ClawclawGameTransportClient {
|
|
23
29
|
readonly wsConnected: boolean;
|
|
24
30
|
readonly wsConnectionActive: boolean;
|
|
25
31
|
readonly wsConnectionId: string | null;
|
|
26
|
-
discoverGameServer(): Promise<
|
|
32
|
+
discoverGameServer(): Promise<ClawclawGameServerDiscoveryResult>;
|
|
27
33
|
connectWs(): Promise<boolean>;
|
|
28
34
|
reconnectWsToGameServer(): Promise<void>;
|
|
29
35
|
disconnectWs(options?: { preserveGameSyncResumeState?: boolean }): void;
|
|
@@ -46,6 +52,9 @@ export interface ClawclawGameTransportOptions {
|
|
|
46
52
|
info: WsCloseInfo,
|
|
47
53
|
): Promise<ClawclawGameTransportStopReason | void> | ClawclawGameTransportStopReason | void;
|
|
48
54
|
onConnectAttemptFailed(error: unknown): void;
|
|
55
|
+
onParticipationProbe?(
|
|
56
|
+
queue: Record<string, any>,
|
|
57
|
+
): Promise<ClawclawGameTransportStopReason | void> | ClawclawGameTransportStopReason | void;
|
|
49
58
|
onProtocolError(info: WsProtocolErrorInfo): void;
|
|
50
59
|
onRecoveryStarted?(info: WsRecoveryStartedInfo): Promise<void> | void;
|
|
51
60
|
routePollMs?: number;
|
|
@@ -194,8 +203,9 @@ export class ClawclawGameTransport implements ClawclawGameTransportPort {
|
|
|
194
203
|
) {
|
|
195
204
|
this.connectAttemptActive = true;
|
|
196
205
|
try {
|
|
197
|
-
const
|
|
198
|
-
if (
|
|
206
|
+
const discovery = await client.discoverGameServer();
|
|
207
|
+
if (await this.applyParticipationProbe(discovery)) return;
|
|
208
|
+
if (!discovery.routeChanged) await client.reconnectWsToGameServer();
|
|
199
209
|
} catch (error) {
|
|
200
210
|
this.options.onConnectAttemptFailed(error);
|
|
201
211
|
} finally {
|
|
@@ -213,7 +223,8 @@ export class ClawclawGameTransport implements ClawclawGameTransportPort {
|
|
|
213
223
|
try {
|
|
214
224
|
// This call is required even while WsClient is auto-reconnecting: the
|
|
215
225
|
// authoritative GameServer route may have changed underneath it.
|
|
216
|
-
await client.discoverGameServer();
|
|
226
|
+
const discovery = await client.discoverGameServer();
|
|
227
|
+
if (await this.applyParticipationProbe(discovery)) return;
|
|
217
228
|
if (!client.wsConnectionActive) await client.connectWs();
|
|
218
229
|
if (!client.wsConnectionActive) {
|
|
219
230
|
this.options.onConnectAttemptFailed(new Error('Game WebSocket connection is unavailable.'));
|
|
@@ -225,6 +236,20 @@ export class ClawclawGameTransport implements ClawclawGameTransportPort {
|
|
|
225
236
|
}
|
|
226
237
|
}
|
|
227
238
|
|
|
239
|
+
private async applyParticipationProbe(
|
|
240
|
+
discovery: ClawclawGameServerDiscoveryResult,
|
|
241
|
+
): Promise<boolean> {
|
|
242
|
+
if (!discovery.queue || !this.options.onParticipationProbe) return false;
|
|
243
|
+
// Preserve the per-attempt disconnect Event before a Lobby probe can end
|
|
244
|
+
// this transport generation.
|
|
245
|
+
await this.flush();
|
|
246
|
+
if (this.stopped) return true;
|
|
247
|
+
const reason = await this.options.onParticipationProbe(structuredClone(discovery.queue));
|
|
248
|
+
if (!reason) return false;
|
|
249
|
+
this.finish({ reason, queueState: structuredClone(discovery.queue) });
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
|
|
228
253
|
private enqueue(operation: () => void | Promise<void>): void {
|
|
229
254
|
if (this.stopped) return;
|
|
230
255
|
this.operationTail = this.operationTail.then(async () => {
|
|
@@ -141,6 +141,9 @@ type GameAttachGate =
|
|
|
141
141
|
|
|
142
142
|
type ReconciledTransport = 'game_ws' | 'room_ws';
|
|
143
143
|
|
|
144
|
+
const GAME_TERMINAL_SETTLEMENT_ATTEMPTS = 2;
|
|
145
|
+
const GAME_TERMINAL_SETTLEMENT_RETRY_MS = 250;
|
|
146
|
+
|
|
144
147
|
interface SourceCoalescingBoundaryState {
|
|
145
148
|
connected: boolean;
|
|
146
149
|
ended: boolean;
|
|
@@ -1128,6 +1131,10 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
1128
1131
|
this.requireRuntime().connectionLiveness(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, atMs);
|
|
1129
1132
|
},
|
|
1130
1133
|
onClose: (connectionId, info) => this.handleGameClose(connectionId, info),
|
|
1134
|
+
onParticipationProbe: (participation) => this.handleGameParticipationProbe(
|
|
1135
|
+
gameId,
|
|
1136
|
+
participation,
|
|
1137
|
+
),
|
|
1131
1138
|
onConnectAttemptFailed: (error) => {
|
|
1132
1139
|
this.diagnostic('runtime.source.connect_failed', {
|
|
1133
1140
|
transport: 'game_ws',
|
|
@@ -1180,10 +1187,156 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
|
|
|
1180
1187
|
},
|
|
1181
1188
|
};
|
|
1182
1189
|
}
|
|
1190
|
+
if (outcome.reason === 'reconcile' && outcome.queueState) {
|
|
1191
|
+
const reconciledQueue = normalizeClawclawQueueState(outcome.queueState);
|
|
1192
|
+
await this.acceptQueueState(reconciledQueue);
|
|
1193
|
+
const status = queueStatus(reconciledQueue);
|
|
1194
|
+
if (status === 'not_in_queue') {
|
|
1195
|
+
return {
|
|
1196
|
+
kind: 'complete',
|
|
1197
|
+
completion: { reason: this.leaveRequested ? 'left' : 'not_participating' },
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
return { kind: 'continue', queue: reconciledQueue };
|
|
1201
|
+
}
|
|
1183
1202
|
await this.reconcileBackoff('game_ws', outcome.reason);
|
|
1184
1203
|
return { kind: 'continue' };
|
|
1185
1204
|
}
|
|
1186
1205
|
|
|
1206
|
+
private async handleGameParticipationProbe(
|
|
1207
|
+
gameId: string | undefined,
|
|
1208
|
+
value: Record<string, any>,
|
|
1209
|
+
): Promise<ClawclawGameTransportStopReason | void> {
|
|
1210
|
+
if (!gameId) return;
|
|
1211
|
+
const queue = normalizeClawclawQueueState(value);
|
|
1212
|
+
const status = queueStatus(queue);
|
|
1213
|
+
if (status !== 'not_in_queue' && status !== 'in_room') return;
|
|
1214
|
+
if (this.leaveRequested) return 'reconcile';
|
|
1215
|
+
|
|
1216
|
+
let settlement: Record<string, any> | undefined;
|
|
1217
|
+
let settlementGameId: string | undefined;
|
|
1218
|
+
let settlementErrorCode: string | undefined;
|
|
1219
|
+
for (let attempt = 1; attempt <= GAME_TERMINAL_SETTLEMENT_ATTEMPTS; attempt += 1) {
|
|
1220
|
+
try {
|
|
1221
|
+
const candidate = unwrapData(await this.client.getSettlement());
|
|
1222
|
+
if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
|
|
1223
|
+
settlementGameId = typeof candidate.game_id === 'string' ? candidate.game_id : undefined;
|
|
1224
|
+
if (settlementGameId === gameId) {
|
|
1225
|
+
settlement = structuredClone(candidate);
|
|
1226
|
+
break;
|
|
1227
|
+
}
|
|
1228
|
+
settlementErrorCode = settlementGameId
|
|
1229
|
+
? 'SETTLEMENT_GAME_ID_MISMATCH'
|
|
1230
|
+
: 'SETTLEMENT_GAME_ID_MISSING';
|
|
1231
|
+
} else {
|
|
1232
|
+
settlementErrorCode = 'SETTLEMENT_INVALID';
|
|
1233
|
+
}
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
settlementErrorCode = apiErrorCode(error) ?? 'SETTLEMENT_UNAVAILABLE';
|
|
1236
|
+
}
|
|
1237
|
+
if (attempt < GAME_TERMINAL_SETTLEMENT_ATTEMPTS) {
|
|
1238
|
+
await this.sleep(GAME_TERMINAL_SETTLEMENT_RETRY_MS, this.abortController.signal);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
if (settlement) {
|
|
1243
|
+
await this.submitRecoveredGameOver(gameId, queue, settlement);
|
|
1244
|
+
return 'game_over';
|
|
1245
|
+
}
|
|
1246
|
+
await this.submitMissingGameTerminal(
|
|
1247
|
+
gameId,
|
|
1248
|
+
queue,
|
|
1249
|
+
settlementErrorCode ?? 'SETTLEMENT_UNAVAILABLE',
|
|
1250
|
+
settlementGameId,
|
|
1251
|
+
);
|
|
1252
|
+
return 'reconcile';
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
private async submitRecoveredGameOver(
|
|
1256
|
+
gameId: string,
|
|
1257
|
+
queue: Record<string, any>,
|
|
1258
|
+
settlement: Record<string, any>,
|
|
1259
|
+
): Promise<void> {
|
|
1260
|
+
const receivedAt = new Date().toISOString();
|
|
1261
|
+
const sourceSeq = `settlement:${gameId}`;
|
|
1262
|
+
const winningFaction = typeof settlement.winning_faction === 'string'
|
|
1263
|
+
? settlement.winning_faction
|
|
1264
|
+
: undefined;
|
|
1265
|
+
const winReason = typeof settlement.win_reason === 'string'
|
|
1266
|
+
? settlement.win_reason
|
|
1267
|
+
: undefined;
|
|
1268
|
+
this.currentStage = 'ended';
|
|
1269
|
+
this.currentTransport = 'lobby_http';
|
|
1270
|
+
this.currentConnection = 'connected';
|
|
1271
|
+
this.currentQueue = structuredClone(queue);
|
|
1272
|
+
await this.submit({
|
|
1273
|
+
scope: this.requireRuntime().currentSegment().scope,
|
|
1274
|
+
sourceId: CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
|
|
1275
|
+
connectionId: 'lobby-http',
|
|
1276
|
+
sourceKey: `game-terminal-recovered:${gameId}`,
|
|
1277
|
+
sourceSeq,
|
|
1278
|
+
state: this.runtimeState('ending'),
|
|
1279
|
+
events: [{
|
|
1280
|
+
type: 'game_over_recovered',
|
|
1281
|
+
producer: 'local_synth',
|
|
1282
|
+
payload: {
|
|
1283
|
+
game_id: gameId,
|
|
1284
|
+
recovered: true,
|
|
1285
|
+
recovery_source: 'settlement_http',
|
|
1286
|
+
...(winningFaction ? { winner: winningFaction, winning_faction: winningFaction } : {}),
|
|
1287
|
+
...(winReason ? { reason: winReason, win_reason: winReason } : {}),
|
|
1288
|
+
...(settlement.your_result && typeof settlement.your_result === 'object'
|
|
1289
|
+
? { your_result: structuredClone(settlement.your_result) }
|
|
1290
|
+
: {}),
|
|
1291
|
+
...(this.participationMode ? { game_mode: this.participationMode } : {}),
|
|
1292
|
+
},
|
|
1293
|
+
sourceEventId: `game-terminal-recovered:${gameId}`,
|
|
1294
|
+
sourceSeq,
|
|
1295
|
+
receivedAt,
|
|
1296
|
+
}],
|
|
1297
|
+
completeness: 'complete',
|
|
1298
|
+
receivedAt,
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
private async submitMissingGameTerminal(
|
|
1303
|
+
gameId: string,
|
|
1304
|
+
queue: Record<string, any>,
|
|
1305
|
+
settlementErrorCode: string,
|
|
1306
|
+
settlementGameId?: string,
|
|
1307
|
+
): Promise<void> {
|
|
1308
|
+
const receivedAt = new Date().toISOString();
|
|
1309
|
+
const sourceSeq = `terminal-missing:${gameId}`;
|
|
1310
|
+
this.currentStage = 'ended';
|
|
1311
|
+
this.currentTransport = 'lobby_http';
|
|
1312
|
+
this.currentConnection = 'connected';
|
|
1313
|
+
this.currentQueue = structuredClone(queue);
|
|
1314
|
+
await this.submit({
|
|
1315
|
+
scope: this.requireRuntime().currentSegment().scope,
|
|
1316
|
+
sourceId: CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
|
|
1317
|
+
connectionId: 'lobby-http',
|
|
1318
|
+
sourceKey: `game-terminal-missing:${gameId}`,
|
|
1319
|
+
sourceSeq,
|
|
1320
|
+
state: this.runtimeState('ending'),
|
|
1321
|
+
events: [{
|
|
1322
|
+
type: 'game_terminal_missing',
|
|
1323
|
+
producer: 'local_synth',
|
|
1324
|
+
payload: {
|
|
1325
|
+
game_id: gameId,
|
|
1326
|
+
queue_status: queueStatus(queue),
|
|
1327
|
+
settlement_error_code: settlementErrorCode,
|
|
1328
|
+
...(settlementGameId ? { settlement_game_id: settlementGameId } : {}),
|
|
1329
|
+
...(this.participationMode ? { game_mode: this.participationMode } : {}),
|
|
1330
|
+
},
|
|
1331
|
+
sourceEventId: `game-terminal-missing:${gameId}`,
|
|
1332
|
+
sourceSeq,
|
|
1333
|
+
receivedAt,
|
|
1334
|
+
}],
|
|
1335
|
+
completeness: 'complete',
|
|
1336
|
+
receivedAt,
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1187
1340
|
private async waitForGameAttach(
|
|
1188
1341
|
transport: ClawclawGameTransportPort,
|
|
1189
1342
|
): Promise<ClawclawGameTransportOutcome | undefined> {
|
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
export interface ClawclawSourceClient extends ClawclawGameTransportClient {
|
|
18
18
|
readonly lobbyAgentWsUrl: string;
|
|
19
19
|
getQueueStatus(gameType?: string): Promise<any>;
|
|
20
|
+
getSettlement(): Promise<any>;
|
|
20
21
|
joinQueue(options?: {
|
|
21
22
|
gameType?: string;
|
|
22
23
|
mode?: QueueMode;
|
|
@@ -9,7 +9,11 @@ import {
|
|
|
9
9
|
type ClawclawTriggerManifest,
|
|
10
10
|
} from '../../../../sdk/trigger-plugin/index.js';
|
|
11
11
|
import { normalizeBehaviorInput, normalizeBehaviorInputFields } from '../../behavior-input-fields.js';
|
|
12
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
importRuntimeModule,
|
|
14
|
+
runtimeModuleThreadLoaderConfig,
|
|
15
|
+
type RuntimeModuleThreadLoaderConfig,
|
|
16
|
+
} from '../../../framework/modules/runtime-module-loader.js';
|
|
13
17
|
import { assertPluginApiVersion } from '../plugin-api-version.js';
|
|
14
18
|
import type { ResolvedClawclawTriggerSource } from './trigger-source.js';
|
|
15
19
|
|
|
@@ -74,11 +78,45 @@ function normalizedManifest(value: unknown): ClawclawTriggerManifest {
|
|
|
74
78
|
return structuredClone({ ...manifest, inputs }) as unknown as ClawclawTriggerManifest;
|
|
75
79
|
}
|
|
76
80
|
|
|
81
|
+
export interface TriggerThreadModuleSpec {
|
|
82
|
+
readonly triggerId: string;
|
|
83
|
+
readonly sourceUrl: string;
|
|
84
|
+
readonly source: ResolvedClawclawTriggerSource;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function validateClawclawTriggerModule(
|
|
88
|
+
loaded: Readonly<Record<string, unknown>>,
|
|
89
|
+
source: ResolvedClawclawTriggerSource,
|
|
90
|
+
): ClawclawTriggerClass {
|
|
91
|
+
if (typeof loaded.default !== 'function') {
|
|
92
|
+
throw new Error(`Trigger module '${source.id}' has no default class.`);
|
|
93
|
+
}
|
|
94
|
+
const ModuleClass = loaded.default as unknown as ClawclawTriggerClass;
|
|
95
|
+
const manifest = normalizedManifest(ModuleClass.manifest);
|
|
96
|
+
if (!isDeepStrictEqual(manifest, source.manifest)) {
|
|
97
|
+
throw new Error(`Trigger module '${source.id}' changed after static discovery.`);
|
|
98
|
+
}
|
|
99
|
+
return ModuleClass;
|
|
100
|
+
}
|
|
101
|
+
|
|
77
102
|
/** One Runtime-scoped direct importer. Disabled Trigger sources never reach it. */
|
|
78
103
|
export class TriggerModuleLoader {
|
|
79
104
|
private readonly runtimeId = randomUUID();
|
|
80
105
|
private readonly loaded = new Map<string, Promise<ClawclawTriggerClass>>();
|
|
81
106
|
|
|
107
|
+
threadConfig(): RuntimeModuleThreadLoaderConfig {
|
|
108
|
+
return runtimeModuleThreadLoaderConfig();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
threadSpec(source: ResolvedClawclawTriggerSource): TriggerThreadModuleSpec {
|
|
112
|
+
assertPluginApiVersion(
|
|
113
|
+
'trigger_api_version_unsupported',
|
|
114
|
+
TRIGGER_PLUGIN_API_VERSION,
|
|
115
|
+
source.apiVersion,
|
|
116
|
+
);
|
|
117
|
+
return { triggerId: source.id, sourceUrl: this.sourceUrl(source), source };
|
|
118
|
+
}
|
|
119
|
+
|
|
82
120
|
load(source: ResolvedClawclawTriggerSource): Promise<ClawclawTriggerClass> {
|
|
83
121
|
try {
|
|
84
122
|
assertPluginApiVersion(
|
|
@@ -91,17 +129,8 @@ export class TriggerModuleLoader {
|
|
|
91
129
|
}
|
|
92
130
|
let pending = this.loaded.get(source.id);
|
|
93
131
|
if (pending) return pending;
|
|
94
|
-
pending = importRuntimeModule(new URL(this.sourceUrl(source)))
|
|
95
|
-
|
|
96
|
-
throw new Error(`Trigger module '${source.id}' has no default class.`);
|
|
97
|
-
}
|
|
98
|
-
const ModuleClass = loaded.default as unknown as ClawclawTriggerClass;
|
|
99
|
-
const manifest = normalizedManifest(ModuleClass.manifest);
|
|
100
|
-
if (!isDeepStrictEqual(manifest, source.manifest)) {
|
|
101
|
-
throw new Error(`Trigger module '${source.id}' changed after static discovery.`);
|
|
102
|
-
}
|
|
103
|
-
return ModuleClass;
|
|
104
|
-
});
|
|
132
|
+
pending = importRuntimeModule(new URL(this.sourceUrl(source)))
|
|
133
|
+
.then((loaded) => validateClawclawTriggerModule(loaded, source));
|
|
105
134
|
this.loaded.set(source.id, pending);
|
|
106
135
|
return pending;
|
|
107
136
|
}
|