@myclaw163/game-agent-runtime 0.1.2 → 0.1.3
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/README.md +2 -0
- package/dist/framework/events/sqlite-event-repository.js +1 -1
- package/dist/framework/persistence/sqlite-maintenance.d.ts +26 -0
- package/dist/framework/persistence/sqlite-maintenance.js +177 -0
- package/dist/framework/plugins/runtime-input-journal.js +1 -1
- package/dist/framework/state/history/sqlite-state-history-repository.js +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -47,6 +47,8 @@ import { createGridGame } from '@myclaw163/game-agent-runtime/examples/grid-game
|
|
|
47
47
|
|
|
48
48
|
## 接入自己的游戏
|
|
49
49
|
|
|
50
|
+
离线数据库维护通过 `framework/persistence/sqlite-maintenance.js` 的 `tryAcquireRuntimeSqliteMaintenance(runtimeDirectory)` 使用。它与 Owner 共用系统锁,Owner 运行时返回 `null`;成功后可调用 `inspect(paths)`、`remove(paths, scopes, { inactiveBefore })` 和 `compact(paths)`,最后必须 `close()`。删除覆盖事件、投递、Mailbox、State 历史和插件 epoch 的关联记录,并保留全局自增序号。默认拒绝未关闭或最近活动的 scope;接入方确认过期异常退出数据后可显式设置 `allowInactiveOpenScopes`。保留时间、容量上限、整局分组和中断重试由接入方管理,GAR 不规定业务清理策略。
|
|
51
|
+
|
|
50
52
|
1. 用 Source 接入权威 State 和 Event,并保留输入时间及来源。
|
|
51
53
|
2. 实现感知/策略适配器:整理脚本输入、游戏执行条件和 SDK。
|
|
52
54
|
3. 注册 Action 和只读 Query,连接游戏后端。
|
|
@@ -241,7 +241,7 @@ export class SqliteEventRepository {
|
|
|
241
241
|
})),
|
|
242
242
|
mailboxItems: this.db.prepare(`SELECT * FROM mailbox_items${where}`).all(...params).map(mailboxItemFromRow),
|
|
243
243
|
// The mirror uses SQLite's global sequence, not the selected session's last row.
|
|
244
|
-
nextCommitSeq: numberValue(this.db.prepare(
|
|
244
|
+
nextCommitSeq: numberValue(this.db.prepare("SELECT MAX(seq) AS seq FROM (SELECT seq FROM sqlite_sequence WHERE name='events' UNION ALL SELECT MAX(commit_seq) FROM events)").get()?.seq) + 1,
|
|
245
245
|
};
|
|
246
246
|
}
|
|
247
247
|
schemaVersion() {
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface RuntimeSqlitePaths {
|
|
2
|
+
eventLedger: string;
|
|
3
|
+
stateHistory: string;
|
|
4
|
+
inputJournal: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ArchivedScope {
|
|
7
|
+
sessionId: string;
|
|
8
|
+
segmentId: string;
|
|
9
|
+
kind: string;
|
|
10
|
+
identity: string | null;
|
|
11
|
+
openedAt: string | null;
|
|
12
|
+
closedAt: string | null;
|
|
13
|
+
lastActivityAt: string | null;
|
|
14
|
+
open: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface RuntimeSqliteMaintenance {
|
|
17
|
+
inspect(paths: RuntimeSqlitePaths): ArchivedScope[];
|
|
18
|
+
remove(paths: RuntimeSqlitePaths, scopes: readonly Pick<ArchivedScope, 'sessionId' | 'segmentId'>[], options: {
|
|
19
|
+
inactiveBefore: string;
|
|
20
|
+
allowInactiveOpenScopes?: boolean;
|
|
21
|
+
}): void;
|
|
22
|
+
compact(paths: RuntimeSqlitePaths): void;
|
|
23
|
+
close(): void;
|
|
24
|
+
}
|
|
25
|
+
/** Acquires the SAME OS lock used by a Runtime Owner. No live store is modified. */
|
|
26
|
+
export declare function tryAcquireRuntimeSqliteMaintenance(directory: string): RuntimeSqliteMaintenance | null;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
4
|
+
import { tryAcquireRuntimeLock } from '../../owner/runtime-lock.js';
|
|
5
|
+
import { loadNodeSqliteModule } from '../load-node-sqlite.js';
|
|
6
|
+
/** Acquires the SAME OS lock used by a Runtime Owner. No live store is modified. */
|
|
7
|
+
export function tryAcquireRuntimeSqliteMaintenance(directory) {
|
|
8
|
+
const lease = tryAcquireRuntimeLock(directory);
|
|
9
|
+
if (!lease)
|
|
10
|
+
return null;
|
|
11
|
+
let root;
|
|
12
|
+
let closed = false;
|
|
13
|
+
let module;
|
|
14
|
+
try {
|
|
15
|
+
root = realpathSync(directory);
|
|
16
|
+
module = loadNodeSqliteModule(createRequire(import.meta.url));
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
lease.release();
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
const connection = (paths) => {
|
|
23
|
+
if (closed)
|
|
24
|
+
throw Error('runtime_maintenance_closed');
|
|
25
|
+
const db = new module.DatabaseSync(':memory:');
|
|
26
|
+
try {
|
|
27
|
+
db.exec('PRAGMA foreign_keys=ON; PRAGMA busy_timeout=1000');
|
|
28
|
+
for (const [alias, path] of [['eventsdb', paths.eventLedger], ['historydb', paths.stateHistory], ['epochsdb', paths.inputJournal]]) {
|
|
29
|
+
if (!existsSync(path))
|
|
30
|
+
continue;
|
|
31
|
+
const target = realpathSync(path);
|
|
32
|
+
const child = relative(root, target);
|
|
33
|
+
if (!child || isAbsolute(child) || child === '..' || child.startsWith('../') || child.startsWith('..\\')) {
|
|
34
|
+
throw Error('runtime_maintenance_path_outside_lock');
|
|
35
|
+
}
|
|
36
|
+
db.prepare(`ATTACH DATABASE ? AS ${alias}`).run(resolve(target));
|
|
37
|
+
}
|
|
38
|
+
return db;
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
db.close();
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const table = (db, alias, name) => {
|
|
46
|
+
if (!db.prepare('PRAGMA database_list').all().some(row => row.name === alias))
|
|
47
|
+
return false;
|
|
48
|
+
return !!db.prepare(`SELECT 1 FROM ${alias}.sqlite_schema WHERE type='table' AND name=?`).get(name);
|
|
49
|
+
};
|
|
50
|
+
const inspect = (db) => {
|
|
51
|
+
const scopes = new Map();
|
|
52
|
+
const merge = (sessionId, segmentId, at) => {
|
|
53
|
+
const key = JSON.stringify([sessionId, segmentId]);
|
|
54
|
+
let scope = scopes.get(key);
|
|
55
|
+
if (!scope) {
|
|
56
|
+
scope = { sessionId, segmentId, kind: 'unknown', identity: null, openedAt: null, closedAt: null, lastActivityAt: null, open: false };
|
|
57
|
+
scopes.set(key, scope);
|
|
58
|
+
}
|
|
59
|
+
if (at && Number.isFinite(Date.parse(at)) && (!scope.lastActivityAt || Date.parse(at) > Date.parse(scope.lastActivityAt)))
|
|
60
|
+
scope.lastActivityAt = at;
|
|
61
|
+
return scope;
|
|
62
|
+
};
|
|
63
|
+
if (table(db, 'eventsdb', 'event_segments')) {
|
|
64
|
+
for (const row of db.prepare('SELECT * FROM eventsdb.event_segments').all()) {
|
|
65
|
+
const scope = merge(row.session_id, row.segment_id, row.closed_at ?? row.opened_at);
|
|
66
|
+
Object.assign(scope, { kind: row.kind, identity: row.scope_ref ?? null, openedAt: row.opened_at,
|
|
67
|
+
closedAt: row.closed_at ?? null, open: row.status === 'open' || row.is_current === 1 });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const [alias, name, time] of [
|
|
71
|
+
['eventsdb', 'events', 'MAX(received_at)'],
|
|
72
|
+
['epochsdb', 'runtime_epochs', 'MAX(received_at)'],
|
|
73
|
+
['epochsdb', 'runtime_plugin_progress', 'MAX(updated_at)'],
|
|
74
|
+
])
|
|
75
|
+
if (table(db, alias, name)) {
|
|
76
|
+
for (const row of db.prepare(`SELECT session_id,segment_id,${time} AS at FROM ${alias}.${name} GROUP BY session_id,segment_id`).all()) {
|
|
77
|
+
merge(row.session_id, row.segment_id, row.at);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (table(db, 'historydb', 'history_scopes')) {
|
|
81
|
+
for (const row of db.prepare('SELECT * FROM historydb.history_scopes').all()) {
|
|
82
|
+
const scope = merge(row.session_id, row.segment_id, new Date(row.sealed_at_ms ?? row.opened_at_ms).toISOString());
|
|
83
|
+
scope.open ||= row.status === 'OPEN';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const name of ['state_frames', 'trajectory_records'])
|
|
87
|
+
if (table(db, 'historydb', name)) {
|
|
88
|
+
for (const row of db.prepare(`SELECT session_id,segment_id,MAX(received_at_ms) AS at FROM historydb.${name} GROUP BY session_id,segment_id`).all()) {
|
|
89
|
+
merge(row.session_id, row.segment_id, Number.isFinite(Number(row.at)) ? new Date(Number(row.at)).toISOString() : null);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return [...scopes.values()];
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
inspect(paths) { const db = connection(paths); try {
|
|
96
|
+
return inspect(db);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
db.close();
|
|
100
|
+
} },
|
|
101
|
+
remove(paths, selected, options) {
|
|
102
|
+
const cutoff = Date.parse(options.inactiveBefore);
|
|
103
|
+
if (!Number.isFinite(cutoff))
|
|
104
|
+
throw Error('runtime_maintenance_invalid_cutoff');
|
|
105
|
+
const db = connection(paths);
|
|
106
|
+
try {
|
|
107
|
+
db.exec('BEGIN IMMEDIATE');
|
|
108
|
+
const current = inspect(db);
|
|
109
|
+
for (const scope of selected) {
|
|
110
|
+
const actual = current.find(row => row.sessionId === scope.sessionId && row.segmentId === scope.segmentId);
|
|
111
|
+
if (actual && (!actual.lastActivityAt || Date.parse(actual.lastActivityAt) >= cutoff
|
|
112
|
+
|| actual.open && !options.allowInactiveOpenScopes))
|
|
113
|
+
throw Error('runtime_maintenance_scope_protected');
|
|
114
|
+
}
|
|
115
|
+
const remove = (alias, name, where, args) => {
|
|
116
|
+
if (table(db, alias, name))
|
|
117
|
+
db.prepare(`DELETE FROM ${alias}.${name} WHERE ${where}`).run(...args);
|
|
118
|
+
};
|
|
119
|
+
for (const scope of selected) {
|
|
120
|
+
const args = [scope.sessionId, scope.segmentId];
|
|
121
|
+
const eventIds = 'SELECT event_id FROM eventsdb.events WHERE session_id=? AND segment_id=?';
|
|
122
|
+
if (table(db, 'eventsdb', 'events')) {
|
|
123
|
+
remove('eventsdb', 'mailbox_items', 'session_id=? AND segment_id=?', args);
|
|
124
|
+
remove('eventsdb', 'event_deliveries', `event_id IN (${eventIds})`, args);
|
|
125
|
+
remove('eventsdb', 'source_checkpoints', `event_id IN (${eventIds})`, args);
|
|
126
|
+
remove('eventsdb', 'events', 'session_id=? AND segment_id=?', args);
|
|
127
|
+
}
|
|
128
|
+
remove('eventsdb', 'event_segments', 'session_id=? AND segment_id=?', args);
|
|
129
|
+
for (const name of ['trajectory_records', 'state_frames', 'history_scopes'])
|
|
130
|
+
remove('historydb', name, 'session_id=? AND segment_id=?', args);
|
|
131
|
+
if (table(db, 'epochsdb', 'runtime_epochs')) {
|
|
132
|
+
for (const name of ['runtime_plugin_outcomes', 'runtime_plugin_states']) {
|
|
133
|
+
remove('epochsdb', name, 'epoch_seq IN (SELECT epoch_seq FROM epochsdb.runtime_epochs WHERE session_id=? AND segment_id=?)', args);
|
|
134
|
+
}
|
|
135
|
+
remove('epochsdb', 'runtime_epochs', 'session_id=? AND segment_id=?', args);
|
|
136
|
+
}
|
|
137
|
+
remove('epochsdb', 'runtime_plugin_progress', 'session_id=? AND segment_id=?', args);
|
|
138
|
+
}
|
|
139
|
+
if (table(db, 'eventsdb', 'play_sessions')) {
|
|
140
|
+
for (const sessionId of new Set(selected.map(scope => scope.sessionId))) {
|
|
141
|
+
remove('eventsdb', 'play_sessions', 'session_id=? AND NOT EXISTS (SELECT 1 FROM eventsdb.event_segments s WHERE s.session_id=play_sessions.session_id)', [sessionId]);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
db.exec('COMMIT');
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
try {
|
|
148
|
+
db.exec('ROLLBACK');
|
|
149
|
+
}
|
|
150
|
+
catch { }
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
db.close();
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
compact(paths) {
|
|
158
|
+
const db = connection(paths);
|
|
159
|
+
try {
|
|
160
|
+
for (const row of db.prepare('PRAGMA database_list').all()) {
|
|
161
|
+
if (!['eventsdb', 'historydb', 'epochsdb'].includes(row.name))
|
|
162
|
+
continue;
|
|
163
|
+
db.exec(`PRAGMA ${row.name}.wal_checkpoint(TRUNCATE)`);
|
|
164
|
+
db.exec(`VACUUM ${row.name}`);
|
|
165
|
+
db.exec(`PRAGMA ${row.name}.wal_checkpoint(TRUNCATE)`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
db.close();
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
close() { if (!closed) {
|
|
173
|
+
closed = true;
|
|
174
|
+
lease.release();
|
|
175
|
+
} },
|
|
176
|
+
};
|
|
177
|
+
}
|
|
@@ -579,7 +579,7 @@ export class SqliteRuntimeInputJournal {
|
|
|
579
579
|
pluginProgress,
|
|
580
580
|
pluginRecords,
|
|
581
581
|
states,
|
|
582
|
-
nextEpochSeq: numberValue(this.db.prepare(
|
|
582
|
+
nextEpochSeq: numberValue(this.db.prepare("SELECT MAX(seq) AS seq FROM (SELECT seq FROM sqlite_sequence WHERE name='runtime_epochs' UNION ALL SELECT MAX(epoch_seq) FROM runtime_epochs)").get()?.seq) + 1,
|
|
583
583
|
};
|
|
584
584
|
}
|
|
585
585
|
findByIdentity(scope, sourceId, sourceKey) {
|
|
@@ -280,8 +280,8 @@ export class SqliteStateHistoryRepository {
|
|
|
280
280
|
scopes: this.db.prepare(`SELECT * FROM history_scopes${where}`).all(...params).map((row) => this.scopeFromRow(row)),
|
|
281
281
|
stateFrames,
|
|
282
282
|
records,
|
|
283
|
-
nextFrameSeq: Number(this.db.prepare(
|
|
284
|
-
nextRecordSeq: Number(this.db.prepare(
|
|
283
|
+
nextFrameSeq: Number(this.db.prepare("SELECT MAX(seq) AS seq FROM (SELECT seq FROM sqlite_sequence WHERE name='state_frames' UNION ALL SELECT MAX(frame_seq) FROM state_frames)").get()?.seq ?? 0) + 1,
|
|
284
|
+
nextRecordSeq: Number(this.db.prepare("SELECT MAX(seq) AS seq FROM (SELECT seq FROM sqlite_sequence WHERE name='trajectory_records' UNION ALL SELECT MAX(record_seq) FROM trajectory_records)").get()?.seq ?? 0) + 1,
|
|
285
285
|
};
|
|
286
286
|
}
|
|
287
287
|
rememberStateFrame(frame) {
|