@myclaw163/clawclaw-cli 0.9.2 → 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 +23 -35
- package/docs/custom-modules/api-reference.md +95 -273
- package/docs/custom-modules/behavior.md +94 -78
- package/docs/custom-modules/examples/auto-escape.ts +5 -5
- package/docs/custom-modules/examples/go-to-point.ts +11 -11
- package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
- package/docs/custom-modules/examples/task-reminder.ts +4 -5
- package/docs/custom-modules/perception.md +42 -603
- package/docs/custom-modules/skill.md +1 -1
- package/docs/desktop-event-push.md +3 -3
- package/docs/runtime/README.md +16 -17
- package/docs/runtime/agent-notifications.md +31 -12
- package/docs/runtime/behavior-runtime.md +47 -46
- package/docs/runtime/components-and-boundaries.md +70 -28
- package/docs/runtime/events-and-state.md +41 -18
- 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 +10 -7
- package/docs/user-guide/api-reference.md +81 -164
- package/docs/user-guide/behavior.md +84 -68
- package/docs/user-guide/installation.md +7 -7
- package/docs/user-guide/perception.md +42 -586
- 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 +8 -13
- package/scripts/install-local-runtime.mjs +35 -0
- package/scripts/qa-install.mjs +105 -0
- package/skills/clawclaw/SKILL.md +49 -49
- package/skills/clawclaw/references/BEHAVIORS.md +42 -73
- package/skills/clawclaw/references/CHANNELS.md +2 -2
- package/skills/clawclaw/references/COMMANDS.md +60 -101
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +94 -78
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +95 -180
- package/skills/clawclaw/references/CUSTOM-MODULES.md +24 -24
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +42 -608
- 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 +26 -10
- package/src/commands/capability.ts +3 -3
- package/src/commands/load.ts +3 -2
- package/src/commands/perception.ts +5 -0
- package/src/commands/strategy.ts +2 -0
- 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/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 +18 -4
- package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
- 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 +7 -9
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
- package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
- 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 -972
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +25 -17
- package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
- package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
- package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
- 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 +119 -297
- package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
- package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +18 -7
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
- package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
- 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/trigger-plugin.ts +8 -3
- package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
- 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 +11 -0
- package/src/runtime/clawclaw/runtime.ts +8 -0
- package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
- package/src/runtime/clawclaw/strategy-memory.ts +1 -77
- package/src/runtime/clawclaw-event-catalog.ts +12 -12
- 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 -396
- 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 -2071
- 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 -320
- package/src/runtime/parent-process-watch.ts +1 -51
- package/src/runtime/process-identity.ts +1 -72
- package/src/sdk/behavior-plugin/index.ts +9 -3
- package/src/sdk/index.ts +40 -2
- package/src/sdk/module-input/index.ts +5 -0
- package/src/sdk/perception-plugin/index.ts +3 -1
- package/src/sdk/perception-plugin/module.ts +12 -2
- package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
- package/src/sdk/perception-plugin/reminder.ts +2 -1
- package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
- package/src/sdk/strategy-memory.ts +1 -12
- package/src/sdk/strategy-plugin/index.ts +36 -0
- package/src/sdk/trigger-plugin/index.ts +1 -0
- package/docs/custom-modules/trigger.md +0 -295
|
@@ -1,1843 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
type ActionAdmissionOptions,
|
|
7
|
-
type RegisteredActionService,
|
|
8
|
-
} from './capability-registry.js';
|
|
9
|
-
import {
|
|
10
|
-
actionFailureDiagnosticSeverity,
|
|
11
|
-
summarizeActionError,
|
|
12
|
-
} from './action-diagnostics.js';
|
|
13
|
-
import type {
|
|
14
|
-
ActionCaller,
|
|
15
|
-
ActionResult,
|
|
16
|
-
ObservationProvider,
|
|
17
|
-
ObservationResult,
|
|
18
|
-
ScopeRef,
|
|
19
|
-
} from './contracts.js';
|
|
20
|
-
import {
|
|
21
|
-
EventIngress,
|
|
22
|
-
type EventCatalog,
|
|
23
|
-
MemoryEventRepository,
|
|
24
|
-
SqliteEventRepository,
|
|
25
|
-
type CanonicalEvent,
|
|
26
|
-
type CurrentEventScope,
|
|
27
|
-
type EventRepository,
|
|
28
|
-
type EventSegmentRecord,
|
|
29
|
-
type PlaySessionRecord,
|
|
30
|
-
type PublishEventInput,
|
|
31
|
-
} from './events/index.js';
|
|
32
|
-
import {
|
|
33
|
-
MemoryRuntimeInputJournal,
|
|
34
|
-
RuntimePluginScheduler,
|
|
35
|
-
SqliteRuntimeInputJournal,
|
|
36
|
-
assertRuntimeInputBatch,
|
|
37
|
-
runtimeSourceEventId,
|
|
38
|
-
type RuntimeEpoch,
|
|
39
|
-
type RuntimeEpochExecutionResult,
|
|
40
|
-
type RuntimePersistenceStore,
|
|
41
|
-
type RuntimeEpochPlugin,
|
|
42
|
-
type RuntimeEpochWork,
|
|
43
|
-
type RuntimeInputAcceptance,
|
|
44
|
-
type RuntimeInputBatch,
|
|
45
|
-
type RuntimePluginCapabilityAccess,
|
|
46
|
-
type RuntimePluginDescriptor,
|
|
47
|
-
type RuntimeEventProposal,
|
|
48
|
-
type RuntimeSourceContext,
|
|
49
|
-
type RuntimeSourceEvent,
|
|
50
|
-
type RuntimeSourcePlugin,
|
|
51
|
-
type RuntimeSourceStopHandle,
|
|
52
|
-
} from './plugins/index.js';
|
|
53
|
-
import {
|
|
54
|
-
ParticipationManager,
|
|
55
|
-
type ParticipationSnapshot,
|
|
56
|
-
type ParticipationTransition,
|
|
57
|
-
} from './participation-manager.js';
|
|
58
|
-
import {
|
|
59
|
-
CurrentStateStore,
|
|
60
|
-
HistoryWriter,
|
|
61
|
-
type HistoryWriterDegradedScopeHealth,
|
|
62
|
-
type HistoryWriterHealth,
|
|
63
|
-
MemoryStateHistoryRepository,
|
|
64
|
-
SqliteStateHistoryRepository,
|
|
65
|
-
StateFreshnessEvaluator,
|
|
66
|
-
StateIngress,
|
|
67
|
-
type FlushableStateIngressObserver,
|
|
68
|
-
type StateIngressObserver,
|
|
69
|
-
StateProvider,
|
|
70
|
-
type RuntimeConnectionState,
|
|
71
|
-
type RuntimeScope,
|
|
72
|
-
type StateHistoryRepository,
|
|
73
|
-
type StateFreshnessPolicy,
|
|
74
|
-
type StateFreshnessPolicyResolver,
|
|
75
|
-
type StateProviderResult,
|
|
76
|
-
type TrajectoryRecord,
|
|
77
|
-
} from './state/index.js';
|
|
78
|
-
import { performance } from 'node:perf_hooks';
|
|
79
|
-
import { randomUUID } from 'crypto';
|
|
80
|
-
import type { TelemetryRecorder } from '../observability/index.js';
|
|
81
|
-
|
|
82
|
-
export interface RuntimePersistenceStatus {
|
|
83
|
-
events: 'sqlite' | 'memory';
|
|
84
|
-
stateHistory: 'sqlite' | 'memory';
|
|
85
|
-
inputJournal: 'sqlite' | 'memory';
|
|
86
|
-
warnings: string[];
|
|
87
|
-
historyWriter: PublicHistoryWriterHealth;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Durable Event/session store used by the fixed Runtime loop. */
|
|
91
|
-
export type RuntimeRepository = EventRepository;
|
|
92
|
-
|
|
93
|
-
export interface RuntimeOptions<TPosition = unknown> {
|
|
94
|
-
adapterId: string;
|
|
95
|
-
accountId: string;
|
|
96
|
-
eventCatalog: EventCatalog;
|
|
97
|
-
eventLedgerPath?: string;
|
|
98
|
-
stateHistoryPath?: string;
|
|
99
|
-
inputJournalPath?: string;
|
|
100
|
-
eventRepository?: RuntimeRepository;
|
|
101
|
-
/**
|
|
102
|
-
* Consumers whose delivery rows are created atomically with each Event.
|
|
103
|
-
* Omit to retain the legacy local-agent consumer; pass [] when adapters own
|
|
104
|
-
* their delivery lanes and create them only while enabled.
|
|
105
|
-
*/
|
|
106
|
-
initialEventConsumerIds?: readonly string[];
|
|
107
|
-
stateHistoryRepository?: StateHistoryRepository<TPosition>;
|
|
108
|
-
inputJournal?: RuntimePersistenceStore<Record<string, any>, Record<string, unknown>>;
|
|
109
|
-
historyObserverFactory?: (
|
|
110
|
-
writer: HistoryWriter<TPosition>,
|
|
111
|
-
) => StateIngressObserver<Record<string, any>>;
|
|
112
|
-
stateObservers?: FlushableStateIngressObserver<Record<string, any>>[];
|
|
113
|
-
resume?: boolean;
|
|
114
|
-
resumeKey?: string;
|
|
115
|
-
mode?: string;
|
|
116
|
-
stateFreshnessPolicy?: StateFreshnessPolicy;
|
|
117
|
-
/** Optional per-source override for transports with different State cadence. */
|
|
118
|
-
stateFreshnessPolicyResolver?: StateFreshnessPolicyResolver;
|
|
119
|
-
/** Owner-side operational telemetry. It is never part of Event or State. */
|
|
120
|
-
observability?: TelemetryRecorder;
|
|
121
|
-
/** Static per-epoch plugin graph used by the Runtime loop. */
|
|
122
|
-
runtimeEpochPlugins?: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
|
|
123
|
-
/** Projects a game-neutral Runtime State into the current game-facing view. */
|
|
124
|
-
currentStateFromRuntimeState?: (
|
|
125
|
-
state: Readonly<Record<string, any>>,
|
|
126
|
-
) => Record<string, any> | null;
|
|
127
|
-
initialSegment: {
|
|
128
|
-
kind: string;
|
|
129
|
-
identity?: string;
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
export type PublicRuntimeScope = Omit<RuntimeScope, 'accountId'>;
|
|
134
|
-
|
|
135
|
-
export interface PublicHistoryWriterDegradedScopeHealth
|
|
136
|
-
extends Omit<HistoryWriterDegradedScopeHealth, 'scope'> {
|
|
137
|
-
scope: PublicRuntimeScope;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export interface PublicHistoryWriterHealth extends HistoryWriterHealth {
|
|
141
|
-
degradedScopes: PublicHistoryWriterDegradedScopeHealth[];
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
export interface ExpectedRuntimeScope {
|
|
145
|
-
sessionId: string;
|
|
146
|
-
segmentId: string;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** Latest durable value of one plugin-owned State topic at a Ready boundary. */
|
|
150
|
-
export interface RuntimeReadyPluginState {
|
|
151
|
-
pluginId: string;
|
|
152
|
-
topic: string;
|
|
153
|
-
value: unknown;
|
|
154
|
-
updatedEpochSeq: number;
|
|
155
|
-
updatedDomainTick?: number;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Result of a plugin's invocation for the Ready View's closing epoch. */
|
|
159
|
-
export interface RuntimeReadyPluginOutcome {
|
|
160
|
-
pluginId: string;
|
|
161
|
-
epochSeq: number;
|
|
162
|
-
domainTick?: number;
|
|
163
|
-
outcome: RuntimeEpochExecutionResult['outcomes'][number]['outcome'];
|
|
164
|
-
reason?: string;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/** One coherent, non-consuming view at the latest fully closed epoch. */
|
|
168
|
-
export interface RuntimeReadyView<TState = Record<string, any> | null> {
|
|
169
|
-
scope: PublicRuntimeScope;
|
|
170
|
-
state: StateProviderResult<TState>;
|
|
171
|
-
/** Topic-keyed latest values, carried only within the same Runtime segment. */
|
|
172
|
-
pluginStates: Record<string, RuntimeReadyPluginState>;
|
|
173
|
-
/** Plugin-keyed outcomes for this exact closing epoch. */
|
|
174
|
-
pluginOutcomes: Record<string, RuntimeReadyPluginOutcome>;
|
|
175
|
-
events: CanonicalEvent[];
|
|
176
|
-
throughCommitSeq: number;
|
|
177
|
-
frameSeq: number;
|
|
178
|
-
eventWatermark: number;
|
|
179
|
-
epochSeq: number;
|
|
180
|
-
hasMore: boolean;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
interface RuntimeReadyAnchor<TState = Record<string, any> | null> {
|
|
184
|
-
scope: RuntimeScope;
|
|
185
|
-
state: StateProviderResult<TState>;
|
|
186
|
-
pluginStates: Record<string, RuntimeReadyPluginState>;
|
|
187
|
-
pluginOutcomes: Record<string, RuntimeReadyPluginOutcome>;
|
|
188
|
-
frameSeq: number;
|
|
189
|
-
eventWatermark: number;
|
|
190
|
-
epochSeq: number;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
const CLOSED_READY_ANCHOR_LIMIT = 256;
|
|
194
|
-
|
|
195
|
-
function runtimeScope(snapshot: ParticipationSnapshot): RuntimeScope {
|
|
196
|
-
return {
|
|
197
|
-
adapterId: snapshot.session.adapterId,
|
|
198
|
-
accountId: snapshot.session.accountId,
|
|
199
|
-
sessionId: snapshot.session.id,
|
|
200
|
-
segmentId: snapshot.segment.id,
|
|
201
|
-
segmentSeq: snapshot.segment.ordinal,
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function eventSession(snapshot: ParticipationSnapshot, current: boolean): PlaySessionRecord {
|
|
206
|
-
return {
|
|
207
|
-
sessionId: snapshot.session.id,
|
|
208
|
-
adapterId: snapshot.session.adapterId,
|
|
209
|
-
accountId: snapshot.session.accountId,
|
|
210
|
-
resumeKey: snapshot.session.resumeKey,
|
|
211
|
-
mode: snapshot.session.mode,
|
|
212
|
-
status: snapshot.session.endedAt ? 'sealed' : 'open',
|
|
213
|
-
isCurrent: current,
|
|
214
|
-
openedAt: snapshot.session.startedAt,
|
|
215
|
-
sealedAt: snapshot.session.endedAt,
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function eventSegment(
|
|
220
|
-
segment: ParticipationSnapshot['segment'],
|
|
221
|
-
current: boolean,
|
|
222
|
-
): EventSegmentRecord {
|
|
223
|
-
return {
|
|
224
|
-
segmentId: segment.id,
|
|
225
|
-
sessionId: segment.sessionId,
|
|
226
|
-
sequence: segment.ordinal,
|
|
227
|
-
kind: segment.kind,
|
|
228
|
-
scopeRef: segment.identity,
|
|
229
|
-
status: segment.endedAt ? 'closed' : 'open',
|
|
230
|
-
isCurrent: current,
|
|
231
|
-
openedAt: segment.startedAt,
|
|
232
|
-
closedAt: segment.endedAt,
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
function participationFromCurrent(scope: CurrentEventScope): ParticipationSnapshot {
|
|
237
|
-
return {
|
|
238
|
-
session: {
|
|
239
|
-
id: scope.session.sessionId,
|
|
240
|
-
adapterId: scope.session.adapterId,
|
|
241
|
-
accountId: scope.session.accountId,
|
|
242
|
-
resumeKey: scope.session.resumeKey,
|
|
243
|
-
mode: scope.session.mode,
|
|
244
|
-
startedAt: scope.session.openedAt,
|
|
245
|
-
endedAt: scope.session.sealedAt,
|
|
246
|
-
},
|
|
247
|
-
segment: {
|
|
248
|
-
id: scope.segment.segmentId,
|
|
249
|
-
sessionId: scope.segment.sessionId,
|
|
250
|
-
kind: scope.segment.kind,
|
|
251
|
-
identity: scope.segment.scopeRef,
|
|
252
|
-
ordinal: scope.segment.sequence,
|
|
253
|
-
startedAt: scope.segment.openedAt,
|
|
254
|
-
endedAt: scope.segment.closedAt,
|
|
255
|
-
},
|
|
256
|
-
// A process restart always creates new physical connections. Never restore
|
|
257
|
-
// a connection id from durable logical participation state.
|
|
258
|
-
connections: {},
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
function sameScope(envelope: ScopeRef, scope: ScopeRef): boolean {
|
|
263
|
-
return envelope.adapterId === scope.adapterId
|
|
264
|
-
&& envelope.accountId === scope.accountId
|
|
265
|
-
&& envelope.sessionId === scope.sessionId
|
|
266
|
-
&& envelope.segmentId === scope.segmentId;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
function milliseconds(value: string | undefined): number | undefined {
|
|
270
|
-
if (!value) return undefined;
|
|
271
|
-
const parsed = Date.parse(value);
|
|
272
|
-
return Number.isFinite(parsed) ? parsed : undefined;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/**
|
|
276
|
-
* Game-neutral coordinator for one participation. Source Plugins submit
|
|
277
|
-
* complete InputBatch values; Runtime persists them, assigns epoch_seq and
|
|
278
|
-
* drives the static Epoch Plugin graph.
|
|
279
|
-
*/
|
|
280
|
-
export class Runtime<TPosition = unknown>
|
|
281
|
-
implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
282
|
-
readonly adapterId: string;
|
|
283
|
-
readonly accountId: string;
|
|
284
|
-
readonly repository: RuntimeRepository;
|
|
285
|
-
readonly stateHistoryRepository: StateHistoryRepository<TPosition>;
|
|
286
|
-
readonly inputJournal: RuntimePersistenceStore<Record<string, any>, Record<string, unknown>>;
|
|
287
|
-
readonly observations = new ObservationRegistry();
|
|
288
|
-
readonly actions = new ActionRegistry();
|
|
289
|
-
|
|
290
|
-
private readonly eventCatalog: EventCatalog;
|
|
291
|
-
private readonly eventIngress: EventIngress;
|
|
292
|
-
private readonly stateStore = new CurrentStateStore<Record<string, any>>();
|
|
293
|
-
private readonly stateIngress: StateIngress<Record<string, any>>;
|
|
294
|
-
private readonly stateProvider: StateProvider<Record<string, any>, Record<string, any> | null>;
|
|
295
|
-
private readonly historyWriter: HistoryWriter<TPosition>;
|
|
296
|
-
private readonly stateObservers: FlushableStateIngressObserver<Record<string, any>>[];
|
|
297
|
-
private readonly participation: ParticipationManager;
|
|
298
|
-
private readonly pluginScheduler: RuntimePluginScheduler<Record<string, any>, Record<string, unknown>>;
|
|
299
|
-
private readonly connectionScopes = new Map<string, RuntimeScope>();
|
|
300
|
-
private readonly sourcePlugins = new Map<
|
|
301
|
-
string,
|
|
302
|
-
{ plugin: RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>>; handle: RuntimeSourceStopHandle }
|
|
303
|
-
>();
|
|
304
|
-
private readonly observability?: TelemetryRecorder;
|
|
305
|
-
private readonly currentStateFromRuntimeState: (
|
|
306
|
-
state: Readonly<Record<string, any>>,
|
|
307
|
-
) => Record<string, any> | null;
|
|
308
|
-
private readonly persistenceBase: Omit<RuntimePersistenceStatus, 'historyWriter'>;
|
|
309
|
-
private lastHistoryWriterHealthSignature: string | null = null;
|
|
310
|
-
private closed = false;
|
|
311
|
-
private closing = false;
|
|
312
|
-
private sourceInputOpen = true;
|
|
313
|
-
private closePromise?: Promise<void>;
|
|
314
|
-
private fatalError: Error | null = null;
|
|
315
|
-
private ownerRestartGapOpen = false;
|
|
316
|
-
private readyState: StateProviderResult<Record<string, any> | null> | null = null;
|
|
317
|
-
private readyScope: RuntimeScope | null = null;
|
|
318
|
-
private readyFrameSeq = 0;
|
|
319
|
-
private readyEventWatermark = 0;
|
|
320
|
-
private readyEpochSeq = 0;
|
|
321
|
-
private readyPluginStates: Record<string, RuntimeReadyPluginState> = {};
|
|
322
|
-
private readyPluginOutcomes: Record<string, RuntimeReadyPluginOutcome> = {};
|
|
323
|
-
private latestAcceptedEpochSeq = 0;
|
|
324
|
-
private readonly acceptedAgentStateByEpoch = new Map<
|
|
325
|
-
number,
|
|
326
|
-
StateProviderResult<Record<string, any> | null>
|
|
327
|
-
>();
|
|
328
|
-
private readonly epochCompletions = new Map<number, Promise<RuntimeEpochExecutionResult>>();
|
|
329
|
-
private readonly epochIntakeTimings = new Map<number, {
|
|
330
|
-
startedAtMs: number;
|
|
331
|
-
journalMs: number;
|
|
332
|
-
historyMs: number;
|
|
333
|
-
stateProjectionMs: number;
|
|
334
|
-
intakeTotalMs: number;
|
|
335
|
-
}>();
|
|
336
|
-
private readonly closedReadyAnchors = new Map<
|
|
337
|
-
number,
|
|
338
|
-
RuntimeReadyAnchor<Record<string, any> | null>
|
|
339
|
-
>();
|
|
340
|
-
private startPromise?: Promise<void>;
|
|
341
|
-
|
|
342
|
-
constructor(options: RuntimeOptions<TPosition>) {
|
|
343
|
-
this.adapterId = options.adapterId;
|
|
344
|
-
this.accountId = options.accountId;
|
|
345
|
-
this.observability = options.observability;
|
|
346
|
-
const warnings: string[] = [];
|
|
347
|
-
|
|
348
|
-
if (options.eventRepository) {
|
|
349
|
-
this.repository = options.eventRepository;
|
|
350
|
-
} else if (options.eventLedgerPath) {
|
|
351
|
-
const opened = SqliteEventRepository.open(options.eventLedgerPath);
|
|
352
|
-
if (opened.ok) {
|
|
353
|
-
this.repository = opened.repository;
|
|
354
|
-
} else {
|
|
355
|
-
const cause = opened.unavailable.cause
|
|
356
|
-
? ` Cause: ${opened.unavailable.cause}`
|
|
357
|
-
: '';
|
|
358
|
-
throw new Error(
|
|
359
|
-
`EVENT_LEDGER_${opened.unavailable.code}: ${opened.unavailable.message}${cause}`,
|
|
360
|
-
);
|
|
361
|
-
}
|
|
362
|
-
} else {
|
|
363
|
-
// Pathless instances are useful to tests and embedded hosts that own
|
|
364
|
-
// both the runtime and every consumer. Production adapters should pass
|
|
365
|
-
// a durable repository or ledger path.
|
|
366
|
-
this.repository = new MemoryEventRepository();
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
let historyPersistence: RuntimePersistenceStatus['stateHistory'] = 'memory';
|
|
370
|
-
if (options.stateHistoryRepository) {
|
|
371
|
-
this.stateHistoryRepository = options.stateHistoryRepository;
|
|
372
|
-
historyPersistence = options.stateHistoryRepository instanceof SqliteStateHistoryRepository
|
|
373
|
-
|| (options.stateHistoryRepository as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
|
|
374
|
-
? 'sqlite'
|
|
375
|
-
: 'memory';
|
|
376
|
-
} else if (options.stateHistoryPath) {
|
|
377
|
-
try {
|
|
378
|
-
this.stateHistoryRepository = new SqliteStateHistoryRepository<TPosition>(options.stateHistoryPath);
|
|
379
|
-
historyPersistence = 'sqlite';
|
|
380
|
-
} catch (error) {
|
|
381
|
-
this.stateHistoryRepository = new MemoryStateHistoryRepository<TPosition>();
|
|
382
|
-
warnings.push(`STATE_HISTORY_SQLITE_UNAVAILABLE: ${error instanceof Error ? error.message : String(error)}`);
|
|
383
|
-
}
|
|
384
|
-
} else {
|
|
385
|
-
this.stateHistoryRepository = new MemoryStateHistoryRepository<TPosition>();
|
|
386
|
-
}
|
|
387
|
-
let inputJournalPersistence: RuntimePersistenceStatus['inputJournal'] = 'memory';
|
|
388
|
-
if (options.inputJournal) {
|
|
389
|
-
this.inputJournal = options.inputJournal;
|
|
390
|
-
inputJournalPersistence = options.inputJournal instanceof SqliteRuntimeInputJournal
|
|
391
|
-
|| (options.inputJournal as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
|
|
392
|
-
? 'sqlite'
|
|
393
|
-
: 'memory';
|
|
394
|
-
} else if (options.inputJournalPath) {
|
|
395
|
-
this.inputJournal = new SqliteRuntimeInputJournal(options.inputJournalPath);
|
|
396
|
-
inputJournalPersistence = 'sqlite';
|
|
397
|
-
} else {
|
|
398
|
-
this.inputJournal = new MemoryRuntimeInputJournal();
|
|
399
|
-
}
|
|
400
|
-
const eventPersistence = this.repository instanceof SqliteEventRepository
|
|
401
|
-
|| (this.repository as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
|
|
402
|
-
? 'sqlite'
|
|
403
|
-
: 'memory';
|
|
404
|
-
this.persistenceBase = {
|
|
405
|
-
events: eventPersistence,
|
|
406
|
-
stateHistory: historyPersistence,
|
|
407
|
-
inputJournal: inputJournalPersistence,
|
|
408
|
-
warnings,
|
|
409
|
-
};
|
|
410
|
-
this.currentStateFromRuntimeState = options.currentStateFromRuntimeState
|
|
411
|
-
?? ((state) => structuredClone(state));
|
|
412
|
-
|
|
413
|
-
this.historyWriter = new HistoryWriter(this.stateHistoryRepository, {
|
|
414
|
-
onHealthChanged: (health) => this.onHistoryWriterHealthChanged(health),
|
|
415
|
-
});
|
|
416
|
-
const historyObserver = options.historyObserverFactory?.(this.historyWriter);
|
|
417
|
-
this.stateObservers = [...(options.stateObservers ?? [])];
|
|
418
|
-
this.stateIngress = new StateIngress(this.stateStore, [
|
|
419
|
-
...(historyObserver ? [historyObserver] : []),
|
|
420
|
-
...this.stateObservers,
|
|
421
|
-
]);
|
|
422
|
-
this.stateProvider = new StateProvider(
|
|
423
|
-
this.stateStore,
|
|
424
|
-
new StateFreshnessEvaluator(
|
|
425
|
-
options.stateFreshnessPolicy,
|
|
426
|
-
options.stateFreshnessPolicyResolver,
|
|
427
|
-
),
|
|
428
|
-
(snapshot) => snapshot.backendState,
|
|
429
|
-
);
|
|
430
|
-
this.eventCatalog = options.eventCatalog;
|
|
431
|
-
this.eventIngress = new EventIngress(this.repository, this.eventCatalog, {
|
|
432
|
-
consumerIds: options.initialEventConsumerIds,
|
|
433
|
-
});
|
|
434
|
-
for (const plugin of options.runtimeEpochPlugins ?? []) {
|
|
435
|
-
for (const output of plugin.produces?.events ?? []) {
|
|
436
|
-
const catalogEntry = options.eventCatalog.get(output);
|
|
437
|
-
if (!catalogEntry) {
|
|
438
|
-
throw new Error(
|
|
439
|
-
`Runtime Epoch Plugin "${plugin.id}" output "${output}" `
|
|
440
|
-
+ 'is not registered in the Event Catalog.',
|
|
441
|
-
);
|
|
442
|
-
}
|
|
443
|
-
if (catalogEntry.producer !== 'local_synth') {
|
|
444
|
-
throw new Error(
|
|
445
|
-
`Runtime Epoch Plugin "${plugin.id}" cannot own backend Event "${output}".`,
|
|
446
|
-
);
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
this.pluginScheduler = new RuntimePluginScheduler({
|
|
451
|
-
plugins: options.runtimeEpochPlugins,
|
|
452
|
-
inputJournal: this.inputJournal,
|
|
453
|
-
pluginStore: this.inputJournal,
|
|
454
|
-
stateHistory: this.stateHistoryRepository,
|
|
455
|
-
commitInputEvents: (work) => this.commitInputEvents(work),
|
|
456
|
-
listEvents: ({ scope, ...filter }) => this.repository.listCommittedEvents({
|
|
457
|
-
sessionId: scope.sessionId,
|
|
458
|
-
segmentId: scope.segmentId,
|
|
459
|
-
afterCommitSeq: filter.afterCommitSeq,
|
|
460
|
-
maxCommitSeq: filter.maxCommitSeq,
|
|
461
|
-
...(filter.epochSeq === undefined ? {} : { epochSeq: filter.epochSeq }),
|
|
462
|
-
...(filter.maxEpochSeq === undefined ? {} : { maxEpochSeq: filter.maxEpochSeq }),
|
|
463
|
-
...(filter.types ? { types: [...filter.types] } : {}),
|
|
464
|
-
order: 'asc',
|
|
465
|
-
}),
|
|
466
|
-
publishEvent: (pluginId, epoch, proposal, proposalIndex) => this.eventIngress.publish(
|
|
467
|
-
this.pluginEventInput(pluginId, epoch, proposal, proposalIndex),
|
|
468
|
-
),
|
|
469
|
-
resolveEventDelivery: (decision) => this.repository.resolveEventDelivery(decision),
|
|
470
|
-
highWaterCommitSeq: (scope) => this.repository.highWaterCommitSeq(
|
|
471
|
-
scope.sessionId,
|
|
472
|
-
),
|
|
473
|
-
currentSegment: () => {
|
|
474
|
-
const segment = this.currentSegment();
|
|
475
|
-
return {
|
|
476
|
-
kind: segment.kind,
|
|
477
|
-
...(segment.identity === undefined ? {} : { identity: segment.identity }),
|
|
478
|
-
};
|
|
479
|
-
},
|
|
480
|
-
capabilitiesFor: (plugin, scope, signal, epochSeq) => this.pluginCapabilityAccess(
|
|
481
|
-
plugin,
|
|
482
|
-
scope,
|
|
483
|
-
signal,
|
|
484
|
-
epochSeq,
|
|
485
|
-
),
|
|
486
|
-
onEpochClosed: (work, result) => this.onEpochClosed(work.epoch, work.frame.frameSeq, result),
|
|
487
|
-
onFatalError: (error, pluginId, scope) => {
|
|
488
|
-
this.fatalError = error instanceof Error ? error : new Error(String(error));
|
|
489
|
-
this.actions.beginStopping('runtime_plugin_fatal');
|
|
490
|
-
this.observability?.error('runtime.plugin.fatal', this.fatalError, {
|
|
491
|
-
plugin_id: pluginId,
|
|
492
|
-
}, { component: 'runtime.epoch', scope });
|
|
493
|
-
},
|
|
494
|
-
onDiagnostic: (name, attributes, scope, severity = 'debug') => {
|
|
495
|
-
this.observability?.log(
|
|
496
|
-
severity,
|
|
497
|
-
name,
|
|
498
|
-
attributes,
|
|
499
|
-
{ component: 'runtime.epoch', scope },
|
|
500
|
-
);
|
|
501
|
-
},
|
|
502
|
-
});
|
|
503
|
-
|
|
504
|
-
const accountScope = { adapterId: this.adapterId, accountId: this.accountId };
|
|
505
|
-
const durableCurrent = this.repository.currentScope(accountScope);
|
|
506
|
-
const resumesBySessionKey = options.resumeKey !== undefined
|
|
507
|
-
&& durableCurrent?.session.resumeKey === options.resumeKey;
|
|
508
|
-
const canResume = canResumeRuntimeScope(durableCurrent, options);
|
|
509
|
-
if (!canResume && durableCurrent) this.sealDurableScope(durableCurrent);
|
|
510
|
-
|
|
511
|
-
this.participation = new ParticipationManager({
|
|
512
|
-
initial: canResume && durableCurrent ? participationFromCurrent(durableCurrent) : undefined,
|
|
513
|
-
onTransition: (transition) => this.persistTransition(transition),
|
|
514
|
-
});
|
|
515
|
-
if (!canResume) {
|
|
516
|
-
this.participation.openSession({
|
|
517
|
-
adapterId: this.adapterId,
|
|
518
|
-
accountId: this.accountId,
|
|
519
|
-
resumeKey: options.resumeKey,
|
|
520
|
-
mode: options.mode,
|
|
521
|
-
initialSegment: options.initialSegment,
|
|
522
|
-
});
|
|
523
|
-
} else {
|
|
524
|
-
if (options.mode) this.participation.updateMode(options.mode);
|
|
525
|
-
const restoredSegmentId = this.participation.requireSnapshot().segment.id;
|
|
526
|
-
const activated = this.participation.activateSegment(
|
|
527
|
-
options.initialSegment.kind,
|
|
528
|
-
options.initialSegment.identity,
|
|
529
|
-
);
|
|
530
|
-
if (activated.segment.id === restoredSegmentId) {
|
|
531
|
-
// A live-only source may have advanced while the owner was down. The
|
|
532
|
-
// logical segment resumes, but its history completeness cannot.
|
|
533
|
-
this.openStateScope(activated, false);
|
|
534
|
-
this.ownerRestartGapOpen = true;
|
|
535
|
-
this.enqueueOwnerRestartGap('stream_gap_started');
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
this.actions.activateScope(this.scope());
|
|
539
|
-
this.readyScope = this.scope();
|
|
540
|
-
this.readyState = this.readAgentState();
|
|
541
|
-
this.readyEventWatermark = this.repository.highWaterCommitSeq(
|
|
542
|
-
this.scope().sessionId,
|
|
543
|
-
);
|
|
544
|
-
|
|
545
|
-
const scope = this.scope();
|
|
546
|
-
this.observability?.log('info', 'runtime.owner.started', {
|
|
547
|
-
adapter_id: this.adapterId,
|
|
548
|
-
persistence: this.persistence,
|
|
549
|
-
resumed: canResume,
|
|
550
|
-
resume_match: canResume
|
|
551
|
-
? resumesBySessionKey ? 'session_key' : 'current_segment'
|
|
552
|
-
: 'none',
|
|
553
|
-
}, { component: 'runtime', scope });
|
|
554
|
-
for (const warning of warnings) {
|
|
555
|
-
this.observability?.log('warn', 'runtime.persistence.degraded', {
|
|
556
|
-
warning,
|
|
557
|
-
event_repository: eventPersistence,
|
|
558
|
-
state_history_repository: historyPersistence,
|
|
559
|
-
}, { component: 'runtime.persistence', scope });
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
/** Dynamic owner health; unlike the repository choice, writer health can change at runtime. */
|
|
564
|
-
get persistence(): RuntimePersistenceStatus {
|
|
565
|
-
return {
|
|
566
|
-
...this.persistenceBase,
|
|
567
|
-
warnings: [...this.persistenceBase.warnings],
|
|
568
|
-
historyWriter: this.historyWriterHealth(),
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
historyWriterHealth(): PublicHistoryWriterHealth {
|
|
573
|
-
return {
|
|
574
|
-
...this.historyWriter.health(),
|
|
575
|
-
degradedScopes: this.historyWriter.degradedScopeHealth().map((entry) => {
|
|
576
|
-
const { accountId: _accountId, ...scope } = entry.scope;
|
|
577
|
-
return { ...entry, scope };
|
|
578
|
-
}),
|
|
579
|
-
};
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
scope(): RuntimeScope {
|
|
583
|
-
return runtimeScope(this.participation.requireSnapshot());
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
currentSegment(): { scope: RuntimeScope; kind: string; identity?: string } {
|
|
587
|
-
const snapshot = this.participation.requireSnapshot();
|
|
588
|
-
return {
|
|
589
|
-
scope: runtimeScope(snapshot),
|
|
590
|
-
kind: snapshot.segment.kind,
|
|
591
|
-
...(snapshot.segment.identity === undefined ? {} : { identity: snapshot.segment.identity }),
|
|
592
|
-
};
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
publicScope(): PublicRuntimeScope {
|
|
596
|
-
return this.publicScopeFor(this.scope());
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
private publicScopeFor(runtimeScope: RuntimeScope): PublicRuntimeScope {
|
|
600
|
-
const { accountId: _accountId, ...scope } = runtimeScope;
|
|
601
|
-
return scope;
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
runtimeEpochPluginDescriptors(): ReturnType<RuntimePluginScheduler['descriptors']> {
|
|
605
|
-
return this.pluginScheduler.descriptors();
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
/** Full-diagnostic, on-demand scheduler state; never sampled by default. */
|
|
609
|
-
runtimeEpochDiagnosticSnapshot(): ReturnType<RuntimePluginScheduler['diagnosticSnapshot']> {
|
|
610
|
-
return this.pluginScheduler.diagnosticSnapshot(this.scope());
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
/** Full-only retained row counts; implementations without a hot cache report an empty object. */
|
|
614
|
-
runtimeRetainedRecordCounts(): Readonly<Record<string, unknown>> {
|
|
615
|
-
const counts = (value: unknown): Readonly<Record<string, number>> => (
|
|
616
|
-
(value as { diagnosticCounts?: () => Readonly<Record<string, number>> })
|
|
617
|
-
?.diagnosticCounts?.() ?? {}
|
|
618
|
-
);
|
|
619
|
-
return {
|
|
620
|
-
event_repository: counts(this.repository),
|
|
621
|
-
state_history: counts(this.stateHistoryRepository),
|
|
622
|
-
input_journal: counts(this.inputJournal),
|
|
623
|
-
};
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
runtimePersistenceDiagnostics(): Readonly<Record<string, unknown>> {
|
|
627
|
-
return (this.repository as { persistenceHealth?: () => Readonly<Record<string, unknown>> })
|
|
628
|
-
.persistenceHealth?.() ?? {};
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
runtimePluginDescriptors(): RuntimePluginDescriptor[] {
|
|
632
|
-
return [
|
|
633
|
-
...[...this.sourcePlugins.values()].map(({ plugin }) => ({
|
|
634
|
-
kind: 'source' as const,
|
|
635
|
-
id: plugin.id,
|
|
636
|
-
version: plugin.version,
|
|
637
|
-
})),
|
|
638
|
-
...this.pluginScheduler.descriptors(),
|
|
639
|
-
];
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
/** Start the current scope's Epoch Plugin graph before external input arrives. */
|
|
643
|
-
async start(): Promise<void> {
|
|
644
|
-
this.assertOpen();
|
|
645
|
-
if (!this.startPromise) {
|
|
646
|
-
const attempt = (async () => {
|
|
647
|
-
await this.pluginScheduler.activateScope(this.scope());
|
|
648
|
-
await this.recoverOpenEpochs();
|
|
649
|
-
})();
|
|
650
|
-
this.startPromise = attempt.catch((error) => {
|
|
651
|
-
this.startPromise = undefined;
|
|
652
|
-
throw error;
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
await this.startPromise;
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
async startSourcePlugin(
|
|
659
|
-
plugin: RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>>,
|
|
660
|
-
): Promise<void> {
|
|
661
|
-
this.assertOpen();
|
|
662
|
-
if (plugin.kind !== 'source') throw new TypeError(`Runtime Source Plugin ${plugin.id} has invalid kind.`);
|
|
663
|
-
if (!plugin.id?.trim()) throw new TypeError('Runtime Source Plugin id must not be empty.');
|
|
664
|
-
if (!plugin.version?.trim()) throw new TypeError(`Runtime Source Plugin ${plugin.id} version must not be empty.`);
|
|
665
|
-
if (this.sourcePlugins.has(plugin.id)) throw new Error(`Duplicate Runtime Source Plugin id: ${plugin.id}`);
|
|
666
|
-
if (this.pluginScheduler.descriptors().some((candidate) => candidate.id === plugin.id)) {
|
|
667
|
-
throw new Error(`Runtime Plugin id is shared by Source and Epoch Plugin: ${plugin.id}`);
|
|
668
|
-
}
|
|
669
|
-
await this.start();
|
|
670
|
-
const handle = await plugin.start(this);
|
|
671
|
-
if (!handle || typeof handle.stop !== 'function') {
|
|
672
|
-
throw new TypeError(`Runtime Source Plugin ${plugin.id} did not return a stop handle.`);
|
|
673
|
-
}
|
|
674
|
-
this.sourcePlugins.set(plugin.id, { plugin, handle });
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
closeActionScope(scope: RuntimeScope, reason: string): void {
|
|
678
|
-
this.actions.closeScope(scope, reason);
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
async activateSegment(kind: string, identity?: string): Promise<RuntimeScope> {
|
|
682
|
-
this.assertOpen();
|
|
683
|
-
const previous = this.scope();
|
|
684
|
-
const current = this.participation.requireSnapshot().segment;
|
|
685
|
-
const changesSegment = current.kind !== kind
|
|
686
|
-
|| (
|
|
687
|
-
identity !== undefined
|
|
688
|
-
&& current.identity !== undefined
|
|
689
|
-
&& current.identity !== identity
|
|
690
|
-
);
|
|
691
|
-
if (changesSegment) await this.pluginScheduler.flush('segment_ending');
|
|
692
|
-
const next = runtimeScope(this.participation.activateSegment(kind, identity));
|
|
693
|
-
if (previous.segmentId !== next.segmentId) {
|
|
694
|
-
this.resetReadyView(next);
|
|
695
|
-
this.observability?.log('info', 'runtime.scope.switched', {
|
|
696
|
-
previous_segment_id: previous.segmentId,
|
|
697
|
-
previous_segment_seq: previous.segmentSeq,
|
|
698
|
-
segment_kind: kind,
|
|
699
|
-
has_identity: !!identity,
|
|
700
|
-
}, { component: 'runtime', scope: next });
|
|
701
|
-
}
|
|
702
|
-
return next;
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
adoptResumeKey(resumeKey: string): RuntimeScope {
|
|
706
|
-
this.assertOpen();
|
|
707
|
-
return runtimeScope(this.participation.adoptResumeKey(resumeKey));
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
updateMode(mode: string): RuntimeScope {
|
|
711
|
-
this.assertOpen();
|
|
712
|
-
return runtimeScope(this.participation.updateMode(mode));
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
bindConnection(sourceId: string, connectionId: string, atMs = Date.now()): RuntimeScope {
|
|
716
|
-
this.assertOpen();
|
|
717
|
-
const key = this.connectionKey(sourceId, connectionId);
|
|
718
|
-
const current = this.scope();
|
|
719
|
-
const existing = this.connectionScopes.get(key);
|
|
720
|
-
if (existing) {
|
|
721
|
-
if (!sameScope(existing, current)) {
|
|
722
|
-
throw new Error('Connection is already frozen to a different runtime scope.');
|
|
723
|
-
}
|
|
724
|
-
if (this.participation.connectionId(sourceId) !== connectionId) {
|
|
725
|
-
throw new Error('Connection has already been superseded by a newer connection.');
|
|
726
|
-
}
|
|
727
|
-
return structuredClone(existing);
|
|
728
|
-
}
|
|
729
|
-
const snapshot = this.participation.bindConnection(sourceId, connectionId);
|
|
730
|
-
this.stateIngress.openScope(runtimeScope(snapshot), atMs);
|
|
731
|
-
this.stateIngress.connectionOpened(connectionId, atMs);
|
|
732
|
-
if (this.ownerRestartGapOpen) {
|
|
733
|
-
this.ownerRestartGapOpen = false;
|
|
734
|
-
this.enqueueOwnerRestartGap('stream_gap_ended', connectionId, atMs);
|
|
735
|
-
}
|
|
736
|
-
const scope = runtimeScope(snapshot);
|
|
737
|
-
this.connectionScopes.set(key, structuredClone(scope));
|
|
738
|
-
this.observability?.log('info', 'runtime.connection.bound', {
|
|
739
|
-
source_id: sourceId,
|
|
740
|
-
}, { component: 'runtime.transport', scope: { ...scope, connectionId } });
|
|
741
|
-
return scope;
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
/** Explicitly move a still-live physical connection to a new logical segment. */
|
|
745
|
-
rebindConnectionScope(sourceId: string, connectionId: string, atMs = Date.now()): RuntimeScope {
|
|
746
|
-
this.assertOpen();
|
|
747
|
-
if (this.participation.connectionId(sourceId) !== connectionId) {
|
|
748
|
-
throw new Error('Only the active connection can be rebound to a new runtime scope.');
|
|
749
|
-
}
|
|
750
|
-
const scope = this.scope();
|
|
751
|
-
const key = this.connectionKey(sourceId, connectionId);
|
|
752
|
-
const existing = this.connectionScopes.get(key);
|
|
753
|
-
if (existing && sameScope(existing, scope)) return structuredClone(scope);
|
|
754
|
-
this.connectionScopes.set(key, structuredClone(scope));
|
|
755
|
-
this.stateIngress.openScope(scope, atMs);
|
|
756
|
-
this.stateIngress.connectionOpened(connectionId, atMs);
|
|
757
|
-
this.observability?.log('info', 'runtime.connection.scope_rebound', {
|
|
758
|
-
source_id: sourceId,
|
|
759
|
-
}, { component: 'runtime.transport', scope: { ...scope, connectionId } });
|
|
760
|
-
return structuredClone(scope);
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
connectionScope(sourceId: string, connectionId: string): RuntimeScope | null {
|
|
764
|
-
const scope = this.connectionScopes.get(this.connectionKey(sourceId, connectionId));
|
|
765
|
-
return scope ? structuredClone(scope) : null;
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
isActiveConnection(sourceId: string, connectionId: string): boolean {
|
|
769
|
-
return this.participation.connectionId(sourceId) === connectionId;
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
connectionChanged(
|
|
773
|
-
sourceId: string,
|
|
774
|
-
connectionId: string,
|
|
775
|
-
state: RuntimeConnectionState,
|
|
776
|
-
atMs = Date.now(),
|
|
777
|
-
): void {
|
|
778
|
-
if (this.closed || this.participation.connectionId(sourceId) !== connectionId) return;
|
|
779
|
-
this.stateIngress.connectionChanged(connectionId, state, atMs);
|
|
780
|
-
const scope = this.scope();
|
|
781
|
-
this.observability?.log(
|
|
782
|
-
state === 'connected' ? 'info' : 'warn',
|
|
783
|
-
`runtime.connection.${state}`,
|
|
784
|
-
{ source_id: sourceId },
|
|
785
|
-
{ component: 'runtime.transport', scope: { ...scope, connectionId } },
|
|
786
|
-
);
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
connectionLiveness(sourceId: string, connectionId: string, atMs = Date.now()): boolean {
|
|
790
|
-
if (this.closed || this.participation.connectionId(sourceId) !== connectionId) return false;
|
|
791
|
-
return this.stateIngress.livenessReceived(connectionId, atMs);
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
diagnostic(
|
|
795
|
-
name: string,
|
|
796
|
-
attributes: Readonly<Record<string, unknown>> = {},
|
|
797
|
-
severity: 'debug' | 'info' | 'warn' | 'error' = 'debug',
|
|
798
|
-
): void {
|
|
799
|
-
this.observability?.log(severity, name, { ...attributes }, {
|
|
800
|
-
component: 'runtime.source',
|
|
801
|
-
scope: this.publicScope(),
|
|
802
|
-
});
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
/**
|
|
806
|
-
* The fixed Runtime intake boundary. Acceptance persists the complete input
|
|
807
|
-
* immediately; plugin work is queued independently so Source intake never
|
|
808
|
-
* waits for a slow Perception or Behavior invocation.
|
|
809
|
-
*/
|
|
810
|
-
async acceptInputBatch(
|
|
811
|
-
batch: RuntimeInputBatch<Record<string, any>, Record<string, unknown>>,
|
|
812
|
-
): Promise<RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>> {
|
|
813
|
-
this.assertSourceInputOpen();
|
|
814
|
-
const intakeStartedAtMs = performance.now();
|
|
815
|
-
const journalStartedAtMs = performance.now();
|
|
816
|
-
let acceptance: RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>;
|
|
817
|
-
try {
|
|
818
|
-
assertRuntimeInputBatch(batch);
|
|
819
|
-
if (!sameScope(batch.scope, this.scope())) {
|
|
820
|
-
throw new Error('Runtime InputBatch scope does not match the active participation segment.');
|
|
821
|
-
}
|
|
822
|
-
acceptance = this.inputJournal.accept(batch);
|
|
823
|
-
} catch (error) {
|
|
824
|
-
this.observability?.error('runtime.input.rejected', error, {
|
|
825
|
-
source_id: batch?.sourceId,
|
|
826
|
-
source_key: batch?.sourceKey,
|
|
827
|
-
reason: error instanceof Error ? error.name : 'invalid_input',
|
|
828
|
-
}, { component: 'runtime.input', scope: this.publicScope() });
|
|
829
|
-
throw error;
|
|
830
|
-
}
|
|
831
|
-
const journalMs = Math.max(0, performance.now() - journalStartedAtMs);
|
|
832
|
-
if (!acceptance.inserted) {
|
|
833
|
-
this.observability?.log('debug', 'runtime.input.duplicate', {
|
|
834
|
-
source_id: batch.sourceId,
|
|
835
|
-
source_key: batch.sourceKey,
|
|
836
|
-
epoch_seq: acceptance.epoch.epochSeq,
|
|
837
|
-
}, { component: 'runtime.input', scope: this.publicScope() });
|
|
838
|
-
return acceptance;
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
const epoch = acceptance.epoch;
|
|
842
|
-
this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, epoch.epochSeq);
|
|
843
|
-
const historyStartedAtMs = performance.now();
|
|
844
|
-
const previousFrame = this.stateHistoryRepository.latestStateFrame(epoch.scope);
|
|
845
|
-
const frame = this.stateHistoryRepository.appendStateFrame({
|
|
846
|
-
epochSeq: epoch.epochSeq,
|
|
847
|
-
scope: epoch.scope,
|
|
848
|
-
sourceId: epoch.sourceId,
|
|
849
|
-
connectionId: epoch.connectionId,
|
|
850
|
-
sourceKey: `runtime-epoch:${epoch.epochSeq}`,
|
|
851
|
-
sourceSeq: epoch.sourceSeq,
|
|
852
|
-
backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
|
|
853
|
-
observedAtMs: milliseconds(epoch.observedAt),
|
|
854
|
-
receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
|
|
855
|
-
state: epoch.state,
|
|
856
|
-
}).frame;
|
|
857
|
-
const historyMs = Math.max(0, performance.now() - historyStartedAtMs);
|
|
858
|
-
|
|
859
|
-
const stateProjectionStartedAtMs = performance.now();
|
|
860
|
-
const projectedState = this.currentStateFromRuntimeState(epoch.state);
|
|
861
|
-
if (projectedState !== null) {
|
|
862
|
-
const current = this.stateIngress.snapshot();
|
|
863
|
-
if (current.meta.connectionId !== epoch.connectionId) {
|
|
864
|
-
this.stateIngress.connectionOpened(
|
|
865
|
-
epoch.connectionId,
|
|
866
|
-
milliseconds(epoch.receivedAt) ?? Date.now(),
|
|
867
|
-
);
|
|
868
|
-
}
|
|
869
|
-
const applied = this.stateIngress.accept({
|
|
870
|
-
scope: epoch.scope,
|
|
871
|
-
sourceId: epoch.sourceId,
|
|
872
|
-
connectionId: epoch.connectionId,
|
|
873
|
-
payload: projectedState,
|
|
874
|
-
sourceKey: `runtime-epoch:${epoch.epochSeq}`,
|
|
875
|
-
sourceSeq: epoch.epochSeq,
|
|
876
|
-
backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
|
|
877
|
-
observedAtMs: milliseconds(epoch.observedAt),
|
|
878
|
-
receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
|
|
879
|
-
});
|
|
880
|
-
if (!applied.accepted) {
|
|
881
|
-
throw new Error(`Runtime current-State projection was rejected: ${applied.reason}.`);
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
const currentState = this.readAgentState();
|
|
885
|
-
this.acceptedAgentStateByEpoch.set(epoch.epochSeq, structuredClone(currentState));
|
|
886
|
-
const stateProjectionMs = Math.max(0, performance.now() - stateProjectionStartedAtMs);
|
|
887
|
-
const intakeTotalMs = Math.max(0, performance.now() - intakeStartedAtMs);
|
|
888
|
-
this.epochIntakeTimings.set(epoch.epochSeq, {
|
|
889
|
-
startedAtMs: intakeStartedAtMs,
|
|
890
|
-
journalMs,
|
|
891
|
-
historyMs,
|
|
892
|
-
stateProjectionMs,
|
|
893
|
-
intakeTotalMs,
|
|
894
|
-
});
|
|
895
|
-
|
|
896
|
-
this.observability?.log('debug', 'runtime.input.accepted', {
|
|
897
|
-
source_id: epoch.sourceId,
|
|
898
|
-
source_seq: epoch.sourceSeq,
|
|
899
|
-
source_key: epoch.sourceKey,
|
|
900
|
-
epoch_seq: epoch.epochSeq,
|
|
901
|
-
domain_tick: epoch.domainTick,
|
|
902
|
-
event_count: epoch.events.length,
|
|
903
|
-
completeness: epoch.completeness,
|
|
904
|
-
coalescing: epoch.coalescing ?? 'allowed',
|
|
905
|
-
stage: typeof epoch.state.stage === 'string' ? epoch.state.stage : undefined,
|
|
906
|
-
cause: typeof epoch.state.cause === 'string' ? epoch.state.cause : undefined,
|
|
907
|
-
connection: typeof epoch.state.connection === 'string' ? epoch.state.connection : undefined,
|
|
908
|
-
game_snapshot_status: epoch.state.game_snapshot?.status,
|
|
909
|
-
journal_ms: Math.round(journalMs * 1_000) / 1_000,
|
|
910
|
-
state_history_ms: Math.round(historyMs * 1_000) / 1_000,
|
|
911
|
-
state_projection_ms: Math.round(stateProjectionMs * 1_000) / 1_000,
|
|
912
|
-
intake_total_ms: Math.round(intakeTotalMs * 1_000) / 1_000,
|
|
913
|
-
}, { component: 'runtime.input', scope: this.publicScope() });
|
|
914
|
-
|
|
915
|
-
const completion = this.pluginScheduler.enqueue({
|
|
916
|
-
epoch,
|
|
917
|
-
frame,
|
|
918
|
-
currentState,
|
|
919
|
-
previousState: previousFrame?.state ?? null,
|
|
920
|
-
epochEvents: [],
|
|
921
|
-
});
|
|
922
|
-
this.trackEpochCompletion(epoch.epochSeq, completion);
|
|
923
|
-
void completion.catch((error) => {
|
|
924
|
-
this.observability?.error('runtime.epoch.processing_failed', error, {
|
|
925
|
-
epoch_seq: epoch.epochSeq,
|
|
926
|
-
source_id: epoch.sourceId,
|
|
927
|
-
}, { component: 'runtime.epoch', scope: this.publicScope() });
|
|
928
|
-
});
|
|
929
|
-
return acceptance;
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
readState(nowMs = Date.now()): StateProviderResult<Record<string, any> | null> {
|
|
933
|
-
return this.stateProvider.read(this.scope(), nowMs);
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
/** Agent-safe State view. Internal account identity never crosses owner IPC. */
|
|
937
|
-
readAgentState(nowMs = Date.now()): StateProviderResult<Record<string, any> | null> {
|
|
938
|
-
const result = this.readState(nowMs);
|
|
939
|
-
const scope = result.stateStatus.scope;
|
|
940
|
-
return {
|
|
941
|
-
...result,
|
|
942
|
-
stateStatus: {
|
|
943
|
-
...result.stateStatus,
|
|
944
|
-
scope: scope ? this.publicScope() as any : null,
|
|
945
|
-
},
|
|
946
|
-
};
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
async queryObservation<Q, R>(
|
|
950
|
-
capability: string,
|
|
951
|
-
request: Q,
|
|
952
|
-
expectedScope: ExpectedRuntimeScope,
|
|
953
|
-
): Promise<ObservationResult<R>> {
|
|
954
|
-
const scope = this.assertExpectedScope(expectedScope);
|
|
955
|
-
return this.observations.query<Q, R>(capability, request, scope);
|
|
956
|
-
}
|
|
957
|
-
|
|
958
|
-
async performAction<A, R>(
|
|
959
|
-
capability: string,
|
|
960
|
-
action: A,
|
|
961
|
-
expectedScope: ExpectedRuntimeScope,
|
|
962
|
-
caller: ActionCaller,
|
|
963
|
-
admission: ActionAdmissionOptions = {},
|
|
964
|
-
): Promise<ActionResult<R>> {
|
|
965
|
-
const scope = this.assertExpectedScope(expectedScope);
|
|
966
|
-
const startedAt = Date.now();
|
|
967
|
-
const detailId = this.observability?.captureEnabled('actions') ? captureId() : undefined;
|
|
968
|
-
if (detailId) this.observability?.log('debug', 'runtime.detail.actions.requested', {
|
|
969
|
-
request_id: detailId, capability, caller, request: action,
|
|
970
|
-
}, { component: 'runtime.actions', scope });
|
|
971
|
-
try {
|
|
972
|
-
const result = await this.actions.perform<A, R>(capability, action, scope, caller, {
|
|
973
|
-
...admission,
|
|
974
|
-
latestAcceptedState: () => this.latestAcceptedActionState(scope),
|
|
975
|
-
});
|
|
976
|
-
if (detailId) this.observability?.log('debug', 'runtime.detail.actions.receipt', {
|
|
977
|
-
request_id: detailId, capability, caller, action_id: result.actionId, result,
|
|
978
|
-
duration_ms: Date.now() - startedAt,
|
|
979
|
-
}, { component: 'runtime.actions', scope });
|
|
980
|
-
const attributes = {
|
|
981
|
-
capability,
|
|
982
|
-
caller_kind: caller.kind,
|
|
983
|
-
status: result.status,
|
|
984
|
-
...(result.source ? { action_source: result.source } : {}),
|
|
985
|
-
...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}),
|
|
986
|
-
duration_ms: Date.now() - startedAt,
|
|
987
|
-
};
|
|
988
|
-
const context = {
|
|
989
|
-
component: 'runtime.actions',
|
|
990
|
-
scope,
|
|
991
|
-
correlation: {
|
|
992
|
-
actionId: result.actionId,
|
|
993
|
-
...(caller.kind === 'behavior' ? {
|
|
994
|
-
behaviorActivationId: caller.activationId,
|
|
995
|
-
behaviorActivationGeneration: caller.activationGeneration,
|
|
996
|
-
} : {}),
|
|
997
|
-
},
|
|
998
|
-
};
|
|
999
|
-
if (result.status === 'failure') {
|
|
1000
|
-
const summary = summarizeActionError(result.error);
|
|
1001
|
-
const severity = actionFailureDiagnosticSeverity(result);
|
|
1002
|
-
if (severity === 'warn') {
|
|
1003
|
-
this.observability?.log('warn', 'runtime.action.failed', {
|
|
1004
|
-
...attributes,
|
|
1005
|
-
error_code: summary.code,
|
|
1006
|
-
http_status: summary.httpStatus,
|
|
1007
|
-
error_message_present: summary.messagePresent,
|
|
1008
|
-
error_message_length: summary.messageLength,
|
|
1009
|
-
}, context);
|
|
1010
|
-
} else {
|
|
1011
|
-
this.observability?.error('runtime.action.failed', {
|
|
1012
|
-
name: 'ActionFailure',
|
|
1013
|
-
...(summary.code ? { code: summary.code } : {}),
|
|
1014
|
-
}, {
|
|
1015
|
-
...attributes,
|
|
1016
|
-
error_code: summary.code,
|
|
1017
|
-
http_status: summary.httpStatus,
|
|
1018
|
-
error_message_present: summary.messagePresent,
|
|
1019
|
-
error_message_length: summary.messageLength,
|
|
1020
|
-
}, context);
|
|
1021
|
-
}
|
|
1022
|
-
} else if (result.status === 'deferred') {
|
|
1023
|
-
const summary = summarizeActionError(result.error);
|
|
1024
|
-
this.observability?.log('info', 'runtime.action.deferred', {
|
|
1025
|
-
...attributes,
|
|
1026
|
-
control_code: summary.code ?? 'CONTROL_DEFERRED',
|
|
1027
|
-
}, context);
|
|
1028
|
-
} else {
|
|
1029
|
-
this.observability?.log(
|
|
1030
|
-
result.status === 'partial' ? 'warn' : 'info',
|
|
1031
|
-
'runtime.action.completed',
|
|
1032
|
-
attributes,
|
|
1033
|
-
context,
|
|
1034
|
-
);
|
|
1035
|
-
}
|
|
1036
|
-
return result;
|
|
1037
|
-
} catch (error) {
|
|
1038
|
-
const summary = summarizeActionError(error);
|
|
1039
|
-
if (detailId) this.observability?.log('debug', 'runtime.detail.actions.failed', {
|
|
1040
|
-
request_id: detailId, capability, caller, error, duration_ms: Date.now() - startedAt,
|
|
1041
|
-
}, { component: 'runtime.actions', scope });
|
|
1042
|
-
this.observability?.error('runtime.action.failed', {
|
|
1043
|
-
name: error instanceof Error ? error.name : 'ActionFailure',
|
|
1044
|
-
...(summary.code ? { code: summary.code } : {}),
|
|
1045
|
-
}, {
|
|
1046
|
-
capability,
|
|
1047
|
-
caller_kind: caller.kind,
|
|
1048
|
-
duration_ms: Date.now() - startedAt,
|
|
1049
|
-
error_message_present: summary.messagePresent,
|
|
1050
|
-
error_message_length: summary.messageLength,
|
|
1051
|
-
}, {
|
|
1052
|
-
component: 'runtime.actions',
|
|
1053
|
-
scope,
|
|
1054
|
-
correlation: caller.kind === 'behavior'
|
|
1055
|
-
? {
|
|
1056
|
-
behaviorActivationId: caller.activationId,
|
|
1057
|
-
behaviorActivationGeneration: caller.activationGeneration,
|
|
1058
|
-
}
|
|
1059
|
-
: undefined,
|
|
1060
|
-
});
|
|
1061
|
-
throw error;
|
|
1062
|
-
}
|
|
1063
|
-
}
|
|
1064
|
-
|
|
1065
|
-
/**
|
|
1066
|
-
* Non-consuming view bounded by the latest fully closed epoch. Consumers
|
|
1067
|
-
* get one State/Event position without changing any delivery cursor.
|
|
1068
|
-
*/
|
|
1069
|
-
readReadyView(afterCommitSeq = 0, limit = 100): RuntimeReadyView {
|
|
1070
|
-
const scope = this.scope();
|
|
1071
|
-
const readyForCurrentScope = !!this.readyScope && sameScope(this.readyScope, scope);
|
|
1072
|
-
const boundedLimit = Math.max(1, Math.min(500, Math.trunc(limit) || 100));
|
|
1073
|
-
const pending = this.repository.listCommittedEvents({
|
|
1074
|
-
sessionId: scope.sessionId,
|
|
1075
|
-
segmentId: scope.segmentId,
|
|
1076
|
-
afterCommitSeq,
|
|
1077
|
-
maxCommitSeq: readyForCurrentScope ? this.readyEventWatermark : 0,
|
|
1078
|
-
maxEpochSeq: readyForCurrentScope ? this.readyEpochSeq : 0,
|
|
1079
|
-
order: 'asc',
|
|
1080
|
-
limit: boundedLimit + 1,
|
|
1081
|
-
});
|
|
1082
|
-
const events = pending.slice(0, boundedLimit);
|
|
1083
|
-
return {
|
|
1084
|
-
scope: this.publicScope(),
|
|
1085
|
-
state: structuredClone(
|
|
1086
|
-
readyForCurrentScope ? this.readyState ?? this.readAgentState() : this.readAgentState(),
|
|
1087
|
-
),
|
|
1088
|
-
pluginStates: structuredClone(readyForCurrentScope ? this.readyPluginStates : {}),
|
|
1089
|
-
pluginOutcomes: structuredClone(readyForCurrentScope ? this.readyPluginOutcomes : {}),
|
|
1090
|
-
events,
|
|
1091
|
-
throughCommitSeq: events.at(-1)?.commitSeq ?? afterCommitSeq,
|
|
1092
|
-
frameSeq: readyForCurrentScope ? this.readyFrameSeq : 0,
|
|
1093
|
-
eventWatermark: readyForCurrentScope ? this.readyEventWatermark : 0,
|
|
1094
|
-
epochSeq: readyForCurrentScope ? this.readyEpochSeq : 0,
|
|
1095
|
-
hasMore: pending.length > events.length,
|
|
1096
|
-
};
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
/** Waits for one exact epoch and returns the immutable State/Event view closed at it. */
|
|
1100
|
-
async waitForEpochReadyView(
|
|
1101
|
-
epochSeq: number,
|
|
1102
|
-
afterCommitSeq = 0,
|
|
1103
|
-
limit = 100,
|
|
1104
|
-
): Promise<RuntimeReadyView> {
|
|
1105
|
-
if (!Number.isInteger(epochSeq) || epochSeq <= 0) {
|
|
1106
|
-
throw new TypeError('Runtime epochSeq must be a positive integer.');
|
|
1107
|
-
}
|
|
1108
|
-
let anchor = this.closedReadyAnchors.get(epochSeq);
|
|
1109
|
-
if (!anchor) {
|
|
1110
|
-
const completion = this.epochCompletions.get(epochSeq);
|
|
1111
|
-
if (!completion) throw new Error(`Runtime epoch ${epochSeq} is not pending in this Runtime.`);
|
|
1112
|
-
await completion;
|
|
1113
|
-
anchor = this.closedReadyAnchors.get(epochSeq);
|
|
1114
|
-
}
|
|
1115
|
-
if (!anchor) throw new Error(`Runtime epoch ${epochSeq} closed without a Ready View.`);
|
|
1116
|
-
return this.readyViewFromAnchor(anchor, afterCommitSeq, limit);
|
|
1117
|
-
}
|
|
1118
|
-
|
|
1119
|
-
async flush(): Promise<void> {
|
|
1120
|
-
await this.pluginScheduler.waitForIdle();
|
|
1121
|
-
await this.historyWriter.flush();
|
|
1122
|
-
await Promise.all(this.stateObservers.map((observer) => observer.flush?.()));
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
close(): Promise<void> {
|
|
1126
|
-
if (!this.closePromise) this.closePromise = this.closeInternal();
|
|
1127
|
-
return this.closePromise;
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
private async closeInternal(): Promise<void> {
|
|
1131
|
-
if (this.closed) return;
|
|
1132
|
-
this.closing = true;
|
|
1133
|
-
const closingScope = this.scope();
|
|
1134
|
-
const failures: unknown[] = [];
|
|
1135
|
-
this.observability?.log('info', 'runtime.shutdown.started', {
|
|
1136
|
-
latest_accepted_epoch_seq: this.latestAcceptedEpochSeq,
|
|
1137
|
-
ready_epoch_seq: this.readyEpochSeq,
|
|
1138
|
-
ready_event_watermark: this.readyEventWatermark,
|
|
1139
|
-
}, { component: 'runtime.shutdown', scope: closingScope });
|
|
1140
|
-
// Fence new side effects first. Already-admitted Actions may still return
|
|
1141
|
-
// Source input, so Sources remain active until those Actions settle.
|
|
1142
|
-
this.actions.beginStopping('runtime_closed');
|
|
1143
|
-
const sources = [...this.sourcePlugins.values()].reverse();
|
|
1144
|
-
try {
|
|
1145
|
-
try {
|
|
1146
|
-
await this.actions.waitForIdle();
|
|
1147
|
-
} catch (error) {
|
|
1148
|
-
failures.push(error);
|
|
1149
|
-
}
|
|
1150
|
-
const sourceStops = await Promise.allSettled(
|
|
1151
|
-
sources.map(({ handle }) => Promise.resolve().then(() => handle.stop('shutdown'))),
|
|
1152
|
-
);
|
|
1153
|
-
for (const settlement of sourceStops) {
|
|
1154
|
-
if (settlement.status === 'rejected') failures.push(settlement.reason);
|
|
1155
|
-
}
|
|
1156
|
-
this.sourcePlugins.clear();
|
|
1157
|
-
this.sourceInputOpen = false;
|
|
1158
|
-
const terminalEpochSeq = this.latestAcceptedEpochSeq;
|
|
1159
|
-
this.observability?.log('info', 'runtime.shutdown.drain_started', {
|
|
1160
|
-
terminal_epoch_seq: terminalEpochSeq,
|
|
1161
|
-
ready_epoch_seq: this.readyEpochSeq,
|
|
1162
|
-
ready_event_watermark: this.readyEventWatermark,
|
|
1163
|
-
}, { component: 'runtime.shutdown', scope: closingScope });
|
|
1164
|
-
try {
|
|
1165
|
-
await this.pluginScheduler.close();
|
|
1166
|
-
} catch (error) {
|
|
1167
|
-
failures.push(error);
|
|
1168
|
-
}
|
|
1169
|
-
try {
|
|
1170
|
-
await this.historyWriter.flush();
|
|
1171
|
-
await Promise.all(this.stateObservers.map((observer) => observer.flush?.()));
|
|
1172
|
-
await Promise.all(this.stateObservers.map((observer) => observer.close?.()));
|
|
1173
|
-
} catch (error) {
|
|
1174
|
-
failures.push(error);
|
|
1175
|
-
}
|
|
1176
|
-
// A Runtime session is the lifetime of one local Owner, not the lifetime
|
|
1177
|
-
// of the backend participation. A later Owner may recover the same room,
|
|
1178
|
-
// queue, or game from authoritative backend status, but it must not leave
|
|
1179
|
-
// this process's durable session/segment marked current after shutdown.
|
|
1180
|
-
try {
|
|
1181
|
-
this.participation.closeSession('owner_stopped');
|
|
1182
|
-
} catch (error) {
|
|
1183
|
-
failures.push(error);
|
|
1184
|
-
}
|
|
1185
|
-
if (failures.length > 0) {
|
|
1186
|
-
throw new AggregateError(failures, `${failures.length} Runtime shutdown operation(s) failed.`);
|
|
1187
|
-
}
|
|
1188
|
-
this.observability?.log('info', 'runtime.shutdown.drain_completed', {
|
|
1189
|
-
terminal_epoch_seq: terminalEpochSeq,
|
|
1190
|
-
ready_epoch_seq: this.readyEpochSeq,
|
|
1191
|
-
ready_event_watermark: this.readyEventWatermark,
|
|
1192
|
-
event_watermark: this.repository.highWaterCommitSeq(
|
|
1193
|
-
closingScope.sessionId,
|
|
1194
|
-
closingScope.segmentId,
|
|
1195
|
-
),
|
|
1196
|
-
}, { component: 'runtime.shutdown', scope: closingScope });
|
|
1197
|
-
} catch (error) {
|
|
1198
|
-
this.observability?.error('runtime.shutdown.drain_incomplete', error, {
|
|
1199
|
-
terminal_epoch_seq: this.latestAcceptedEpochSeq,
|
|
1200
|
-
ready_epoch_seq: this.readyEpochSeq,
|
|
1201
|
-
}, { component: 'runtime.shutdown', scope: closingScope });
|
|
1202
|
-
throw error;
|
|
1203
|
-
} finally {
|
|
1204
|
-
this.sourceInputOpen = false;
|
|
1205
|
-
this.closing = false;
|
|
1206
|
-
this.closed = true;
|
|
1207
|
-
await this.stateHistoryRepository.close?.();
|
|
1208
|
-
await this.inputJournal.close?.();
|
|
1209
|
-
await this.repository.close?.();
|
|
1210
|
-
this.observability?.log('info', 'runtime.owner.stopped', {
|
|
1211
|
-
event_repository: this.persistence.events,
|
|
1212
|
-
state_history_repository: this.persistence.stateHistory,
|
|
1213
|
-
}, { component: 'runtime', scope: closingScope });
|
|
1214
|
-
if (this.observability) await this.observability.flushWithin(2_000).catch(() => false);
|
|
1215
|
-
}
|
|
1216
|
-
}
|
|
1217
|
-
|
|
1218
|
-
private sourceEventInput(
|
|
1219
|
-
epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
|
|
1220
|
-
sourceEvent: RuntimeSourceEvent<Record<string, unknown>>,
|
|
1221
|
-
index: number,
|
|
1222
|
-
): PublishEventInput {
|
|
1223
|
-
if (typeof sourceEvent.type !== 'string' || !sourceEvent.type.trim()) {
|
|
1224
|
-
throw new TypeError(`Runtime InputBatch Event ${index} requires type.`);
|
|
1225
|
-
}
|
|
1226
|
-
return {
|
|
1227
|
-
epochSeq: epoch.epochSeq,
|
|
1228
|
-
type: sourceEvent.type,
|
|
1229
|
-
producer: sourceEvent.producer ?? 'backend_push',
|
|
1230
|
-
sessionId: epoch.scope.sessionId,
|
|
1231
|
-
segmentId: epoch.scope.segmentId,
|
|
1232
|
-
payload: sourceEvent.payload,
|
|
1233
|
-
occurredAt: sourceEvent.observedAt ?? epoch.observedAt,
|
|
1234
|
-
receivedAt: sourceEvent.receivedAt ?? epoch.receivedAt,
|
|
1235
|
-
eventId: runtimeSourceEventId(epoch, sourceEvent, index),
|
|
1236
|
-
source: {
|
|
1237
|
-
sourceId: epoch.sourceId,
|
|
1238
|
-
eventId: sourceEvent.sourceEventId,
|
|
1239
|
-
sequence: sourceEvent.sourceSeq,
|
|
1240
|
-
connectionId: epoch.connectionId,
|
|
1241
|
-
replayed: sourceEvent.replayed,
|
|
1242
|
-
checkpoint: sourceEvent.checkpoint,
|
|
1243
|
-
},
|
|
1244
|
-
};
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
private pluginEventInput(
|
|
1248
|
-
pluginId: string,
|
|
1249
|
-
epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
|
|
1250
|
-
proposal: RuntimeEventProposal,
|
|
1251
|
-
proposalIndex: number,
|
|
1252
|
-
): PublishEventInput {
|
|
1253
|
-
const eventId = this.epochEventId(epoch, pluginId, proposal, proposalIndex);
|
|
1254
|
-
return {
|
|
1255
|
-
epochSeq: epoch.epochSeq,
|
|
1256
|
-
type: proposal.type,
|
|
1257
|
-
producer: 'local_synth',
|
|
1258
|
-
producerPluginId: pluginId,
|
|
1259
|
-
producerOutputIndex: proposalIndex,
|
|
1260
|
-
sessionId: epoch.scope.sessionId,
|
|
1261
|
-
segmentId: epoch.scope.segmentId,
|
|
1262
|
-
wakeAgent: proposal.wakeAgent,
|
|
1263
|
-
payload: proposal.payload,
|
|
1264
|
-
occurredAt: proposal.occurredAt,
|
|
1265
|
-
receivedAt: new Date().toISOString(),
|
|
1266
|
-
eventId,
|
|
1267
|
-
source: {
|
|
1268
|
-
sourceId: `runtime-plugin:${pluginId}`,
|
|
1269
|
-
eventId,
|
|
1270
|
-
connectionId: epoch.connectionId,
|
|
1271
|
-
},
|
|
1272
|
-
};
|
|
1273
|
-
}
|
|
1274
|
-
|
|
1275
|
-
private async commitInputEvents(
|
|
1276
|
-
work: RuntimeEpochWork<Record<string, any>, Record<string, unknown>>,
|
|
1277
|
-
): Promise<CanonicalEvent[]> {
|
|
1278
|
-
const { epoch } = work;
|
|
1279
|
-
const committedEvents: CanonicalEvent[] = [];
|
|
1280
|
-
for (const [index, sourceEvent] of epoch.events.entries()) {
|
|
1281
|
-
if (!this.eventCatalog.get(sourceEvent.type)) {
|
|
1282
|
-
this.observability?.log('warn', 'runtime.backend_event.unregistered', {
|
|
1283
|
-
event_type: sourceEvent.type,
|
|
1284
|
-
source_id: epoch.sourceId,
|
|
1285
|
-
epoch_seq: epoch.epochSeq,
|
|
1286
|
-
}, { component: 'runtime.event-catalog', scope: this.publicScope() });
|
|
1287
|
-
}
|
|
1288
|
-
const committed = await this.eventIngress.publish(this.sourceEventInput(epoch, sourceEvent, index));
|
|
1289
|
-
if (committed.inserted) committedEvents.push(committed.event);
|
|
1290
|
-
}
|
|
1291
|
-
return committedEvents;
|
|
1292
|
-
}
|
|
1293
|
-
|
|
1294
|
-
private async recoverOpenEpochs(): Promise<void> {
|
|
1295
|
-
const scope = this.scope();
|
|
1296
|
-
const openEpochs: RuntimeEpoch<Record<string, any>, Record<string, unknown>>[] = [];
|
|
1297
|
-
let afterEpochSeq = 0;
|
|
1298
|
-
while (true) {
|
|
1299
|
-
const page = this.inputJournal.listOpen(scope, afterEpochSeq, 10_000);
|
|
1300
|
-
if (page.length === 0) break;
|
|
1301
|
-
openEpochs.push(...page);
|
|
1302
|
-
afterEpochSeq = page.at(-1)!.epochSeq;
|
|
1303
|
-
if (page.length < 10_000) break;
|
|
1304
|
-
}
|
|
1305
|
-
if (openEpochs.length === 0) return;
|
|
1306
|
-
|
|
1307
|
-
const wanted = new Set(openEpochs.map((epoch) => epoch.epochSeq));
|
|
1308
|
-
const frameByEpoch = new Map<number, ReturnType<
|
|
1309
|
-
StateHistoryRepository<TPosition>['latestStateFrame']
|
|
1310
|
-
>>();
|
|
1311
|
-
let afterFrameSeq = 0;
|
|
1312
|
-
while (wanted.size > 0) {
|
|
1313
|
-
const page = this.stateHistoryRepository.queryStateFrames({
|
|
1314
|
-
scope,
|
|
1315
|
-
afterFrameSeq,
|
|
1316
|
-
order: 'asc',
|
|
1317
|
-
limit: 10_000,
|
|
1318
|
-
});
|
|
1319
|
-
if (page.frames.length === 0) break;
|
|
1320
|
-
for (const frame of page.frames) {
|
|
1321
|
-
if (frame.epochSeq !== undefined && wanted.delete(frame.epochSeq)) {
|
|
1322
|
-
frameByEpoch.set(frame.epochSeq, frame);
|
|
1323
|
-
}
|
|
1324
|
-
}
|
|
1325
|
-
afterFrameSeq = page.frames.at(-1)!.frameSeq;
|
|
1326
|
-
if (!page.page.hasMore) break;
|
|
1327
|
-
}
|
|
1328
|
-
|
|
1329
|
-
this.observability?.log('info', 'runtime.recovery.started', {
|
|
1330
|
-
open_epoch_count: openEpochs.length,
|
|
1331
|
-
first_epoch_seq: openEpochs[0].epochSeq,
|
|
1332
|
-
latest_epoch_seq: openEpochs.at(-1)!.epochSeq,
|
|
1333
|
-
}, { component: 'runtime.recovery', scope });
|
|
1334
|
-
const completions = openEpochs.map((epoch) => {
|
|
1335
|
-
this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, epoch.epochSeq);
|
|
1336
|
-
const existing = frameByEpoch.get(epoch.epochSeq);
|
|
1337
|
-
const frame = existing ?? this.stateHistoryRepository.appendStateFrame({
|
|
1338
|
-
epochSeq: epoch.epochSeq,
|
|
1339
|
-
scope: epoch.scope,
|
|
1340
|
-
sourceId: epoch.sourceId,
|
|
1341
|
-
connectionId: epoch.connectionId,
|
|
1342
|
-
sourceKey: `runtime-epoch:${epoch.epochSeq}`,
|
|
1343
|
-
sourceSeq: epoch.sourceSeq,
|
|
1344
|
-
backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
|
|
1345
|
-
observedAtMs: milliseconds(epoch.observedAt),
|
|
1346
|
-
receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
|
|
1347
|
-
state: epoch.state,
|
|
1348
|
-
}).frame;
|
|
1349
|
-
const previousState = this.stateHistoryRepository.queryStateFrames({
|
|
1350
|
-
scope,
|
|
1351
|
-
beforeFrameSeq: frame.frameSeq,
|
|
1352
|
-
order: 'desc',
|
|
1353
|
-
limit: 1,
|
|
1354
|
-
}).frames[0]?.state ?? null;
|
|
1355
|
-
const currentState = this.recoveredAgentState(epoch);
|
|
1356
|
-
this.acceptedAgentStateByEpoch.set(epoch.epochSeq, structuredClone(currentState));
|
|
1357
|
-
const completion = this.pluginScheduler.enqueue({
|
|
1358
|
-
epoch,
|
|
1359
|
-
frame,
|
|
1360
|
-
currentState,
|
|
1361
|
-
previousState,
|
|
1362
|
-
epochEvents: [],
|
|
1363
|
-
});
|
|
1364
|
-
this.trackEpochCompletion(epoch.epochSeq, completion);
|
|
1365
|
-
return completion;
|
|
1366
|
-
});
|
|
1367
|
-
await Promise.all(completions);
|
|
1368
|
-
this.observability?.log('info', 'runtime.recovery.completed', {
|
|
1369
|
-
recovered_epoch_count: openEpochs.length,
|
|
1370
|
-
ready_epoch_seq: this.readyEpochSeq,
|
|
1371
|
-
}, { component: 'runtime.recovery', scope });
|
|
1372
|
-
}
|
|
1373
|
-
|
|
1374
|
-
private epochEventId(
|
|
1375
|
-
epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
|
|
1376
|
-
pluginId: string,
|
|
1377
|
-
proposal: RuntimeEventProposal,
|
|
1378
|
-
proposalIndex: number,
|
|
1379
|
-
): string {
|
|
1380
|
-
const scope = proposal.dedupeScope === 'session'
|
|
1381
|
-
? ['session', epoch.scope.sessionId]
|
|
1382
|
-
: ['segment', epoch.scope.sessionId, epoch.scope.segmentId];
|
|
1383
|
-
return JSON.stringify([
|
|
1384
|
-
'runtime-epoch-plugin',
|
|
1385
|
-
pluginId,
|
|
1386
|
-
epoch.epochSeq,
|
|
1387
|
-
proposalIndex,
|
|
1388
|
-
...scope,
|
|
1389
|
-
proposal.type,
|
|
1390
|
-
proposal.dedupeKey,
|
|
1391
|
-
]);
|
|
1392
|
-
}
|
|
1393
|
-
|
|
1394
|
-
private recoveredAgentState(
|
|
1395
|
-
epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
|
|
1396
|
-
): StateProviderResult<Record<string, any> | null> {
|
|
1397
|
-
let afterFrameSeq: number | undefined;
|
|
1398
|
-
let projected: Record<string, any> | null = null;
|
|
1399
|
-
while (projected === null) {
|
|
1400
|
-
const page = this.stateHistoryRepository.queryStateFrames({
|
|
1401
|
-
scope: epoch.scope,
|
|
1402
|
-
toEpochSeq: epoch.epochSeq,
|
|
1403
|
-
...(afterFrameSeq === undefined ? {} : { beforeFrameSeq: afterFrameSeq }),
|
|
1404
|
-
order: 'desc',
|
|
1405
|
-
limit: 1_000,
|
|
1406
|
-
});
|
|
1407
|
-
for (const candidate of page.frames) {
|
|
1408
|
-
projected = this.currentStateFromRuntimeState(candidate.state);
|
|
1409
|
-
if (projected !== null) break;
|
|
1410
|
-
}
|
|
1411
|
-
if (projected !== null || !page.page.hasMore || page.frames.length === 0) break;
|
|
1412
|
-
afterFrameSeq = page.frames.at(-1)!.frameSeq;
|
|
1413
|
-
}
|
|
1414
|
-
const receivedAtMs = milliseconds(epoch.receivedAt) ?? Date.now();
|
|
1415
|
-
return {
|
|
1416
|
-
state: projected === null ? null : structuredClone(projected),
|
|
1417
|
-
stateStatus: {
|
|
1418
|
-
status: projected === null ? 'unavailable' : 'fresh',
|
|
1419
|
-
semantics: 'latest_received',
|
|
1420
|
-
source: projected === null ? null : 'durable_snapshot',
|
|
1421
|
-
scope: this.publicScope() as RuntimeScope,
|
|
1422
|
-
connectionId: epoch.connectionId,
|
|
1423
|
-
connectionState: projected === null ? 'owner_unavailable' : 'connected',
|
|
1424
|
-
receivedAtMs,
|
|
1425
|
-
ageMs: Math.max(0, Date.now() - receivedAtMs),
|
|
1426
|
-
backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : null,
|
|
1427
|
-
reason: projected === null ? 'state_not_available_at_epoch' : null,
|
|
1428
|
-
},
|
|
1429
|
-
...(projected === null ? {
|
|
1430
|
-
stateError: {
|
|
1431
|
-
code: 'STATE_NOT_READY',
|
|
1432
|
-
message: 'No game-facing State exists at or before this Runtime epoch.',
|
|
1433
|
-
},
|
|
1434
|
-
} : {}),
|
|
1435
|
-
};
|
|
1436
|
-
}
|
|
1437
|
-
|
|
1438
|
-
private async onEpochClosed(
|
|
1439
|
-
epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
|
|
1440
|
-
frameSeq: number,
|
|
1441
|
-
result: RuntimeEpochExecutionResult,
|
|
1442
|
-
): Promise<void> {
|
|
1443
|
-
const finalizeStartedAtMs = performance.now();
|
|
1444
|
-
const isCurrentScope = sameScope(epoch.scope, this.scope());
|
|
1445
|
-
const acceptedState = this.acceptedAgentStateByEpoch.get(epoch.epochSeq)
|
|
1446
|
-
?? this.recoveredAgentState(epoch);
|
|
1447
|
-
const previousAnchor = [...this.closedReadyAnchors.values()]
|
|
1448
|
-
.reverse()
|
|
1449
|
-
.find((candidate) => (
|
|
1450
|
-
candidate.epochSeq < epoch.epochSeq
|
|
1451
|
-
&& sameScope(candidate.scope, epoch.scope)
|
|
1452
|
-
));
|
|
1453
|
-
const pluginStates = structuredClone(previousAnchor?.pluginStates ?? {});
|
|
1454
|
-
const domainTick = epoch.domainTick === undefined
|
|
1455
|
-
? undefined
|
|
1456
|
-
: Number(epoch.domainTick);
|
|
1457
|
-
const normalizedDomainTick = domainTick !== undefined && Number.isFinite(domainTick)
|
|
1458
|
-
? domainTick
|
|
1459
|
-
: undefined;
|
|
1460
|
-
for (const row of this.inputJournal.states(epoch.epochSeq)) {
|
|
1461
|
-
pluginStates[row.topic] = {
|
|
1462
|
-
pluginId: row.pluginId,
|
|
1463
|
-
topic: row.topic,
|
|
1464
|
-
value: structuredClone(row.value),
|
|
1465
|
-
updatedEpochSeq: epoch.epochSeq,
|
|
1466
|
-
...(normalizedDomainTick === undefined ? {} : { updatedDomainTick: normalizedDomainTick }),
|
|
1467
|
-
};
|
|
1468
|
-
}
|
|
1469
|
-
const pluginOutcomes = Object.fromEntries(result.outcomes.map((outcome) => [
|
|
1470
|
-
outcome.pluginId,
|
|
1471
|
-
{
|
|
1472
|
-
pluginId: outcome.pluginId,
|
|
1473
|
-
epochSeq: epoch.epochSeq,
|
|
1474
|
-
...(normalizedDomainTick === undefined ? {} : { domainTick: normalizedDomainTick }),
|
|
1475
|
-
outcome: outcome.outcome,
|
|
1476
|
-
...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
|
|
1477
|
-
} satisfies RuntimeReadyPluginOutcome,
|
|
1478
|
-
]));
|
|
1479
|
-
const anchor: RuntimeReadyAnchor<Record<string, any> | null> = {
|
|
1480
|
-
scope: structuredClone(epoch.scope),
|
|
1481
|
-
state: structuredClone(acceptedState),
|
|
1482
|
-
pluginStates,
|
|
1483
|
-
pluginOutcomes,
|
|
1484
|
-
frameSeq,
|
|
1485
|
-
eventWatermark: result.eventWatermark,
|
|
1486
|
-
epochSeq: epoch.epochSeq,
|
|
1487
|
-
};
|
|
1488
|
-
this.closedReadyAnchors.set(epoch.epochSeq, anchor);
|
|
1489
|
-
while (this.closedReadyAnchors.size > CLOSED_READY_ANCHOR_LIMIT) {
|
|
1490
|
-
const oldest = this.closedReadyAnchors.keys().next().value as number | undefined;
|
|
1491
|
-
if (oldest === undefined) break;
|
|
1492
|
-
this.closedReadyAnchors.delete(oldest);
|
|
1493
|
-
}
|
|
1494
|
-
this.epochCompletions.delete(epoch.epochSeq);
|
|
1495
|
-
if (isCurrentScope) {
|
|
1496
|
-
this.readyScope = structuredClone(epoch.scope);
|
|
1497
|
-
this.readyEpochSeq = epoch.epochSeq;
|
|
1498
|
-
this.readyFrameSeq = frameSeq;
|
|
1499
|
-
this.readyState = structuredClone(acceptedState);
|
|
1500
|
-
this.readyPluginStates = structuredClone(pluginStates);
|
|
1501
|
-
this.readyPluginOutcomes = structuredClone(pluginOutcomes);
|
|
1502
|
-
this.readyEventWatermark = result.eventWatermark;
|
|
1503
|
-
}
|
|
1504
|
-
for (const acceptedEpochSeq of this.acceptedAgentStateByEpoch.keys()) {
|
|
1505
|
-
if (acceptedEpochSeq <= epoch.epochSeq) this.acceptedAgentStateByEpoch.delete(acceptedEpochSeq);
|
|
1506
|
-
}
|
|
1507
|
-
const intakeTiming = this.epochIntakeTimings.get(epoch.epochSeq);
|
|
1508
|
-
this.epochIntakeTimings.delete(epoch.epochSeq);
|
|
1509
|
-
const finalizeMs = Math.max(0, performance.now() - finalizeStartedAtMs);
|
|
1510
|
-
const totalMs = intakeTiming
|
|
1511
|
-
? Math.max(0, performance.now() - intakeTiming.startedAtMs)
|
|
1512
|
-
: result.durationMs + finalizeMs;
|
|
1513
|
-
const longestPlugin = [...result.outcomes].sort((left, right) => right.durationMs - left.durationMs)[0];
|
|
1514
|
-
const persistenceHealth = (
|
|
1515
|
-
this.repository as { persistenceHealth?: () => Record<string, unknown> }
|
|
1516
|
-
).persistenceHealth?.();
|
|
1517
|
-
this.observability?.log('debug', 'runtime.view.ready', {
|
|
1518
|
-
epoch_seq: epoch.epochSeq,
|
|
1519
|
-
latest_epoch_seq: this.latestAcceptedEpochSeq,
|
|
1520
|
-
lag: Math.max(0, this.latestAcceptedEpochSeq - epoch.epochSeq),
|
|
1521
|
-
frame_seq: frameSeq,
|
|
1522
|
-
event_watermark: result.eventWatermark,
|
|
1523
|
-
current_scope: isCurrentScope,
|
|
1524
|
-
total_duration_ms: Math.round(totalMs * 1_000) / 1_000,
|
|
1525
|
-
received_to_ready_ms: Math.max(0, Date.now() - (milliseconds(epoch.receivedAt) ?? Date.now())),
|
|
1526
|
-
intake_duration_ms: Math.round((intakeTiming?.intakeTotalMs ?? 0) * 1_000) / 1_000,
|
|
1527
|
-
scheduler_duration_ms: Math.round(result.durationMs * 1_000) / 1_000,
|
|
1528
|
-
ready_view_finalize_ms: Math.round(finalizeMs * 1_000) / 1_000,
|
|
1529
|
-
longest_plugin_id: longestPlugin?.pluginId,
|
|
1530
|
-
longest_plugin_duration_ms: longestPlugin
|
|
1531
|
-
? Math.round(longestPlugin.durationMs * 1_000) / 1_000
|
|
1532
|
-
: 0,
|
|
1533
|
-
persistence_pending_operations: persistenceHealth?.pendingOperations,
|
|
1534
|
-
persistence_degraded: persistenceHealth?.degraded,
|
|
1535
|
-
}, { component: 'runtime.view', scope: this.publicScope() });
|
|
1536
|
-
}
|
|
1537
|
-
|
|
1538
|
-
private resetReadyView(scope: RuntimeScope): void {
|
|
1539
|
-
this.readyScope = structuredClone(scope);
|
|
1540
|
-
this.readyState = this.readAgentState();
|
|
1541
|
-
this.readyFrameSeq = 0;
|
|
1542
|
-
this.readyEventWatermark = 0;
|
|
1543
|
-
this.readyEpochSeq = 0;
|
|
1544
|
-
this.readyPluginStates = {};
|
|
1545
|
-
this.readyPluginOutcomes = {};
|
|
1546
|
-
}
|
|
1547
|
-
|
|
1548
|
-
private trackEpochCompletion(
|
|
1549
|
-
epochSeq: number,
|
|
1550
|
-
completion: Promise<RuntimeEpochExecutionResult>,
|
|
1551
|
-
): void {
|
|
1552
|
-
this.epochCompletions.set(epochSeq, completion);
|
|
1553
|
-
void completion.catch(() => {
|
|
1554
|
-
if (!this.closedReadyAnchors.has(epochSeq)) this.epochCompletions.delete(epochSeq);
|
|
1555
|
-
});
|
|
1556
|
-
}
|
|
1557
|
-
|
|
1558
|
-
private readyViewFromAnchor(
|
|
1559
|
-
anchor: RuntimeReadyAnchor<Record<string, any> | null>,
|
|
1560
|
-
afterCommitSeq: number,
|
|
1561
|
-
limit: number,
|
|
1562
|
-
): RuntimeReadyView {
|
|
1563
|
-
const boundedLimit = Math.max(1, Math.min(500, Math.trunc(limit) || 100));
|
|
1564
|
-
const pending = this.repository.listCommittedEvents({
|
|
1565
|
-
sessionId: anchor.scope.sessionId,
|
|
1566
|
-
segmentId: anchor.scope.segmentId,
|
|
1567
|
-
afterCommitSeq,
|
|
1568
|
-
maxCommitSeq: anchor.eventWatermark,
|
|
1569
|
-
maxEpochSeq: anchor.epochSeq,
|
|
1570
|
-
order: 'asc',
|
|
1571
|
-
limit: boundedLimit + 1,
|
|
1572
|
-
});
|
|
1573
|
-
const events = pending.slice(0, boundedLimit);
|
|
1574
|
-
return {
|
|
1575
|
-
scope: this.publicScopeFor(anchor.scope),
|
|
1576
|
-
state: structuredClone(anchor.state),
|
|
1577
|
-
pluginStates: structuredClone(anchor.pluginStates),
|
|
1578
|
-
pluginOutcomes: structuredClone(anchor.pluginOutcomes),
|
|
1579
|
-
events,
|
|
1580
|
-
throughCommitSeq: events.at(-1)?.commitSeq ?? afterCommitSeq,
|
|
1581
|
-
frameSeq: anchor.frameSeq,
|
|
1582
|
-
eventWatermark: anchor.eventWatermark,
|
|
1583
|
-
epochSeq: anchor.epochSeq,
|
|
1584
|
-
hasMore: pending.length > events.length,
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
|
|
1588
|
-
private pluginCapabilityAccess(
|
|
1589
|
-
plugin: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>,
|
|
1590
|
-
scope: RuntimeScope,
|
|
1591
|
-
signal: AbortSignal,
|
|
1592
|
-
epochSeq: number,
|
|
1593
|
-
): RuntimePluginCapabilityAccess {
|
|
1594
|
-
const provided = new Set(plugin.capabilities?.provides ?? []);
|
|
1595
|
-
const used = new Set(plugin.capabilities?.uses ?? []);
|
|
1596
|
-
const requireDeclared = (kind: 'provide' | 'use', capability: string): void => {
|
|
1597
|
-
const declarations = kind === 'provide' ? provided : used;
|
|
1598
|
-
if (!declarations.has(capability)) {
|
|
1599
|
-
throw new Error(
|
|
1600
|
-
`Runtime Epoch Plugin ${plugin.id} did not declare capability ${kind} ${capability}.`,
|
|
1601
|
-
);
|
|
1602
|
-
}
|
|
1603
|
-
};
|
|
1604
|
-
const requireCurrentScope = (): void => {
|
|
1605
|
-
if (!sameScope(scope, this.scope())) {
|
|
1606
|
-
throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
|
|
1607
|
-
}
|
|
1608
|
-
};
|
|
1609
|
-
return Object.freeze({
|
|
1610
|
-
provideObservation: <Q, R>(provider: ObservationProvider<Q, R>): (() => void) => {
|
|
1611
|
-
requireCurrentScope();
|
|
1612
|
-
requireDeclared('provide', provider.capability);
|
|
1613
|
-
const scopedProvider: ObservationProvider<Q, R> = {
|
|
1614
|
-
capability: provider.capability,
|
|
1615
|
-
query: (request, requestedScope, queryContext) => {
|
|
1616
|
-
if (!sameScope(scope, requestedScope) || !sameScope(scope, this.scope())) {
|
|
1617
|
-
throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
|
|
1618
|
-
}
|
|
1619
|
-
return provider.query(request, requestedScope, queryContext);
|
|
1620
|
-
},
|
|
1621
|
-
};
|
|
1622
|
-
return this.observations.register(scopedProvider);
|
|
1623
|
-
},
|
|
1624
|
-
provideAction: <A, R>(service: RegisteredActionService<A, R>): (() => void) => {
|
|
1625
|
-
requireCurrentScope();
|
|
1626
|
-
requireDeclared('provide', service.capability);
|
|
1627
|
-
const scopedService: RegisteredActionService<A, R> = {
|
|
1628
|
-
capability: service.capability,
|
|
1629
|
-
...(service.describeControl
|
|
1630
|
-
? {
|
|
1631
|
-
describeControl: (action, requestedScope, caller) => service.describeControl!(
|
|
1632
|
-
action,
|
|
1633
|
-
requestedScope,
|
|
1634
|
-
caller,
|
|
1635
|
-
),
|
|
1636
|
-
}
|
|
1637
|
-
: {}),
|
|
1638
|
-
perform: (action, requestedScope, caller, actionContext) => {
|
|
1639
|
-
if (!sameScope(scope, requestedScope) || !sameScope(scope, this.scope())) {
|
|
1640
|
-
throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
|
|
1641
|
-
}
|
|
1642
|
-
return service.perform(action, requestedScope, caller, actionContext);
|
|
1643
|
-
},
|
|
1644
|
-
};
|
|
1645
|
-
return this.actions.register(scopedService);
|
|
1646
|
-
},
|
|
1647
|
-
queryObservation: <Q, R>(capability: string, request: Q): Promise<ObservationResult<R>> => {
|
|
1648
|
-
requireCurrentScope();
|
|
1649
|
-
requireDeclared('use', capability);
|
|
1650
|
-
const stateFrame = this.stateHistoryRepository.queryStateFrames({
|
|
1651
|
-
scope,
|
|
1652
|
-
fromEpochSeq: epochSeq,
|
|
1653
|
-
toEpochSeq: epochSeq,
|
|
1654
|
-
order: 'desc',
|
|
1655
|
-
limit: 1,
|
|
1656
|
-
}).frames[0];
|
|
1657
|
-
return this.observations.query<Q, R>(capability, request, scope, {
|
|
1658
|
-
epochSeq,
|
|
1659
|
-
...(stateFrame === undefined ? {} : { stateFrame: structuredClone(stateFrame) }),
|
|
1660
|
-
});
|
|
1661
|
-
},
|
|
1662
|
-
performAction: <A, R>(
|
|
1663
|
-
capability: string,
|
|
1664
|
-
action: A,
|
|
1665
|
-
caller: ActionCaller = { kind: 'system', id: `runtime-plugin:${plugin.id}` },
|
|
1666
|
-
): Promise<ActionResult<R>> => {
|
|
1667
|
-
requireCurrentScope();
|
|
1668
|
-
requireDeclared('use', capability);
|
|
1669
|
-
return this.actions.perform<A, R>(
|
|
1670
|
-
capability,
|
|
1671
|
-
action,
|
|
1672
|
-
scope,
|
|
1673
|
-
caller,
|
|
1674
|
-
{
|
|
1675
|
-
isAuthorized: () => !signal.aborted && sameScope(scope, this.scope()),
|
|
1676
|
-
latestAcceptedState: () => this.latestAcceptedActionState(scope),
|
|
1677
|
-
},
|
|
1678
|
-
);
|
|
1679
|
-
},
|
|
1680
|
-
});
|
|
1681
|
-
}
|
|
1682
|
-
|
|
1683
|
-
private latestAcceptedActionState(scope: RuntimeScope) {
|
|
1684
|
-
if (!sameScope(scope, this.scope())) return null;
|
|
1685
|
-
const frame = this.stateHistoryRepository.latestStateFrame(scope);
|
|
1686
|
-
if (!frame || frame.epochSeq === undefined) return null;
|
|
1687
|
-
return {
|
|
1688
|
-
epochSeq: frame.epochSeq,
|
|
1689
|
-
state: structuredClone(frame.state),
|
|
1690
|
-
};
|
|
1691
|
-
}
|
|
1692
|
-
|
|
1693
|
-
private persistTransition(transition: ParticipationTransition): void {
|
|
1694
|
-
if (transition.type === 'session_opened') {
|
|
1695
|
-
this.actions.activateScope(runtimeScope(transition.snapshot));
|
|
1696
|
-
this.repository.saveSession(eventSession(transition.snapshot, true));
|
|
1697
|
-
this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
|
|
1698
|
-
this.openStateScope(transition.snapshot);
|
|
1699
|
-
return;
|
|
1700
|
-
}
|
|
1701
|
-
if (transition.type === 'session_updated') {
|
|
1702
|
-
this.repository.saveSession(eventSession(transition.snapshot, true));
|
|
1703
|
-
return;
|
|
1704
|
-
}
|
|
1705
|
-
if (transition.type === 'segment_updated') {
|
|
1706
|
-
this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
|
|
1707
|
-
return;
|
|
1708
|
-
}
|
|
1709
|
-
if (transition.type === 'segment_changed') {
|
|
1710
|
-
this.actions.activateScope(runtimeScope(transition.snapshot));
|
|
1711
|
-
// Save the new current segment first: repository implementations use the
|
|
1712
|
-
// old current pointer to defer unread details into backlog atomically.
|
|
1713
|
-
this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
|
|
1714
|
-
if (transition.previous) {
|
|
1715
|
-
this.repository.saveSegment(eventSegment(transition.previous, false));
|
|
1716
|
-
const previousScope: RuntimeScope = {
|
|
1717
|
-
adapterId: transition.snapshot.session.adapterId,
|
|
1718
|
-
accountId: transition.snapshot.session.accountId,
|
|
1719
|
-
sessionId: transition.snapshot.session.id,
|
|
1720
|
-
segmentId: transition.previous.id,
|
|
1721
|
-
segmentSeq: transition.previous.ordinal,
|
|
1722
|
-
};
|
|
1723
|
-
this.stateHistoryRepository.sealScope(previousScope, Date.parse(transition.snapshot.segment.startedAt));
|
|
1724
|
-
}
|
|
1725
|
-
this.openStateScope(transition.snapshot);
|
|
1726
|
-
return;
|
|
1727
|
-
}
|
|
1728
|
-
if (transition.type === 'session_closed') {
|
|
1729
|
-
this.repository.saveSegment(eventSegment(transition.snapshot.segment, false));
|
|
1730
|
-
this.repository.saveSession(eventSession(transition.snapshot, false));
|
|
1731
|
-
this.stateHistoryRepository.sealScope(runtimeScope(transition.snapshot));
|
|
1732
|
-
}
|
|
1733
|
-
}
|
|
1734
|
-
|
|
1735
|
-
private openStateScope(snapshot: ParticipationSnapshot, historyComplete = true): void {
|
|
1736
|
-
const scope = runtimeScope(snapshot);
|
|
1737
|
-
const atMs = Date.parse(snapshot.segment.startedAt);
|
|
1738
|
-
this.stateIngress.openScope(scope, Number.isFinite(atMs) ? atMs : Date.now());
|
|
1739
|
-
this.historyWriter.openScope(
|
|
1740
|
-
scope,
|
|
1741
|
-
Number.isFinite(atMs) ? atMs : Date.now(),
|
|
1742
|
-
historyComplete,
|
|
1743
|
-
);
|
|
1744
|
-
}
|
|
1745
|
-
|
|
1746
|
-
private connectionKey(sourceId: string, connectionId: string): string {
|
|
1747
|
-
return `${sourceId}\u001f${connectionId}`;
|
|
1748
|
-
}
|
|
1749
|
-
|
|
1750
|
-
private enqueueOwnerRestartGap(
|
|
1751
|
-
kind: 'stream_gap_started' | 'stream_gap_ended',
|
|
1752
|
-
connectionId?: string,
|
|
1753
|
-
atMs = Date.now(),
|
|
1754
|
-
): void {
|
|
1755
|
-
const record: TrajectoryRecord<TPosition> = {
|
|
1756
|
-
recordId: randomUUID(),
|
|
1757
|
-
scope: this.scope(),
|
|
1758
|
-
connectionId,
|
|
1759
|
-
subjectId: '__owner__',
|
|
1760
|
-
subjectKind: 'system',
|
|
1761
|
-
kind,
|
|
1762
|
-
sourceType: 'local_lifecycle',
|
|
1763
|
-
sourceKey: `owner-restart:${kind}:${atMs}`,
|
|
1764
|
-
receivedAtMs: atMs,
|
|
1765
|
-
attributes: { reason: 'owner_restart' },
|
|
1766
|
-
};
|
|
1767
|
-
this.historyWriter.enqueue([record]);
|
|
1768
|
-
}
|
|
1769
|
-
|
|
1770
|
-
private sealDurableScope(scope: CurrentEventScope): void {
|
|
1771
|
-
const now = new Date().toISOString();
|
|
1772
|
-
this.repository.saveSegment({
|
|
1773
|
-
...scope.segment,
|
|
1774
|
-
status: 'closed',
|
|
1775
|
-
isCurrent: false,
|
|
1776
|
-
closedAt: scope.segment.closedAt ?? now,
|
|
1777
|
-
});
|
|
1778
|
-
this.repository.saveSession({
|
|
1779
|
-
...scope.session,
|
|
1780
|
-
status: 'sealed',
|
|
1781
|
-
isCurrent: false,
|
|
1782
|
-
sealedAt: scope.session.sealedAt ?? now,
|
|
1783
|
-
});
|
|
1784
|
-
}
|
|
1785
|
-
|
|
1786
|
-
private assertOpen(): void {
|
|
1787
|
-
if (this.closed) throw new Error('Runtime is closed.');
|
|
1788
|
-
if (this.closing) throw new Error('Runtime is closing.');
|
|
1789
|
-
if (this.fatalError) throw this.fatalError;
|
|
1790
|
-
}
|
|
1791
|
-
|
|
1792
|
-
private assertSourceInputOpen(): void {
|
|
1793
|
-
if (this.closed || !this.sourceInputOpen) throw new Error('Runtime input is closed.');
|
|
1794
|
-
if (this.fatalError) throw this.fatalError;
|
|
1795
|
-
}
|
|
1796
|
-
|
|
1797
|
-
private assertExpectedScope(expected: ExpectedRuntimeScope): RuntimeScope {
|
|
1798
|
-
this.assertOpen();
|
|
1799
|
-
const scope = this.scope();
|
|
1800
|
-
if (scope.sessionId !== expected.sessionId || scope.segmentId !== expected.segmentId) {
|
|
1801
|
-
throw new Error('runtime_scope_changed');
|
|
1802
|
-
}
|
|
1803
|
-
return scope;
|
|
1804
|
-
}
|
|
1805
|
-
|
|
1806
|
-
private onHistoryWriterHealthChanged(health: HistoryWriterHealth): void {
|
|
1807
|
-
const degradedScopes = this.historyWriter.degradedScopeHealth();
|
|
1808
|
-
// Queue depth changes on normal frames, so it is intentionally excluded
|
|
1809
|
-
// from transition identity. A new affected scope or reason is a real
|
|
1810
|
-
// health transition and is emitted once.
|
|
1811
|
-
const signature = JSON.stringify({
|
|
1812
|
-
status: health.status,
|
|
1813
|
-
scopes: degradedScopes.map((entry) => ({
|
|
1814
|
-
scope: {
|
|
1815
|
-
adapterId: entry.scope.adapterId,
|
|
1816
|
-
sessionId: entry.scope.sessionId,
|
|
1817
|
-
segmentId: entry.scope.segmentId,
|
|
1818
|
-
segmentSeq: entry.scope.segmentSeq,
|
|
1819
|
-
},
|
|
1820
|
-
reason: entry.reason,
|
|
1821
|
-
})),
|
|
1822
|
-
});
|
|
1823
|
-
if (signature === this.lastHistoryWriterHealthSignature) return;
|
|
1824
|
-
const previous = this.lastHistoryWriterHealthSignature;
|
|
1825
|
-
this.lastHistoryWriterHealthSignature = signature;
|
|
1826
|
-
if (previous === null && health.status === 'healthy') return;
|
|
1827
|
-
const activeScope = degradedScopes[0]?.scope ?? this.scope();
|
|
1828
|
-
const { accountId: _accountId, ...scope } = activeScope;
|
|
1829
|
-
this.observability?.log(
|
|
1830
|
-
health.status === 'degraded' ? 'warn' : 'info',
|
|
1831
|
-
'runtime.state_history.writer_health_changed',
|
|
1832
|
-
{
|
|
1833
|
-
status: health.status,
|
|
1834
|
-
reason: health.reason,
|
|
1835
|
-
queue_depth: health.queueDepth,
|
|
1836
|
-
dropped_record_count: health.droppedRecordCount,
|
|
1837
|
-
degraded_since_ms: health.degradedSinceMs,
|
|
1838
|
-
degraded_scope_count: degradedScopes.length,
|
|
1839
|
-
},
|
|
1840
|
-
{ component: 'runtime.state-history', scope },
|
|
1841
|
-
);
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1
|
+
import { Runtime as CoreRuntime, type RuntimeOptions } from '@myclaw163/game-agent-runtime/framework/runtime.js';
|
|
2
|
+
import { CLAWCLAW_STORE_COMPATIBILITY } from '../clawclaw/persistence-compatibility.js';
|
|
3
|
+
import { actionFailureDiagnosticSeverity } from './action-diagnostics.js';
|
|
4
|
+
export * from '@myclaw163/game-agent-runtime/framework/runtime.js';
|
|
5
|
+
export class Runtime<P=unknown> extends CoreRuntime<P> { constructor(options:RuntimeOptions<P>) { super({eventStoreCompatibility:CLAWCLAW_STORE_COMPATIBILITY,actionFailureSeverity:actionFailureDiagnosticSeverity,...options}); } }
|