@myclaw163/clawclaw-cli 0.8.14 → 0.8.16
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/scripts/sync-bundled-skill.mjs +28 -57
- package/skills/clawclaw/SKILL.md +6 -2
- package/skills/clawclaw/references/BEHAVIORS.md +16 -1
- package/skills/clawclaw/references/COMMANDS.md +1 -1
- 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/HUB.md +2 -1
- package/src/commands/account.ts +36 -0
- package/src/commands/capability.ts +6 -1
- package/src/commands/load.ts +11 -0
- package/src/lib/agent-workspace-runtime.ts +2 -1
- package/src/lib/agent-workspace-skills.ts +235 -23
- package/src/lib/agent-workspace-sync.ts +17 -5
- package/src/lib/capability-cloud-refresh.ts +10 -1
- package/src/lib/capability-cloud-sync.ts +71 -1
- package/src/lib/capability-workspace.ts +2 -0
- package/src/lib/game-client.ts +10 -0
- package/src/runtime/clawclaw/behavior-decision.ts +4 -1
- package/src/runtime/clawclaw/owner.ts +79 -2
- package/src/runtime/clawclaw/plugins/assembly.ts +4 -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-normalization.ts +3 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +46 -50
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +39 -9
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +167 -7
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +107 -0
- package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
- 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 +28 -4
- 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 +126 -17
- 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/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-event-catalog.ts +1 -0
- package/src/runtime/framework/events/memory-event-repository.ts +12 -0
- package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +3 -0
- package/src/runtime/framework/plugins/contracts.ts +3 -0
- package/src/runtime/framework/plugins/runtime-input-journal.ts +12 -0
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +150 -23
- package/src/runtime/framework/runtime.ts +18 -0
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +10 -0
- package/src/runtime/game-sync-protocol.ts +47 -0
- package/src/runtime/observability/redaction.ts +28 -1
- package/src/runtime/ws-client.ts +7 -0
- package/src/sdk/perception-plugin/index.ts +13 -8
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { Worker } from 'node:worker_threads';
|
|
3
|
+
import type { BehaviorInput } from '../../../../sdk/behavior-plugin/index.js';
|
|
4
|
+
import type {
|
|
5
|
+
TriggerInput,
|
|
6
|
+
TriggerResetReason,
|
|
7
|
+
} from '../../../../sdk/trigger-plugin/index.js';
|
|
8
|
+
import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index.js';
|
|
9
|
+
import type {
|
|
10
|
+
RuntimeModuleThreadLoaderConfig,
|
|
11
|
+
} from '../../../framework/modules/runtime-module-loader.js';
|
|
12
|
+
import type { TriggerThreadModuleSpec } from './trigger-module-loader.js';
|
|
13
|
+
|
|
14
|
+
const WORKER_BOOTSTRAP_URL = new URL(
|
|
15
|
+
'../../../framework/modules/runtime-module-worker-bootstrap.mjs',
|
|
16
|
+
import.meta.url,
|
|
17
|
+
);
|
|
18
|
+
const WORKER_HOST_URL = new URL('./trigger-thread-worker.ts', import.meta.url).href;
|
|
19
|
+
const MAX_TRIGGER_WORKERS = 10;
|
|
20
|
+
const START_TIMEOUT_MS = 20_000;
|
|
21
|
+
|
|
22
|
+
export interface TriggerThreadPoolOptions {
|
|
23
|
+
readonly modules: readonly TriggerThreadModuleSpec[];
|
|
24
|
+
readonly loader: RuntimeModuleThreadLoaderConfig;
|
|
25
|
+
readonly maxOldGenerationSizeMb?: number;
|
|
26
|
+
readonly diagnosticsEnabled?: boolean;
|
|
27
|
+
readonly diagnostic?: (
|
|
28
|
+
name: string,
|
|
29
|
+
attributes?: Readonly<Record<string, unknown>>,
|
|
30
|
+
severity?: RuntimeDiagnosticSeverity,
|
|
31
|
+
) => void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface TriggerThreadEvaluation {
|
|
35
|
+
readonly epochId: number;
|
|
36
|
+
readonly triggerId: string;
|
|
37
|
+
readonly input: Readonly<TriggerInput>;
|
|
38
|
+
readonly readInput: Readonly<BehaviorInput>;
|
|
39
|
+
readonly resetReason?: TriggerResetReason;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface TriggerThreadPoolSnapshot {
|
|
43
|
+
readonly state: 'new' | 'starting' | 'running' | 'stopping' | 'stopped';
|
|
44
|
+
readonly workerCount: number;
|
|
45
|
+
readonly busyWorkerCount: number;
|
|
46
|
+
readonly queuedRequestCount: number;
|
|
47
|
+
readonly inFlightRequestCount: number;
|
|
48
|
+
readonly workerHeapUsedBytes: number;
|
|
49
|
+
readonly peakWorkerHeapUsedBytes: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface PendingRequest {
|
|
53
|
+
readonly requestId: string;
|
|
54
|
+
readonly evaluation: TriggerThreadEvaluation;
|
|
55
|
+
readonly signal: AbortSignal;
|
|
56
|
+
readonly resolve: (value: unknown) => void;
|
|
57
|
+
readonly reject: (error: Error) => void;
|
|
58
|
+
readonly onAbort: () => void;
|
|
59
|
+
settled: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface TriggerLane {
|
|
63
|
+
readonly id: number;
|
|
64
|
+
readonly modules: readonly TriggerThreadModuleSpec[];
|
|
65
|
+
readonly queue: PendingRequest[];
|
|
66
|
+
worker?: Worker;
|
|
67
|
+
state: 'starting' | 'idle' | 'busy' | 'restarting' | 'stopped';
|
|
68
|
+
current?: PendingRequest;
|
|
69
|
+
readyResolve?: () => void;
|
|
70
|
+
readyReject?: (error: Error) => void;
|
|
71
|
+
heapUsedBytes?: number;
|
|
72
|
+
generation: number;
|
|
73
|
+
consecutiveWorkerFailures: number;
|
|
74
|
+
restartTask?: Promise<void>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface WorkerMessageBase {
|
|
78
|
+
readonly type: string;
|
|
79
|
+
readonly poolId: string;
|
|
80
|
+
readonly laneId: number;
|
|
81
|
+
readonly requestId?: string;
|
|
82
|
+
readonly heapUsedBytes?: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface WorkerReadyMessage extends WorkerMessageBase {
|
|
86
|
+
readonly type: 'ready';
|
|
87
|
+
readonly triggerIds: readonly string[];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
interface WorkerResultMessage extends WorkerMessageBase {
|
|
91
|
+
readonly type: 'result';
|
|
92
|
+
readonly requestId: string;
|
|
93
|
+
readonly triggerId: string;
|
|
94
|
+
readonly result: unknown;
|
|
95
|
+
readonly outputBytes: number;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface WorkerErrorMessage extends WorkerMessageBase {
|
|
99
|
+
readonly type: 'request_error' | 'error';
|
|
100
|
+
readonly triggerId?: string;
|
|
101
|
+
readonly code: string;
|
|
102
|
+
readonly message?: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function asError(value: unknown, fallback: string): Error {
|
|
106
|
+
return value instanceof Error ? value : new Error(typeof value === 'string' ? value : fallback);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function abortError(signal: AbortSignal): Error {
|
|
110
|
+
return asError(signal.reason, 'trigger_thread_request_aborted');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export class TriggerThreadPool {
|
|
114
|
+
private readonly poolId = randomUUID();
|
|
115
|
+
private readonly maxOldGenerationSizeMb: number;
|
|
116
|
+
private readonly lanes: TriggerLane[];
|
|
117
|
+
private readonly laneByTrigger = new Map<string, TriggerLane>();
|
|
118
|
+
private state: TriggerThreadPoolSnapshot['state'] = 'new';
|
|
119
|
+
private peakWorkerHeapUsedBytes = 0;
|
|
120
|
+
|
|
121
|
+
constructor(private readonly options: TriggerThreadPoolOptions) {
|
|
122
|
+
const ids = options.modules.map(({ triggerId }) => triggerId);
|
|
123
|
+
if (new Set(ids).size !== ids.length) throw new Error('trigger_thread_module_duplicate');
|
|
124
|
+
this.maxOldGenerationSizeMb = Math.max(16, Math.min(
|
|
125
|
+
256,
|
|
126
|
+
Math.floor(options.maxOldGenerationSizeMb ?? 64),
|
|
127
|
+
));
|
|
128
|
+
const laneCount = Math.min(MAX_TRIGGER_WORKERS, options.modules.length);
|
|
129
|
+
const groups = Array.from({ length: laneCount }, () => [] as TriggerThreadModuleSpec[]);
|
|
130
|
+
options.modules.forEach((module, index) => groups[index % Math.max(1, laneCount)]!.push(module));
|
|
131
|
+
this.lanes = groups.map((modules, index) => ({
|
|
132
|
+
id: index + 1,
|
|
133
|
+
modules,
|
|
134
|
+
queue: [],
|
|
135
|
+
state: 'stopped',
|
|
136
|
+
generation: 0,
|
|
137
|
+
consecutiveWorkerFailures: 0,
|
|
138
|
+
}));
|
|
139
|
+
for (const lane of this.lanes) {
|
|
140
|
+
for (const module of lane.modules) this.laneByTrigger.set(module.triggerId, lane);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async start(): Promise<void> {
|
|
145
|
+
if (this.state === 'running') return;
|
|
146
|
+
if (this.state === 'stopping' || this.state === 'stopped') {
|
|
147
|
+
throw new Error('trigger_thread_pool_stopped');
|
|
148
|
+
}
|
|
149
|
+
this.state = 'starting';
|
|
150
|
+
const starts = await Promise.allSettled(this.lanes.map((lane) => this.spawn(lane)));
|
|
151
|
+
if (this.state !== 'starting') throw new Error('trigger_thread_pool_stopped');
|
|
152
|
+
for (const [index, result] of starts.entries()) {
|
|
153
|
+
if (result.status === 'fulfilled') continue;
|
|
154
|
+
const lane = this.lanes[index]!;
|
|
155
|
+
lane.state = 'stopped';
|
|
156
|
+
const worker = lane.worker;
|
|
157
|
+
lane.worker = undefined;
|
|
158
|
+
await worker?.terminate().catch(() => -1);
|
|
159
|
+
this.diagnostic('trigger.module.disabled', {
|
|
160
|
+
trigger_ids: lane.modules.map(({ triggerId }) => triggerId),
|
|
161
|
+
reason: 'worker_start_failed',
|
|
162
|
+
error_code: asError(result.reason, 'trigger_thread_start_failed').message.split(':', 1)[0],
|
|
163
|
+
}, 'error');
|
|
164
|
+
}
|
|
165
|
+
this.state = 'running';
|
|
166
|
+
this.diagnostic('trigger.thread_pool.started', {
|
|
167
|
+
worker_count: this.lanes.filter(({ state }) => state !== 'stopped').length,
|
|
168
|
+
unavailable_trigger_ids: this.lanes
|
|
169
|
+
.filter(({ state }) => state === 'stopped')
|
|
170
|
+
.flatMap(({ modules }) => modules.map(({ triggerId }) => triggerId)),
|
|
171
|
+
max_worker_count: MAX_TRIGGER_WORKERS,
|
|
172
|
+
worker_max_old_generation_mb: this.maxOldGenerationSizeMb,
|
|
173
|
+
}, 'info');
|
|
174
|
+
this.pumpAll();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
evaluate(evaluation: TriggerThreadEvaluation, signal: AbortSignal): Promise<unknown> {
|
|
178
|
+
if (this.state !== 'running') return Promise.reject(new Error('trigger_thread_pool_not_running'));
|
|
179
|
+
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
180
|
+
const lane = this.laneByTrigger.get(evaluation.triggerId);
|
|
181
|
+
if (!lane || lane.state === 'stopped') {
|
|
182
|
+
return Promise.reject(new Error(`trigger_thread_unavailable:${evaluation.triggerId}`));
|
|
183
|
+
}
|
|
184
|
+
return new Promise((resolve, reject) => {
|
|
185
|
+
const request: PendingRequest = {
|
|
186
|
+
requestId: randomUUID(),
|
|
187
|
+
evaluation,
|
|
188
|
+
signal,
|
|
189
|
+
resolve,
|
|
190
|
+
reject,
|
|
191
|
+
settled: false,
|
|
192
|
+
onAbort: () => this.abortRequest(lane, request),
|
|
193
|
+
};
|
|
194
|
+
signal.addEventListener('abort', request.onAbort, { once: true });
|
|
195
|
+
const insertion = lane.queue.findIndex(({ evaluation: queued }) => (
|
|
196
|
+
queued.epochId > evaluation.epochId
|
|
197
|
+
));
|
|
198
|
+
if (insertion < 0) lane.queue.push(request);
|
|
199
|
+
else lane.queue.splice(insertion, 0, request);
|
|
200
|
+
this.pump(lane);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async stop(): Promise<void> {
|
|
205
|
+
if (this.state === 'stopped') return;
|
|
206
|
+
this.state = 'stopping';
|
|
207
|
+
for (const lane of this.lanes) {
|
|
208
|
+
const error = new Error('trigger_thread_pool_stopped');
|
|
209
|
+
if (lane.current) this.rejectRequest(lane.current, error);
|
|
210
|
+
for (const request of [...lane.queue]) this.rejectRequest(request, error);
|
|
211
|
+
lane.queue.length = 0;
|
|
212
|
+
lane.current = undefined;
|
|
213
|
+
lane.state = 'stopped';
|
|
214
|
+
const worker = lane.worker;
|
|
215
|
+
lane.worker = undefined;
|
|
216
|
+
if (worker) await worker.terminate().catch(() => -1);
|
|
217
|
+
}
|
|
218
|
+
this.state = 'stopped';
|
|
219
|
+
this.diagnostic('trigger.thread_pool.stopped', {
|
|
220
|
+
worker_count: 0,
|
|
221
|
+
peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
|
|
222
|
+
}, 'info');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
snapshot(): TriggerThreadPoolSnapshot {
|
|
226
|
+
const requests = this.lanes.flatMap((lane) => [
|
|
227
|
+
...(lane.current ? [lane.current] : []),
|
|
228
|
+
...lane.queue,
|
|
229
|
+
]);
|
|
230
|
+
return {
|
|
231
|
+
state: this.state,
|
|
232
|
+
workerCount: this.lanes.filter(({ worker }) => !!worker).length,
|
|
233
|
+
busyWorkerCount: this.lanes.filter(({ state }) => state === 'busy').length,
|
|
234
|
+
queuedRequestCount: this.lanes.reduce((sum, lane) => sum + lane.queue.length, 0),
|
|
235
|
+
inFlightRequestCount: requests.length,
|
|
236
|
+
workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
|
|
237
|
+
peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private spawn(lane: TriggerLane): Promise<void> {
|
|
242
|
+
lane.generation += 1;
|
|
243
|
+
const generation = lane.generation;
|
|
244
|
+
lane.state = 'starting';
|
|
245
|
+
const worker = new Worker(WORKER_BOOTSTRAP_URL, {
|
|
246
|
+
execArgv: [],
|
|
247
|
+
resourceLimits: { maxOldGenerationSizeMb: this.maxOldGenerationSizeMb },
|
|
248
|
+
stdout: true,
|
|
249
|
+
stderr: true,
|
|
250
|
+
workerData: {
|
|
251
|
+
runtimeModuleBootstrap: {
|
|
252
|
+
hostUrl: WORKER_HOST_URL,
|
|
253
|
+
hooksUrl: this.options.loader.hooksUrl,
|
|
254
|
+
sdkAliases: this.options.loader.sdkAliases,
|
|
255
|
+
esmModuleRoots: [...new Set(lane.modules.map((module) => (
|
|
256
|
+
new URL('.', module.sourceUrl).href
|
|
257
|
+
)))],
|
|
258
|
+
},
|
|
259
|
+
poolId: this.poolId,
|
|
260
|
+
laneId: lane.id,
|
|
261
|
+
modules: lane.modules,
|
|
262
|
+
diagnosticsEnabled: this.options.diagnosticsEnabled === true,
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
lane.worker = worker;
|
|
266
|
+
worker.stdout?.on('data', (chunk: Buffer) => this.diagnostic(
|
|
267
|
+
'trigger.thread.stdout',
|
|
268
|
+
{ trigger_ids: lane.modules.map(({ triggerId }) => triggerId), lane_id: lane.id, bytes: chunk.length },
|
|
269
|
+
));
|
|
270
|
+
worker.stderr?.on('data', (chunk: Buffer) => this.diagnostic(
|
|
271
|
+
'trigger.thread.stderr',
|
|
272
|
+
{ trigger_ids: lane.modules.map(({ triggerId }) => triggerId), lane_id: lane.id, bytes: chunk.length },
|
|
273
|
+
));
|
|
274
|
+
worker.on('message', (message: unknown) => {
|
|
275
|
+
if (lane.worker === worker && lane.generation === generation) this.handleMessage(lane, message);
|
|
276
|
+
});
|
|
277
|
+
worker.once('error', (error) => {
|
|
278
|
+
if (lane.worker === worker && lane.generation === generation) this.failLane(lane, error);
|
|
279
|
+
});
|
|
280
|
+
worker.once('exit', (code) => {
|
|
281
|
+
if (lane.worker === worker && lane.generation === generation && lane.state !== 'stopped') {
|
|
282
|
+
this.failLane(lane, new Error(`trigger_thread_worker_exited:${code}`));
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
return new Promise<void>((resolve, reject) => {
|
|
286
|
+
let timer!: ReturnType<typeof setTimeout>;
|
|
287
|
+
const finishResolve = (): void => {
|
|
288
|
+
clearTimeout(timer);
|
|
289
|
+
lane.readyResolve = undefined;
|
|
290
|
+
lane.readyReject = undefined;
|
|
291
|
+
resolve();
|
|
292
|
+
};
|
|
293
|
+
const finishReject = (error: Error): void => {
|
|
294
|
+
clearTimeout(timer);
|
|
295
|
+
lane.readyResolve = undefined;
|
|
296
|
+
lane.readyReject = undefined;
|
|
297
|
+
reject(error);
|
|
298
|
+
};
|
|
299
|
+
lane.readyResolve = finishResolve;
|
|
300
|
+
lane.readyReject = finishReject;
|
|
301
|
+
timer = setTimeout(
|
|
302
|
+
() => finishReject(new Error('trigger_thread_worker_start_timeout')),
|
|
303
|
+
START_TIMEOUT_MS,
|
|
304
|
+
);
|
|
305
|
+
timer.unref?.();
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private handleMessage(lane: TriggerLane, value: unknown): void {
|
|
310
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
311
|
+
this.failLane(lane, new Error('trigger_thread_protocol_invalid'));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const message = value as WorkerReadyMessage | WorkerResultMessage | WorkerErrorMessage;
|
|
315
|
+
if (message.poolId !== this.poolId || message.laneId !== lane.id) {
|
|
316
|
+
this.failLane(lane, new Error('trigger_thread_protocol_identity_mismatch'));
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
if (typeof message.heapUsedBytes === 'number' && Number.isFinite(message.heapUsedBytes)) {
|
|
320
|
+
lane.heapUsedBytes = Math.max(0, message.heapUsedBytes);
|
|
321
|
+
this.peakWorkerHeapUsedBytes = Math.max(
|
|
322
|
+
this.peakWorkerHeapUsedBytes,
|
|
323
|
+
this.currentWorkerHeapUsedBytes(),
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
if (message.type === 'ready') {
|
|
327
|
+
if (
|
|
328
|
+
lane.state !== 'starting'
|
|
329
|
+
|| message.triggerIds.length !== lane.modules.length
|
|
330
|
+
|| message.triggerIds.some((id, index) => id !== lane.modules[index]?.triggerId)
|
|
331
|
+
) {
|
|
332
|
+
this.failLane(lane, new Error('trigger_thread_ready_invalid'));
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
lane.state = 'idle';
|
|
336
|
+
lane.readyResolve?.();
|
|
337
|
+
this.pump(lane);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
const request = lane.current;
|
|
341
|
+
if (!request || message.requestId !== request.requestId) {
|
|
342
|
+
this.failLane(lane, new Error('trigger_thread_request_mismatch'));
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
lane.current = undefined;
|
|
346
|
+
lane.state = 'idle';
|
|
347
|
+
if (message.type === 'result') {
|
|
348
|
+
if (message.triggerId !== request.evaluation.triggerId) {
|
|
349
|
+
this.rejectRequest(request, new Error('trigger_thread_result_invalid'));
|
|
350
|
+
} else {
|
|
351
|
+
lane.consecutiveWorkerFailures = 0;
|
|
352
|
+
this.resolveRequest(request, message.result);
|
|
353
|
+
}
|
|
354
|
+
} else {
|
|
355
|
+
const detail = message.message?.trim().slice(0, 512);
|
|
356
|
+
this.rejectRequest(request, new Error(detail ? `${message.code}: ${detail}` : message.code));
|
|
357
|
+
}
|
|
358
|
+
this.pump(lane);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private pumpAll(): void {
|
|
362
|
+
for (const lane of this.lanes) this.pump(lane);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
private pump(lane: TriggerLane): void {
|
|
366
|
+
if (this.state !== 'running' || lane.state !== 'idle' || lane.current) return;
|
|
367
|
+
while (lane.queue.length > 0) {
|
|
368
|
+
const request = lane.queue.shift()!;
|
|
369
|
+
if (request.settled || request.signal.aborted) {
|
|
370
|
+
if (!request.settled) this.rejectRequest(request, abortError(request.signal));
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
lane.current = request;
|
|
374
|
+
lane.state = 'busy';
|
|
375
|
+
try {
|
|
376
|
+
lane.worker!.postMessage({
|
|
377
|
+
type: 'evaluate',
|
|
378
|
+
poolId: this.poolId,
|
|
379
|
+
requestId: request.requestId,
|
|
380
|
+
triggerId: request.evaluation.triggerId,
|
|
381
|
+
input: request.evaluation.input,
|
|
382
|
+
readInput: request.evaluation.readInput,
|
|
383
|
+
...(request.evaluation.resetReason === undefined
|
|
384
|
+
? {}
|
|
385
|
+
: { resetReason: request.evaluation.resetReason }),
|
|
386
|
+
});
|
|
387
|
+
} catch (error) {
|
|
388
|
+
this.rejectRequest(request, asError(error, 'trigger_thread_submit_failed'));
|
|
389
|
+
this.restartLane(lane, 'submit_failed');
|
|
390
|
+
}
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private abortRequest(lane: TriggerLane, request: PendingRequest): void {
|
|
396
|
+
if (request.settled) return;
|
|
397
|
+
const queued = lane.queue.indexOf(request);
|
|
398
|
+
if (queued >= 0) lane.queue.splice(queued, 1);
|
|
399
|
+
const active = lane.current === request;
|
|
400
|
+
this.rejectRequest(request, abortError(request.signal));
|
|
401
|
+
if (active) this.restartLane(lane, 'request_aborted');
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private resolveRequest(request: PendingRequest, value: unknown): void {
|
|
405
|
+
if (request.settled) return;
|
|
406
|
+
request.settled = true;
|
|
407
|
+
request.signal.removeEventListener('abort', request.onAbort);
|
|
408
|
+
request.resolve(structuredClone(value));
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
private rejectRequest(request: PendingRequest, error: Error): void {
|
|
412
|
+
if (request.settled) return;
|
|
413
|
+
request.settled = true;
|
|
414
|
+
request.signal.removeEventListener('abort', request.onAbort);
|
|
415
|
+
request.reject(error);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
private failLane(lane: TriggerLane, error: Error): void {
|
|
419
|
+
lane.readyReject?.(error);
|
|
420
|
+
if (lane.current) this.rejectRequest(lane.current, error);
|
|
421
|
+
lane.consecutiveWorkerFailures += 1;
|
|
422
|
+
this.diagnostic('trigger.thread.failed', {
|
|
423
|
+
trigger_id: lane.current?.evaluation.triggerId ?? null,
|
|
424
|
+
trigger_ids: lane.modules.map(({ triggerId }) => triggerId),
|
|
425
|
+
lane_id: lane.id,
|
|
426
|
+
error_code: error.message.split(':', 1)[0],
|
|
427
|
+
}, 'error');
|
|
428
|
+
if (this.state !== 'running') return;
|
|
429
|
+
if (lane.consecutiveWorkerFailures >= 3) {
|
|
430
|
+
const worker = lane.worker;
|
|
431
|
+
lane.worker = undefined;
|
|
432
|
+
lane.current = undefined;
|
|
433
|
+
lane.state = 'stopped';
|
|
434
|
+
void worker?.terminate().catch(() => -1);
|
|
435
|
+
for (const request of [...lane.queue]) {
|
|
436
|
+
this.rejectRequest(request, new Error('trigger_thread_disabled_after_worker_failures'));
|
|
437
|
+
}
|
|
438
|
+
lane.queue.length = 0;
|
|
439
|
+
this.diagnostic('trigger.module.disabled', {
|
|
440
|
+
trigger_ids: lane.modules.map(({ triggerId }) => triggerId),
|
|
441
|
+
reason: 'worker_failures',
|
|
442
|
+
consecutive_failures: lane.consecutiveWorkerFailures,
|
|
443
|
+
}, 'error');
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
this.restartLane(lane, 'worker_error');
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
private restartLane(lane: TriggerLane, reason: string): void {
|
|
450
|
+
if (lane.restartTask || this.state !== 'running') return;
|
|
451
|
+
const worker = lane.worker;
|
|
452
|
+
lane.worker = undefined;
|
|
453
|
+
lane.current = undefined;
|
|
454
|
+
lane.state = 'restarting';
|
|
455
|
+
lane.restartTask = Promise.resolve(worker?.terminate()).catch(() => -1).then(async () => {
|
|
456
|
+
if (this.state !== 'running') return;
|
|
457
|
+
await this.spawn(lane);
|
|
458
|
+
this.diagnostic('trigger.thread.restarted', {
|
|
459
|
+
trigger_ids: lane.modules.map(({ triggerId }) => triggerId),
|
|
460
|
+
lane_id: lane.id,
|
|
461
|
+
reason,
|
|
462
|
+
}, 'warn');
|
|
463
|
+
}).catch((error) => {
|
|
464
|
+
lane.state = 'stopped';
|
|
465
|
+
for (const request of [...lane.queue]) {
|
|
466
|
+
this.rejectRequest(request, asError(error, 'trigger_thread_restart_failed'));
|
|
467
|
+
}
|
|
468
|
+
lane.queue.length = 0;
|
|
469
|
+
this.diagnostic('trigger.thread.replacement_failed', {
|
|
470
|
+
trigger_ids: lane.modules.map(({ triggerId }) => triggerId),
|
|
471
|
+
lane_id: lane.id,
|
|
472
|
+
reason,
|
|
473
|
+
error_code: asError(error, 'trigger_thread_restart_failed').message.split(':', 1)[0],
|
|
474
|
+
}, 'error');
|
|
475
|
+
}).finally(() => {
|
|
476
|
+
lane.restartTask = undefined;
|
|
477
|
+
this.pump(lane);
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
private currentWorkerHeapUsedBytes(): number {
|
|
482
|
+
return this.lanes.reduce((sum, lane) => sum + (lane.heapUsedBytes ?? 0), 0);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private diagnostic(
|
|
486
|
+
name: string,
|
|
487
|
+
attributes?: Readonly<Record<string, unknown>>,
|
|
488
|
+
severity?: RuntimeDiagnosticSeverity,
|
|
489
|
+
): void {
|
|
490
|
+
try {
|
|
491
|
+
this.options.diagnostic?.(name, attributes, severity);
|
|
492
|
+
} catch {
|
|
493
|
+
// Diagnostics never alter Trigger execution.
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
2
|
+
import type {
|
|
3
|
+
ClawclawTrigger,
|
|
4
|
+
ClawclawTriggerClass,
|
|
5
|
+
TriggerInput,
|
|
6
|
+
TriggerResetReason,
|
|
7
|
+
} from '../../../../sdk/trigger-plugin/index.js';
|
|
8
|
+
import type { BehaviorInput } from '../../../../sdk/behavior-plugin/index.js';
|
|
9
|
+
import { createBehaviorReadApi } from '../../behavior-read-api.js';
|
|
10
|
+
import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js';
|
|
11
|
+
import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
|
|
12
|
+
import {
|
|
13
|
+
validateClawclawTriggerModule,
|
|
14
|
+
type TriggerThreadModuleSpec,
|
|
15
|
+
} from './trigger-module-loader.js';
|
|
16
|
+
|
|
17
|
+
interface TriggerThreadWorkerData {
|
|
18
|
+
readonly poolId: string;
|
|
19
|
+
readonly laneId: number;
|
|
20
|
+
readonly modules: readonly TriggerThreadModuleSpec[];
|
|
21
|
+
readonly diagnosticsEnabled?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface TriggerEvaluateRequest {
|
|
25
|
+
readonly type: 'evaluate';
|
|
26
|
+
readonly poolId: string;
|
|
27
|
+
readonly requestId: string;
|
|
28
|
+
readonly triggerId: string;
|
|
29
|
+
readonly input: TriggerInput;
|
|
30
|
+
readonly readInput: BehaviorInput;
|
|
31
|
+
readonly resetReason?: TriggerResetReason;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function errorMessage(error: unknown): string {
|
|
35
|
+
return error instanceof Error ? error.message : String(error);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function errorCode(error: unknown): string {
|
|
39
|
+
const message = errorMessage(error).trim();
|
|
40
|
+
return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message)?.[1]
|
|
41
|
+
?? 'TRIGGER_THREAD_OPERATION_FAILED';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
|
|
45
|
+
if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
|
|
46
|
+
const object = value as object;
|
|
47
|
+
if (seen.has(object)) return value;
|
|
48
|
+
seen.add(object);
|
|
49
|
+
for (const child of Object.values(object)) deepFreeze(child, seen);
|
|
50
|
+
return Object.freeze(value);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const port = parentPort;
|
|
54
|
+
if (!port) throw new Error('trigger_thread_parent_missing');
|
|
55
|
+
const data = workerData as Partial<TriggerThreadWorkerData> | undefined;
|
|
56
|
+
if (
|
|
57
|
+
!data
|
|
58
|
+
|| typeof data.poolId !== 'string'
|
|
59
|
+
|| typeof data.laneId !== 'number'
|
|
60
|
+
|| !Array.isArray(data.modules)
|
|
61
|
+
|| data.modules.length === 0
|
|
62
|
+
) throw new Error('trigger_thread_worker_data_invalid');
|
|
63
|
+
|
|
64
|
+
function diagnosticMemory(): Readonly<Record<string, number>> {
|
|
65
|
+
return data?.diagnosticsEnabled === true
|
|
66
|
+
? { heapUsedBytes: process.memoryUsage().heapUsed }
|
|
67
|
+
: {};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function send(value: Readonly<Record<string, unknown>>): void {
|
|
71
|
+
port!.postMessage({ ...value, poolId: data!.poolId!, laneId: data!.laneId! });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const classes = new Map<string, ClawclawTriggerClass>();
|
|
75
|
+
const modules = new Map<string, ClawclawTrigger>();
|
|
76
|
+
const observationMemories = new Map<string, ClawclawBehaviorObservationMemory>();
|
|
77
|
+
try {
|
|
78
|
+
for (const spec of data.modules) {
|
|
79
|
+
const loaded = await import(spec.sourceUrl) as Record<string, unknown>;
|
|
80
|
+
const ModuleClass = validateClawclawTriggerModule(loaded, spec.source);
|
|
81
|
+
classes.set(spec.triggerId, ModuleClass);
|
|
82
|
+
modules.set(spec.triggerId, new ModuleClass());
|
|
83
|
+
observationMemories.set(spec.triggerId, new ClawclawBehaviorObservationMemory());
|
|
84
|
+
}
|
|
85
|
+
} catch (error) {
|
|
86
|
+
send({
|
|
87
|
+
type: 'error',
|
|
88
|
+
code: errorCode(error),
|
|
89
|
+
message: errorMessage(error),
|
|
90
|
+
...diagnosticMemory(),
|
|
91
|
+
});
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function evaluate(request: TriggerEvaluateRequest): Promise<void> {
|
|
96
|
+
if (
|
|
97
|
+
request.poolId !== data!.poolId
|
|
98
|
+
|| typeof request.requestId !== 'string'
|
|
99
|
+
|| typeof request.triggerId !== 'string'
|
|
100
|
+
|| !request.input
|
|
101
|
+
|| !request.readInput
|
|
102
|
+
) throw new Error('trigger_thread_request_invalid');
|
|
103
|
+
const module = modules.get(request.triggerId);
|
|
104
|
+
const ModuleClass = classes.get(request.triggerId);
|
|
105
|
+
const observationMemory = observationMemories.get(request.triggerId);
|
|
106
|
+
if (!module || !ModuleClass || !observationMemory) throw new Error('trigger_thread_module_unknown');
|
|
107
|
+
let invocationActive = true;
|
|
108
|
+
try {
|
|
109
|
+
if (request.resetReason) {
|
|
110
|
+
observationMemory.clear();
|
|
111
|
+
await module.reset?.(request.resetReason);
|
|
112
|
+
}
|
|
113
|
+
const observationSnapshot = observationMemory.capture(request.readInput);
|
|
114
|
+
const value = await module.evaluate(
|
|
115
|
+
deepFreeze(request.input),
|
|
116
|
+
createBehaviorReadApi(deepFreeze(request.readInput), {
|
|
117
|
+
isActive: () => invocationActive,
|
|
118
|
+
observationSnapshot,
|
|
119
|
+
}),
|
|
120
|
+
);
|
|
121
|
+
const result = structuredClone(value);
|
|
122
|
+
const size = assertRuntimeModuleOutputSize(result, 'trigger_output');
|
|
123
|
+
send({
|
|
124
|
+
type: 'result',
|
|
125
|
+
requestId: request.requestId,
|
|
126
|
+
triggerId: request.triggerId,
|
|
127
|
+
result,
|
|
128
|
+
outputBytes: size.bytes,
|
|
129
|
+
...diagnosticMemory(),
|
|
130
|
+
});
|
|
131
|
+
} catch (error) {
|
|
132
|
+
modules.set(request.triggerId, new ModuleClass());
|
|
133
|
+
observationMemory.clear();
|
|
134
|
+
send({
|
|
135
|
+
type: 'request_error',
|
|
136
|
+
requestId: request.requestId,
|
|
137
|
+
triggerId: request.triggerId,
|
|
138
|
+
code: errorCode(error),
|
|
139
|
+
message: errorMessage(error),
|
|
140
|
+
...diagnosticMemory(),
|
|
141
|
+
});
|
|
142
|
+
} finally {
|
|
143
|
+
invocationActive = false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
let operationTail = Promise.resolve();
|
|
148
|
+
port.on('message', (request: TriggerEvaluateRequest) => {
|
|
149
|
+
operationTail = operationTail.then(() => evaluate(request)).catch((error) => {
|
|
150
|
+
send({
|
|
151
|
+
type: 'error',
|
|
152
|
+
requestId: typeof request?.requestId === 'string' ? request.requestId : undefined,
|
|
153
|
+
code: errorCode(error),
|
|
154
|
+
message: errorMessage(error),
|
|
155
|
+
...diagnosticMemory(),
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
send({
|
|
161
|
+
type: 'ready',
|
|
162
|
+
triggerIds: [...modules.keys()],
|
|
163
|
+
...diagnosticMemory(),
|
|
164
|
+
});
|
|
@@ -12,6 +12,7 @@ export const CLAWCLAW_VISUAL_EVENT_TYPES = [
|
|
|
12
12
|
'visual.player_motion_changed',
|
|
13
13
|
'visual.player_stopped',
|
|
14
14
|
'visual.player_resumed',
|
|
15
|
+
'visual.player_stop_ended',
|
|
15
16
|
'visual.no_significant_stop',
|
|
16
17
|
'visual.player_area_changed',
|
|
17
18
|
'visual.player_position_changed',
|
|
@@ -93,6 +93,18 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
93
93
|
private readonly remoteSequences = new Map<string, string>();
|
|
94
94
|
private readonly mailboxItems = new Map<string, MailboxItem>();
|
|
95
95
|
private readonly mailboxUniqueItems = new Map<string, string>();
|
|
96
|
+
|
|
97
|
+
diagnosticCounts(): Readonly<Record<string, number>> {
|
|
98
|
+
return {
|
|
99
|
+
sessions: this.sessions.size,
|
|
100
|
+
segments: this.segments.size,
|
|
101
|
+
events: this.events.size,
|
|
102
|
+
deliveries: this.deliveries.size,
|
|
103
|
+
checkpoints: this.checkpoints.size,
|
|
104
|
+
leases: this.leases.size,
|
|
105
|
+
mailbox_items: this.mailboxItems.size,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
96
108
|
private nextCommitSeq = 1;
|
|
97
109
|
|
|
98
110
|
constructor(snapshot?: EventRepositorySnapshot) {
|