@myclaw163/clawclaw-cli 0.8.13 → 0.8.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/custom-modules/perception.md +4 -4
- package/docs/runtime/README.md +1 -1
- package/docs/runtime/behavior-runtime.md +1 -1
- package/docs/runtime/official-perception-modules.md +23 -30
- package/docs/runtime/perception-replay.md +1 -1
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +8 -4
- package/skills/clawclaw/references/BEHAVIORS.md +16 -1
- package/skills/clawclaw/references/CHANNELS.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +2 -2
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
- package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
- package/skills/clawclaw/references/STREAM.md +4 -2
- package/src/lib/game-client.ts +12 -4
- package/src/pipeline/event-format.ts +5 -0
- package/src/pipeline/event-hints.ts +10 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
- package/src/runtime/clawclaw/behavior-decision.ts +4 -1
- package/src/runtime/clawclaw/behavior-input.ts +5 -0
- package/src/runtime/clawclaw/owner.ts +64 -1
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
- package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
- package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +201 -43
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +45 -9
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +170 -8
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
- package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +33 -9
- package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
- package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +327 -23
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
- package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
- package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
- package/src/runtime/clawclaw/runtime.ts +31 -3
- package/src/runtime/clawclaw-event-catalog.ts +3 -0
- package/src/runtime/framework/events/event-repository.ts +1 -1
- package/src/runtime/framework/events/memory-event-repository.ts +71 -1
- package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
- package/src/runtime/framework/mailbox/types.ts +2 -0
- package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +383 -0
- package/src/runtime/framework/plugins/contracts.ts +5 -2
- package/src/runtime/framework/plugins/runtime-input-journal.ts +185 -17
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +173 -34
- package/src/runtime/framework/runtime.ts +75 -4
- package/src/runtime/framework/state/history/contracts.ts +9 -1
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +59 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
- package/src/runtime/observability/redaction.ts +28 -1
- package/src/sdk/behavior-plugin/index.ts +5 -24
- package/src/sdk/module-input/index.ts +47 -0
- package/src/sdk/perception-plugin/index.ts +13 -8
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { createRequire } from 'module';
|
|
3
|
+
import { pathToFileURL } from 'url';
|
|
4
|
+
import { Worker } from 'worker_threads';
|
|
5
|
+
import type { MailboxRepository } from '../mailbox/mailbox-repository.js';
|
|
6
|
+
import type {
|
|
7
|
+
AckMailboxClaimRequest,
|
|
8
|
+
ClaimMailboxItemsRequest,
|
|
9
|
+
EnqueueMailboxItem,
|
|
10
|
+
MailboxPeekFilter,
|
|
11
|
+
NackMailboxClaimRequest,
|
|
12
|
+
SuppressMailboxItemsFilter,
|
|
13
|
+
} from '../mailbox/types.js';
|
|
14
|
+
import { MemoryEventRepository } from '../events/memory-event-repository.js';
|
|
15
|
+
import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
|
|
16
|
+
import type { EventRepository } from '../events/event-repository.js';
|
|
17
|
+
import type {
|
|
18
|
+
AcquireLeaseRequest,
|
|
19
|
+
CommittedEventListFilter,
|
|
20
|
+
CommitEventRequest,
|
|
21
|
+
ConsumerLease,
|
|
22
|
+
DetailStateTransition,
|
|
23
|
+
EventAccountScope,
|
|
24
|
+
EventListFilter,
|
|
25
|
+
EventSegmentRecord,
|
|
26
|
+
LatestEventScopeOptions,
|
|
27
|
+
MonitorDeliveryAttempt,
|
|
28
|
+
MonitorStateTransition,
|
|
29
|
+
PlaySessionRecord,
|
|
30
|
+
} from '../events/types.js';
|
|
31
|
+
import type {
|
|
32
|
+
RuntimeEpochPluginProgress,
|
|
33
|
+
RuntimeEpochPluginRecord,
|
|
34
|
+
RuntimeEpochStateRecord,
|
|
35
|
+
RuntimeInputBatch,
|
|
36
|
+
RuntimePersistenceStore,
|
|
37
|
+
} from '../plugins/contracts.js';
|
|
38
|
+
import { MemoryRuntimeInputJournal, SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
|
|
39
|
+
import type { RuntimeScope } from '../state/types.js';
|
|
40
|
+
import type {
|
|
41
|
+
HistoryQuery,
|
|
42
|
+
StateFrameQuery,
|
|
43
|
+
StateFrameRecord,
|
|
44
|
+
StateHistoryRepository,
|
|
45
|
+
TrajectoryRecord,
|
|
46
|
+
} from '../state/history/contracts.js';
|
|
47
|
+
import { MemoryStateHistoryRepository } from '../state/history/memory-state-history-repository.js';
|
|
48
|
+
import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
|
|
49
|
+
|
|
50
|
+
type StoreName = 'events' | 'history' | 'input';
|
|
51
|
+
interface PersistenceOperation { store: StoreName; method: string; args: unknown[] }
|
|
52
|
+
const localRequire = createRequire(import.meta.url);
|
|
53
|
+
|
|
54
|
+
export interface MemoryFirstPersistenceOptions {
|
|
55
|
+
eventLedgerPath: string;
|
|
56
|
+
stateHistoryPath: string;
|
|
57
|
+
inputJournalPath: string;
|
|
58
|
+
maxPendingOperations?: number;
|
|
59
|
+
batchSize?: number;
|
|
60
|
+
flushIntervalMs?: number;
|
|
61
|
+
onDegraded?: (error: Error, health: AsyncPersistenceHealth) => void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface ResolvedMemoryFirstPersistenceOptions {
|
|
65
|
+
eventLedgerPath: string;
|
|
66
|
+
stateHistoryPath: string;
|
|
67
|
+
inputJournalPath: string;
|
|
68
|
+
maxPendingOperations: number;
|
|
69
|
+
batchSize: number;
|
|
70
|
+
flushIntervalMs: number;
|
|
71
|
+
onDegraded?: MemoryFirstPersistenceOptions['onDegraded'];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface AsyncPersistenceHealth {
|
|
75
|
+
mode: 'memory-first-sqlite-mirror';
|
|
76
|
+
pendingOperations: number;
|
|
77
|
+
droppedOperations: number;
|
|
78
|
+
degraded: boolean;
|
|
79
|
+
error?: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
class AsyncSqliteMirror {
|
|
83
|
+
private readonly worker: Worker;
|
|
84
|
+
private readonly local: PersistenceOperation[] = [];
|
|
85
|
+
private readonly waiters = new Map<number, { resolve(): void; reject(error: Error): void }>();
|
|
86
|
+
private timer?: NodeJS.Timeout;
|
|
87
|
+
private nextMessageId = 1;
|
|
88
|
+
private sentOperations = 0;
|
|
89
|
+
private acknowledgedOperations = 0;
|
|
90
|
+
private readonly batchSizes = new Map<number, number>();
|
|
91
|
+
private droppedOperations = 0;
|
|
92
|
+
private degradedError?: Error;
|
|
93
|
+
private closing?: Promise<void>;
|
|
94
|
+
private references = 3;
|
|
95
|
+
|
|
96
|
+
constructor(private readonly options: ResolvedMemoryFirstPersistenceOptions) {
|
|
97
|
+
const workerUrl = new URL('./async-sqlite-persistence-worker.ts', import.meta.url).href;
|
|
98
|
+
// Resolve from this package, not from the process cwd. Installed CCL is
|
|
99
|
+
// commonly launched from an Agent workspace that does not contain tsx.
|
|
100
|
+
const tsxApiUrl = pathToFileURL(localRequire.resolve('tsx/esm/api')).href;
|
|
101
|
+
const bootstrap = `void (async () => {
|
|
102
|
+
const { register } = await import(${JSON.stringify(tsxApiUrl)});
|
|
103
|
+
register();
|
|
104
|
+
await import(${JSON.stringify(workerUrl)});
|
|
105
|
+
})();`;
|
|
106
|
+
this.worker = new Worker(bootstrap, {
|
|
107
|
+
eval: true,
|
|
108
|
+
workerData: {
|
|
109
|
+
eventLedgerPath: options.eventLedgerPath,
|
|
110
|
+
stateHistoryPath: options.stateHistoryPath,
|
|
111
|
+
inputJournalPath: options.inputJournalPath,
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
this.worker.on('message', (message: { type: string; id: number; error?: string }) => {
|
|
115
|
+
if (message.type === 'ack') {
|
|
116
|
+
this.acknowledgedOperations += this.batchSizes.get(message.id) ?? 0;
|
|
117
|
+
this.batchSizes.delete(message.id);
|
|
118
|
+
}
|
|
119
|
+
const waiter = this.waiters.get(message.id);
|
|
120
|
+
if (message.type === 'error') {
|
|
121
|
+
const error = new Error(message.error ?? 'Async SQLite persistence failed.');
|
|
122
|
+
this.degrade(error);
|
|
123
|
+
waiter?.reject(error);
|
|
124
|
+
} else {
|
|
125
|
+
waiter?.resolve();
|
|
126
|
+
}
|
|
127
|
+
this.waiters.delete(message.id);
|
|
128
|
+
});
|
|
129
|
+
this.worker.on('error', (error) => this.degrade(error));
|
|
130
|
+
this.worker.on('exit', (code) => {
|
|
131
|
+
if (code !== 0 && !this.closing) this.degrade(new Error(`Async SQLite worker exited with code ${code}.`));
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
enqueue(operation: PersistenceOperation): void {
|
|
136
|
+
if (this.degradedError || this.closing) {
|
|
137
|
+
this.droppedOperations += 1;
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (this.pendingCount() >= this.options.maxPendingOperations) {
|
|
141
|
+
this.degrade(new Error(`Async SQLite queue exceeded ${this.options.maxPendingOperations} operations.`));
|
|
142
|
+
this.droppedOperations += 1;
|
|
143
|
+
this.local.length = 0;
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
this.local.push(structuredClone(operation));
|
|
147
|
+
if (this.local.length >= this.options.batchSize) this.dispatch();
|
|
148
|
+
else this.timer ??= setTimeout(() => this.dispatch(), this.options.flushIntervalMs);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
health(): AsyncPersistenceHealth {
|
|
152
|
+
return {
|
|
153
|
+
mode: 'memory-first-sqlite-mirror',
|
|
154
|
+
pendingOperations: this.pendingCount(),
|
|
155
|
+
droppedOperations: this.droppedOperations,
|
|
156
|
+
degraded: !!this.degradedError,
|
|
157
|
+
...(this.degradedError ? { error: this.degradedError.message } : {}),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async release(): Promise<void> {
|
|
162
|
+
this.references -= 1;
|
|
163
|
+
if (this.references > 0) return;
|
|
164
|
+
await this.close();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private pendingCount(): number {
|
|
168
|
+
return this.local.length + Math.max(0, this.sentOperations - this.acknowledgedOperations);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private dispatch(): void {
|
|
172
|
+
if (this.timer) clearTimeout(this.timer);
|
|
173
|
+
this.timer = undefined;
|
|
174
|
+
if (this.local.length === 0 || this.degradedError) return;
|
|
175
|
+
const operations = this.local.splice(0, this.options.batchSize);
|
|
176
|
+
const id = this.nextMessageId++;
|
|
177
|
+
this.sentOperations += operations.length;
|
|
178
|
+
this.batchSizes.set(id, operations.length);
|
|
179
|
+
this.worker.postMessage({ type: 'batch', id, operations });
|
|
180
|
+
if (this.local.length > 0) this.timer = setTimeout(() => this.dispatch(), 0);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private async flush(): Promise<void> {
|
|
184
|
+
if (this.degradedError) return;
|
|
185
|
+
while (this.local.length > 0) this.dispatch();
|
|
186
|
+
const id = this.nextMessageId++;
|
|
187
|
+
await new Promise<void>((resolve, reject) => {
|
|
188
|
+
this.waiters.set(id, { resolve, reject });
|
|
189
|
+
this.worker.postMessage({ type: 'barrier', id });
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private close(): Promise<void> {
|
|
194
|
+
if (this.closing) return this.closing;
|
|
195
|
+
this.closing = (async () => {
|
|
196
|
+
if (this.timer) clearTimeout(this.timer);
|
|
197
|
+
this.timer = undefined;
|
|
198
|
+
try {
|
|
199
|
+
await this.flush();
|
|
200
|
+
if (!this.degradedError) {
|
|
201
|
+
const id = this.nextMessageId++;
|
|
202
|
+
await new Promise<void>((resolve, reject) => {
|
|
203
|
+
this.waiters.set(id, { resolve, reject });
|
|
204
|
+
this.worker.postMessage({ type: 'close', id });
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
} finally {
|
|
208
|
+
await this.worker.terminate();
|
|
209
|
+
}
|
|
210
|
+
})();
|
|
211
|
+
return this.closing;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private degrade(error: Error): void {
|
|
215
|
+
if (this.degradedError) return;
|
|
216
|
+
this.degradedError = error;
|
|
217
|
+
for (const waiter of this.waiters.values()) waiter.reject(error);
|
|
218
|
+
this.waiters.clear();
|
|
219
|
+
this.options.onDegraded?.(error, this.health());
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
abstract class MirroredStore {
|
|
224
|
+
readonly persistenceKind = 'memory-first-sqlite' as const;
|
|
225
|
+
constructor(protected readonly mirror: AsyncSqliteMirror) {}
|
|
226
|
+
persistenceHealth(): AsyncPersistenceHealth { return this.mirror.health(); }
|
|
227
|
+
close(): Promise<void> { return this.mirror.release(); }
|
|
228
|
+
protected persist(store: StoreName, method: string, ...args: unknown[]): void {
|
|
229
|
+
this.mirror.enqueue({ store, method, args });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
class MemoryFirstEventRepository extends MirroredStore implements EventRepository, MailboxRepository {
|
|
234
|
+
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository) { super(mirror); }
|
|
235
|
+
diagnosticCounts() { return this.memory.diagnosticCounts(); }
|
|
236
|
+
saveSession(value: PlaySessionRecord): void { this.memory.saveSession(value); this.persist('events', 'saveSession', value); }
|
|
237
|
+
saveSegment(value: EventSegmentRecord): void { this.memory.saveSegment(value); this.persist('events', 'saveSegment', value); }
|
|
238
|
+
currentScope(account?: EventAccountScope) { return this.memory.currentScope(account); }
|
|
239
|
+
latestScope(account: EventAccountScope, options?: LatestEventScopeOptions) { return this.memory.latestScope(account, options); }
|
|
240
|
+
commitEvent(value: CommitEventRequest) { const result = this.memory.commitEvent(value); this.persist('events', 'commitEvent', value); return result; }
|
|
241
|
+
eventById(eventId: string) { return this.memory.eventById(eventId); }
|
|
242
|
+
latestEventByType(sessionId: string, type: string, segmentId?: string) { return this.memory.latestEventByType(sessionId, type, segmentId); }
|
|
243
|
+
highWaterCommitSeq(sessionId: string, segmentId?: string) { return this.memory.highWaterCommitSeq(sessionId, segmentId); }
|
|
244
|
+
listCommittedEvents(filter: CommittedEventListFilter) { return this.memory.listCommittedEvents(filter); }
|
|
245
|
+
ensureDeliveries(sessionId: string, consumerId: string, channels?: readonly ConsumerLease['channel'][]): void {
|
|
246
|
+
this.memory.ensureDeliveries(sessionId, consumerId, channels);
|
|
247
|
+
this.persist('events', 'ensureDeliveries', sessionId, consumerId, channels);
|
|
248
|
+
}
|
|
249
|
+
delivery(eventId: string, consumerId: string) { return this.memory.delivery(eventId, consumerId); }
|
|
250
|
+
listEvents(filter: EventListFilter, consumerId: string, channels?: readonly ConsumerLease['channel'][]) {
|
|
251
|
+
this.ensureDeliveries(filter.sessionId, consumerId, channels);
|
|
252
|
+
return this.memory.listEvents(filter, consumerId, channels);
|
|
253
|
+
}
|
|
254
|
+
backlogSummary(sessionId: string, consumerId: string) {
|
|
255
|
+
this.ensureDeliveries(sessionId, consumerId, ['details']);
|
|
256
|
+
return this.memory.backlogSummary(sessionId, consumerId);
|
|
257
|
+
}
|
|
258
|
+
transitionDetails(value: DetailStateTransition) {
|
|
259
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
260
|
+
const result = this.memory.transitionDetails(stable); this.persist('events', 'transitionDetails', stable); return result;
|
|
261
|
+
}
|
|
262
|
+
transitionMonitor(value: MonitorStateTransition) {
|
|
263
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
264
|
+
const result = this.memory.transitionMonitor(stable); this.persist('events', 'transitionMonitor', stable); return result;
|
|
265
|
+
}
|
|
266
|
+
recordMonitorAttempt(value: MonitorDeliveryAttempt) {
|
|
267
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
268
|
+
const result = this.memory.recordMonitorAttempt(stable); this.persist('events', 'recordMonitorAttempt', stable); return result;
|
|
269
|
+
}
|
|
270
|
+
acquireLease(value: AcquireLeaseRequest) {
|
|
271
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
272
|
+
const result = this.memory.acquireLease(stable); this.persist('events', 'acquireLease', stable); return result;
|
|
273
|
+
}
|
|
274
|
+
leaseIsValid(lease: ConsumerLease, nowMs?: number) { return this.memory.leaseIsValid(lease, nowMs); }
|
|
275
|
+
releaseLease(lease: ConsumerLease) { const result = this.memory.releaseLease(lease); this.persist('events', 'releaseLease', lease); return result; }
|
|
276
|
+
sourceCheckpoint(sourceId: string) { return this.memory.sourceCheckpoint(sourceId); }
|
|
277
|
+
enqueueMailboxItem<T = unknown>(value: EnqueueMailboxItem<T>) {
|
|
278
|
+
const nowMs = Date.now();
|
|
279
|
+
const stable = { ...value, createdAt: value.createdAt ?? new Date(nowMs).toISOString(), availableAtMs: value.availableAtMs ?? 0 };
|
|
280
|
+
const result = this.memory.enqueueMailboxItem(stable); this.persist('events', 'enqueueMailboxItem', stable); return result;
|
|
281
|
+
}
|
|
282
|
+
mailboxItem<T = unknown>(itemId: string) { return this.memory.mailboxItem<T>(itemId); }
|
|
283
|
+
mailboxItemForEvent<T = unknown>(consumerId: string, eventId: string, mode: 'short') { return this.memory.mailboxItemForEvent<T>(consumerId, eventId, mode); }
|
|
284
|
+
peekMailbox<T = unknown>(filter: MailboxPeekFilter) { return this.memory.peekMailbox<T>(filter); }
|
|
285
|
+
claimMailbox<T = unknown>(value: ClaimMailboxItemsRequest) {
|
|
286
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now(), claimToken: value.claimToken ?? randomUUID() };
|
|
287
|
+
const result = this.memory.claimMailbox<T>(stable); this.persist('events', 'claimMailbox', stable); return result;
|
|
288
|
+
}
|
|
289
|
+
ackMailboxClaim(value: AckMailboxClaimRequest) {
|
|
290
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
291
|
+
const result = this.memory.ackMailboxClaim(stable); this.persist('events', 'ackMailboxClaim', stable); return result;
|
|
292
|
+
}
|
|
293
|
+
nackMailboxClaim(value: NackMailboxClaimRequest) {
|
|
294
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
295
|
+
const result = this.memory.nackMailboxClaim(stable); this.persist('events', 'nackMailboxClaim', stable); return result;
|
|
296
|
+
}
|
|
297
|
+
suppressMailboxItems(value: SuppressMailboxItemsFilter) {
|
|
298
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
299
|
+
const result = this.memory.suppressMailboxItems(stable); this.persist('events', 'suppressMailboxItems', stable); return result;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
class MemoryFirstStateHistory<TPosition, TState extends Record<string, unknown>> extends MirroredStore
|
|
304
|
+
implements StateHistoryRepository<TPosition, TState> {
|
|
305
|
+
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryStateHistoryRepository<TPosition, TState>) { super(mirror); }
|
|
306
|
+
diagnosticCounts() { return this.memory.diagnosticCounts(); }
|
|
307
|
+
openScope(scope: RuntimeScope, openedAtMs = Date.now(), historyComplete = true) {
|
|
308
|
+
const result = this.memory.openScope(scope, openedAtMs, historyComplete);
|
|
309
|
+
this.persist('history', 'openScope', scope, openedAtMs, historyComplete); return result;
|
|
310
|
+
}
|
|
311
|
+
sealScope(scope: RuntimeScope, sealedAtMs = Date.now()) { this.memory.sealScope(scope, sealedAtMs); this.persist('history', 'sealScope', scope, sealedAtMs); }
|
|
312
|
+
markScopeIncomplete(scope: RuntimeScope) { this.memory.markScopeIncomplete(scope); this.persist('history', 'markScopeIncomplete', scope); }
|
|
313
|
+
getScope(scope: RuntimeScope) { return this.memory.getScope(scope); }
|
|
314
|
+
appendStateFrame(frame: StateFrameRecord<TState>) { const result = this.memory.appendStateFrame(frame); this.persist('history', 'appendStateFrame', frame); return result; }
|
|
315
|
+
queryStateFrames(query: StateFrameQuery) { return this.memory.queryStateFrames(query); }
|
|
316
|
+
latestStateFrame(scope: RuntimeScope) { return this.memory.latestStateFrame(scope); }
|
|
317
|
+
append(records: TrajectoryRecord<TPosition>[]) { const result = this.memory.append(records); this.persist('history', 'append', records); return result; }
|
|
318
|
+
query(query: HistoryQuery) { return this.memory.query(query); }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
class MemoryFirstInputJournal<TState extends Record<string, unknown>, TEvent extends Record<string, unknown>>
|
|
322
|
+
extends MirroredStore implements RuntimePersistenceStore<TState, TEvent> {
|
|
323
|
+
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryRuntimeInputJournal<TState, TEvent>) { super(mirror); }
|
|
324
|
+
diagnosticCounts() { return this.memory.diagnosticCounts(); }
|
|
325
|
+
accept(batch: RuntimeInputBatch<TState, TEvent>) { const result = this.memory.accept(batch); if (result.inserted) this.persist('input', 'accept', batch); return result; }
|
|
326
|
+
epoch(epochSeq: number) { return this.memory.epoch(epochSeq); }
|
|
327
|
+
list(scope: RuntimeScope, afterEpochSeq?: number, limit?: number) { return this.memory.list(scope, afterEpochSeq, limit); }
|
|
328
|
+
listOpen(scope: RuntimeScope, afterEpochSeq?: number, limit?: number) { return this.memory.listOpen(scope, afterEpochSeq, limit); }
|
|
329
|
+
inputEventsCommitted(epochSeq: number) { return this.memory.inputEventsCommitted(epochSeq); }
|
|
330
|
+
markInputEventsCommitted(epochSeq: number, watermark: number, committedAt = new Date().toISOString()) { this.memory.markInputEventsCommitted(epochSeq, watermark); this.persist('input', 'markInputEventsCommitted', epochSeq, watermark, committedAt); }
|
|
331
|
+
eventWatermarkThrough(scope: RuntimeScope, epochSeq: number) { return this.memory.eventWatermarkThrough(scope, epochSeq); }
|
|
332
|
+
markEventWatermark(epochSeq: number, watermark: number) { this.memory.markEventWatermark(epochSeq, watermark); this.persist('input', 'markEventWatermark', epochSeq, watermark); }
|
|
333
|
+
markClosed(epochSeq: number, closedAt = new Date().toISOString(), durationMs?: number) { this.memory.markClosed(epochSeq); this.persist('input', 'markClosed', epochSeq, closedAt, durationMs); }
|
|
334
|
+
recordPlugin(record: RuntimeEpochPluginRecord) { this.memory.recordPlugin(record); this.persist('input', 'recordPlugin', record); }
|
|
335
|
+
pluginRecords(epochSeq: number) { return this.memory.pluginRecords(epochSeq); }
|
|
336
|
+
pluginProgress(pluginId: string, scope: RuntimeScope) { return this.memory.pluginProgress(pluginId, scope); }
|
|
337
|
+
savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope) { this.memory.savePluginProgress(progress, scope); this.persist('input', 'savePluginProgress', progress, scope); }
|
|
338
|
+
saveStates(records: readonly RuntimeEpochStateRecord[]) { this.memory.saveStates(records); this.persist('input', 'saveStates', records); }
|
|
339
|
+
states(epochSeq: number) { return this.memory.states(epochSeq); }
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export interface MemoryFirstPersistence<TPosition = unknown, TState extends Record<string, unknown> = Record<string, unknown>, TEvent extends Record<string, unknown> = Record<string, unknown>> {
|
|
343
|
+
eventRepository: EventRepository & MailboxRepository;
|
|
344
|
+
stateHistoryRepository: StateHistoryRepository<TPosition, TState>;
|
|
345
|
+
inputJournal: RuntimePersistenceStore<TState, TEvent>;
|
|
346
|
+
health(): AsyncPersistenceHealth;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export function createMemoryFirstPersistence<
|
|
350
|
+
TPosition = unknown,
|
|
351
|
+
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
352
|
+
TEvent extends Record<string, unknown> = Record<string, unknown>,
|
|
353
|
+
>(options: MemoryFirstPersistenceOptions): MemoryFirstPersistence<TPosition, TState, TEvent> {
|
|
354
|
+
const eventSqlite = SqliteEventRepository.open(options.eventLedgerPath);
|
|
355
|
+
if (!eventSqlite.ok) throw new Error(`${eventSqlite.unavailable.code}: ${eventSqlite.unavailable.message}`);
|
|
356
|
+
const historySqlite = new SqliteStateHistoryRepository<TPosition, TState>(options.stateHistoryPath);
|
|
357
|
+
const inputSqlite = new SqliteRuntimeInputJournal<TState, TEvent>(options.inputJournalPath);
|
|
358
|
+
let eventMemory: MemoryEventRepository;
|
|
359
|
+
let historyMemory: MemoryStateHistoryRepository<TPosition, TState>;
|
|
360
|
+
let inputMemory: MemoryRuntimeInputJournal<TState, TEvent>;
|
|
361
|
+
try {
|
|
362
|
+
eventMemory = new MemoryEventRepository(eventSqlite.repository.snapshot());
|
|
363
|
+
historyMemory = new MemoryStateHistoryRepository(historySqlite.snapshot());
|
|
364
|
+
inputMemory = new MemoryRuntimeInputJournal(inputSqlite.snapshot());
|
|
365
|
+
} finally {
|
|
366
|
+
eventSqlite.repository.close();
|
|
367
|
+
historySqlite.close();
|
|
368
|
+
inputSqlite.close();
|
|
369
|
+
}
|
|
370
|
+
const required: ResolvedMemoryFirstPersistenceOptions = {
|
|
371
|
+
...options,
|
|
372
|
+
maxPendingOperations: options.maxPendingOperations ?? 20_000,
|
|
373
|
+
batchSize: options.batchSize ?? 128,
|
|
374
|
+
flushIntervalMs: options.flushIntervalMs ?? 8,
|
|
375
|
+
};
|
|
376
|
+
const mirror = new AsyncSqliteMirror(required);
|
|
377
|
+
return {
|
|
378
|
+
eventRepository: new MemoryFirstEventRepository(mirror, eventMemory),
|
|
379
|
+
stateHistoryRepository: new MemoryFirstStateHistory(mirror, historyMemory),
|
|
380
|
+
inputJournal: new MemoryFirstInputJournal(mirror, inputMemory),
|
|
381
|
+
health: () => mirror.health(),
|
|
382
|
+
};
|
|
383
|
+
}
|
|
@@ -201,6 +201,8 @@ extends RuntimePluginIdentity<'epoch'> {
|
|
|
201
201
|
* in-flight capacity delays newer computation instead of discarding work.
|
|
202
202
|
*/
|
|
203
203
|
readonly maxInFlight?: number;
|
|
204
|
+
/** Maximum retained epochs for non-strict catch-up before oldest work is coalesced. */
|
|
205
|
+
readonly maxPendingEpochs?: number;
|
|
204
206
|
readonly failurePolicy?: RuntimePluginFailureMode | RuntimePluginFailurePolicy;
|
|
205
207
|
/** Per-call deadline; Runtime still owns cancellation and stale-output rejection. */
|
|
206
208
|
readonly timeoutMs?: number;
|
|
@@ -298,6 +300,7 @@ export interface RuntimeEpochPluginDescriptor extends RuntimePluginIdentity<'epo
|
|
|
298
300
|
readonly after: readonly string[];
|
|
299
301
|
readonly catchUp: RuntimeEpochCatchUp;
|
|
300
302
|
readonly maxInFlight: number;
|
|
303
|
+
readonly maxPendingEpochs: number;
|
|
301
304
|
readonly consumes: Readonly<NonNullable<RuntimeEpochPlugin['consumes']>>;
|
|
302
305
|
readonly produces: Readonly<NonNullable<RuntimeEpochPlugin['produces']>>;
|
|
303
306
|
readonly capabilities: Readonly<RuntimePluginCapabilityDeclaration>;
|
|
@@ -347,7 +350,7 @@ export interface RuntimeInputJournal<TState = Record<string, unknown>, TEvent =
|
|
|
347
350
|
eventWatermarkThrough(scope: RuntimeScope, epochSeq: number): number;
|
|
348
351
|
markEventWatermark(epochSeq: number, eventWatermark: number): void;
|
|
349
352
|
markClosed(epochSeq: number, closedAt?: string, durationMs?: number): void;
|
|
350
|
-
close?(): void
|
|
353
|
+
close?(): void | Promise<void>;
|
|
351
354
|
}
|
|
352
355
|
|
|
353
356
|
/** Durable outcomes, derived State and independent Event cursors for plugins. */
|
|
@@ -358,7 +361,7 @@ export interface RuntimePluginStore {
|
|
|
358
361
|
savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope): void;
|
|
359
362
|
saveStates(records: readonly RuntimeEpochStateRecord[]): void;
|
|
360
363
|
states(epochSeq: number): RuntimeEpochStateRecord[];
|
|
361
|
-
close?(): void
|
|
364
|
+
close?(): void | Promise<void>;
|
|
362
365
|
}
|
|
363
366
|
|
|
364
367
|
/** One physical database may implement both logical persistence contracts. */
|