@myclaw163/clawclaw-cli 0.9.1 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/QUICKSTART_OTHER.md +5 -5
- package/README.md +7 -8
- package/bin/clawclaw-channel.mjs +2 -2
- package/bin/clawclaw-cli.mjs +2 -2
- package/docs/configuration.md +25 -99
- package/docs/custom-modules/README.md +27 -40
- package/docs/custom-modules/api-reference.md +132 -273
- package/docs/custom-modules/behavior.md +185 -75
- package/docs/custom-modules/examples/auto-escape.ts +41 -0
- package/docs/custom-modules/examples/go-to-point.ts +11 -11
- package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
- package/docs/custom-modules/examples/task-reminder.ts +4 -5
- package/docs/custom-modules/perception.md +46 -806
- package/docs/custom-modules/skill.md +1 -1
- package/docs/desktop-event-push.md +3 -3
- package/docs/runtime/README.md +18 -19
- package/docs/runtime/agent-notifications.md +31 -12
- package/docs/runtime/behavior-runtime.md +54 -48
- package/docs/runtime/components-and-boundaries.md +87 -137
- package/docs/runtime/events-and-state.md +52 -17
- package/docs/runtime/framework-package.md +73 -0
- package/docs/runtime/official-perception-modules.md +5 -5
- package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
- package/docs/runtime/short-commands-and-capabilities.md +8 -9
- package/docs/user-guide/README.md +12 -9
- package/docs/user-guide/api-reference.md +132 -180
- package/docs/user-guide/behavior.md +175 -65
- package/docs/user-guide/installation.md +7 -7
- package/docs/user-guide/perception.md +46 -789
- package/docs/user-guide/skill.md +1 -1
- package/package.json +24 -9
- package/scripts/check-framework-boundaries.mjs +27 -0
- package/scripts/check-skill-command-surface.mjs +9 -14
- package/scripts/install-local-runtime.mjs +35 -0
- package/scripts/qa-install.mjs +105 -0
- package/skills/clawclaw/SKILL.md +50 -48
- package/skills/clawclaw/references/BEHAVIORS.md +45 -65
- package/skills/clawclaw/references/CHANNELS.md +2 -2
- package/skills/clawclaw/references/COMMANDS.md +65 -87
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +185 -75
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +145 -198
- package/skills/clawclaw/references/CUSTOM-MODULES.md +28 -29
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +46 -811
- package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
- package/skills/clawclaw/references/HUB.md +1 -1
- package/skills/clawclaw/references/STREAM.md +8 -8
- package/skills/clawclaw/references/TACTICS.md +1 -1
- package/src/channel/claude-channel-ipc-server.ts +1 -0
- package/src/cli.ts +4 -2
- package/src/commands/behavior.ts +49 -104
- package/src/commands/capability.ts +3 -3
- package/src/commands/load.ts +18 -25
- package/src/commands/module-runtime-control.ts +113 -0
- package/src/commands/perception.ts +23 -4
- package/src/commands/strategy.ts +2 -0
- package/src/commands/trigger.ts +1 -1
- package/src/lib/capability-load-diagnostics.ts +3 -3
- package/src/lib/perception-config.ts +18 -6
- package/src/lib/runtime-cadence-config.ts +16 -0
- package/src/lib/workspace-runtime-lock.ts +3 -46
- package/src/pipeline/canonical-event-presentation.ts +23 -124
- package/src/pipeline/event-format.ts +12 -21
- package/src/pipeline/event-hints.ts +6 -6
- package/src/pipeline/game-sync-event-normalization.ts +57 -63
- package/src/runtime/clawclaw/behavior-decision.ts +7 -3
- package/src/runtime/clawclaw/behavior-input.ts +8 -4
- package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
- package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
- package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
- package/src/runtime/clawclaw/notification-policy.ts +42 -0
- package/src/runtime/clawclaw/notification-turn.ts +19 -0
- package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
- package/src/runtime/clawclaw/owner.ts +67 -8
- package/src/runtime/clawclaw/perception-module-manifest.ts +22 -8
- package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
- package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
- package/src/runtime/clawclaw/plugins/assembly.ts +29 -41
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -482
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -186
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
- package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1707
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -271
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -960
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +9 -107
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +5 -4
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
- package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
- package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
- package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -0
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
- package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +136 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +13 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +13 -24
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +19 -8
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +23 -15
- package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +8 -103
- package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
- package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
- package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
- package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +69 -13
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
- package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
- package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
- package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
- package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
- package/src/runtime/clawclaw/runtime-state.ts +12 -1
- package/src/runtime/clawclaw/runtime.ts +11 -3
- package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -0
- package/src/runtime/clawclaw/strategy-memory.ts +1 -0
- package/src/runtime/clawclaw-event-catalog.ts +17 -17
- package/src/runtime/framework/action-diagnostics.ts +3 -83
- package/src/runtime/framework/capability-registry.ts +2 -395
- package/src/runtime/framework/contracts.ts +2 -144
- package/src/runtime/framework/control/control-scheduler.ts +2 -1268
- package/src/runtime/framework/control/domain-set.ts +2 -81
- package/src/runtime/framework/control/index.ts +1 -3
- package/src/runtime/framework/control/types.ts +2 -191
- package/src/runtime/framework/control-coordinator.ts +2 -11
- package/src/runtime/framework/events/event-catalog.ts +2 -74
- package/src/runtime/framework/events/event-delivery-service.ts +2 -200
- package/src/runtime/framework/events/event-ingress.ts +2 -99
- package/src/runtime/framework/events/event-repository.ts +2 -82
- package/src/runtime/framework/events/index.ts +2 -7
- package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
- package/src/runtime/framework/events/runtime-resume.ts +2 -20
- package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
- package/src/runtime/framework/events/test-helpers.ts +1 -1
- package/src/runtime/framework/events/types.ts +2 -312
- package/src/runtime/framework/index.ts +3 -7
- package/src/runtime/framework/load-node-sqlite.ts +2 -17
- package/src/runtime/framework/mailbox/coalescer.ts +2 -83
- package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
- package/src/runtime/framework/mailbox/identity.ts +2 -38
- package/src/runtime/framework/mailbox/index.ts +1 -7
- package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
- package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
- package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
- package/src/runtime/framework/mailbox/types.ts +2 -145
- package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
- package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
- package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
- package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
- package/src/runtime/framework/participation-manager.ts +2 -253
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
- package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
- package/src/runtime/framework/plugins/contracts.ts +2 -388
- package/src/runtime/framework/plugins/index.ts +1 -4
- package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
- package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2060
- package/src/runtime/framework/runtime.ts +5 -1843
- package/src/runtime/framework/serial-task-queue.ts +2 -14
- package/src/runtime/framework/state/contracts.ts +2 -49
- package/src/runtime/framework/state/current-state-store.ts +2 -184
- package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
- package/src/runtime/framework/state/freshness.ts +2 -72
- package/src/runtime/framework/state/history/contracts.ts +2 -158
- package/src/runtime/framework/state/history/history-writer.ts +2 -194
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
- package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
- package/src/runtime/framework/state/index.ts +1 -13
- package/src/runtime/framework/state/state-ingress.ts +2 -95
- package/src/runtime/framework/state/state-provider.ts +2 -62
- package/src/runtime/framework/state/types.ts +2 -155
- package/src/runtime/host-monitor-rate-gate.ts +1 -123
- package/src/runtime/mailbox-host-relay.ts +1 -326
- package/src/runtime/observability/detail-capture.ts +4 -108
- package/src/runtime/observability/process-timing.ts +2 -59
- package/src/runtime/observability/recorder.ts +2 -238
- package/src/runtime/observability/redaction.ts +2 -181
- package/src/runtime/observability/reporter.ts +2 -154
- package/src/runtime/observability/sinks.ts +2 -135
- package/src/runtime/observability/types.ts +2 -92
- package/src/runtime/owner-control.ts +45 -315
- package/src/runtime/parent-process-watch.ts +1 -51
- package/src/runtime/process-identity.ts +1 -72
- package/src/sdk/behavior-plugin/index.ts +13 -4
- package/src/sdk/index.ts +44 -3
- package/src/sdk/module-input/index.ts +5 -0
- package/src/sdk/perception-plugin/index.ts +9 -5
- package/src/sdk/perception-plugin/module.ts +25 -6
- package/src/sdk/perception-plugin/reaction.ts +1 -1
- package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
- package/src/sdk/perception-plugin/reminder.ts +2 -1
- package/src/{runtime/clawclaw/plugins/source → sdk/perception-plugin}/task-change-tracker.ts +1 -2
- package/src/sdk/strategy-memory.ts +1 -0
- package/src/sdk/strategy-plugin/index.ts +36 -0
- package/src/sdk/trigger-plugin/index.ts +4 -3
- package/docs/custom-modules/examples/nearby-escape.ts +0 -56
- package/docs/custom-modules/examples/nearby-notice.ts +0 -36
- package/docs/custom-modules/trigger.md +0 -295
- package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
- package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -233
- package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +0 -49
- package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
- /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
|
@@ -1,866 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import { mkdirSync } from 'fs';
|
|
4
|
-
import { dirname } from 'path';
|
|
5
|
-
import { loadNodeSqliteModule } from '../load-node-sqlite.js';
|
|
6
|
-
import { cloneCanonical, runtimeScopeKey, sameRuntimeScope, type RuntimeScope } from '../state/types.js';
|
|
7
|
-
import type {
|
|
8
|
-
RuntimeEpoch,
|
|
9
|
-
RuntimePersistenceStore,
|
|
10
|
-
RuntimeEpochPluginProgress,
|
|
11
|
-
RuntimeEpochPluginRecord,
|
|
12
|
-
RuntimeEpochStateRecord,
|
|
13
|
-
RuntimeInputAcceptance,
|
|
14
|
-
RuntimeInputBatch,
|
|
15
|
-
} from './contracts.js';
|
|
16
|
-
|
|
17
|
-
interface StatementLike {
|
|
18
|
-
run(...params: unknown[]): { changes: number | bigint; lastInsertRowid?: number | bigint };
|
|
19
|
-
get(...params: unknown[]): Record<string, unknown> | undefined;
|
|
20
|
-
all(...params: unknown[]): Array<Record<string, unknown>>;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
interface DatabaseLike {
|
|
24
|
-
exec(sql: string): void;
|
|
25
|
-
prepare(sql: string): StatementLike;
|
|
26
|
-
close(): void;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
interface SqliteModuleLike {
|
|
30
|
-
DatabaseSync: new (path: string) => DatabaseLike;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const localRequire = createRequire(import.meta.url);
|
|
34
|
-
|
|
35
|
-
function canonicalPayload(batch: RuntimeInputBatch<any, any>): Record<string, unknown> {
|
|
36
|
-
return {
|
|
37
|
-
scope: batch.scope,
|
|
38
|
-
sourceId: batch.sourceId,
|
|
39
|
-
connectionId: batch.connectionId,
|
|
40
|
-
sourceKey: batch.sourceKey,
|
|
41
|
-
sourceSeq: batch.sourceSeq,
|
|
42
|
-
domainTick: batch.domainTick,
|
|
43
|
-
state: batch.state,
|
|
44
|
-
events: batch.events,
|
|
45
|
-
eventWatermark: batch.eventWatermark,
|
|
46
|
-
completeness: batch.completeness,
|
|
47
|
-
coalescing: batch.coalescing,
|
|
48
|
-
observedAt: batch.observedAt,
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function payloadHash(batch: RuntimeInputBatch<any, any>): string {
|
|
53
|
-
return createHash('sha256').update(JSON.stringify(canonicalPayload(batch))).digest('hex');
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function assertOptionalSequence(value: unknown, field: string): void {
|
|
57
|
-
if (value === undefined) return;
|
|
58
|
-
if (typeof value === 'number' && Number.isFinite(value)) return;
|
|
59
|
-
if (typeof value === 'string' && value.length > 0) return;
|
|
60
|
-
throw new TypeError(`Runtime InputBatch ${field} must be a finite number or non-empty string.`);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function assertOptionalTimestamp(value: unknown, field: string): void {
|
|
64
|
-
if (value === undefined) return;
|
|
65
|
-
if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) {
|
|
66
|
-
throw new TypeError(`Runtime InputBatch ${field} must be an ISO timestamp.`);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function assertRuntimeInputBatch(batch: RuntimeInputBatch<any, any>): void {
|
|
71
|
-
if (!batch || typeof batch !== 'object') throw new TypeError('Runtime InputBatch is required.');
|
|
72
|
-
if (!batch.scope || typeof batch.scope !== 'object') {
|
|
73
|
-
throw new TypeError('Runtime InputBatch scope is required.');
|
|
74
|
-
}
|
|
75
|
-
for (const key of ['adapterId', 'accountId', 'sessionId', 'segmentId'] as const) {
|
|
76
|
-
if (typeof batch.scope[key] !== 'string' || !batch.scope[key].trim()) {
|
|
77
|
-
throw new TypeError(`Runtime InputBatch scope.${key} is required.`);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
if (
|
|
81
|
-
batch.scope.segmentSeq !== undefined
|
|
82
|
-
&& (!Number.isInteger(batch.scope.segmentSeq) || batch.scope.segmentSeq <= 0)
|
|
83
|
-
) {
|
|
84
|
-
throw new TypeError('Runtime InputBatch scope.segmentSeq must be a positive integer.');
|
|
85
|
-
}
|
|
86
|
-
if (typeof batch.sourceId !== 'string' || !batch.sourceId.trim()) {
|
|
87
|
-
throw new TypeError('Runtime InputBatch sourceId is required.');
|
|
88
|
-
}
|
|
89
|
-
if (typeof batch.connectionId !== 'string' || !batch.connectionId.trim()) {
|
|
90
|
-
throw new TypeError('Runtime InputBatch connectionId is required.');
|
|
91
|
-
}
|
|
92
|
-
if (typeof batch.sourceKey !== 'string' || !batch.sourceKey.trim()) {
|
|
93
|
-
throw new TypeError('Runtime InputBatch sourceKey is required.');
|
|
94
|
-
}
|
|
95
|
-
assertOptionalSequence(batch.sourceSeq, 'sourceSeq');
|
|
96
|
-
assertOptionalSequence(batch.domainTick, 'domainTick');
|
|
97
|
-
assertOptionalSequence(batch.eventWatermark, 'eventWatermark');
|
|
98
|
-
if (!batch.state || typeof batch.state !== 'object' || Array.isArray(batch.state)) {
|
|
99
|
-
throw new TypeError('Runtime InputBatch requires one complete State object.');
|
|
100
|
-
}
|
|
101
|
-
if (!Array.isArray(batch.events)) throw new TypeError('Runtime InputBatch events must be an explicit array.');
|
|
102
|
-
for (const [index, event] of batch.events.entries()) {
|
|
103
|
-
if (!event || typeof event !== 'object' || Array.isArray(event)) {
|
|
104
|
-
throw new TypeError(`Runtime InputBatch Event ${index} must be an object.`);
|
|
105
|
-
}
|
|
106
|
-
if (typeof event.type !== 'string' || !event.type.trim()) {
|
|
107
|
-
throw new TypeError(`Runtime InputBatch Event ${index} requires type.`);
|
|
108
|
-
}
|
|
109
|
-
if (!event.payload || typeof event.payload !== 'object' || Array.isArray(event.payload)) {
|
|
110
|
-
throw new TypeError(`Runtime InputBatch Event ${index} requires an object payload.`);
|
|
111
|
-
}
|
|
112
|
-
if (
|
|
113
|
-
event.producer !== undefined
|
|
114
|
-
&& event.producer !== 'backend_push'
|
|
115
|
-
&& event.producer !== 'local_synth'
|
|
116
|
-
) {
|
|
117
|
-
throw new TypeError(`Runtime InputBatch Event ${index} producer is invalid.`);
|
|
118
|
-
}
|
|
119
|
-
if (
|
|
120
|
-
event.sourceEventId !== undefined
|
|
121
|
-
&& (typeof event.sourceEventId !== 'string' || !event.sourceEventId.trim())
|
|
122
|
-
) {
|
|
123
|
-
throw new TypeError(`Runtime InputBatch Event ${index} sourceEventId must be a non-empty string.`);
|
|
124
|
-
}
|
|
125
|
-
assertOptionalSequence(event.sourceSeq, `Event ${index} sourceSeq`);
|
|
126
|
-
assertOptionalTimestamp(event.observedAt, `Event ${index} observedAt`);
|
|
127
|
-
assertOptionalTimestamp(event.receivedAt, `Event ${index} receivedAt`);
|
|
128
|
-
if (event.replayed !== undefined && typeof event.replayed !== 'boolean') {
|
|
129
|
-
throw new TypeError(`Runtime InputBatch Event ${index} replayed must be a boolean.`);
|
|
130
|
-
}
|
|
131
|
-
if (event.checkpoint !== undefined && typeof event.checkpoint !== 'string') {
|
|
132
|
-
throw new TypeError(`Runtime InputBatch Event ${index} checkpoint must be a string.`);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
if (batch.completeness !== 'complete' && batch.completeness !== 'best_effort') {
|
|
136
|
-
throw new TypeError('Runtime InputBatch completeness is invalid.');
|
|
137
|
-
}
|
|
138
|
-
if (
|
|
139
|
-
batch.coalescing !== undefined
|
|
140
|
-
&& batch.coalescing !== 'allowed'
|
|
141
|
-
&& batch.coalescing !== 'forbidden'
|
|
142
|
-
) {
|
|
143
|
-
throw new TypeError('Runtime InputBatch coalescing is invalid.');
|
|
144
|
-
}
|
|
145
|
-
assertOptionalTimestamp(batch.observedAt, 'observedAt');
|
|
146
|
-
if (typeof batch.receivedAt !== 'string' || !Number.isFinite(Date.parse(batch.receivedAt))) {
|
|
147
|
-
throw new TypeError('Runtime InputBatch receivedAt must be an ISO timestamp.');
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function sourceIdentity(batch: RuntimeInputBatch<any, any>): string {
|
|
152
|
-
return [runtimeScopeKey(batch.scope), batch.sourceId, batch.sourceKey].join('\u001f');
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
export class RuntimeInputConflictError extends Error {
|
|
156
|
-
constructor(readonly sourceId: string, readonly sourceKey: string) {
|
|
157
|
-
super(`Runtime input ${sourceId}/${sourceKey} was retried with different content.`);
|
|
158
|
-
this.name = 'RuntimeInputConflictError';
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
export interface RuntimeInputJournalSnapshot<TState = Record<string, unknown>, TEvent = Record<string, unknown>> {
|
|
163
|
-
epochs: Array<{
|
|
164
|
-
epoch: RuntimeEpoch<TState, TEvent>;
|
|
165
|
-
closed: boolean;
|
|
166
|
-
inputEventsCommitted: boolean;
|
|
167
|
-
eventWatermark: number;
|
|
168
|
-
}>;
|
|
169
|
-
pluginProgress: Array<{ scope: RuntimeScope; progress: RuntimeEpochPluginProgress }>;
|
|
170
|
-
pluginRecords: RuntimeEpochPluginRecord[];
|
|
171
|
-
states: RuntimeEpochStateRecord[];
|
|
172
|
-
nextEpochSeq: number;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
export class MemoryRuntimeInputJournal<TState = Record<string, unknown>, TEvent = Record<string, unknown>>
|
|
176
|
-
implements RuntimePersistenceStore<TState, TEvent> {
|
|
177
|
-
private readonly epochs: RuntimeEpoch<TState, TEvent>[] = [];
|
|
178
|
-
private readonly epochsBySeq = new Map<number, RuntimeEpoch<TState, TEvent>>();
|
|
179
|
-
private readonly epochsByScope = new Map<string, RuntimeEpoch<TState, TEvent>[]>();
|
|
180
|
-
private readonly hashes = new Map<string, string>();
|
|
181
|
-
private readonly byIdentity = new Map<string, RuntimeEpoch<TState, TEvent>>();
|
|
182
|
-
private readonly closed = new Set<number>();
|
|
183
|
-
private readonly inputEventCommits = new Set<number>();
|
|
184
|
-
private readonly eventWatermarks = new Map<number, number>();
|
|
185
|
-
private readonly progress = new Map<string, RuntimeEpochPluginProgress>();
|
|
186
|
-
private readonly pluginOutcomeRecords: RuntimeEpochPluginRecord[] = [];
|
|
187
|
-
private readonly pluginOutcomeRecordsByEpoch = new Map<number, RuntimeEpochPluginRecord[]>();
|
|
188
|
-
private readonly stateRecords: RuntimeEpochStateRecord[] = [];
|
|
189
|
-
private readonly stateRecordsByEpoch = new Map<number, RuntimeEpochStateRecord[]>();
|
|
190
|
-
|
|
191
|
-
diagnosticCounts(): Readonly<Record<string, number>> {
|
|
192
|
-
return {
|
|
193
|
-
epochs: this.epochs.length,
|
|
194
|
-
closed_epochs: this.closed.size,
|
|
195
|
-
input_event_commits: this.inputEventCommits.size,
|
|
196
|
-
event_watermarks: this.eventWatermarks.size,
|
|
197
|
-
plugin_progress: this.progress.size,
|
|
198
|
-
plugin_records: this.pluginOutcomeRecords.length,
|
|
199
|
-
plugin_states: this.stateRecords.length,
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
private nextEpochSeq = 1;
|
|
203
|
-
|
|
204
|
-
constructor(snapshot?: RuntimeInputJournalSnapshot<TState, TEvent>) {
|
|
205
|
-
if (!snapshot) return;
|
|
206
|
-
for (const item of snapshot.epochs) {
|
|
207
|
-
const epoch = cloneCanonical(item.epoch);
|
|
208
|
-
const identity = sourceIdentity(epoch);
|
|
209
|
-
this.epochs.push(epoch);
|
|
210
|
-
this.indexEpoch(epoch);
|
|
211
|
-
this.byIdentity.set(identity, epoch);
|
|
212
|
-
this.hashes.set(identity, payloadHash(epoch as RuntimeInputBatch));
|
|
213
|
-
if (item.closed) this.closed.add(epoch.epochSeq);
|
|
214
|
-
if (item.inputEventsCommitted) this.inputEventCommits.add(epoch.epochSeq);
|
|
215
|
-
if (item.eventWatermark > 0) this.eventWatermarks.set(epoch.epochSeq, item.eventWatermark);
|
|
216
|
-
}
|
|
217
|
-
for (const item of snapshot.pluginProgress) {
|
|
218
|
-
this.progress.set(`${runtimeScopeKey(item.scope)}\u001f${item.progress.pluginId}`, cloneCanonical(item.progress));
|
|
219
|
-
}
|
|
220
|
-
for (const record of snapshot.pluginRecords) this.indexPluginRecord(cloneCanonical(record));
|
|
221
|
-
for (const record of snapshot.states) this.indexStateRecord(cloneCanonical(record));
|
|
222
|
-
this.nextEpochSeq = Math.max(snapshot.nextEpochSeq, 1);
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
snapshot(): RuntimeInputJournalSnapshot<TState, TEvent> {
|
|
226
|
-
const scopeByKey = new Map<string, RuntimeScope>();
|
|
227
|
-
for (const epoch of this.epochs) scopeByKey.set(runtimeScopeKey(epoch.scope), epoch.scope);
|
|
228
|
-
const pluginProgress: RuntimeInputJournalSnapshot['pluginProgress'] = [];
|
|
229
|
-
for (const [key, progress] of this.progress) {
|
|
230
|
-
const scopeKey = key.slice(0, key.lastIndexOf('\u001f'));
|
|
231
|
-
const scope = scopeByKey.get(scopeKey);
|
|
232
|
-
if (scope) pluginProgress.push({ scope: cloneCanonical(scope), progress: cloneCanonical(progress) });
|
|
233
|
-
}
|
|
234
|
-
return cloneCanonical({
|
|
235
|
-
epochs: this.epochs.map((epoch) => ({
|
|
236
|
-
epoch,
|
|
237
|
-
closed: this.closed.has(epoch.epochSeq),
|
|
238
|
-
inputEventsCommitted: this.inputEventCommits.has(epoch.epochSeq),
|
|
239
|
-
eventWatermark: this.eventWatermarks.get(epoch.epochSeq) ?? 0,
|
|
240
|
-
})),
|
|
241
|
-
pluginProgress,
|
|
242
|
-
pluginRecords: this.pluginOutcomeRecords,
|
|
243
|
-
states: this.stateRecords,
|
|
244
|
-
nextEpochSeq: this.nextEpochSeq,
|
|
245
|
-
});
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
accept(batch: RuntimeInputBatch<TState, TEvent>): RuntimeInputAcceptance<TState, TEvent> {
|
|
249
|
-
assertRuntimeInputBatch(batch);
|
|
250
|
-
const identity = sourceIdentity(batch);
|
|
251
|
-
const hash = payloadHash(batch as RuntimeInputBatch);
|
|
252
|
-
const existing = this.byIdentity.get(identity);
|
|
253
|
-
if (existing) {
|
|
254
|
-
if (this.hashes.get(identity) !== hash) throw new RuntimeInputConflictError(batch.sourceId, batch.sourceKey);
|
|
255
|
-
return { inserted: false, epoch: cloneCanonical(existing) };
|
|
256
|
-
}
|
|
257
|
-
const epoch: RuntimeEpoch<TState, TEvent> = {
|
|
258
|
-
...cloneCanonical(batch),
|
|
259
|
-
epochSeq: this.nextEpochSeq++,
|
|
260
|
-
};
|
|
261
|
-
this.epochs.push(epoch);
|
|
262
|
-
this.indexEpoch(epoch);
|
|
263
|
-
this.byIdentity.set(identity, epoch);
|
|
264
|
-
this.hashes.set(identity, hash);
|
|
265
|
-
return { inserted: true, epoch: cloneCanonical(epoch) };
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
epoch(epochSeq: number): RuntimeEpoch<TState, TEvent> | null {
|
|
269
|
-
const value = this.epochsBySeq.get(epochSeq);
|
|
270
|
-
return value ? cloneCanonical(value) : null;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
list(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
|
|
274
|
-
return (this.epochsByScope.get(runtimeScopeKey(scope)) ?? [])
|
|
275
|
-
.filter((item) => item.epochSeq > afterEpochSeq)
|
|
276
|
-
.slice(0, Math.max(1, Math.min(limit, 10_000)))
|
|
277
|
-
.map(cloneCanonical);
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
listOpen(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
|
|
281
|
-
return (this.epochsByScope.get(runtimeScopeKey(scope)) ?? [])
|
|
282
|
-
.filter((item) => (
|
|
283
|
-
item.epochSeq > afterEpochSeq
|
|
284
|
-
&& !this.closed.has(item.epochSeq)
|
|
285
|
-
))
|
|
286
|
-
.slice(0, Math.max(1, Math.min(limit, 10_000)))
|
|
287
|
-
.map(cloneCanonical);
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
markClosed(epochSeq: number, _closedAt?: string, _durationMs?: number): void {
|
|
291
|
-
this.closed.add(epochSeq);
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
eventWatermarkThrough(scope: RuntimeScope, epochSeq: number): number {
|
|
295
|
-
const epochs = this.epochsByScope.get(runtimeScopeKey(scope)) ?? [];
|
|
296
|
-
let maximum = 0;
|
|
297
|
-
for (const candidate of epochs) {
|
|
298
|
-
if (candidate.epochSeq > epochSeq) break;
|
|
299
|
-
maximum = Math.max(maximum, this.eventWatermarks.get(candidate.epochSeq) ?? 0);
|
|
300
|
-
}
|
|
301
|
-
return maximum;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
inputEventsCommitted(epochSeq: number): boolean {
|
|
305
|
-
return this.inputEventCommits.has(epochSeq);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
markInputEventsCommitted(epochSeq: number, eventWatermark: number): void {
|
|
309
|
-
this.inputEventCommits.add(epochSeq);
|
|
310
|
-
this.eventWatermarks.set(epochSeq, Math.max(this.eventWatermarks.get(epochSeq) ?? 0, eventWatermark));
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
markEventWatermark(epochSeq: number, eventWatermark: number): void {
|
|
314
|
-
this.eventWatermarks.set(epochSeq, Math.max(this.eventWatermarks.get(epochSeq) ?? 0, eventWatermark));
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
recordPlugin(record: RuntimeEpochPluginRecord): void {
|
|
318
|
-
const epochRecords = this.pluginOutcomeRecordsByEpoch.get(record.epochSeq) ?? [];
|
|
319
|
-
const index = epochRecords.findIndex((candidate) => (
|
|
320
|
-
candidate.epochSeq === record.epochSeq && candidate.pluginId === record.pluginId
|
|
321
|
-
));
|
|
322
|
-
const stored = cloneCanonical(record);
|
|
323
|
-
if (index >= 0) {
|
|
324
|
-
const previous = epochRecords[index];
|
|
325
|
-
epochRecords[index] = stored;
|
|
326
|
-
const allIndex = this.pluginOutcomeRecords.indexOf(previous);
|
|
327
|
-
if (allIndex >= 0) this.pluginOutcomeRecords[allIndex] = stored;
|
|
328
|
-
} else this.indexPluginRecord(stored);
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
pluginRecords(epochSeq: number): RuntimeEpochPluginRecord[] {
|
|
332
|
-
return (this.pluginOutcomeRecordsByEpoch.get(epochSeq) ?? [])
|
|
333
|
-
.sort((a, b) => a.pluginId.localeCompare(b.pluginId))
|
|
334
|
-
.map(cloneCanonical);
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
pluginProgress(pluginId: string, scope: RuntimeScope): RuntimeEpochPluginProgress {
|
|
338
|
-
return cloneCanonical(this.progress.get(`${runtimeScopeKey(scope)}\u001f${pluginId}`) ?? {
|
|
339
|
-
pluginId,
|
|
340
|
-
completedThroughEpochSeq: 0,
|
|
341
|
-
eventCursor: 0,
|
|
342
|
-
updatedAt: new Date(0).toISOString(),
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope): void {
|
|
347
|
-
this.progress.set(`${runtimeScopeKey(scope)}\u001f${progress.pluginId}`, cloneCanonical(progress));
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
saveStates(records: readonly RuntimeEpochStateRecord[]): void {
|
|
351
|
-
for (const record of records) {
|
|
352
|
-
const epochRecords = this.stateRecordsByEpoch.get(record.epochSeq) ?? [];
|
|
353
|
-
const index = epochRecords.findIndex((candidate) => (
|
|
354
|
-
candidate.pluginId === record.pluginId && candidate.topic === record.topic
|
|
355
|
-
));
|
|
356
|
-
const stored = cloneCanonical(record);
|
|
357
|
-
if (index >= 0) {
|
|
358
|
-
const previous = epochRecords[index];
|
|
359
|
-
epochRecords[index] = stored;
|
|
360
|
-
const allIndex = this.stateRecords.indexOf(previous);
|
|
361
|
-
if (allIndex >= 0) this.stateRecords[allIndex] = stored;
|
|
362
|
-
} else this.indexStateRecord(stored);
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
states(epochSeq: number): RuntimeEpochStateRecord[] {
|
|
367
|
-
return (this.stateRecordsByEpoch.get(epochSeq) ?? []).map(cloneCanonical);
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
private indexEpoch(epoch: RuntimeEpoch<TState, TEvent>): void {
|
|
371
|
-
this.epochsBySeq.set(epoch.epochSeq, epoch);
|
|
372
|
-
const key = runtimeScopeKey(epoch.scope);
|
|
373
|
-
const scoped = this.epochsByScope.get(key) ?? [];
|
|
374
|
-
scoped.push(epoch);
|
|
375
|
-
this.epochsByScope.set(key, scoped);
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
private indexPluginRecord(record: RuntimeEpochPluginRecord): void {
|
|
379
|
-
this.pluginOutcomeRecords.push(record);
|
|
380
|
-
const rows = this.pluginOutcomeRecordsByEpoch.get(record.epochSeq) ?? [];
|
|
381
|
-
rows.push(record);
|
|
382
|
-
this.pluginOutcomeRecordsByEpoch.set(record.epochSeq, rows);
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
private indexStateRecord(record: RuntimeEpochStateRecord): void {
|
|
386
|
-
this.stateRecords.push(record);
|
|
387
|
-
const rows = this.stateRecordsByEpoch.get(record.epochSeq) ?? [];
|
|
388
|
-
rows.push(record);
|
|
389
|
-
this.stateRecordsByEpoch.set(record.epochSeq, rows);
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function parseJson<T>(value: unknown): T {
|
|
395
|
-
if (typeof value !== 'string') throw new Error('Runtime Input Journal contains invalid JSON.');
|
|
396
|
-
return JSON.parse(value) as T;
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
function numberValue(value: unknown): number {
|
|
400
|
-
return typeof value === 'bigint' ? Number(value) : Number(value ?? 0);
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
export class SqliteRuntimeInputJournal<TState = Record<string, unknown>, TEvent = Record<string, unknown>>
|
|
404
|
-
implements RuntimePersistenceStore<TState, TEvent> {
|
|
405
|
-
private readonly db: DatabaseLike;
|
|
406
|
-
|
|
407
|
-
constructor(path: string) {
|
|
408
|
-
const sqlite = loadNodeSqliteModule<Partial<SqliteModuleLike>>(localRequire);
|
|
409
|
-
if (typeof sqlite.DatabaseSync !== 'function') throw new Error('node:sqlite is unavailable in this Node.js runtime');
|
|
410
|
-
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
|
|
411
|
-
this.db = new sqlite.DatabaseSync(path);
|
|
412
|
-
this.initialize();
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
accept(batch: RuntimeInputBatch<TState, TEvent>): RuntimeInputAcceptance<TState, TEvent> {
|
|
416
|
-
assertRuntimeInputBatch(batch);
|
|
417
|
-
const hash = payloadHash(batch as RuntimeInputBatch);
|
|
418
|
-
const existing = this.findByIdentity(batch.scope, batch.sourceId, batch.sourceKey);
|
|
419
|
-
if (existing) {
|
|
420
|
-
if (String(existing.payload_hash) !== hash) throw new RuntimeInputConflictError(batch.sourceId, batch.sourceKey);
|
|
421
|
-
return { inserted: false, epoch: this.fromRow(existing) };
|
|
422
|
-
}
|
|
423
|
-
const result = this.db.prepare(`
|
|
424
|
-
INSERT INTO runtime_epochs(
|
|
425
|
-
adapter_id, account_id, session_id, segment_id, segment_seq,
|
|
426
|
-
source_id, connection_id, source_key, source_seq_json, domain_tick_json,
|
|
427
|
-
state_json, events_json, event_watermark_json, completeness, coalescing,
|
|
428
|
-
observed_at, received_at, payload_hash, status
|
|
429
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'accepted')
|
|
430
|
-
`).run(
|
|
431
|
-
batch.scope.adapterId,
|
|
432
|
-
batch.scope.accountId,
|
|
433
|
-
batch.scope.sessionId,
|
|
434
|
-
batch.scope.segmentId,
|
|
435
|
-
batch.scope.segmentSeq ?? null,
|
|
436
|
-
batch.sourceId,
|
|
437
|
-
batch.connectionId,
|
|
438
|
-
batch.sourceKey,
|
|
439
|
-
batch.sourceSeq === undefined ? null : JSON.stringify(batch.sourceSeq),
|
|
440
|
-
batch.domainTick === undefined ? null : JSON.stringify(batch.domainTick),
|
|
441
|
-
JSON.stringify(batch.state),
|
|
442
|
-
JSON.stringify(batch.events),
|
|
443
|
-
batch.eventWatermark === undefined ? null : JSON.stringify(batch.eventWatermark),
|
|
444
|
-
batch.completeness,
|
|
445
|
-
batch.coalescing ?? 'allowed',
|
|
446
|
-
batch.observedAt ?? null,
|
|
447
|
-
batch.receivedAt,
|
|
448
|
-
hash,
|
|
449
|
-
);
|
|
450
|
-
const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?')
|
|
451
|
-
.get(numberValue(result.lastInsertRowid));
|
|
452
|
-
if (!row) throw new Error('Runtime epoch was inserted but could not be read.');
|
|
453
|
-
return { inserted: true, epoch: this.fromRow(row) };
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
epoch(epochSeq: number): RuntimeEpoch<TState, TEvent> | null {
|
|
457
|
-
const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?').get(epochSeq);
|
|
458
|
-
return row ? this.fromRow(row) : null;
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
list(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
|
|
462
|
-
return this.db.prepare(`
|
|
463
|
-
SELECT * FROM runtime_epochs
|
|
464
|
-
WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
|
|
465
|
-
AND epoch_seq > ?
|
|
466
|
-
ORDER BY epoch_seq ASC LIMIT ?
|
|
467
|
-
`).all(
|
|
468
|
-
scope.adapterId,
|
|
469
|
-
scope.accountId,
|
|
470
|
-
scope.sessionId,
|
|
471
|
-
scope.segmentId,
|
|
472
|
-
afterEpochSeq,
|
|
473
|
-
Math.max(1, Math.min(limit, 10_000)),
|
|
474
|
-
).map((row) => this.fromRow(row));
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
listOpen(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
|
|
478
|
-
return this.db.prepare(`
|
|
479
|
-
SELECT * FROM runtime_epochs
|
|
480
|
-
WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
|
|
481
|
-
AND epoch_seq > ? AND status = 'accepted'
|
|
482
|
-
ORDER BY epoch_seq ASC LIMIT ?
|
|
483
|
-
`).all(
|
|
484
|
-
scope.adapterId,
|
|
485
|
-
scope.accountId,
|
|
486
|
-
scope.sessionId,
|
|
487
|
-
scope.segmentId,
|
|
488
|
-
afterEpochSeq,
|
|
489
|
-
Math.max(1, Math.min(limit, 10_000)),
|
|
490
|
-
).map((row) => this.fromRow(row));
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
markClosed(
|
|
494
|
-
epochSeq: number,
|
|
495
|
-
closedAt = new Date().toISOString(),
|
|
496
|
-
durationMs?: number,
|
|
497
|
-
): void {
|
|
498
|
-
this.db.prepare(`
|
|
499
|
-
UPDATE runtime_epochs
|
|
500
|
-
SET status = 'closed', closed_at = ?, processing_duration_ms = ?
|
|
501
|
-
WHERE epoch_seq = ?
|
|
502
|
-
`).run(closedAt, durationMs ?? null, epochSeq);
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
inputEventsCommitted(epochSeq: number): boolean {
|
|
506
|
-
const row = this.db.prepare('SELECT input_events_committed_at FROM runtime_epochs WHERE epoch_seq = ?')
|
|
507
|
-
.get(epochSeq);
|
|
508
|
-
return typeof row?.input_events_committed_at === 'string';
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
markInputEventsCommitted(
|
|
512
|
-
epochSeq: number,
|
|
513
|
-
eventWatermark: number,
|
|
514
|
-
committedAt = new Date().toISOString(),
|
|
515
|
-
): void {
|
|
516
|
-
this.db.prepare(`
|
|
517
|
-
UPDATE runtime_epochs
|
|
518
|
-
SET input_events_committed_at = ?,
|
|
519
|
-
event_commit_watermark = MAX(COALESCE(event_commit_watermark, 0), ?)
|
|
520
|
-
WHERE epoch_seq = ?
|
|
521
|
-
`).run(committedAt, eventWatermark, epochSeq);
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
eventWatermarkThrough(scope: RuntimeScope, epochSeq: number): number {
|
|
525
|
-
const row = this.db.prepare(`
|
|
526
|
-
SELECT event_commit_watermark AS watermark
|
|
527
|
-
FROM runtime_epochs
|
|
528
|
-
WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
|
|
529
|
-
AND epoch_seq <= ? AND event_commit_watermark IS NOT NULL
|
|
530
|
-
ORDER BY event_commit_watermark DESC
|
|
531
|
-
LIMIT 1
|
|
532
|
-
`).get(
|
|
533
|
-
scope.adapterId,
|
|
534
|
-
scope.accountId,
|
|
535
|
-
scope.sessionId,
|
|
536
|
-
scope.segmentId,
|
|
537
|
-
epochSeq,
|
|
538
|
-
);
|
|
539
|
-
return numberValue(row?.watermark);
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
markEventWatermark(epochSeq: number, eventWatermark: number): void {
|
|
543
|
-
this.db.prepare(`
|
|
544
|
-
UPDATE runtime_epochs
|
|
545
|
-
SET event_commit_watermark = MAX(COALESCE(event_commit_watermark, 0), ?)
|
|
546
|
-
WHERE epoch_seq = ?
|
|
547
|
-
`).run(eventWatermark, epochSeq);
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
recordPlugin(record: RuntimeEpochPluginRecord): void {
|
|
551
|
-
this.db.prepare(`
|
|
552
|
-
INSERT OR REPLACE INTO runtime_plugin_outcomes(
|
|
553
|
-
epoch_seq, plugin_id, invocation_id, outcome, reason, duration_ms,
|
|
554
|
-
state_count, event_count, event_cursor_before, event_cursor_after, recorded_at
|
|
555
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
556
|
-
`).run(
|
|
557
|
-
record.epochSeq,
|
|
558
|
-
record.pluginId,
|
|
559
|
-
record.invocationId,
|
|
560
|
-
record.outcome,
|
|
561
|
-
record.reason ?? null,
|
|
562
|
-
record.durationMs,
|
|
563
|
-
record.stateCount,
|
|
564
|
-
record.eventCount,
|
|
565
|
-
record.eventCursorBefore,
|
|
566
|
-
record.eventCursorAfter,
|
|
567
|
-
record.recordedAt,
|
|
568
|
-
);
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
pluginRecords(epochSeq: number): RuntimeEpochPluginRecord[] {
|
|
572
|
-
return this.db.prepare(`
|
|
573
|
-
SELECT * FROM runtime_plugin_outcomes
|
|
574
|
-
WHERE epoch_seq = ?
|
|
575
|
-
ORDER BY plugin_id
|
|
576
|
-
`).all(epochSeq).map((row) => ({
|
|
577
|
-
epochSeq: numberValue(row.epoch_seq),
|
|
578
|
-
pluginId: String(row.plugin_id),
|
|
579
|
-
invocationId: String(row.invocation_id),
|
|
580
|
-
outcome: row.outcome as RuntimeEpochPluginRecord['outcome'],
|
|
581
|
-
...(typeof row.reason === 'string' ? { reason: row.reason } : {}),
|
|
582
|
-
durationMs: numberValue(row.duration_ms),
|
|
583
|
-
stateCount: numberValue(row.state_count),
|
|
584
|
-
eventCount: numberValue(row.event_count),
|
|
585
|
-
eventCursorBefore: numberValue(row.event_cursor_before),
|
|
586
|
-
eventCursorAfter: numberValue(row.event_cursor_after),
|
|
587
|
-
recordedAt: String(row.recorded_at),
|
|
588
|
-
}));
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
pluginProgress(pluginId: string, scope: RuntimeScope): RuntimeEpochPluginProgress {
|
|
592
|
-
const row = this.db.prepare(`
|
|
593
|
-
SELECT * FROM runtime_plugin_progress
|
|
594
|
-
WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ? AND plugin_id = ?
|
|
595
|
-
`).get(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, pluginId);
|
|
596
|
-
return row ? {
|
|
597
|
-
pluginId,
|
|
598
|
-
completedThroughEpochSeq: numberValue(row.completed_through_epoch_seq),
|
|
599
|
-
eventCursor: numberValue(row.event_cursor),
|
|
600
|
-
...(typeof row.checkpoint_json === 'string'
|
|
601
|
-
? { checkpoint: parseJson(row.checkpoint_json) }
|
|
602
|
-
: {}),
|
|
603
|
-
updatedAt: String(row.updated_at),
|
|
604
|
-
} : {
|
|
605
|
-
pluginId,
|
|
606
|
-
completedThroughEpochSeq: 0,
|
|
607
|
-
eventCursor: 0,
|
|
608
|
-
updatedAt: new Date(0).toISOString(),
|
|
609
|
-
};
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope): void {
|
|
613
|
-
this.db.prepare(`
|
|
614
|
-
INSERT INTO runtime_plugin_progress(
|
|
615
|
-
adapter_id, account_id, session_id, segment_id, plugin_id,
|
|
616
|
-
completed_through_epoch_seq, event_cursor, checkpoint_json, updated_at
|
|
617
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
618
|
-
ON CONFLICT(adapter_id, account_id, session_id, segment_id, plugin_id)
|
|
619
|
-
DO UPDATE SET
|
|
620
|
-
completed_through_epoch_seq = excluded.completed_through_epoch_seq,
|
|
621
|
-
event_cursor = excluded.event_cursor,
|
|
622
|
-
checkpoint_json = excluded.checkpoint_json,
|
|
623
|
-
updated_at = excluded.updated_at
|
|
624
|
-
`).run(
|
|
625
|
-
scope.adapterId,
|
|
626
|
-
scope.accountId,
|
|
627
|
-
scope.sessionId,
|
|
628
|
-
scope.segmentId,
|
|
629
|
-
progress.pluginId,
|
|
630
|
-
progress.completedThroughEpochSeq,
|
|
631
|
-
progress.eventCursor,
|
|
632
|
-
progress.checkpoint === undefined ? null : JSON.stringify(progress.checkpoint),
|
|
633
|
-
progress.updatedAt,
|
|
634
|
-
);
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
saveStates(records: readonly RuntimeEpochStateRecord[]): void {
|
|
638
|
-
const statement = this.db.prepare(`
|
|
639
|
-
INSERT OR REPLACE INTO runtime_plugin_states(epoch_seq, plugin_id, topic, value_json)
|
|
640
|
-
VALUES (?, ?, ?, ?)
|
|
641
|
-
`);
|
|
642
|
-
this.db.exec('BEGIN IMMEDIATE');
|
|
643
|
-
try {
|
|
644
|
-
for (const record of records) {
|
|
645
|
-
statement.run(record.epochSeq, record.pluginId, record.topic, JSON.stringify(record.value));
|
|
646
|
-
}
|
|
647
|
-
this.db.exec('COMMIT');
|
|
648
|
-
} catch (error) {
|
|
649
|
-
this.db.exec('ROLLBACK');
|
|
650
|
-
throw error;
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
states(epochSeq: number): RuntimeEpochStateRecord[] {
|
|
655
|
-
return this.db.prepare(`
|
|
656
|
-
SELECT epoch_seq, plugin_id, topic, value_json
|
|
657
|
-
FROM runtime_plugin_states WHERE epoch_seq = ? ORDER BY plugin_id, topic
|
|
658
|
-
`).all(epochSeq).map((row) => ({
|
|
659
|
-
epochSeq: numberValue(row.epoch_seq),
|
|
660
|
-
pluginId: String(row.plugin_id),
|
|
661
|
-
topic: String(row.topic),
|
|
662
|
-
value: parseJson(row.value_json),
|
|
663
|
-
}));
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
close(): void {
|
|
667
|
-
this.db.close();
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
671
|
-
snapshot(scope?: RuntimeScope | null): RuntimeInputJournalSnapshot<TState, TEvent> {
|
|
672
|
-
const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
|
|
673
|
-
: ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
|
|
674
|
-
const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
|
|
675
|
-
const epochRows = this.db.prepare(`SELECT * FROM runtime_epochs${where} ORDER BY epoch_seq ASC`).all(...params);
|
|
676
|
-
const epochs = epochRows.map((row) => ({
|
|
677
|
-
epoch: this.fromRow(row),
|
|
678
|
-
closed: row.status === 'closed',
|
|
679
|
-
inputEventsCommitted: typeof row.input_events_committed_at === 'string',
|
|
680
|
-
eventWatermark: numberValue(row.event_commit_watermark),
|
|
681
|
-
}));
|
|
682
|
-
const pluginProgress = this.db.prepare(`SELECT * FROM runtime_plugin_progress${where}`).all(...params).map((row) => ({
|
|
683
|
-
scope: {
|
|
684
|
-
adapterId: String(row.adapter_id),
|
|
685
|
-
accountId: String(row.account_id),
|
|
686
|
-
sessionId: String(row.session_id),
|
|
687
|
-
segmentId: String(row.segment_id),
|
|
688
|
-
},
|
|
689
|
-
progress: {
|
|
690
|
-
pluginId: String(row.plugin_id),
|
|
691
|
-
completedThroughEpochSeq: numberValue(row.completed_through_epoch_seq),
|
|
692
|
-
eventCursor: numberValue(row.event_cursor),
|
|
693
|
-
...(typeof row.checkpoint_json === 'string' ? { checkpoint: parseJson(row.checkpoint_json) } : {}),
|
|
694
|
-
updatedAt: String(row.updated_at),
|
|
695
|
-
},
|
|
696
|
-
}));
|
|
697
|
-
const pluginRecords = this.db.prepare(`SELECT * FROM runtime_plugin_outcomes
|
|
698
|
-
WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id`)
|
|
699
|
-
.all(...params).map((row) => ({
|
|
700
|
-
epochSeq: numberValue(row.epoch_seq),
|
|
701
|
-
pluginId: String(row.plugin_id),
|
|
702
|
-
invocationId: String(row.invocation_id),
|
|
703
|
-
outcome: row.outcome as RuntimeEpochPluginRecord['outcome'],
|
|
704
|
-
...(typeof row.reason === 'string' ? { reason: row.reason } : {}),
|
|
705
|
-
durationMs: numberValue(row.duration_ms),
|
|
706
|
-
stateCount: numberValue(row.state_count),
|
|
707
|
-
eventCount: numberValue(row.event_count),
|
|
708
|
-
eventCursorBefore: numberValue(row.event_cursor_before),
|
|
709
|
-
eventCursorAfter: numberValue(row.event_cursor_after),
|
|
710
|
-
recordedAt: String(row.recorded_at),
|
|
711
|
-
}));
|
|
712
|
-
const states = this.db.prepare(`SELECT * FROM runtime_plugin_states
|
|
713
|
-
WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id, topic`)
|
|
714
|
-
.all(...params).map((row) => ({
|
|
715
|
-
epochSeq: numberValue(row.epoch_seq),
|
|
716
|
-
pluginId: String(row.plugin_id),
|
|
717
|
-
topic: String(row.topic),
|
|
718
|
-
value: parseJson(row.value_json),
|
|
719
|
-
}));
|
|
720
|
-
return {
|
|
721
|
-
epochs,
|
|
722
|
-
pluginProgress,
|
|
723
|
-
pluginRecords,
|
|
724
|
-
states,
|
|
725
|
-
nextEpochSeq: numberValue(this.db.prepare('SELECT MAX(epoch_seq) AS seq FROM runtime_epochs').get()?.seq) + 1,
|
|
726
|
-
};
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
private findByIdentity(scope: RuntimeScope, sourceId: string, sourceKey: string) {
|
|
730
|
-
return this.db.prepare(`
|
|
731
|
-
SELECT * FROM runtime_epochs
|
|
732
|
-
WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
|
|
733
|
-
AND source_id = ? AND source_key = ?
|
|
734
|
-
`).get(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, sourceId, sourceKey);
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
private fromRow(row: Record<string, unknown>): RuntimeEpoch<TState, TEvent> {
|
|
738
|
-
return cloneCanonical({
|
|
739
|
-
epochSeq: numberValue(row.epoch_seq),
|
|
740
|
-
scope: {
|
|
741
|
-
adapterId: String(row.adapter_id),
|
|
742
|
-
accountId: String(row.account_id),
|
|
743
|
-
sessionId: String(row.session_id),
|
|
744
|
-
segmentId: String(row.segment_id),
|
|
745
|
-
...(row.segment_seq === null || row.segment_seq === undefined
|
|
746
|
-
? {}
|
|
747
|
-
: { segmentSeq: numberValue(row.segment_seq) }),
|
|
748
|
-
},
|
|
749
|
-
sourceId: String(row.source_id),
|
|
750
|
-
connectionId: String(row.connection_id),
|
|
751
|
-
sourceKey: String(row.source_key),
|
|
752
|
-
...(row.source_seq_json === null ? {} : { sourceSeq: parseJson<number | string>(row.source_seq_json) }),
|
|
753
|
-
...(row.domain_tick_json === null ? {} : { domainTick: parseJson<number | string>(row.domain_tick_json) }),
|
|
754
|
-
state: parseJson<TState>(row.state_json),
|
|
755
|
-
events: parseJson<RuntimeInputBatch<TState, TEvent>['events']>(row.events_json),
|
|
756
|
-
...(row.event_watermark_json === null
|
|
757
|
-
? {}
|
|
758
|
-
: { eventWatermark: parseJson<number | string>(row.event_watermark_json) }),
|
|
759
|
-
completeness: row.completeness as RuntimeInputBatch['completeness'],
|
|
760
|
-
...(row.coalescing === 'forbidden' ? { coalescing: 'forbidden' as const } : {}),
|
|
761
|
-
...(typeof row.observed_at === 'string' ? { observedAt: row.observed_at } : {}),
|
|
762
|
-
receivedAt: String(row.received_at),
|
|
763
|
-
});
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
private initialize(): void {
|
|
767
|
-
this.db.exec(`
|
|
768
|
-
PRAGMA journal_mode = WAL;
|
|
769
|
-
CREATE TABLE IF NOT EXISTS runtime_epochs(
|
|
770
|
-
epoch_seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
771
|
-
adapter_id TEXT NOT NULL,
|
|
772
|
-
account_id TEXT NOT NULL,
|
|
773
|
-
session_id TEXT NOT NULL,
|
|
774
|
-
segment_id TEXT NOT NULL,
|
|
775
|
-
segment_seq INTEGER,
|
|
776
|
-
source_id TEXT NOT NULL,
|
|
777
|
-
connection_id TEXT NOT NULL,
|
|
778
|
-
source_key TEXT NOT NULL,
|
|
779
|
-
source_seq_json TEXT,
|
|
780
|
-
domain_tick_json TEXT,
|
|
781
|
-
state_json TEXT NOT NULL,
|
|
782
|
-
events_json TEXT NOT NULL,
|
|
783
|
-
event_watermark_json TEXT,
|
|
784
|
-
completeness TEXT NOT NULL CHECK(completeness IN ('complete', 'best_effort')),
|
|
785
|
-
coalescing TEXT NOT NULL DEFAULT 'allowed' CHECK(coalescing IN ('allowed', 'forbidden')),
|
|
786
|
-
observed_at TEXT,
|
|
787
|
-
received_at TEXT NOT NULL,
|
|
788
|
-
payload_hash TEXT NOT NULL,
|
|
789
|
-
status TEXT NOT NULL CHECK(status IN ('accepted', 'closed')),
|
|
790
|
-
input_events_committed_at TEXT,
|
|
791
|
-
event_commit_watermark INTEGER,
|
|
792
|
-
closed_at TEXT,
|
|
793
|
-
processing_duration_ms INTEGER,
|
|
794
|
-
UNIQUE(adapter_id, account_id, session_id, segment_id, source_id, source_key)
|
|
795
|
-
);
|
|
796
|
-
CREATE INDEX IF NOT EXISTS runtime_epochs_scope_seq
|
|
797
|
-
ON runtime_epochs(adapter_id, account_id, session_id, segment_id, epoch_seq);
|
|
798
|
-
CREATE INDEX IF NOT EXISTS runtime_epochs_scope_event_watermark
|
|
799
|
-
ON runtime_epochs(
|
|
800
|
-
adapter_id, account_id, session_id, segment_id,
|
|
801
|
-
event_commit_watermark DESC, epoch_seq
|
|
802
|
-
);
|
|
803
|
-
|
|
804
|
-
CREATE TABLE IF NOT EXISTS runtime_plugin_outcomes(
|
|
805
|
-
epoch_seq INTEGER NOT NULL,
|
|
806
|
-
plugin_id TEXT NOT NULL,
|
|
807
|
-
invocation_id TEXT NOT NULL,
|
|
808
|
-
outcome TEXT NOT NULL CHECK(outcome IN ('processed', 'noop', 'failed', 'coalesced')),
|
|
809
|
-
reason TEXT,
|
|
810
|
-
duration_ms INTEGER NOT NULL,
|
|
811
|
-
state_count INTEGER NOT NULL,
|
|
812
|
-
event_count INTEGER NOT NULL,
|
|
813
|
-
event_cursor_before INTEGER NOT NULL,
|
|
814
|
-
event_cursor_after INTEGER NOT NULL,
|
|
815
|
-
recorded_at TEXT NOT NULL,
|
|
816
|
-
PRIMARY KEY(epoch_seq, plugin_id)
|
|
817
|
-
);
|
|
818
|
-
|
|
819
|
-
CREATE TABLE IF NOT EXISTS runtime_plugin_progress(
|
|
820
|
-
adapter_id TEXT NOT NULL,
|
|
821
|
-
account_id TEXT NOT NULL,
|
|
822
|
-
session_id TEXT NOT NULL,
|
|
823
|
-
segment_id TEXT NOT NULL,
|
|
824
|
-
plugin_id TEXT NOT NULL,
|
|
825
|
-
completed_through_epoch_seq INTEGER NOT NULL,
|
|
826
|
-
event_cursor INTEGER NOT NULL,
|
|
827
|
-
checkpoint_json TEXT,
|
|
828
|
-
updated_at TEXT NOT NULL,
|
|
829
|
-
PRIMARY KEY(adapter_id, account_id, session_id, segment_id, plugin_id)
|
|
830
|
-
);
|
|
831
|
-
|
|
832
|
-
CREATE TABLE IF NOT EXISTS runtime_plugin_states(
|
|
833
|
-
epoch_seq INTEGER NOT NULL,
|
|
834
|
-
plugin_id TEXT NOT NULL,
|
|
835
|
-
topic TEXT NOT NULL,
|
|
836
|
-
value_json TEXT NOT NULL,
|
|
837
|
-
PRIMARY KEY(epoch_seq, plugin_id, topic)
|
|
838
|
-
);
|
|
839
|
-
|
|
840
|
-
`);
|
|
841
|
-
const epochColumns = new Set(
|
|
842
|
-
this.db.prepare('PRAGMA table_info(runtime_epochs)').all().map((row) => String(row.name)),
|
|
843
|
-
);
|
|
844
|
-
if (!epochColumns.has('segment_seq')) {
|
|
845
|
-
this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN segment_seq INTEGER;');
|
|
846
|
-
}
|
|
847
|
-
if (!epochColumns.has('input_events_committed_at')) {
|
|
848
|
-
this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN input_events_committed_at TEXT;');
|
|
849
|
-
}
|
|
850
|
-
if (!epochColumns.has('event_commit_watermark')) {
|
|
851
|
-
this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN event_commit_watermark INTEGER;');
|
|
852
|
-
}
|
|
853
|
-
if (!epochColumns.has('coalescing')) {
|
|
854
|
-
this.db.exec("ALTER TABLE runtime_epochs ADD COLUMN coalescing TEXT NOT NULL DEFAULT 'allowed';");
|
|
855
|
-
}
|
|
856
|
-
if (!epochColumns.has('processing_duration_ms')) {
|
|
857
|
-
this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN processing_duration_ms INTEGER;');
|
|
858
|
-
}
|
|
859
|
-
const progressColumns = new Set(
|
|
860
|
-
this.db.prepare('PRAGMA table_info(runtime_plugin_progress)').all().map((row) => String(row.name)),
|
|
861
|
-
);
|
|
862
|
-
if (!progressColumns.has('checkpoint_json')) {
|
|
863
|
-
this.db.exec('ALTER TABLE runtime_plugin_progress ADD COLUMN checkpoint_json TEXT;');
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
}
|
|
1
|
+
// Compatibility facade; implementation lives in the game-neutral runtime package.
|
|
2
|
+
export * from '@myclaw163/game-agent-runtime/framework/plugins/runtime-input-journal.js';
|