@myclaw163/game-agent-runtime 0.1.2 → 0.1.4

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.
@@ -1,3 +1,4 @@
1
+ import { acquireSqliteConnection, sqliteTransaction } from '../../persistence/sqlite-connection.js';
1
2
  import { createRequire } from 'module';
2
3
  import { mkdirSync } from 'fs';
3
4
  import { dirname } from 'path';
@@ -39,19 +40,30 @@ function parseJson(value) {
39
40
  }
40
41
  }
41
42
  export class SqliteStateHistoryRepository {
43
+ references;
42
44
  db;
45
+ release;
43
46
  recentStateFrames = new Map();
44
47
  static isSupported() {
45
48
  return loadNodeSqlite() !== null;
46
49
  }
47
- constructor(path) {
50
+ constructor(path, references = {}) {
51
+ this.references = references;
48
52
  const sqlite = loadNodeSqlite();
49
53
  if (!sqlite)
50
54
  throw new Error('node:sqlite is unavailable in this Node.js runtime');
51
55
  if (path !== ':memory:')
52
56
  mkdirSync(dirname(path), { recursive: true });
53
- this.db = new sqlite.DatabaseSync(path);
54
- this.initialize();
57
+ const lease = acquireSqliteConnection(path);
58
+ this.db = lease.db;
59
+ this.release = lease.release;
60
+ try {
61
+ this.initialize();
62
+ }
63
+ catch (error) {
64
+ this.release();
65
+ throw error;
66
+ }
55
67
  }
56
68
  openScope(scope, openedAtMs = Date.now(), historyComplete = true) {
57
69
  return this.transaction(() => {
@@ -95,13 +107,16 @@ export class SqliteStateHistoryRepository {
95
107
  return row ? this.scopeFromRow(row) : null;
96
108
  }
97
109
  appendStateFrame(frame) {
110
+ const serialized = JSON.stringify(frame.state);
111
+ const reference = frame.epochSeq !== undefined
112
+ && this.references.serializedState?.(frame.epochSeq, frame.scope) === serialized ? frame.epochSeq : null;
98
113
  const result = this.db.prepare(`
99
114
  INSERT OR IGNORE INTO state_frames(
100
115
  adapter_id, account_id, session_id, segment_id,
101
116
  epoch_seq, source_id, connection_id, source_key, source_seq, backend_tick,
102
- observed_at_ms, received_at_ms, state_json
103
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
104
- `).run(frame.scope.adapterId, frame.scope.accountId, frame.scope.sessionId, frame.scope.segmentId, frame.epochSeq ?? null, frame.sourceId ?? null, frame.connectionId, frame.sourceKey, sourceSeqValue(frame.sourceSeq), frame.backendTick ?? null, frame.observedAtMs ?? null, frame.receivedAtMs, JSON.stringify(frame.state));
117
+ observed_at_ms, received_at_ms, state_json, state_ref_epoch_seq
118
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
119
+ `).run(frame.scope.adapterId, frame.scope.accountId, frame.scope.sessionId, frame.scope.segmentId, frame.epochSeq ?? null, frame.sourceId ?? null, frame.connectionId, frame.sourceKey, sourceSeqValue(frame.sourceSeq), frame.backendTick ?? null, frame.observedAtMs ?? null, frame.receivedAtMs, reference === null ? serialized : 'null', reference);
105
120
  const row = this.db.prepare(`
106
121
  SELECT * FROM state_frames
107
122
  WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
@@ -265,7 +280,7 @@ export class SqliteStateHistoryRepository {
265
280
  }
266
281
  close() {
267
282
  this.recentStateFrames.clear();
268
- this.db.close();
283
+ this.release();
269
284
  }
270
285
  /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
271
286
  snapshot(scope) {
@@ -280,8 +295,8 @@ export class SqliteStateHistoryRepository {
280
295
  scopes: this.db.prepare(`SELECT * FROM history_scopes${where}`).all(...params).map((row) => this.scopeFromRow(row)),
281
296
  stateFrames,
282
297
  records,
283
- nextFrameSeq: Number(this.db.prepare('SELECT MAX(frame_seq) AS seq FROM state_frames').get()?.seq ?? 0) + 1,
284
- nextRecordSeq: Number(this.db.prepare('SELECT MAX(record_seq) AS seq FROM trajectory_records').get()?.seq ?? 0) + 1,
298
+ 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,
299
+ 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
300
  };
286
301
  }
287
302
  rememberStateFrame(frame) {
@@ -339,7 +354,7 @@ export class SqliteStateHistoryRepository {
339
354
  this.db.exec('PRAGMA journal_mode = WAL');
340
355
  this.db.exec('PRAGMA busy_timeout = 1000');
341
356
  this.db.exec(`
342
- CREATE TABLE IF NOT EXISTS schema_migrations(
357
+ CREATE TABLE IF NOT EXISTS history_schema_migrations(
343
358
  version INTEGER PRIMARY KEY,
344
359
  applied_at_ms INTEGER NOT NULL
345
360
  );
@@ -425,14 +440,14 @@ export class SqliteStateHistoryRepository {
425
440
  CREATE INDEX IF NOT EXISTS state_frames_scope_tick
426
441
  ON state_frames(adapter_id, account_id, session_id, segment_id, backend_tick, frame_seq);
427
442
 
428
- INSERT OR IGNORE INTO schema_migrations(version, applied_at_ms)
443
+ INSERT OR IGNORE INTO history_schema_migrations(version, applied_at_ms)
429
444
  VALUES (1, unixepoch('subsec') * 1000);
430
445
 
431
- INSERT OR IGNORE INTO schema_migrations(version, applied_at_ms)
446
+ INSERT OR IGNORE INTO history_schema_migrations(version, applied_at_ms)
432
447
  VALUES (2, unixepoch('subsec') * 1000);
433
448
  `);
434
449
  const epochMigration = this.db.prepare(`
435
- SELECT version FROM schema_migrations WHERE version = 3
450
+ SELECT version FROM history_schema_migrations WHERE version = 3
436
451
  `).get();
437
452
  if (!epochMigration) {
438
453
  this.transaction(() => {
@@ -447,25 +462,17 @@ export class SqliteStateHistoryRepository {
447
462
  ON state_frames(adapter_id, account_id, session_id, segment_id, epoch_seq)
448
463
  `);
449
464
  this.db.prepare(`
450
- INSERT INTO schema_migrations(version, applied_at_ms) VALUES (3, ?)
465
+ INSERT INTO history_schema_migrations(version, applied_at_ms) VALUES (3, ?)
451
466
  `).run(Date.now());
452
467
  });
453
468
  }
469
+ if (!this.db.prepare('PRAGMA table_info(state_frames)').all().some(row => row.name === 'state_ref_epoch_seq')) {
470
+ this.db.exec('ALTER TABLE state_frames ADD COLUMN state_ref_epoch_seq INTEGER');
471
+ }
472
+ this.db.prepare('INSERT OR IGNORE INTO history_schema_migrations(version, applied_at_ms) VALUES (4, ?)').run(Date.now());
454
473
  }
455
474
  transaction(run) {
456
- this.db.exec('BEGIN IMMEDIATE');
457
- try {
458
- const value = run();
459
- this.db.exec('COMMIT');
460
- return value;
461
- }
462
- catch (error) {
463
- try {
464
- this.db.exec('ROLLBACK');
465
- }
466
- catch { }
467
- throw error;
468
- }
475
+ return sqliteTransaction(this.db, run);
469
476
  }
470
477
  scopeFromRow(row) {
471
478
  return {
@@ -529,7 +536,16 @@ export class SqliteStateHistoryRepository {
529
536
  return cloneCanonical(record);
530
537
  }
531
538
  stateFrameFromRow(row) {
532
- const state = parseJson(row.state_json);
539
+ let serialized = row.state_json;
540
+ if (row.state_ref_epoch_seq !== null && row.state_ref_epoch_seq !== undefined) {
541
+ serialized = this.references.serializedState?.(numberValue(row.state_ref_epoch_seq), {
542
+ adapterId: String(row.adapter_id), accountId: String(row.account_id),
543
+ sessionId: String(row.session_id), segmentId: String(row.segment_id),
544
+ });
545
+ if (typeof serialized !== 'string')
546
+ throw new Error(`State reference unavailable at frame_seq ${String(row.frame_seq)}`);
547
+ }
548
+ const state = parseJson(serialized);
533
549
  if (!state || typeof state !== 'object' || Array.isArray(state)) {
534
550
  throw new Error(`Invalid State frame JSON at frame_seq ${String(row.frame_seq)}`);
535
551
  }
@@ -1128,6 +1128,9 @@ export class StrategyHost {
1128
1128
  || transition.type === 'failed'
1129
1129
  || transition.type === 'cancelled'
1130
1130
  || transition.type === 'replaced') {
1131
+ // The outgoing activation owns cancellation; mark its pending decisions
1132
+ // before retiring Workers so an expected interruption is not a pool failure.
1133
+ this.interruptDecisions(transition.activationId, `behavior_${transition.type}`);
1131
1134
  this.controls.get(transition.activationId)?.release(`behavior_${transition.type}:${transition.reason}`);
1132
1135
  this.controls.delete(transition.activationId);
1133
1136
  const runtime = this.runtimes.get(transition.activationId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/game-agent-runtime",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "Game-neutral local agent runtime",
6
6
  "engines": {