@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,660 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { Worker } from 'node:worker_threads';
|
|
3
|
+
import type {
|
|
4
|
+
PerceptionBoundary,
|
|
5
|
+
PerceptionEventProposal,
|
|
6
|
+
PerceptionFrame,
|
|
7
|
+
PerceptionSpatialFacts,
|
|
8
|
+
} from './contracts.js';
|
|
9
|
+
import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index.js';
|
|
10
|
+
import type {
|
|
11
|
+
PerceptionThreadLoaderConfig,
|
|
12
|
+
PerceptionThreadModuleSpec,
|
|
13
|
+
} from './perception-module-loader.js';
|
|
14
|
+
|
|
15
|
+
const WORKER_BOOTSTRAP_URL = new URL(
|
|
16
|
+
'../../../framework/modules/runtime-module-worker-bootstrap.mjs',
|
|
17
|
+
import.meta.url,
|
|
18
|
+
);
|
|
19
|
+
const WORKER_HOST_URL = new URL('./perception-reducer-thread-worker.ts', import.meta.url).href;
|
|
20
|
+
const MAX_REDUCER_WORKERS = 10;
|
|
21
|
+
const START_TIMEOUT_MS = 20_000;
|
|
22
|
+
const STOP_RESET_TIMEOUT_MS = 1_000;
|
|
23
|
+
|
|
24
|
+
export type PerceptionReducerResetReason =
|
|
25
|
+
Exclude<PerceptionBoundary['kind'], 'events_requested'> | 'replay';
|
|
26
|
+
export type PerceptionReducerOperation = 'update' | 'commit' | 'flush' | 'reset';
|
|
27
|
+
|
|
28
|
+
export interface PerceptionReducerOperationInput {
|
|
29
|
+
readonly frame?: Readonly<PerceptionFrame>;
|
|
30
|
+
readonly analysis?: unknown;
|
|
31
|
+
readonly boundary?: Readonly<PerceptionBoundary>;
|
|
32
|
+
readonly reason?: PerceptionReducerResetReason;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PerceptionReducerThreadPoolOptions {
|
|
36
|
+
readonly modules: readonly PerceptionThreadModuleSpec[];
|
|
37
|
+
readonly loader: PerceptionThreadLoaderConfig;
|
|
38
|
+
readonly spatialFacts: PerceptionSpatialFacts;
|
|
39
|
+
readonly maxWorkers?: number;
|
|
40
|
+
readonly maxOldGenerationSizeMb?: number;
|
|
41
|
+
readonly diagnosticsEnabled?: boolean;
|
|
42
|
+
readonly diagnostic?: (
|
|
43
|
+
name: string,
|
|
44
|
+
attributes?: Readonly<Record<string, unknown>>,
|
|
45
|
+
severity?: RuntimeDiagnosticSeverity,
|
|
46
|
+
) => void;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface PerceptionReducerThreadPoolSnapshot {
|
|
50
|
+
readonly state: 'new' | 'starting' | 'running' | 'stopping' | 'stopped';
|
|
51
|
+
readonly maxWorkerCount: number;
|
|
52
|
+
readonly workerCount: number;
|
|
53
|
+
readonly busyWorkerCount: number;
|
|
54
|
+
readonly queuedRequestCount: number;
|
|
55
|
+
readonly inFlightRequestCount: number;
|
|
56
|
+
readonly activeModuleCount: number;
|
|
57
|
+
readonly unavailableModuleIds: readonly string[];
|
|
58
|
+
readonly restartedWorkerCount: number;
|
|
59
|
+
readonly workerHeapUsedBytes: number;
|
|
60
|
+
readonly peakWorkerHeapUsedBytes: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface PendingRequest {
|
|
64
|
+
readonly requestId: string;
|
|
65
|
+
readonly moduleId: string;
|
|
66
|
+
readonly operation: PerceptionReducerOperation;
|
|
67
|
+
readonly input: PerceptionReducerOperationInput;
|
|
68
|
+
readonly signal: AbortSignal;
|
|
69
|
+
readonly resolve: (events: readonly PerceptionEventProposal[]) => void;
|
|
70
|
+
readonly reject: (error: Error) => void;
|
|
71
|
+
readonly onAbort: () => void;
|
|
72
|
+
settled: boolean;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface ReducerLane {
|
|
76
|
+
readonly id: number;
|
|
77
|
+
readonly modules: readonly PerceptionThreadModuleSpec[];
|
|
78
|
+
readonly queue: PendingRequest[];
|
|
79
|
+
readonly activeModuleIds: Set<string>;
|
|
80
|
+
worker?: Worker;
|
|
81
|
+
state: 'starting' | 'idle' | 'busy' | 'restarting' | 'stopped';
|
|
82
|
+
current?: PendingRequest;
|
|
83
|
+
readyResolve?: () => void;
|
|
84
|
+
readyReject?: (error: Error) => void;
|
|
85
|
+
heapUsedBytes?: number;
|
|
86
|
+
generation: number;
|
|
87
|
+
consecutiveWorkerFailures: number;
|
|
88
|
+
restartTask?: Promise<void>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
interface WorkerMessageBase {
|
|
92
|
+
readonly type: string;
|
|
93
|
+
readonly poolId: string;
|
|
94
|
+
readonly laneId: number;
|
|
95
|
+
readonly requestId?: string;
|
|
96
|
+
readonly moduleId?: string;
|
|
97
|
+
readonly heapUsedBytes?: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface WorkerReadyMessage extends WorkerMessageBase {
|
|
101
|
+
readonly type: 'ready';
|
|
102
|
+
readonly moduleIds: readonly string[];
|
|
103
|
+
readonly startupFailures: readonly {
|
|
104
|
+
readonly moduleId: string;
|
|
105
|
+
readonly code: string;
|
|
106
|
+
}[];
|
|
107
|
+
readonly debugSnapshots: Readonly<Record<string, unknown>>;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface WorkerResultMessage extends WorkerMessageBase {
|
|
111
|
+
readonly type: 'result';
|
|
112
|
+
readonly requestId: string;
|
|
113
|
+
readonly moduleId: string;
|
|
114
|
+
readonly events: readonly PerceptionEventProposal[];
|
|
115
|
+
readonly debugSnapshot: unknown;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
interface WorkerErrorMessage extends WorkerMessageBase {
|
|
119
|
+
readonly type: 'request_error' | 'error';
|
|
120
|
+
readonly code: string;
|
|
121
|
+
readonly debugSnapshot?: unknown;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function asError(value: unknown, fallback: string): Error {
|
|
125
|
+
return value instanceof Error ? value : new Error(typeof value === 'string' ? value : fallback);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function abortError(signal: AbortSignal): Error {
|
|
129
|
+
return asError(signal.reason, 'perception_reducer_request_aborted');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export class PerceptionReducerThreadPool {
|
|
133
|
+
private readonly poolId = randomUUID();
|
|
134
|
+
private readonly maxWorkers: number;
|
|
135
|
+
private readonly maxOldGenerationSizeMb: number;
|
|
136
|
+
private readonly lanes: ReducerLane[];
|
|
137
|
+
private readonly laneByModule = new Map<string, ReducerLane>();
|
|
138
|
+
private readonly moduleFailures = new Map<string, Error>();
|
|
139
|
+
private readonly debugSnapshots = new Map<string, unknown>();
|
|
140
|
+
private readonly releasedModuleIds = new Set<string>();
|
|
141
|
+
private state: PerceptionReducerThreadPoolSnapshot['state'] = 'new';
|
|
142
|
+
private startTask?: Promise<void>;
|
|
143
|
+
private stopTask?: Promise<void>;
|
|
144
|
+
private peakWorkerHeapUsedBytes = 0;
|
|
145
|
+
private restartedWorkerCount = 0;
|
|
146
|
+
private diagnosticCallback: PerceptionReducerThreadPoolOptions['diagnostic'];
|
|
147
|
+
|
|
148
|
+
constructor(private readonly options: PerceptionReducerThreadPoolOptions) {
|
|
149
|
+
this.diagnosticCallback = options.diagnostic;
|
|
150
|
+
const ids = options.modules.map(({ moduleId }) => moduleId);
|
|
151
|
+
if (ids.length === 0) throw new Error('perception_reducer_modules_empty');
|
|
152
|
+
if (new Set(ids).size !== ids.length) throw new Error('perception_reducer_module_duplicate');
|
|
153
|
+
this.maxWorkers = Math.max(1, Math.min(
|
|
154
|
+
MAX_REDUCER_WORKERS,
|
|
155
|
+
Math.floor(options.maxWorkers ?? MAX_REDUCER_WORKERS),
|
|
156
|
+
));
|
|
157
|
+
this.maxOldGenerationSizeMb = Math.max(16, Math.min(
|
|
158
|
+
256,
|
|
159
|
+
Math.floor(options.maxOldGenerationSizeMb ?? 64),
|
|
160
|
+
));
|
|
161
|
+
const laneCount = Math.min(this.maxWorkers, options.modules.length);
|
|
162
|
+
const groups = Array.from({ length: laneCount }, () => [] as PerceptionThreadModuleSpec[]);
|
|
163
|
+
options.modules.forEach((module, index) => groups[index % laneCount]!.push(module));
|
|
164
|
+
this.lanes = groups.map((modules, index) => ({
|
|
165
|
+
id: index + 1,
|
|
166
|
+
modules,
|
|
167
|
+
queue: [],
|
|
168
|
+
activeModuleIds: new Set(),
|
|
169
|
+
state: 'stopped',
|
|
170
|
+
generation: 0,
|
|
171
|
+
consecutiveWorkerFailures: 0,
|
|
172
|
+
}));
|
|
173
|
+
for (const lane of this.lanes) {
|
|
174
|
+
for (const module of lane.modules) this.laneByModule.set(module.moduleId, lane);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
setDiagnostic(
|
|
179
|
+
diagnostic: PerceptionReducerThreadPoolOptions['diagnostic'],
|
|
180
|
+
): void {
|
|
181
|
+
if (diagnostic) this.diagnosticCallback = diagnostic;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
start(): Promise<void> {
|
|
185
|
+
if (this.state === 'running') return Promise.resolve();
|
|
186
|
+
if (this.startTask) return this.startTask;
|
|
187
|
+
if (this.stopTask) return this.stopTask.then(() => this.start());
|
|
188
|
+
let task!: Promise<void>;
|
|
189
|
+
task = this.startInternal().finally(() => {
|
|
190
|
+
if (this.startTask === task) this.startTask = undefined;
|
|
191
|
+
});
|
|
192
|
+
this.startTask = task;
|
|
193
|
+
return task;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private async startInternal(): Promise<void> {
|
|
197
|
+
this.state = 'starting';
|
|
198
|
+
this.moduleFailures.clear();
|
|
199
|
+
this.debugSnapshots.clear();
|
|
200
|
+
this.releasedModuleIds.clear();
|
|
201
|
+
for (const lane of this.lanes) {
|
|
202
|
+
lane.consecutiveWorkerFailures = 0;
|
|
203
|
+
lane.heapUsedBytes = undefined;
|
|
204
|
+
lane.activeModuleIds.clear();
|
|
205
|
+
}
|
|
206
|
+
const starts = await Promise.allSettled(this.lanes.map((lane) => this.spawn(lane)));
|
|
207
|
+
if (this.state !== 'starting') throw new Error('perception_reducer_pool_stopped');
|
|
208
|
+
for (const [index, result] of starts.entries()) {
|
|
209
|
+
if (result.status === 'fulfilled') continue;
|
|
210
|
+
const lane = this.lanes[index]!;
|
|
211
|
+
lane.state = 'stopped';
|
|
212
|
+
lane.activeModuleIds.clear();
|
|
213
|
+
const failure = asError(result.reason, 'perception_reducer_worker_start_failed');
|
|
214
|
+
for (const { moduleId } of lane.modules) this.moduleFailures.set(moduleId, failure);
|
|
215
|
+
const worker = lane.worker;
|
|
216
|
+
lane.worker = undefined;
|
|
217
|
+
await worker?.terminate().catch(() => -1);
|
|
218
|
+
}
|
|
219
|
+
this.state = 'running';
|
|
220
|
+
this.diagnostic('perception.reducer_pool.started', {
|
|
221
|
+
worker_count: this.lanes.filter(({ worker }) => !!worker).length,
|
|
222
|
+
max_worker_count: this.maxWorkers,
|
|
223
|
+
active_module_count: this.activeModuleCount(),
|
|
224
|
+
unavailable_module_ids: [...this.moduleFailures.keys()],
|
|
225
|
+
worker_max_old_generation_mb: this.maxOldGenerationSizeMb,
|
|
226
|
+
}, 'info');
|
|
227
|
+
this.pumpAll();
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
assertAvailable(moduleId: string): void {
|
|
231
|
+
const lane = this.laneByModule.get(moduleId);
|
|
232
|
+
if (!lane || !lane.activeModuleIds.has(moduleId) || !lane.worker) {
|
|
233
|
+
throw this.moduleFailures.get(moduleId)
|
|
234
|
+
?? new Error(`perception_reducer_unavailable:${moduleId}`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
operate(
|
|
239
|
+
moduleId: string,
|
|
240
|
+
operation: PerceptionReducerOperation,
|
|
241
|
+
input: PerceptionReducerOperationInput,
|
|
242
|
+
signal: AbortSignal,
|
|
243
|
+
): Promise<readonly PerceptionEventProposal[]> {
|
|
244
|
+
if (this.state !== 'running') {
|
|
245
|
+
return Promise.reject(new Error('perception_reducer_pool_not_running'));
|
|
246
|
+
}
|
|
247
|
+
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
248
|
+
const lane = this.laneByModule.get(moduleId);
|
|
249
|
+
if (!lane || !lane.activeModuleIds.has(moduleId) || !lane.worker) {
|
|
250
|
+
return Promise.reject(this.moduleFailures.get(moduleId)
|
|
251
|
+
?? new Error(`perception_reducer_unavailable:${moduleId}`));
|
|
252
|
+
}
|
|
253
|
+
return new Promise((resolve, reject) => {
|
|
254
|
+
const request: PendingRequest = {
|
|
255
|
+
requestId: randomUUID(),
|
|
256
|
+
moduleId,
|
|
257
|
+
operation,
|
|
258
|
+
input,
|
|
259
|
+
signal,
|
|
260
|
+
resolve,
|
|
261
|
+
reject,
|
|
262
|
+
settled: false,
|
|
263
|
+
onAbort: () => this.abortRequest(lane, request),
|
|
264
|
+
};
|
|
265
|
+
signal.addEventListener('abort', request.onAbort, { once: true });
|
|
266
|
+
lane.queue.push(request);
|
|
267
|
+
this.pump(lane);
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async releaseModule(
|
|
272
|
+
moduleId: string,
|
|
273
|
+
reason: 'segment_ending' | 'shutdown',
|
|
274
|
+
): Promise<void> {
|
|
275
|
+
if (this.releasedModuleIds.has(moduleId)) return;
|
|
276
|
+
if (this.state === 'running') {
|
|
277
|
+
const controller = new AbortController();
|
|
278
|
+
const timer = setTimeout(
|
|
279
|
+
() => controller.abort(new Error('perception_reducer_stop_timeout')),
|
|
280
|
+
STOP_RESET_TIMEOUT_MS,
|
|
281
|
+
);
|
|
282
|
+
timer.unref?.();
|
|
283
|
+
try {
|
|
284
|
+
await this.operate(moduleId, 'reset', { reason }, controller.signal);
|
|
285
|
+
} catch {
|
|
286
|
+
// The worker is terminated below when the last runner releases it.
|
|
287
|
+
} finally {
|
|
288
|
+
clearTimeout(timer);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
this.releasedModuleIds.add(moduleId);
|
|
292
|
+
if (this.releasedModuleIds.size === this.options.modules.length) await this.stop();
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
stop(): Promise<void> {
|
|
296
|
+
if (this.state === 'stopped') return Promise.resolve();
|
|
297
|
+
if (this.stopTask) return this.stopTask;
|
|
298
|
+
let task!: Promise<void>;
|
|
299
|
+
task = this.stopInternal().finally(() => {
|
|
300
|
+
if (this.stopTask === task) this.stopTask = undefined;
|
|
301
|
+
});
|
|
302
|
+
this.stopTask = task;
|
|
303
|
+
return task;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private async stopInternal(): Promise<void> {
|
|
307
|
+
this.state = 'stopping';
|
|
308
|
+
const error = new Error('perception_reducer_pool_stopped');
|
|
309
|
+
await Promise.all(this.lanes.map(async (lane) => {
|
|
310
|
+
lane.readyReject?.(error);
|
|
311
|
+
if (lane.current) this.rejectRequest(lane.current, error);
|
|
312
|
+
for (const request of [...lane.queue]) this.rejectRequest(request, error);
|
|
313
|
+
lane.queue.length = 0;
|
|
314
|
+
lane.current = undefined;
|
|
315
|
+
lane.activeModuleIds.clear();
|
|
316
|
+
lane.state = 'stopped';
|
|
317
|
+
lane.generation += 1;
|
|
318
|
+
const worker = lane.worker;
|
|
319
|
+
lane.worker = undefined;
|
|
320
|
+
await worker?.terminate().catch(() => -1);
|
|
321
|
+
}));
|
|
322
|
+
this.state = 'stopped';
|
|
323
|
+
this.moduleFailures.clear();
|
|
324
|
+
this.debugSnapshots.clear();
|
|
325
|
+
this.diagnostic('perception.reducer_pool.stopped', {
|
|
326
|
+
worker_count: 0,
|
|
327
|
+
peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
|
|
328
|
+
}, 'info');
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
debugSnapshot(moduleId: string): unknown {
|
|
332
|
+
return structuredClone(this.debugSnapshots.get(moduleId) ?? null);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
snapshot(): PerceptionReducerThreadPoolSnapshot {
|
|
336
|
+
const queuedRequestCount = this.lanes.reduce((sum, lane) => sum + lane.queue.length, 0);
|
|
337
|
+
const busyWorkerCount = this.lanes.filter(({ state }) => state === 'busy').length;
|
|
338
|
+
return {
|
|
339
|
+
state: this.state,
|
|
340
|
+
maxWorkerCount: this.maxWorkers,
|
|
341
|
+
workerCount: this.lanes.filter(({ worker }) => !!worker).length,
|
|
342
|
+
busyWorkerCount,
|
|
343
|
+
queuedRequestCount,
|
|
344
|
+
inFlightRequestCount: queuedRequestCount + busyWorkerCount,
|
|
345
|
+
activeModuleCount: this.activeModuleCount(),
|
|
346
|
+
unavailableModuleIds: [...this.moduleFailures.keys()].sort(),
|
|
347
|
+
restartedWorkerCount: this.restartedWorkerCount,
|
|
348
|
+
workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
|
|
349
|
+
peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private spawn(lane: ReducerLane): Promise<void> {
|
|
354
|
+
lane.generation += 1;
|
|
355
|
+
const generation = lane.generation;
|
|
356
|
+
lane.state = 'starting';
|
|
357
|
+
lane.activeModuleIds.clear();
|
|
358
|
+
const worker = new Worker(WORKER_BOOTSTRAP_URL, {
|
|
359
|
+
execArgv: [],
|
|
360
|
+
resourceLimits: { maxOldGenerationSizeMb: this.maxOldGenerationSizeMb },
|
|
361
|
+
stdout: true,
|
|
362
|
+
stderr: true,
|
|
363
|
+
workerData: {
|
|
364
|
+
runtimeModuleBootstrap: {
|
|
365
|
+
hostUrl: WORKER_HOST_URL,
|
|
366
|
+
hooksUrl: this.options.loader.hooksUrl,
|
|
367
|
+
sdkAliases: this.options.loader.sdkAliases,
|
|
368
|
+
esmModuleRoots: [...new Set(lane.modules.map((module) => (
|
|
369
|
+
new URL('.', module.sourceUrl).href
|
|
370
|
+
)))],
|
|
371
|
+
},
|
|
372
|
+
poolId: this.poolId,
|
|
373
|
+
laneId: lane.id,
|
|
374
|
+
modules: lane.modules,
|
|
375
|
+
spatialFacts: this.options.spatialFacts,
|
|
376
|
+
diagnosticsEnabled: this.options.diagnosticsEnabled === true,
|
|
377
|
+
},
|
|
378
|
+
});
|
|
379
|
+
lane.worker = worker;
|
|
380
|
+
worker.stdout?.on('data', (chunk: Buffer) => this.diagnostic(
|
|
381
|
+
'perception.reducer_worker.stdout',
|
|
382
|
+
{ lane_id: lane.id, module_ids: lane.modules.map(({ moduleId }) => moduleId), bytes: chunk.length },
|
|
383
|
+
));
|
|
384
|
+
worker.stderr?.on('data', (chunk: Buffer) => this.diagnostic(
|
|
385
|
+
'perception.reducer_worker.stderr',
|
|
386
|
+
{ lane_id: lane.id, module_ids: lane.modules.map(({ moduleId }) => moduleId), bytes: chunk.length },
|
|
387
|
+
));
|
|
388
|
+
worker.on('message', (message: unknown) => {
|
|
389
|
+
if (lane.worker === worker && lane.generation === generation) this.handleMessage(lane, message);
|
|
390
|
+
});
|
|
391
|
+
worker.once('error', (error) => {
|
|
392
|
+
if (lane.worker === worker && lane.generation === generation) this.failLane(lane, error);
|
|
393
|
+
});
|
|
394
|
+
worker.once('exit', (code) => {
|
|
395
|
+
if (lane.worker === worker && lane.generation === generation && lane.state !== 'stopped') {
|
|
396
|
+
this.failLane(lane, new Error(`perception_reducer_worker_exited:${code}`));
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
return new Promise<void>((resolve, reject) => {
|
|
400
|
+
let timer!: ReturnType<typeof setTimeout>;
|
|
401
|
+
const finishResolve = (): void => {
|
|
402
|
+
clearTimeout(timer);
|
|
403
|
+
lane.readyResolve = undefined;
|
|
404
|
+
lane.readyReject = undefined;
|
|
405
|
+
resolve();
|
|
406
|
+
};
|
|
407
|
+
const finishReject = (error: Error): void => {
|
|
408
|
+
clearTimeout(timer);
|
|
409
|
+
lane.readyResolve = undefined;
|
|
410
|
+
lane.readyReject = undefined;
|
|
411
|
+
reject(error);
|
|
412
|
+
};
|
|
413
|
+
lane.readyResolve = finishResolve;
|
|
414
|
+
lane.readyReject = finishReject;
|
|
415
|
+
timer = setTimeout(
|
|
416
|
+
() => finishReject(new Error('perception_reducer_worker_start_timeout')),
|
|
417
|
+
START_TIMEOUT_MS,
|
|
418
|
+
);
|
|
419
|
+
timer.unref?.();
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
private handleMessage(lane: ReducerLane, value: unknown): void {
|
|
424
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
425
|
+
this.failLane(lane, new Error('perception_reducer_protocol_invalid'));
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const message = value as WorkerReadyMessage | WorkerResultMessage | WorkerErrorMessage;
|
|
429
|
+
if (message.poolId !== this.poolId || message.laneId !== lane.id) {
|
|
430
|
+
this.failLane(lane, new Error('perception_reducer_identity_mismatch'));
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (this.options.diagnosticsEnabled === true && (
|
|
434
|
+
!Number.isFinite(message.heapUsedBytes)
|
|
435
|
+
|| Number(message.heapUsedBytes) < 0
|
|
436
|
+
)) {
|
|
437
|
+
this.failLane(lane, new Error('perception_reducer_worker_memory_invalid'));
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (typeof message.heapUsedBytes === 'number') {
|
|
441
|
+
lane.heapUsedBytes = message.heapUsedBytes;
|
|
442
|
+
this.peakWorkerHeapUsedBytes = Math.max(
|
|
443
|
+
this.peakWorkerHeapUsedBytes,
|
|
444
|
+
this.currentWorkerHeapUsedBytes(),
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
if (message.type === 'ready') {
|
|
448
|
+
if (lane.state !== 'starting' || !Array.isArray(message.moduleIds)) {
|
|
449
|
+
this.failLane(lane, new Error('perception_reducer_ready_invalid'));
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
const expected = new Set(lane.modules.map(({ moduleId }) => moduleId));
|
|
453
|
+
if (message.moduleIds.some((moduleId) => !expected.has(moduleId))) {
|
|
454
|
+
this.failLane(lane, new Error('perception_reducer_ready_invalid'));
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
lane.activeModuleIds.clear();
|
|
458
|
+
for (const moduleId of message.moduleIds) {
|
|
459
|
+
lane.activeModuleIds.add(moduleId);
|
|
460
|
+
this.moduleFailures.delete(moduleId);
|
|
461
|
+
this.debugSnapshots.set(moduleId, structuredClone(message.debugSnapshots[moduleId] ?? null));
|
|
462
|
+
}
|
|
463
|
+
for (const failure of message.startupFailures ?? []) {
|
|
464
|
+
if (!expected.has(failure.moduleId)) continue;
|
|
465
|
+
this.moduleFailures.set(failure.moduleId, new Error(failure.code));
|
|
466
|
+
this.debugSnapshots.delete(failure.moduleId);
|
|
467
|
+
}
|
|
468
|
+
for (const moduleId of expected) {
|
|
469
|
+
if (!lane.activeModuleIds.has(moduleId) && !this.moduleFailures.has(moduleId)) {
|
|
470
|
+
this.moduleFailures.set(moduleId, new Error('perception_reducer_worker_module_missing'));
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
lane.state = lane.activeModuleIds.size > 0 ? 'idle' : 'stopped';
|
|
474
|
+
lane.readyResolve?.();
|
|
475
|
+
if (lane.state === 'stopped') {
|
|
476
|
+
const worker = lane.worker;
|
|
477
|
+
lane.worker = undefined;
|
|
478
|
+
void worker?.terminate().catch(() => -1);
|
|
479
|
+
}
|
|
480
|
+
this.pump(lane);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const request = lane.current;
|
|
484
|
+
if (!request || message.requestId !== request.requestId || message.moduleId !== request.moduleId) {
|
|
485
|
+
this.failLane(lane, new Error('perception_reducer_request_mismatch'));
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
lane.current = undefined;
|
|
489
|
+
lane.state = 'idle';
|
|
490
|
+
if ('debugSnapshot' in message) {
|
|
491
|
+
this.debugSnapshots.set(request.moduleId, structuredClone(message.debugSnapshot ?? null));
|
|
492
|
+
}
|
|
493
|
+
if (message.type === 'result') {
|
|
494
|
+
lane.consecutiveWorkerFailures = 0;
|
|
495
|
+
this.resolveRequest(request, message.events);
|
|
496
|
+
} else if (message.type === 'request_error') {
|
|
497
|
+
this.rejectRequest(request, new Error(message.code));
|
|
498
|
+
} else {
|
|
499
|
+
this.rejectRequest(request, new Error(message.code ?? 'perception_reducer_worker_failed'));
|
|
500
|
+
this.restartLane(lane, 'worker_error');
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
this.pump(lane);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
private pumpAll(): void {
|
|
507
|
+
for (const lane of this.lanes) this.pump(lane);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
private pump(lane: ReducerLane): void {
|
|
511
|
+
if (this.state !== 'running' || lane.state !== 'idle' || lane.current) return;
|
|
512
|
+
while (lane.queue.length > 0) {
|
|
513
|
+
const request = lane.queue.shift()!;
|
|
514
|
+
if (request.settled || request.signal.aborted) {
|
|
515
|
+
if (!request.settled) this.rejectRequest(request, abortError(request.signal));
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (!lane.activeModuleIds.has(request.moduleId)) {
|
|
519
|
+
this.rejectRequest(request, this.moduleFailures.get(request.moduleId)
|
|
520
|
+
?? new Error(`perception_reducer_unavailable:${request.moduleId}`));
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
lane.current = request;
|
|
524
|
+
lane.state = 'busy';
|
|
525
|
+
try {
|
|
526
|
+
lane.worker!.postMessage({
|
|
527
|
+
type: 'operate',
|
|
528
|
+
poolId: this.poolId,
|
|
529
|
+
requestId: request.requestId,
|
|
530
|
+
moduleId: request.moduleId,
|
|
531
|
+
operation: request.operation,
|
|
532
|
+
...request.input,
|
|
533
|
+
});
|
|
534
|
+
} catch (error) {
|
|
535
|
+
this.rejectRequest(request, asError(error, 'perception_reducer_submit_failed'));
|
|
536
|
+
this.restartLane(lane, 'submit_failed');
|
|
537
|
+
}
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
private abortRequest(lane: ReducerLane, request: PendingRequest): void {
|
|
543
|
+
if (request.settled) return;
|
|
544
|
+
const queued = lane.queue.indexOf(request);
|
|
545
|
+
if (queued >= 0) lane.queue.splice(queued, 1);
|
|
546
|
+
const active = lane.current === request;
|
|
547
|
+
this.rejectRequest(request, abortError(request.signal));
|
|
548
|
+
if (active) this.restartLane(lane, 'request_aborted');
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
private resolveRequest(
|
|
552
|
+
request: PendingRequest,
|
|
553
|
+
events: readonly PerceptionEventProposal[],
|
|
554
|
+
): void {
|
|
555
|
+
if (request.settled) return;
|
|
556
|
+
request.settled = true;
|
|
557
|
+
request.signal.removeEventListener('abort', request.onAbort);
|
|
558
|
+
request.resolve(structuredClone(events));
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
private rejectRequest(request: PendingRequest, error: Error): void {
|
|
562
|
+
if (request.settled) return;
|
|
563
|
+
request.settled = true;
|
|
564
|
+
request.signal.removeEventListener('abort', request.onAbort);
|
|
565
|
+
request.reject(error);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
private failLane(lane: ReducerLane, error: Error): void {
|
|
569
|
+
lane.readyReject?.(error);
|
|
570
|
+
if (lane.current) {
|
|
571
|
+
const current = lane.current;
|
|
572
|
+
lane.current = undefined;
|
|
573
|
+
this.rejectRequest(current, error);
|
|
574
|
+
}
|
|
575
|
+
if (this.state !== 'running') return;
|
|
576
|
+
this.restartLane(lane, 'worker_failed', error);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
private restartLane(lane: ReducerLane, reason: string, failure?: Error): void {
|
|
580
|
+
if (lane.restartTask || this.state !== 'running') return;
|
|
581
|
+
lane.consecutiveWorkerFailures += 1;
|
|
582
|
+
for (const moduleId of lane.activeModuleIds) this.debugSnapshots.delete(moduleId);
|
|
583
|
+
lane.activeModuleIds.clear();
|
|
584
|
+
const stateLost = failure ?? new Error(`perception_reducer_state_lost:${reason}`);
|
|
585
|
+
for (const request of [...lane.queue]) this.rejectRequest(request, stateLost);
|
|
586
|
+
lane.queue.length = 0;
|
|
587
|
+
if (lane.consecutiveWorkerFailures >= 3) {
|
|
588
|
+
const worker = lane.worker;
|
|
589
|
+
lane.worker = undefined;
|
|
590
|
+
lane.current = undefined;
|
|
591
|
+
lane.state = 'stopped';
|
|
592
|
+
lane.generation += 1;
|
|
593
|
+
void worker?.terminate().catch(() => -1);
|
|
594
|
+
for (const { moduleId } of lane.modules) {
|
|
595
|
+
this.moduleFailures.set(
|
|
596
|
+
moduleId,
|
|
597
|
+
new Error('perception_reducer_disabled_after_worker_failures'),
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
this.diagnostic('perception.module.disabled', {
|
|
601
|
+
module_ids: lane.modules.map(({ moduleId }) => moduleId),
|
|
602
|
+
reason: 'reducer_worker_failures',
|
|
603
|
+
consecutive_failures: lane.consecutiveWorkerFailures,
|
|
604
|
+
}, 'error');
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
const worker = lane.worker;
|
|
608
|
+
lane.worker = undefined;
|
|
609
|
+
lane.current = undefined;
|
|
610
|
+
lane.state = 'restarting';
|
|
611
|
+
lane.generation += 1;
|
|
612
|
+
lane.restartTask = Promise.resolve(worker?.terminate()).catch(() => -1).then(async () => {
|
|
613
|
+
if (this.state !== 'running') return;
|
|
614
|
+
await this.spawn(lane);
|
|
615
|
+
this.restartedWorkerCount += 1;
|
|
616
|
+
this.diagnostic('perception.reducer_worker.restarted', {
|
|
617
|
+
lane_id: lane.id,
|
|
618
|
+
module_ids: lane.modules.map(({ moduleId }) => moduleId),
|
|
619
|
+
reason,
|
|
620
|
+
}, 'warn');
|
|
621
|
+
}).catch((error) => {
|
|
622
|
+
lane.state = 'stopped';
|
|
623
|
+
for (const { moduleId } of lane.modules) {
|
|
624
|
+
this.moduleFailures.set(
|
|
625
|
+
moduleId,
|
|
626
|
+
asError(error, 'perception_reducer_restart_failed'),
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
this.diagnostic('perception.reducer_worker.replacement_failed', {
|
|
630
|
+
lane_id: lane.id,
|
|
631
|
+
module_ids: lane.modules.map(({ moduleId }) => moduleId),
|
|
632
|
+
reason,
|
|
633
|
+
error_code: asError(error, 'perception_reducer_restart_failed').message.split(':', 1)[0],
|
|
634
|
+
}, 'error');
|
|
635
|
+
}).finally(() => {
|
|
636
|
+
lane.restartTask = undefined;
|
|
637
|
+
this.pump(lane);
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
private activeModuleCount(): number {
|
|
642
|
+
return this.lanes.reduce((sum, lane) => sum + lane.activeModuleIds.size, 0);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
private currentWorkerHeapUsedBytes(): number {
|
|
646
|
+
return this.lanes.reduce((sum, lane) => sum + (lane.heapUsedBytes ?? 0), 0);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
private diagnostic(
|
|
650
|
+
name: string,
|
|
651
|
+
attributes?: Readonly<Record<string, unknown>>,
|
|
652
|
+
severity?: RuntimeDiagnosticSeverity,
|
|
653
|
+
): void {
|
|
654
|
+
try {
|
|
655
|
+
this.diagnosticCallback?.(name, attributes, severity);
|
|
656
|
+
} catch {
|
|
657
|
+
// Diagnostics never alter reducer execution or lifecycle.
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|