@myclaw163/clawclaw-cli 0.9.1 → 0.10.1
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/QUICKSTART_OTHER.md +5 -5
- package/README.md +7 -8
- package/bin/clawclaw-channel.mjs +2 -2
- package/bin/clawclaw-cli.mjs +2 -2
- package/docs/configuration.md +25 -99
- package/docs/custom-modules/README.md +27 -40
- package/docs/custom-modules/api-reference.md +132 -273
- package/docs/custom-modules/behavior.md +185 -75
- package/docs/custom-modules/examples/auto-escape.ts +41 -0
- package/docs/custom-modules/examples/go-to-point.ts +11 -11
- package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
- package/docs/custom-modules/examples/task-reminder.ts +4 -5
- package/docs/custom-modules/perception.md +46 -806
- package/docs/custom-modules/skill.md +1 -1
- package/docs/desktop-event-push.md +3 -3
- package/docs/runtime/README.md +18 -19
- package/docs/runtime/agent-notifications.md +31 -12
- package/docs/runtime/behavior-runtime.md +54 -48
- package/docs/runtime/components-and-boundaries.md +87 -137
- package/docs/runtime/events-and-state.md +52 -17
- package/docs/runtime/framework-package.md +73 -0
- package/docs/runtime/official-perception-modules.md +5 -5
- package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
- package/docs/runtime/short-commands-and-capabilities.md +8 -9
- package/docs/user-guide/README.md +12 -9
- package/docs/user-guide/api-reference.md +132 -180
- package/docs/user-guide/behavior.md +175 -65
- package/docs/user-guide/installation.md +7 -7
- package/docs/user-guide/perception.md +46 -789
- package/docs/user-guide/skill.md +1 -1
- package/package.json +24 -9
- package/scripts/check-framework-boundaries.mjs +27 -0
- package/scripts/check-skill-command-surface.mjs +9 -14
- package/scripts/install-local-runtime.mjs +35 -0
- package/scripts/qa-install.mjs +105 -0
- package/skills/clawclaw/SKILL.md +50 -48
- package/skills/clawclaw/references/BEHAVIORS.md +45 -65
- package/skills/clawclaw/references/CHANNELS.md +2 -2
- package/skills/clawclaw/references/COMMANDS.md +65 -87
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +185 -75
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +145 -198
- package/skills/clawclaw/references/CUSTOM-MODULES.md +28 -29
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +46 -811
- package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
- package/skills/clawclaw/references/HUB.md +1 -1
- package/skills/clawclaw/references/STREAM.md +8 -8
- package/skills/clawclaw/references/TACTICS.md +1 -1
- package/src/channel/claude-channel-ipc-server.ts +1 -0
- package/src/cli.ts +4 -2
- package/src/commands/behavior.ts +49 -104
- package/src/commands/capability.ts +3 -3
- package/src/commands/load.ts +18 -25
- package/src/commands/module-runtime-control.ts +113 -0
- package/src/commands/perception.ts +23 -4
- package/src/commands/strategy.ts +2 -0
- package/src/commands/trigger.ts +1 -1
- package/src/lib/capability-load-diagnostics.ts +3 -3
- package/src/lib/perception-config.ts +18 -6
- package/src/lib/runtime-cadence-config.ts +16 -0
- package/src/lib/workspace-runtime-lock.ts +3 -46
- package/src/pipeline/canonical-event-presentation.ts +23 -124
- package/src/pipeline/event-format.ts +12 -21
- package/src/pipeline/event-hints.ts +6 -6
- package/src/pipeline/game-sync-event-normalization.ts +57 -63
- package/src/runtime/clawclaw/behavior-decision.ts +7 -3
- package/src/runtime/clawclaw/behavior-input.ts +8 -4
- package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
- package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
- package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
- package/src/runtime/clawclaw/notification-policy.ts +42 -0
- package/src/runtime/clawclaw/notification-turn.ts +19 -0
- package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
- package/src/runtime/clawclaw/owner.ts +67 -8
- package/src/runtime/clawclaw/perception-module-manifest.ts +22 -8
- package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
- package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
- package/src/runtime/clawclaw/plugins/assembly.ts +29 -41
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -482
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -186
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
- package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1707
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -271
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -960
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +9 -107
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +5 -4
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
- package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
- package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
- package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -0
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
- package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +136 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +13 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +13 -24
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +19 -8
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +23 -15
- package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +8 -103
- package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
- package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
- package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
- package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +69 -13
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
- package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
- package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
- package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
- package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
- package/src/runtime/clawclaw/runtime-state.ts +12 -1
- package/src/runtime/clawclaw/runtime.ts +11 -3
- package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -0
- package/src/runtime/clawclaw/strategy-memory.ts +1 -0
- package/src/runtime/clawclaw-event-catalog.ts +17 -17
- package/src/runtime/framework/action-diagnostics.ts +3 -83
- package/src/runtime/framework/capability-registry.ts +2 -395
- package/src/runtime/framework/contracts.ts +2 -144
- package/src/runtime/framework/control/control-scheduler.ts +2 -1268
- package/src/runtime/framework/control/domain-set.ts +2 -81
- package/src/runtime/framework/control/index.ts +1 -3
- package/src/runtime/framework/control/types.ts +2 -191
- package/src/runtime/framework/control-coordinator.ts +2 -11
- package/src/runtime/framework/events/event-catalog.ts +2 -74
- package/src/runtime/framework/events/event-delivery-service.ts +2 -200
- package/src/runtime/framework/events/event-ingress.ts +2 -99
- package/src/runtime/framework/events/event-repository.ts +2 -82
- package/src/runtime/framework/events/index.ts +2 -7
- package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
- package/src/runtime/framework/events/runtime-resume.ts +2 -20
- package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
- package/src/runtime/framework/events/test-helpers.ts +1 -1
- package/src/runtime/framework/events/types.ts +2 -312
- package/src/runtime/framework/index.ts +3 -7
- package/src/runtime/framework/load-node-sqlite.ts +2 -17
- package/src/runtime/framework/mailbox/coalescer.ts +2 -83
- package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
- package/src/runtime/framework/mailbox/identity.ts +2 -38
- package/src/runtime/framework/mailbox/index.ts +1 -7
- package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
- package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
- package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
- package/src/runtime/framework/mailbox/types.ts +2 -145
- package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
- package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
- package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
- package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
- package/src/runtime/framework/participation-manager.ts +2 -253
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
- package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
- package/src/runtime/framework/plugins/contracts.ts +2 -388
- package/src/runtime/framework/plugins/index.ts +1 -4
- package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
- package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2060
- package/src/runtime/framework/runtime.ts +5 -1843
- package/src/runtime/framework/serial-task-queue.ts +2 -14
- package/src/runtime/framework/state/contracts.ts +2 -49
- package/src/runtime/framework/state/current-state-store.ts +2 -184
- package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
- package/src/runtime/framework/state/freshness.ts +2 -72
- package/src/runtime/framework/state/history/contracts.ts +2 -158
- package/src/runtime/framework/state/history/history-writer.ts +2 -194
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
- package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
- package/src/runtime/framework/state/index.ts +1 -13
- package/src/runtime/framework/state/state-ingress.ts +2 -95
- package/src/runtime/framework/state/state-provider.ts +2 -62
- package/src/runtime/framework/state/types.ts +2 -155
- package/src/runtime/host-monitor-rate-gate.ts +1 -123
- package/src/runtime/mailbox-host-relay.ts +1 -326
- package/src/runtime/observability/detail-capture.ts +4 -108
- package/src/runtime/observability/process-timing.ts +2 -59
- package/src/runtime/observability/recorder.ts +2 -238
- package/src/runtime/observability/redaction.ts +2 -181
- package/src/runtime/observability/reporter.ts +2 -154
- package/src/runtime/observability/sinks.ts +2 -135
- package/src/runtime/observability/types.ts +2 -92
- package/src/runtime/owner-control.ts +45 -315
- package/src/runtime/parent-process-watch.ts +1 -51
- package/src/runtime/process-identity.ts +1 -72
- package/src/sdk/behavior-plugin/index.ts +13 -4
- package/src/sdk/index.ts +44 -3
- package/src/sdk/module-input/index.ts +5 -0
- package/src/sdk/perception-plugin/index.ts +9 -5
- package/src/sdk/perception-plugin/module.ts +25 -6
- package/src/sdk/perception-plugin/reaction.ts +1 -1
- package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
- package/src/sdk/perception-plugin/reminder.ts +2 -1
- package/src/{runtime/clawclaw/plugins/source → sdk/perception-plugin}/task-change-tracker.ts +1 -2
- package/src/sdk/strategy-memory.ts +1 -0
- package/src/sdk/strategy-plugin/index.ts +36 -0
- package/src/sdk/trigger-plugin/index.ts +4 -3
- package/docs/custom-modules/examples/nearby-escape.ts +0 -56
- package/docs/custom-modules/examples/nearby-notice.ts +0 -36
- package/docs/custom-modules/trigger.md +0 -295
- package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
- package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -233
- package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +0 -49
- package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
- /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
|
@@ -1,962 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import { performance } from 'node:perf_hooks';
|
|
5
|
-
import { Worker } from 'node:worker_threads';
|
|
6
|
-
import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index.js';
|
|
7
|
-
import type {
|
|
8
|
-
BehaviorDecision,
|
|
9
|
-
BehaviorInput,
|
|
10
|
-
BehaviorTiming,
|
|
11
|
-
ClawclawBehaviorManifest,
|
|
12
|
-
} from '../../../../sdk/behavior-plugin/index.js';
|
|
13
|
-
import {
|
|
14
|
-
behaviorSourceUrl,
|
|
15
|
-
behaviorThreadLoaderConfig,
|
|
16
|
-
pinBehaviorSource,
|
|
17
|
-
resolveBehaviorSource,
|
|
18
|
-
} from './behavior-module-loader.js';
|
|
19
|
-
import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
|
|
1
|
+
import { ThreadStrategyExecutor, prepareStrategyInWorker, type ThreadStrategyExecutorOptions, type StrategyThreadPreparation } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
|
|
2
|
+
import type { BehaviorInput, BehaviorDecision, ClawclawBehaviorManifest } from '../../../../sdk/behavior-plugin/index.js';
|
|
20
3
|
import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
|
|
21
|
-
import {
|
|
22
|
-
|
|
23
|
-
export
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url),
|
|
33
|
-
));
|
|
34
|
-
const WORKER_HOST_URL = new URL('./behavior-analysis-thread-host.ts', import.meta.url).href;
|
|
35
|
-
|
|
36
|
-
export interface ThreadBehaviorExecutorOptions {
|
|
37
|
-
readonly fixedWorkers?: boolean;
|
|
38
|
-
readonly snapshotStore?: BehaviorSnapshotStore;
|
|
39
|
-
readonly source: ResolvedClawclawBehaviorSource;
|
|
40
|
-
/** Maximum Worker count and in-flight request window. Tests may reduce it. */
|
|
41
|
-
readonly poolSize?: number;
|
|
42
|
-
/** How long an expanded, idle pool is retained before returning to two Workers. */
|
|
43
|
-
readonly idleWorkerTimeoutMs?: number;
|
|
44
|
-
readonly maxOldGenerationSizeMb?: number;
|
|
45
|
-
/** Samples Worker heaps only for explicit full diagnostics. */
|
|
46
|
-
readonly diagnosticsEnabled?: boolean;
|
|
47
|
-
readonly diagnostic?: (
|
|
48
|
-
name: string,
|
|
49
|
-
attributes?: Readonly<Record<string, unknown>>,
|
|
50
|
-
severity?: RuntimeDiagnosticSeverity,
|
|
51
|
-
) => void;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export interface ThreadBehaviorExecutorSnapshot {
|
|
55
|
-
readonly state: 'new' | 'starting' | 'running' | 'stopping' | 'stopped';
|
|
56
|
-
readonly workerCount: number;
|
|
57
|
-
readonly idleWorkerCount: number;
|
|
58
|
-
readonly busyWorkerCount: number;
|
|
59
|
-
readonly queuedRequestCount: number;
|
|
60
|
-
readonly inFlightRequestCount: number;
|
|
61
|
-
readonly startedWorkerCount: number;
|
|
62
|
-
readonly retiredWorkerCount: number;
|
|
63
|
-
readonly workerHeapUsedBytes: number;
|
|
64
|
-
readonly peakWorkerHeapUsedBytes: number;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
interface PendingRequest {
|
|
68
|
-
snapshotEpoch?: number;
|
|
69
|
-
snapshotGeneration?: number;
|
|
70
|
-
readonly requestId: string;
|
|
71
|
-
readonly operation: 'decide';
|
|
72
|
-
readonly frame: BehaviorInput;
|
|
73
|
-
readonly observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>;
|
|
74
|
-
readonly signal: AbortSignal;
|
|
75
|
-
readonly enqueuedAt: number;
|
|
76
|
-
readonly resolve: (value: unknown) => void;
|
|
77
|
-
readonly reject: (error: Error) => void;
|
|
78
|
-
readonly onAbort: () => void;
|
|
79
|
-
settled: boolean;
|
|
80
|
-
assignedAt?: number;
|
|
81
|
-
slot?: WorkerSlot;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
interface WorkerSlot {
|
|
85
|
-
readonly id: number;
|
|
86
|
-
readonly worker: Worker;
|
|
87
|
-
state: 'starting' | 'idle' | 'busy' | 'retiring';
|
|
88
|
-
idleSince?: number;
|
|
89
|
-
current?: PendingRequest;
|
|
90
|
-
readyResolve?: () => void;
|
|
91
|
-
readyReject?: (error: Error) => void;
|
|
92
|
-
heapUsedBytes?: number;
|
|
93
|
-
retirement?: Promise<void>;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
interface WorkerMessageBase {
|
|
97
|
-
readonly type: string;
|
|
98
|
-
readonly poolId: string;
|
|
99
|
-
readonly slotId: number;
|
|
100
|
-
readonly requestId?: string;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
interface WorkerReadyMessage extends WorkerMessageBase {
|
|
104
|
-
readonly type: 'ready';
|
|
105
|
-
readonly behaviorId: string;
|
|
106
|
-
readonly execution: ResolvedClawclawBehaviorSource['execution'];
|
|
107
|
-
readonly manifest?: Readonly<ClawclawBehaviorManifest>;
|
|
108
|
-
readonly input?: Readonly<Record<string, unknown>>;
|
|
109
|
-
readonly timing?: Readonly<BehaviorTiming>;
|
|
110
|
-
readonly heapUsedBytes?: number;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
interface WorkerResultMessage extends WorkerMessageBase {
|
|
114
|
-
readonly instanceSnapshot?: BehaviorInstanceSnapshot;
|
|
115
|
-
readonly type: 'result';
|
|
116
|
-
readonly requestId: string;
|
|
117
|
-
readonly result: BehaviorDecision;
|
|
118
|
-
readonly queryCount: number;
|
|
119
|
-
readonly durationMs: number;
|
|
120
|
-
readonly heapUsedBytes?: number;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
interface WorkerErrorMessage extends WorkerMessageBase {
|
|
124
|
-
readonly type: 'error';
|
|
125
|
-
readonly code: string;
|
|
126
|
-
readonly message?: string;
|
|
127
|
-
readonly heapUsedBytes?: number;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
function asError(value: unknown, fallback: string): Error {
|
|
131
|
-
return value instanceof Error ? value : new Error(typeof value === 'string' ? value : fallback);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function abortError(signal: AbortSignal): Error {
|
|
135
|
-
return asError(signal.reason, 'behavior_thread_request_aborted');
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function errorCode(error: unknown, fallback: string): string {
|
|
139
|
-
const code = error && typeof error === 'object' && typeof (error as any).code === 'string'
|
|
140
|
-
? (error as any).code.trim()
|
|
141
|
-
: '';
|
|
142
|
-
if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code)) return code;
|
|
143
|
-
const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
|
|
144
|
-
return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1] ?? fallback;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function roundedElapsed(startedAt: number): number {
|
|
148
|
-
return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
export interface BehaviorThreadPreparation {
|
|
152
|
-
readonly manifest: Readonly<ClawclawBehaviorManifest>;
|
|
153
|
-
readonly input: Readonly<Record<string, unknown>>;
|
|
154
|
-
readonly timing?: Readonly<BehaviorTiming>;
|
|
155
|
-
readonly source: ResolvedClawclawBehaviorSource;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Imports and normalizes a Behavior without evaluating player code in the Owner. */
|
|
159
|
-
export async function prepareBehaviorInWorker(
|
|
160
|
-
source: ResolvedClawclawBehaviorSource,
|
|
161
|
-
input: Readonly<Record<string, unknown>>,
|
|
162
|
-
options: Readonly<{
|
|
163
|
-
maxOldGenerationSizeMb?: number;
|
|
164
|
-
diagnosticsEnabled?: boolean;
|
|
165
|
-
}> = {},
|
|
166
|
-
): Promise<BehaviorThreadPreparation> {
|
|
167
|
-
const pinned = pinBehaviorSource(source);
|
|
168
|
-
const sourceUrl = behaviorSourceUrl(pinned);
|
|
169
|
-
const loader = behaviorThreadLoaderConfig();
|
|
170
|
-
const poolId = randomUUID();
|
|
171
|
-
const worker = new Worker(WORKER_BOOTSTRAP, {
|
|
172
|
-
execArgv: [],
|
|
173
|
-
resourceLimits: {
|
|
174
|
-
maxOldGenerationSizeMb: Math.max(16, Math.min(
|
|
175
|
-
256,
|
|
176
|
-
Math.floor(options.maxOldGenerationSizeMb ?? 64),
|
|
177
|
-
)),
|
|
178
|
-
},
|
|
179
|
-
stdout: true,
|
|
180
|
-
stderr: true,
|
|
181
|
-
workerData: {
|
|
182
|
-
runtimeModuleBootstrap: {
|
|
183
|
-
hostUrl: WORKER_HOST_URL,
|
|
184
|
-
hooksUrl: loader.hooksUrl,
|
|
185
|
-
sdkAliases: loader.sdkAliases,
|
|
186
|
-
esmModuleRoots: [new URL('.', sourceUrl).href],
|
|
187
|
-
},
|
|
188
|
-
poolId,
|
|
189
|
-
slotId: 0,
|
|
190
|
-
source: pinned,
|
|
191
|
-
sourceUrl,
|
|
192
|
-
prepareInput: structuredClone(input),
|
|
193
|
-
diagnosticsEnabled: options.diagnosticsEnabled === true,
|
|
194
|
-
},
|
|
195
|
-
});
|
|
196
|
-
try {
|
|
197
|
-
return await new Promise<BehaviorThreadPreparation>((resolve, reject) => {
|
|
198
|
-
let settled = false;
|
|
199
|
-
const finish = (callback: () => void): void => {
|
|
200
|
-
if (settled) return;
|
|
201
|
-
settled = true;
|
|
202
|
-
clearTimeout(timer);
|
|
203
|
-
callback();
|
|
204
|
-
};
|
|
205
|
-
const timer = setTimeout(() => finish(() => reject(
|
|
206
|
-
new Error('behavior_thread_prepare_timeout'),
|
|
207
|
-
)), START_TIMEOUT_MS);
|
|
208
|
-
timer.unref?.();
|
|
209
|
-
worker.on('message', (value: unknown) => {
|
|
210
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return;
|
|
211
|
-
const message = value as WorkerReadyMessage | WorkerErrorMessage;
|
|
212
|
-
if (message.poolId !== poolId || message.slotId !== 0) return;
|
|
213
|
-
if (message.type === 'error') {
|
|
214
|
-
const detail = message.message?.trim().slice(0, MAX_WORKER_ERROR_MESSAGE_LENGTH);
|
|
215
|
-
finish(() => reject(new Error(detail ? `${message.code}: ${detail}` : message.code)));
|
|
216
|
-
return;
|
|
217
|
-
}
|
|
218
|
-
if (
|
|
219
|
-
message.type !== 'ready'
|
|
220
|
-
|| message.behaviorId !== pinned.id
|
|
221
|
-
|| message.execution !== pinned.execution
|
|
222
|
-
|| !message.manifest
|
|
223
|
-
|| !message.input
|
|
224
|
-
) {
|
|
225
|
-
finish(() => reject(new Error('behavior_thread_prepare_invalid')));
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
finish(() => resolve({
|
|
229
|
-
manifest: structuredClone(message.manifest!),
|
|
230
|
-
input: structuredClone(message.input!),
|
|
231
|
-
...(message.timing === undefined ? {} : { timing: structuredClone(message.timing) }),
|
|
232
|
-
source: pinned,
|
|
233
|
-
}));
|
|
234
|
-
});
|
|
235
|
-
worker.once('error', (error) => finish(() => reject(error)));
|
|
236
|
-
worker.once('exit', (code) => {
|
|
237
|
-
if (code !== 0) finish(() => reject(new Error(`behavior_thread_worker_exited:${code}`)));
|
|
238
|
-
});
|
|
239
|
-
});
|
|
240
|
-
} finally {
|
|
241
|
-
await worker.terminate().catch(() => -1);
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/** Adaptive Worker Thread pool for cross-tick computations. */
|
|
246
|
-
export class ThreadBehaviorExecutor {
|
|
247
|
-
private readonly snapshotStore: BehaviorSnapshotStore;
|
|
248
|
-
readonly runtimeInstanceId = randomUUID();
|
|
249
|
-
|
|
250
|
-
private readonly maxWorkerCount: number;
|
|
251
|
-
private readonly maxPendingRequestCount: number;
|
|
252
|
-
private readonly minWorkerCount: number;
|
|
253
|
-
private readonly idleWorkerTimeoutMs: number;
|
|
254
|
-
private readonly maxOldGenerationSizeMb: number;
|
|
255
|
-
private state: ThreadBehaviorExecutorSnapshot['state'] = 'new';
|
|
256
|
-
private readonly slots = new Set<WorkerSlot>();
|
|
257
|
-
private readonly queue: PendingRequest[] = [];
|
|
258
|
-
private readonly inFlight = new Set<PendingRequest>();
|
|
259
|
-
private readonly spawnTasks = new Set<Promise<void>>();
|
|
260
|
-
private startTask?: Promise<void>;
|
|
261
|
-
private stopTask?: Promise<void>;
|
|
262
|
-
private replacementTask?: Promise<void>;
|
|
263
|
-
private replacementRetryTimer?: ReturnType<typeof setTimeout>;
|
|
264
|
-
private idleScaleDownTimer?: ReturnType<typeof setTimeout>;
|
|
265
|
-
private replacementFailureCount = 0;
|
|
266
|
-
private nextSlotId = 1;
|
|
267
|
-
private startedWorkerCount = 0;
|
|
268
|
-
private retiredWorkerCount = 0;
|
|
269
|
-
private peakWorkerHeapUsedBytes = 0;
|
|
270
|
-
private desiredWorkerCount: number;
|
|
271
|
-
|
|
272
|
-
private readonly options: ThreadBehaviorExecutorOptions;
|
|
273
|
-
|
|
274
|
-
constructor(options: ThreadBehaviorExecutorOptions) {
|
|
275
|
-
this.snapshotStore = options.snapshotStore ?? new BehaviorSnapshotStore();
|
|
276
|
-
this.options = Object.freeze({
|
|
277
|
-
...options,
|
|
278
|
-
source: pinBehaviorSource(options.source),
|
|
279
|
-
});
|
|
280
|
-
const execution = options.source.execution ?? 'parallel';
|
|
281
|
-
const maxWorkerCount = execution === 'serial'
|
|
282
|
-
? 1
|
|
283
|
-
: options.poolSize ?? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE;
|
|
284
|
-
if (!Number.isInteger(maxWorkerCount) || maxWorkerCount <= 0 || maxWorkerCount > MAX_POOL_SIZE) {
|
|
285
|
-
throw new TypeError(`poolSize must be between 1 and ${MAX_POOL_SIZE}.`);
|
|
286
|
-
}
|
|
287
|
-
const idleWorkerTimeoutMs = options.idleWorkerTimeoutMs ?? IDLE_SCALE_DOWN_MS;
|
|
288
|
-
if (!Number.isFinite(idleWorkerTimeoutMs) || idleWorkerTimeoutMs < 0) {
|
|
289
|
-
throw new TypeError('idleWorkerTimeoutMs must be a non-negative finite number.');
|
|
290
|
-
}
|
|
291
|
-
this.maxWorkerCount = maxWorkerCount;
|
|
292
|
-
this.maxPendingRequestCount = execution === 'serial'
|
|
293
|
-
? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE
|
|
294
|
-
: maxWorkerCount;
|
|
295
|
-
this.minWorkerCount = options.fixedWorkers ? maxWorkerCount : Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
|
|
296
|
-
this.desiredWorkerCount = this.minWorkerCount;
|
|
297
|
-
this.idleWorkerTimeoutMs = idleWorkerTimeoutMs;
|
|
298
|
-
this.maxOldGenerationSizeMb = Math.max(16, Math.min(
|
|
299
|
-
256,
|
|
300
|
-
Math.floor(options.maxOldGenerationSizeMb ?? 64),
|
|
301
|
-
));
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
get isAlive(): boolean {
|
|
305
|
-
// A temporarily degraded pool remains the same live executor while it
|
|
306
|
-
// restores a retired slot. Capacity is reported separately by snapshot().
|
|
307
|
-
return this.state === 'running';
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
start(signal: AbortSignal): Promise<void> {
|
|
311
|
-
if (this.state === 'running') return Promise.resolve();
|
|
312
|
-
if (this.state === 'starting') return this.awaitStart(signal);
|
|
313
|
-
if (this.state === 'stopping' || this.state === 'stopped') {
|
|
314
|
-
return Promise.reject(new Error('behavior_thread_pool_stopped'));
|
|
315
|
-
}
|
|
316
|
-
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
317
|
-
this.state = 'starting';
|
|
318
|
-
const startedAt = performance.now();
|
|
319
|
-
this.startTask = Promise.all(
|
|
320
|
-
Array.from({ length: this.minWorkerCount }, () => this.spawnSlot('initial')),
|
|
321
|
-
).then(() => {
|
|
322
|
-
if (this.state !== 'starting') throw new Error('behavior_thread_pool_stopped');
|
|
323
|
-
this.state = 'running';
|
|
324
|
-
this.diagnostic('behavior.thread_pool.started', {
|
|
325
|
-
behavior_id: this.options.source.id,
|
|
326
|
-
execution: this.options.source.execution,
|
|
327
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
328
|
-
worker_count: this.slots.size,
|
|
329
|
-
min_worker_count: this.minWorkerCount,
|
|
330
|
-
max_worker_count: this.maxWorkerCount,
|
|
331
|
-
worker_max_old_generation_mb: this.maxOldGenerationSizeMb,
|
|
332
|
-
started_worker_count: this.startedWorkerCount,
|
|
333
|
-
retired_worker_count: this.retiredWorkerCount,
|
|
334
|
-
...(this.options.diagnosticsEnabled === true ? {
|
|
335
|
-
worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
|
|
336
|
-
peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
|
|
337
|
-
} : {}),
|
|
338
|
-
duration_ms: roundedElapsed(startedAt),
|
|
339
|
-
}, 'info');
|
|
340
|
-
}).catch(async (error) => {
|
|
341
|
-
if (this.state === 'starting') this.state = 'stopped';
|
|
342
|
-
await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, 'start_failed')));
|
|
343
|
-
throw error;
|
|
344
|
-
});
|
|
345
|
-
return this.awaitStart(signal).catch(async (error) => {
|
|
346
|
-
if (signal.aborted) await this.stop('switched');
|
|
347
|
-
throw error;
|
|
348
|
-
});
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
update(
|
|
352
|
-
frame: BehaviorInput,
|
|
353
|
-
signal: AbortSignal,
|
|
354
|
-
observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
|
|
355
|
-
): Promise<BehaviorDecision> {
|
|
356
|
-
return this.submit('decide', frame, signal, observationSnapshot) as Promise<BehaviorDecision>;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
async reset(_signal: AbortSignal): Promise<void> {
|
|
360
|
-
this.snapshotStore.reset();
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
stop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void> {
|
|
364
|
-
if (this.stopTask) return this.stopTask;
|
|
365
|
-
this.stopTask = this.performStop(reason);
|
|
366
|
-
return this.stopTask;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
private async performStop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void> {
|
|
370
|
-
if (this.state === 'stopped') return;
|
|
371
|
-
if (this.state === 'new') {
|
|
372
|
-
this.state = 'stopped';
|
|
373
|
-
return;
|
|
374
|
-
}
|
|
375
|
-
this.state = 'stopping';
|
|
376
|
-
if (this.replacementRetryTimer) {
|
|
377
|
-
clearTimeout(this.replacementRetryTimer);
|
|
378
|
-
this.replacementRetryTimer = undefined;
|
|
379
|
-
}
|
|
380
|
-
this.cancelIdleScaleDown();
|
|
381
|
-
const error = new Error('behavior_thread_pool_stopped');
|
|
382
|
-
for (const request of [...this.inFlight]) this.rejectRequest(request, error);
|
|
383
|
-
await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, reason)));
|
|
384
|
-
await Promise.allSettled([...this.spawnTasks]);
|
|
385
|
-
await this.startTask?.catch(() => {});
|
|
386
|
-
await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, reason)));
|
|
387
|
-
this.state = 'stopped';
|
|
388
|
-
this.diagnostic('behavior.thread_pool.stopped', {
|
|
389
|
-
behavior_id: this.options.source.id,
|
|
390
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
391
|
-
reason,
|
|
392
|
-
min_worker_count: this.minWorkerCount,
|
|
393
|
-
max_worker_count: this.maxWorkerCount,
|
|
394
|
-
started_worker_count: this.startedWorkerCount,
|
|
395
|
-
retired_worker_count: this.retiredWorkerCount,
|
|
396
|
-
...(this.options.diagnosticsEnabled === true ? {
|
|
397
|
-
worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
|
|
398
|
-
peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
|
|
399
|
-
} : {}),
|
|
400
|
-
}, 'info');
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
snapshot(): ThreadBehaviorExecutorSnapshot {
|
|
404
|
-
const slots = [...this.slots];
|
|
405
|
-
return {
|
|
406
|
-
state: this.state,
|
|
407
|
-
workerCount: slots.length,
|
|
408
|
-
idleWorkerCount: slots.filter(({ state }) => state === 'idle').length,
|
|
409
|
-
busyWorkerCount: slots.filter(({ state }) => state === 'busy').length,
|
|
410
|
-
queuedRequestCount: this.queue.length,
|
|
411
|
-
inFlightRequestCount: this.inFlight.size,
|
|
412
|
-
startedWorkerCount: this.startedWorkerCount,
|
|
413
|
-
retiredWorkerCount: this.retiredWorkerCount,
|
|
414
|
-
workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
|
|
415
|
-
peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes,
|
|
416
|
-
};
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
private awaitStart(signal: AbortSignal): Promise<void> {
|
|
420
|
-
const task = this.startTask!;
|
|
421
|
-
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
422
|
-
return new Promise<void>((resolve, reject) => {
|
|
423
|
-
const onAbort = (): void => reject(abortError(signal));
|
|
424
|
-
signal.addEventListener('abort', onAbort, { once: true });
|
|
425
|
-
void task.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
private async submit(
|
|
430
|
-
operation: 'decide',
|
|
431
|
-
frame: BehaviorInput,
|
|
432
|
-
signal: AbortSignal,
|
|
433
|
-
observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
|
|
434
|
-
): Promise<unknown> {
|
|
435
|
-
if (signal.aborted) throw abortError(signal);
|
|
436
|
-
await this.awaitStart(signal);
|
|
437
|
-
if (this.state !== 'running') throw new Error('behavior_thread_pool_not_running');
|
|
438
|
-
if (this.inFlight.size >= this.maxPendingRequestCount) {
|
|
439
|
-
throw new Error('behavior_thread_window_full');
|
|
440
|
-
}
|
|
441
|
-
return new Promise<unknown>((resolve, reject) => {
|
|
442
|
-
const request: PendingRequest = {
|
|
443
|
-
requestId: randomUUID(),
|
|
444
|
-
operation,
|
|
445
|
-
// BehaviorInput is already recursively frozen. Keep the Owner snapshot
|
|
446
|
-
// until postMessage performs the one unavoidable Worker-boundary clone.
|
|
447
|
-
frame,
|
|
448
|
-
...(observationSnapshot === undefined
|
|
449
|
-
? {}
|
|
450
|
-
: { observationSnapshot: structuredClone(observationSnapshot) }),
|
|
451
|
-
signal,
|
|
452
|
-
enqueuedAt: performance.now(),
|
|
453
|
-
resolve,
|
|
454
|
-
reject,
|
|
455
|
-
settled: false,
|
|
456
|
-
onAbort: () => this.abortRequest(request),
|
|
457
|
-
};
|
|
458
|
-
signal.addEventListener('abort', request.onAbort, { once: true });
|
|
459
|
-
this.inFlight.add(request);
|
|
460
|
-
this.queue.push(request);
|
|
461
|
-
this.diagnostic(`behavior.${operation}.started`, {
|
|
462
|
-
behavior_id: this.options.source.id,
|
|
463
|
-
executor: 'worker_thread',
|
|
464
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
465
|
-
request_id: request.requestId,
|
|
466
|
-
epoch_id: frame.epochId,
|
|
467
|
-
...(frame.gameState.tick === undefined ? {} : { tick: frame.gameState.tick }),
|
|
468
|
-
}, 'debug');
|
|
469
|
-
this.pump();
|
|
470
|
-
this.growForPressure();
|
|
471
|
-
});
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
private async spawnSlot(reason: 'initial' | 'queue_pressure' | 'replacement'): Promise<void> {
|
|
475
|
-
const source = resolveBehaviorSource(this.options.source);
|
|
476
|
-
const sourceUrl = behaviorSourceUrl(source);
|
|
477
|
-
const slotId = this.nextSlotId++;
|
|
478
|
-
const loader = behaviorThreadLoaderConfig();
|
|
479
|
-
const worker = new Worker(WORKER_BOOTSTRAP, {
|
|
480
|
-
execArgv: [],
|
|
481
|
-
resourceLimits: { maxOldGenerationSizeMb: this.maxOldGenerationSizeMb },
|
|
482
|
-
stdout: true,
|
|
483
|
-
stderr: true,
|
|
484
|
-
workerData: {
|
|
485
|
-
runtimeModuleBootstrap: {
|
|
486
|
-
hostUrl: WORKER_HOST_URL,
|
|
487
|
-
hooksUrl: loader.hooksUrl,
|
|
488
|
-
sdkAliases: loader.sdkAliases,
|
|
489
|
-
esmModuleRoots: [new URL('.', sourceUrl).href],
|
|
490
|
-
},
|
|
491
|
-
poolId: this.runtimeInstanceId,
|
|
492
|
-
slotId,
|
|
493
|
-
source,
|
|
494
|
-
sourceUrl,
|
|
495
|
-
diagnosticsEnabled: this.options.diagnosticsEnabled === true,
|
|
496
|
-
},
|
|
497
|
-
});
|
|
498
|
-
const slot: WorkerSlot = { id: slotId, worker, state: 'starting' };
|
|
499
|
-
this.slots.add(slot);
|
|
500
|
-
worker.stdout?.on('data', (chunk: Buffer) => this.diagnostic(
|
|
501
|
-
'behavior.thread.stdout',
|
|
502
|
-
{ behavior_id: source.id, slot_id: slot.id, bytes: chunk.length },
|
|
503
|
-
'debug',
|
|
504
|
-
));
|
|
505
|
-
worker.stderr?.on('data', (chunk: Buffer) => this.diagnostic(
|
|
506
|
-
'behavior.thread.stderr',
|
|
507
|
-
{ behavior_id: source.id, slot_id: slot.id, bytes: chunk.length },
|
|
508
|
-
'debug',
|
|
509
|
-
));
|
|
510
|
-
worker.on('message', (message: unknown) => this.handleMessage(slot, message));
|
|
511
|
-
worker.once('error', (error) => this.failSlot(slot, error));
|
|
512
|
-
worker.once('exit', (code) => {
|
|
513
|
-
if (slot.state !== 'retiring') {
|
|
514
|
-
this.failSlot(slot, new Error(`behavior_thread_worker_exited:${code}`));
|
|
515
|
-
}
|
|
516
|
-
});
|
|
517
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
518
|
-
try {
|
|
519
|
-
await new Promise<void>((resolve, reject) => {
|
|
520
|
-
slot.readyResolve = resolve;
|
|
521
|
-
slot.readyReject = reject;
|
|
522
|
-
timer = setTimeout(() => reject(new Error('behavior_thread_worker_start_timeout')), START_TIMEOUT_MS);
|
|
523
|
-
timer.unref?.();
|
|
524
|
-
});
|
|
525
|
-
if (this.state !== 'starting' && this.state !== 'running') {
|
|
526
|
-
throw new Error('behavior_thread_pool_stopped');
|
|
527
|
-
}
|
|
528
|
-
slot.state = 'idle';
|
|
529
|
-
slot.idleSince = performance.now();
|
|
530
|
-
this.startedWorkerCount += 1;
|
|
531
|
-
this.diagnostic('behavior.thread.started', {
|
|
532
|
-
behavior_id: source.id,
|
|
533
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
534
|
-
slot_id: slot.id,
|
|
535
|
-
worker_count: this.activeWorkerCount(),
|
|
536
|
-
min_worker_count: this.minWorkerCount,
|
|
537
|
-
max_worker_count: this.maxWorkerCount,
|
|
538
|
-
reason,
|
|
539
|
-
}, 'info');
|
|
540
|
-
} catch (error) {
|
|
541
|
-
await this.retireSlot(slot, 'start_failed');
|
|
542
|
-
throw error;
|
|
543
|
-
} finally {
|
|
544
|
-
if (timer) clearTimeout(timer);
|
|
545
|
-
slot.readyResolve = undefined;
|
|
546
|
-
slot.readyReject = undefined;
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
private pump(): void {
|
|
551
|
-
if (this.state !== 'running') return;
|
|
552
|
-
while (this.queue.length > 0) {
|
|
553
|
-
const slot = [...this.slots].find((candidate) => candidate.state === 'idle');
|
|
554
|
-
if (!slot) return;
|
|
555
|
-
const request = this.queue.shift()!;
|
|
556
|
-
if (request.settled || request.signal.aborted) {
|
|
557
|
-
if (!request.settled) this.rejectRequest(request, abortError(request.signal));
|
|
558
|
-
continue;
|
|
559
|
-
}
|
|
560
|
-
slot.state = 'busy';
|
|
561
|
-
slot.idleSince = undefined;
|
|
562
|
-
slot.current = request;
|
|
563
|
-
request.slot = slot;
|
|
564
|
-
request.assignedAt = performance.now();
|
|
565
|
-
const inherited = this.options.source.stateMode === 'snapshot' ? this.snapshotStore.latest : undefined;
|
|
566
|
-
request.snapshotEpoch = inherited?.epochId;
|
|
567
|
-
request.snapshotGeneration = this.snapshotStore.generation;
|
|
568
|
-
try {
|
|
569
|
-
slot.worker.postMessage({
|
|
570
|
-
type: 'run',
|
|
571
|
-
poolId: this.runtimeInstanceId,
|
|
572
|
-
requestId: request.requestId,
|
|
573
|
-
operation: request.operation,
|
|
574
|
-
frame: request.frame,
|
|
575
|
-
...(inherited ? { instanceSnapshot: inherited.value } : {}),
|
|
576
|
-
...(request.observationSnapshot === undefined
|
|
577
|
-
? {}
|
|
578
|
-
: { observationSnapshot: request.observationSnapshot }),
|
|
579
|
-
});
|
|
580
|
-
} catch (error) {
|
|
581
|
-
this.rejectRequest(request, asError(error, 'behavior_thread_submit_failed'));
|
|
582
|
-
void this.retireSlot(slot, 'submit_failed');
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
private handleMessage(slot: WorkerSlot, value: unknown): void {
|
|
588
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
589
|
-
this.failSlot(slot, new Error('behavior_thread_protocol_invalid'));
|
|
590
|
-
return;
|
|
591
|
-
}
|
|
592
|
-
const message = value as WorkerReadyMessage
|
|
593
|
-
| WorkerResultMessage
|
|
594
|
-
| WorkerErrorMessage;
|
|
595
|
-
if (message.poolId !== this.runtimeInstanceId || message.slotId !== slot.id) {
|
|
596
|
-
this.failSlot(slot, new Error('behavior_thread_protocol_identity_mismatch'));
|
|
597
|
-
return;
|
|
598
|
-
}
|
|
599
|
-
if (message.type === 'ready') {
|
|
600
|
-
if (
|
|
601
|
-
slot.state !== 'starting'
|
|
602
|
-
|| message.behaviorId !== this.options.source.id
|
|
603
|
-
|| message.execution !== this.options.source.execution
|
|
604
|
-
|| (this.options.diagnosticsEnabled === true && (
|
|
605
|
-
!Number.isFinite(message.heapUsedBytes)
|
|
606
|
-
|| Number(message.heapUsedBytes) < 0
|
|
607
|
-
))
|
|
608
|
-
) {
|
|
609
|
-
this.failSlot(slot, new Error('behavior_thread_ready_invalid'));
|
|
610
|
-
return;
|
|
611
|
-
}
|
|
612
|
-
if (typeof message.heapUsedBytes === 'number') this.updateWorkerHeap(slot, message.heapUsedBytes);
|
|
613
|
-
slot.readyResolve?.();
|
|
614
|
-
return;
|
|
615
|
-
}
|
|
616
|
-
if (message.type === 'error') {
|
|
617
|
-
if (Number.isFinite(message.heapUsedBytes) && Number(message.heapUsedBytes) >= 0) {
|
|
618
|
-
this.updateWorkerHeap(slot, Number(message.heapUsedBytes));
|
|
619
|
-
}
|
|
620
|
-
const code = typeof message.code === 'string'
|
|
621
|
-
? message.code
|
|
622
|
-
: 'behavior_thread_worker_failed';
|
|
623
|
-
const detail = typeof message.message === 'string'
|
|
624
|
-
? message.message.trim().slice(0, MAX_WORKER_ERROR_MESSAGE_LENGTH)
|
|
625
|
-
: '';
|
|
626
|
-
const error = new Error(detail ? `${code}: ${detail}` : code);
|
|
627
|
-
if (slot.current && (!message.requestId || message.requestId === slot.current.requestId)) {
|
|
628
|
-
this.rejectRequest(slot.current, error);
|
|
629
|
-
} else {
|
|
630
|
-
slot.readyReject?.(error);
|
|
631
|
-
}
|
|
632
|
-
void this.retireSlot(slot, 'worker_error');
|
|
633
|
-
return;
|
|
634
|
-
}
|
|
635
|
-
const request = slot.current;
|
|
636
|
-
if (!request || message.requestId !== request.requestId) {
|
|
637
|
-
this.failSlot(slot, new Error('behavior_thread_request_mismatch'));
|
|
638
|
-
return;
|
|
639
|
-
}
|
|
640
|
-
if (message.type !== 'result') {
|
|
641
|
-
this.rejectRequest(request, new Error('behavior_thread_response_invalid'));
|
|
642
|
-
void this.retireSlot(slot, 'invalid_response');
|
|
643
|
-
return;
|
|
644
|
-
}
|
|
645
|
-
if (this.options.diagnosticsEnabled === true && (
|
|
646
|
-
!Number.isFinite(message.heapUsedBytes)
|
|
647
|
-
|| Number(message.heapUsedBytes) < 0
|
|
648
|
-
)) {
|
|
649
|
-
this.rejectRequest(request, new Error('behavior_thread_worker_memory_invalid'));
|
|
650
|
-
void this.retireSlot(slot, 'invalid_response');
|
|
651
|
-
return;
|
|
652
|
-
}
|
|
653
|
-
if (typeof message.heapUsedBytes === 'number') this.updateWorkerHeap(slot, message.heapUsedBytes);
|
|
654
|
-
slot.current = undefined;
|
|
655
|
-
slot.state = 'idle';
|
|
656
|
-
slot.idleSince = performance.now();
|
|
657
|
-
request.slot = undefined;
|
|
658
|
-
this.resolveRequest(request, structuredClone(message.result), message);
|
|
659
|
-
this.pump();
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
private resolveRequest(
|
|
663
|
-
request: PendingRequest,
|
|
664
|
-
value: unknown,
|
|
665
|
-
message: WorkerResultMessage,
|
|
666
|
-
): void {
|
|
667
|
-
if (request.settled) return;
|
|
668
|
-
const published = this.options.source.stateMode === 'snapshot' && message.instanceSnapshot
|
|
669
|
-
&& !request.signal.aborted && this.state === 'running'
|
|
670
|
-
? this.snapshotStore.publish(request.frame.epochId, message.instanceSnapshot, request.snapshotGeneration!)
|
|
671
|
-
: false;
|
|
672
|
-
if (this.options.source.stateMode === 'snapshot') this.diagnostic('behavior.snapshot.completed', {
|
|
673
|
-
behavior_id: this.options.source.id, epoch_id: request.frame.epochId,
|
|
674
|
-
inherited_epoch_id: request.snapshotEpoch ?? null, published,
|
|
675
|
-
latest_completed_epoch_id: this.snapshotStore.latest?.epochId ?? null,
|
|
676
|
-
}, 'debug');
|
|
677
|
-
request.settled = true;
|
|
678
|
-
request.signal.removeEventListener('abort', request.onAbort);
|
|
679
|
-
this.inFlight.delete(request);
|
|
680
|
-
this.diagnostic(`behavior.${request.operation}.completed`, {
|
|
681
|
-
behavior_id: this.options.source.id,
|
|
682
|
-
executor: 'worker_thread',
|
|
683
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
684
|
-
request_id: request.requestId,
|
|
685
|
-
epoch_id: request.frame.epochId,
|
|
686
|
-
duration_ms: roundedElapsed(request.enqueuedAt),
|
|
687
|
-
queue_duration_ms: Math.round(
|
|
688
|
-
Math.max(0, (request.assignedAt ?? performance.now()) - request.enqueuedAt) * 1_000,
|
|
689
|
-
) / 1_000,
|
|
690
|
-
worker_duration_ms: message.durationMs,
|
|
691
|
-
read_query_count: message.queryCount,
|
|
692
|
-
...(this.options.diagnosticsEnabled === true ? {
|
|
693
|
-
worker_heap_used_bytes: message.heapUsedBytes,
|
|
694
|
-
worker_pool_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
|
|
695
|
-
peak_worker_pool_heap_used_bytes: this.peakWorkerHeapUsedBytes,
|
|
696
|
-
} : {}),
|
|
697
|
-
}, 'debug');
|
|
698
|
-
request.resolve(value);
|
|
699
|
-
this.scheduleIdleScaleDown();
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
private rejectRequest(request: PendingRequest, error: Error): void {
|
|
703
|
-
if (request.settled) return;
|
|
704
|
-
request.settled = true;
|
|
705
|
-
request.signal.removeEventListener('abort', request.onAbort);
|
|
706
|
-
this.inFlight.delete(request);
|
|
707
|
-
const index = this.queue.indexOf(request);
|
|
708
|
-
if (index >= 0) this.queue.splice(index, 1);
|
|
709
|
-
if (request.slot?.current === request) request.slot.current = undefined;
|
|
710
|
-
request.slot = undefined;
|
|
711
|
-
this.diagnostic(
|
|
712
|
-
request.signal.aborted
|
|
713
|
-
? `behavior.${request.operation}.cancelled`
|
|
714
|
-
: `behavior.${request.operation}.failed`,
|
|
715
|
-
{
|
|
716
|
-
behavior_id: this.options.source.id,
|
|
717
|
-
executor: 'worker_thread',
|
|
718
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
719
|
-
request_id: request.requestId,
|
|
720
|
-
epoch_id: request.frame.epochId,
|
|
721
|
-
duration_ms: roundedElapsed(request.enqueuedAt),
|
|
722
|
-
aborted: request.signal.aborted,
|
|
723
|
-
error_code: errorCode(error, `BEHAVIOR_${request.operation.toUpperCase()}_FAILED`),
|
|
724
|
-
},
|
|
725
|
-
request.signal.aborted ? 'debug' : 'error',
|
|
726
|
-
);
|
|
727
|
-
request.reject(error);
|
|
728
|
-
this.scheduleIdleScaleDown();
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
private abortRequest(request: PendingRequest): void {
|
|
732
|
-
if (request.settled) return;
|
|
733
|
-
const slot = request.slot;
|
|
734
|
-
this.rejectRequest(request, abortError(request.signal));
|
|
735
|
-
// Synchronous behavior code cannot be interrupted inside one isolate.
|
|
736
|
-
// Replace only its slot; computations in the other Workers remain in flight.
|
|
737
|
-
if (slot) void this.retireSlot(slot, 'request_aborted');
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
private failSlot(slot: WorkerSlot, error: Error): void {
|
|
741
|
-
slot.readyReject?.(error);
|
|
742
|
-
if (slot.current) this.rejectRequest(slot.current, error);
|
|
743
|
-
void this.retireSlot(slot, 'failed');
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
private retireSlot(slot: WorkerSlot, reason: string): Promise<void> {
|
|
747
|
-
if (slot.retirement) return slot.retirement;
|
|
748
|
-
slot.readyReject?.(new Error(`behavior_thread_worker_retired:${reason}`));
|
|
749
|
-
slot.state = 'retiring';
|
|
750
|
-
if (slot.current) {
|
|
751
|
-
this.rejectRequest(slot.current, new Error(`behavior_thread_worker_retired:${reason}`));
|
|
752
|
-
}
|
|
753
|
-
const retirement = Promise.resolve(slot.worker.terminate()).catch(() => -1).then(() => {
|
|
754
|
-
this.slots.delete(slot);
|
|
755
|
-
this.retiredWorkerCount += 1;
|
|
756
|
-
this.diagnostic('behavior.thread.retired', {
|
|
757
|
-
behavior_id: this.options.source.id,
|
|
758
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
759
|
-
slot_id: slot.id,
|
|
760
|
-
reason,
|
|
761
|
-
worker_count: this.activeWorkerCount(),
|
|
762
|
-
min_worker_count: this.minWorkerCount,
|
|
763
|
-
max_worker_count: this.maxWorkerCount,
|
|
764
|
-
}, reason === 'request_aborted' ? 'debug' : 'info');
|
|
765
|
-
if (this.state === 'running') this.ensureReplacement('replacement');
|
|
766
|
-
});
|
|
767
|
-
slot.retirement = retirement;
|
|
768
|
-
return retirement;
|
|
769
|
-
}
|
|
770
|
-
|
|
771
|
-
private ensureReplacement(reason: 'queue_pressure' | 'replacement'): void {
|
|
772
|
-
if (
|
|
773
|
-
this.state !== 'running'
|
|
774
|
-
|| this.activeWorkerCount() >= this.desiredWorkerCount
|
|
775
|
-
|| this.replacementTask
|
|
776
|
-
|| this.replacementRetryTimer
|
|
777
|
-
) {
|
|
778
|
-
this.pump();
|
|
779
|
-
return;
|
|
780
|
-
}
|
|
781
|
-
const task = this.spawnSlot(reason).then(() => {
|
|
782
|
-
this.replacementFailureCount = 0;
|
|
783
|
-
this.pump();
|
|
784
|
-
this.scheduleIdleScaleDown();
|
|
785
|
-
}).catch((error) => {
|
|
786
|
-
this.replacementFailureCount += 1;
|
|
787
|
-
const retryDelayMs = Math.min(
|
|
788
|
-
REPLACEMENT_RETRY_MAX_MS,
|
|
789
|
-
REPLACEMENT_RETRY_BASE_MS * (2 ** Math.min(10, this.replacementFailureCount - 1)),
|
|
790
|
-
);
|
|
791
|
-
this.diagnostic('behavior.thread.replacement_failed', {
|
|
792
|
-
behavior_id: this.options.source.id,
|
|
793
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
794
|
-
error_code: errorCode(error, 'BEHAVIOR_THREAD_REPLACEMENT_FAILED'),
|
|
795
|
-
reason,
|
|
796
|
-
retry_delay_ms: retryDelayMs,
|
|
797
|
-
}, 'error');
|
|
798
|
-
if (this.state === 'running') {
|
|
799
|
-
this.replacementRetryTimer = setTimeout(() => {
|
|
800
|
-
this.replacementRetryTimer = undefined;
|
|
801
|
-
this.ensureReplacement(reason);
|
|
802
|
-
}, retryDelayMs);
|
|
803
|
-
this.replacementRetryTimer.unref?.();
|
|
804
|
-
}
|
|
805
|
-
}).finally(() => {
|
|
806
|
-
this.spawnTasks.delete(task);
|
|
807
|
-
this.replacementTask = undefined;
|
|
808
|
-
if (
|
|
809
|
-
this.state === 'running'
|
|
810
|
-
&& this.activeWorkerCount() < this.desiredWorkerCount
|
|
811
|
-
&& !this.replacementRetryTimer
|
|
812
|
-
) this.ensureReplacement(reason);
|
|
813
|
-
});
|
|
814
|
-
this.replacementTask = task;
|
|
815
|
-
this.spawnTasks.add(task);
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
private growForPressure(): void {
|
|
819
|
-
const target = Math.min(this.maxWorkerCount, Math.max(this.minWorkerCount, this.inFlight.size));
|
|
820
|
-
if (target <= this.desiredWorkerCount) return;
|
|
821
|
-
const previous = this.desiredWorkerCount;
|
|
822
|
-
this.desiredWorkerCount = target;
|
|
823
|
-
this.diagnostic('behavior.thread_pool.scale_requested', {
|
|
824
|
-
behavior_id: this.options.source.id,
|
|
825
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
826
|
-
trigger: 'queue_pressure',
|
|
827
|
-
previous_worker_count: previous,
|
|
828
|
-
desired_worker_count: target,
|
|
829
|
-
worker_count: this.activeWorkerCount(),
|
|
830
|
-
min_worker_count: this.minWorkerCount,
|
|
831
|
-
max_worker_count: this.maxWorkerCount,
|
|
832
|
-
queued_request_count: this.queue.length,
|
|
833
|
-
in_flight_request_count: this.inFlight.size,
|
|
834
|
-
}, 'info');
|
|
835
|
-
this.ensureReplacement('queue_pressure');
|
|
836
|
-
this.scheduleIdleScaleDown();
|
|
837
|
-
}
|
|
838
|
-
|
|
839
|
-
private scheduleIdleScaleDown(): void {
|
|
840
|
-
if (this.state !== 'running' || this.idleScaleDownTimer) return;
|
|
841
|
-
const delayMs = this.nextIdleScaleDownDelayMs();
|
|
842
|
-
if (delayMs === undefined) return;
|
|
843
|
-
this.idleScaleDownTimer = setTimeout(() => {
|
|
844
|
-
this.idleScaleDownTimer = undefined;
|
|
845
|
-
if (this.state !== 'running') return;
|
|
846
|
-
// inFlight already contains both assigned and queued requests, so it is the current
|
|
847
|
-
// concurrency demand. Never retire a busy Worker or shrink below that demand.
|
|
848
|
-
const demand = Math.min(
|
|
849
|
-
this.maxWorkerCount,
|
|
850
|
-
Math.max(this.minWorkerCount, this.inFlight.size),
|
|
851
|
-
);
|
|
852
|
-
const previous = this.desiredWorkerCount;
|
|
853
|
-
this.desiredWorkerCount = demand;
|
|
854
|
-
const activeWorkerCount = this.activeWorkerCount();
|
|
855
|
-
const retiredWorkerCount = this.trimIdleWorkers(demand);
|
|
856
|
-
this.diagnostic(
|
|
857
|
-
retiredWorkerCount > 0 || previous !== demand
|
|
858
|
-
? 'behavior.thread_pool.scale_requested'
|
|
859
|
-
: 'behavior.thread_pool.scale_deferred',
|
|
860
|
-
{
|
|
861
|
-
behavior_id: this.options.source.id,
|
|
862
|
-
runtime_instance_id: this.runtimeInstanceId,
|
|
863
|
-
trigger: retiredWorkerCount > 0 ? 'idle' : 'current_demand',
|
|
864
|
-
previous_worker_count: previous,
|
|
865
|
-
desired_worker_count: demand,
|
|
866
|
-
worker_count: activeWorkerCount,
|
|
867
|
-
min_worker_count: this.minWorkerCount,
|
|
868
|
-
max_worker_count: this.maxWorkerCount,
|
|
869
|
-
in_flight_request_count: this.inFlight.size,
|
|
870
|
-
queued_request_count: this.queue.length,
|
|
871
|
-
idle_timeout_ms: this.idleWorkerTimeoutMs,
|
|
872
|
-
retired_worker_count: retiredWorkerCount,
|
|
873
|
-
},
|
|
874
|
-
'info',
|
|
875
|
-
);
|
|
876
|
-
if (this.activeWorkerCount() < this.desiredWorkerCount) {
|
|
877
|
-
this.ensureReplacement('queue_pressure');
|
|
878
|
-
}
|
|
879
|
-
this.scheduleIdleScaleDown();
|
|
880
|
-
}, delayMs);
|
|
881
|
-
this.idleScaleDownTimer.unref?.();
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
private nextIdleScaleDownDelayMs(): number | undefined {
|
|
885
|
-
const excess = this.activeWorkerCount() - this.currentWorkerDemand();
|
|
886
|
-
if (excess <= 0) return undefined;
|
|
887
|
-
const oldestIdleSince = [...this.slots].reduce<number | undefined>((oldest, slot) => {
|
|
888
|
-
if (slot.state !== 'idle' || slot.idleSince === undefined) return oldest;
|
|
889
|
-
return oldest === undefined ? slot.idleSince : Math.min(oldest, slot.idleSince);
|
|
890
|
-
}, undefined);
|
|
891
|
-
if (oldestIdleSince === undefined) return undefined;
|
|
892
|
-
return Math.max(
|
|
893
|
-
0,
|
|
894
|
-
Math.ceil(oldestIdleSince + this.idleWorkerTimeoutMs - performance.now()),
|
|
895
|
-
);
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
private cancelIdleScaleDown(): void {
|
|
899
|
-
if (!this.idleScaleDownTimer) return;
|
|
900
|
-
clearTimeout(this.idleScaleDownTimer);
|
|
901
|
-
this.idleScaleDownTimer = undefined;
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
private trimIdleWorkers(demand = this.currentWorkerDemand()): number {
|
|
905
|
-
let excess = this.activeWorkerCount() - demand;
|
|
906
|
-
if (excess <= 0) return 0;
|
|
907
|
-
const cutoff = performance.now() - this.idleWorkerTimeoutMs;
|
|
908
|
-
const candidates = [...this.slots]
|
|
909
|
-
.filter((slot) => (
|
|
910
|
-
slot.state === 'idle'
|
|
911
|
-
&& slot.idleSince !== undefined
|
|
912
|
-
&& slot.idleSince <= cutoff
|
|
913
|
-
))
|
|
914
|
-
.sort((left, right) => left.idleSince! - right.idleSince!);
|
|
915
|
-
let retired = 0;
|
|
916
|
-
for (const slot of candidates) {
|
|
917
|
-
if (excess <= 0) break;
|
|
918
|
-
excess -= 1;
|
|
919
|
-
retired += 1;
|
|
920
|
-
void this.retireSlot(slot, 'idle');
|
|
921
|
-
}
|
|
922
|
-
return retired;
|
|
923
|
-
}
|
|
924
|
-
|
|
925
|
-
private currentWorkerDemand(): number {
|
|
926
|
-
return Math.min(
|
|
927
|
-
this.maxWorkerCount,
|
|
928
|
-
Math.max(this.minWorkerCount, this.inFlight.size),
|
|
929
|
-
);
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
private activeWorkerCount(): number {
|
|
933
|
-
return [...this.slots].filter((slot) => slot.state !== 'retiring').length;
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
private currentWorkerHeapUsedBytes(): number {
|
|
937
|
-
return [...this.slots].reduce(
|
|
938
|
-
(total, slot) => total + (slot.state === 'retiring' ? 0 : slot.heapUsedBytes ?? 0),
|
|
939
|
-
0,
|
|
940
|
-
);
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
private updateWorkerHeap(slot: WorkerSlot, heapUsedBytes: number): void {
|
|
944
|
-
slot.heapUsedBytes = Math.max(0, heapUsedBytes);
|
|
945
|
-
this.peakWorkerHeapUsedBytes = Math.max(
|
|
946
|
-
this.peakWorkerHeapUsedBytes,
|
|
947
|
-
this.currentWorkerHeapUsedBytes(),
|
|
948
|
-
);
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
private diagnostic(
|
|
952
|
-
name: string,
|
|
953
|
-
attributes?: Readonly<Record<string, unknown>>,
|
|
954
|
-
severity?: RuntimeDiagnosticSeverity,
|
|
955
|
-
): void {
|
|
956
|
-
try {
|
|
957
|
-
this.options.diagnostic?.(name, attributes, severity);
|
|
958
|
-
} catch {
|
|
959
|
-
// Diagnostics are observability only and must never alter pool lifecycle.
|
|
960
|
-
}
|
|
961
|
-
}
|
|
4
|
+
import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
|
|
5
|
+
import { CLAWCLAW_STRATEGY_WORKER_BRIDGE } from './behavior-worker-bridge.js';
|
|
6
|
+
export { PARALLEL_STRATEGY_THREAD_POOL_SIZE as PARALLEL_BEHAVIOR_THREAD_POOL_SIZE } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
|
|
7
|
+
export type { ThreadStrategyExecutorSnapshot as ThreadBehaviorExecutorSnapshot } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
|
|
8
|
+
export type ThreadBehaviorExecutorOptions = Omit<ThreadStrategyExecutorOptions<ResolvedClawclawBehaviorSource, BehaviorInput, ClawclawBehaviorObservationSnapshot>, 'bridge' | 'inputMetadata'>;
|
|
9
|
+
export type BehaviorThreadPreparation = StrategyThreadPreparation<ResolvedClawclawBehaviorSource, ClawclawBehaviorManifest>;
|
|
10
|
+
export const prepareBehaviorInWorker = (source: ResolvedClawclawBehaviorSource, input: Readonly<Record<string,unknown>>, options: {maxOldGenerationSizeMb?: number; diagnosticsEnabled?: boolean} = {}): Promise<BehaviorThreadPreparation> =>
|
|
11
|
+
prepareStrategyInWorker<ResolvedClawclawBehaviorSource, ClawclawBehaviorManifest>(source, input, {...options, bridge: CLAWCLAW_STRATEGY_WORKER_BRIDGE});
|
|
12
|
+
export class ThreadBehaviorExecutor extends ThreadStrategyExecutor<ResolvedClawclawBehaviorSource, BehaviorInput, BehaviorDecision, ClawclawBehaviorObservationSnapshot> {
|
|
13
|
+
constructor(options: ThreadBehaviorExecutorOptions) { super({...options, bridge: CLAWCLAW_STRATEGY_WORKER_BRIDGE,
|
|
14
|
+
inputMetadata: frame => frame.gameState.tick === undefined ? {} : {tick: frame.gameState.tick} }); }
|
|
962
15
|
}
|