@myclaw163/clawclaw-cli 0.9.2 → 0.10.2

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.
Files changed (224) hide show
  1. package/QUICKSTART.md +1 -1
  2. package/QUICKSTART_OTHER.md +13 -12
  3. package/README.md +7 -8
  4. package/bin/clawclaw-channel.mjs +2 -2
  5. package/bin/clawclaw-cli.mjs +2 -2
  6. package/docs/configuration.md +27 -101
  7. package/docs/custom-modules/README.md +23 -35
  8. package/docs/custom-modules/api-reference.md +95 -273
  9. package/docs/custom-modules/behavior.md +94 -78
  10. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  11. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  12. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  13. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  14. package/docs/custom-modules/perception.md +42 -603
  15. package/docs/custom-modules/skill.md +12 -10
  16. package/docs/desktop-event-push.md +3 -3
  17. package/docs/runtime/README.md +16 -17
  18. package/docs/runtime/agent-notifications.md +42 -12
  19. package/docs/runtime/behavior-runtime.md +47 -46
  20. package/docs/runtime/components-and-boundaries.md +70 -28
  21. package/docs/runtime/events-and-state.md +41 -18
  22. package/docs/runtime/framework-package.md +73 -0
  23. package/docs/runtime/official-perception-modules.md +5 -5
  24. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  25. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  26. package/docs/user-guide/README.md +10 -7
  27. package/docs/user-guide/api-reference.md +81 -164
  28. package/docs/user-guide/behavior.md +84 -68
  29. package/docs/user-guide/installation.md +7 -7
  30. package/docs/user-guide/perception.md +42 -586
  31. package/docs/user-guide/skill.md +12 -10
  32. package/package.json +24 -9
  33. package/scripts/check-framework-boundaries.mjs +27 -0
  34. package/scripts/check-skill-command-surface.mjs +20 -23
  35. package/scripts/enable_ccl_permissions.cjs +4 -0
  36. package/scripts/install-local-runtime.mjs +35 -0
  37. package/scripts/postinstall.mjs +1 -1
  38. package/scripts/qa-install.mjs +105 -0
  39. package/scripts/sync-bundled-skill.mjs +35 -28
  40. package/skills/clawclaw/SKILL.md +53 -57
  41. package/skills/clawclaw/references/BEHAVIORS.md +43 -83
  42. package/skills/clawclaw/references/CHANNELS.md +2 -2
  43. package/skills/clawclaw/references/COMMANDS.md +62 -103
  44. package/skills/clawclaw/references/HUB.md +2 -2
  45. package/skills/clawclaw/references/STREAM.md +8 -8
  46. package/skills/clawclaw/references/TACTICS.md +1 -1
  47. package/skills/clawclaw-creator/SKILL.md +82 -0
  48. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
  49. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
  50. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
  51. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
  52. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
  53. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
  54. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
  55. package/src/channel/claude-channel-ipc-server.ts +1 -0
  56. package/src/cli.ts +4 -2
  57. package/src/commands/behavior.ts +26 -10
  58. package/src/commands/capability.ts +17 -14
  59. package/src/commands/load.ts +5 -3
  60. package/src/commands/perception.ts +5 -0
  61. package/src/commands/skill.ts +34 -29
  62. package/src/commands/strategy.ts +2 -0
  63. package/src/commands/upgrade.ts +2 -2
  64. package/src/lib/agent-workspace-skills.ts +20 -13
  65. package/src/lib/capability-cloud-sync.ts +2 -1
  66. package/src/lib/capability-discovery.ts +2 -1
  67. package/src/lib/capability-load-diagnostics.ts +3 -3
  68. package/src/lib/capability-workspace.ts +2 -1
  69. package/src/lib/game-client.ts +7 -1
  70. package/src/lib/package-skills.ts +4 -0
  71. package/src/lib/perception-config.ts +18 -6
  72. package/src/lib/runtime-cadence-config.ts +16 -0
  73. package/src/lib/skill-host.ts +1 -1
  74. package/src/lib/workspace-runtime-lock.ts +3 -46
  75. package/src/pipeline/canonical-event-presentation.ts +23 -124
  76. package/src/pipeline/event-format.ts +12 -21
  77. package/src/pipeline/event-hints.ts +6 -6
  78. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  79. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  80. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  81. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  82. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  83. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  84. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  85. package/src/runtime/clawclaw/owner.ts +47 -9
  86. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  87. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  88. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  89. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  90. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  91. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  92. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  93. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  94. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  95. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  96. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  97. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  98. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  99. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  100. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  101. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  102. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  103. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  104. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  105. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  106. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  107. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  108. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  109. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
  110. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
  111. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  112. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  113. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  114. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  115. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  116. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  117. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  118. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  120. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
  121. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  122. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  123. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
  124. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  125. package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
  126. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  127. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  128. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  129. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  130. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  131. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  132. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  133. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  134. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  135. package/src/runtime/clawclaw/runtime.ts +8 -0
  136. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  137. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  138. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  139. package/src/runtime/framework/action-diagnostics.ts +3 -83
  140. package/src/runtime/framework/capability-registry.ts +2 -395
  141. package/src/runtime/framework/contracts.ts +2 -144
  142. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  143. package/src/runtime/framework/control/domain-set.ts +2 -81
  144. package/src/runtime/framework/control/index.ts +1 -3
  145. package/src/runtime/framework/control/types.ts +2 -191
  146. package/src/runtime/framework/control-coordinator.ts +2 -11
  147. package/src/runtime/framework/events/event-catalog.ts +2 -74
  148. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  149. package/src/runtime/framework/events/event-ingress.ts +2 -99
  150. package/src/runtime/framework/events/event-repository.ts +2 -82
  151. package/src/runtime/framework/events/index.ts +2 -7
  152. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  153. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  154. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  155. package/src/runtime/framework/events/test-helpers.ts +1 -1
  156. package/src/runtime/framework/events/types.ts +2 -312
  157. package/src/runtime/framework/index.ts +3 -7
  158. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  159. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  160. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  161. package/src/runtime/framework/mailbox/identity.ts +2 -38
  162. package/src/runtime/framework/mailbox/index.ts +1 -7
  163. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  164. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  165. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  166. package/src/runtime/framework/mailbox/types.ts +2 -145
  167. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  168. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  169. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  170. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  171. package/src/runtime/framework/participation-manager.ts +2 -253
  172. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  173. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  174. package/src/runtime/framework/plugins/contracts.ts +2 -396
  175. package/src/runtime/framework/plugins/index.ts +1 -4
  176. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  177. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  178. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  179. package/src/runtime/framework/runtime.ts +5 -1843
  180. package/src/runtime/framework/serial-task-queue.ts +2 -14
  181. package/src/runtime/framework/state/contracts.ts +2 -49
  182. package/src/runtime/framework/state/current-state-store.ts +2 -184
  183. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  184. package/src/runtime/framework/state/freshness.ts +2 -72
  185. package/src/runtime/framework/state/history/contracts.ts +2 -158
  186. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  187. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  188. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  189. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  190. package/src/runtime/framework/state/index.ts +1 -13
  191. package/src/runtime/framework/state/state-ingress.ts +2 -95
  192. package/src/runtime/framework/state/state-provider.ts +2 -62
  193. package/src/runtime/framework/state/types.ts +2 -155
  194. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  195. package/src/runtime/game-sync-ingress-worker.ts +7 -1
  196. package/src/runtime/game-sync-protocol.ts +64 -4
  197. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  198. package/src/runtime/mailbox-host-relay.ts +1 -326
  199. package/src/runtime/observability/detail-capture.ts +4 -108
  200. package/src/runtime/observability/process-timing.ts +2 -59
  201. package/src/runtime/observability/recorder.ts +2 -238
  202. package/src/runtime/observability/redaction.ts +2 -181
  203. package/src/runtime/observability/reporter.ts +2 -154
  204. package/src/runtime/observability/sinks.ts +2 -135
  205. package/src/runtime/observability/types.ts +2 -92
  206. package/src/runtime/owner-control.ts +45 -320
  207. package/src/runtime/parent-process-watch.ts +1 -51
  208. package/src/runtime/process-identity.ts +1 -72
  209. package/src/runtime/threaded-ws-client.ts +11 -2
  210. package/src/runtime/ws-client.ts +6 -0
  211. package/src/sdk/behavior-plugin/index.ts +9 -3
  212. package/src/sdk/index.ts +40 -2
  213. package/src/sdk/module-input/index.ts +5 -0
  214. package/src/sdk/perception-plugin/index.ts +3 -1
  215. package/src/sdk/perception-plugin/module.ts +12 -2
  216. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  217. package/src/sdk/perception-plugin/reminder.ts +2 -1
  218. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  219. package/src/sdk/strategy-memory.ts +1 -12
  220. package/src/sdk/strategy-plugin/index.ts +36 -0
  221. package/src/sdk/trigger-plugin/index.ts +1 -0
  222. package/docs/custom-modules/trigger.md +0 -295
  223. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
  224. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
@@ -1,648 +1,2 @@
1
- import { createRequire } from 'module';
2
- import { mkdirSync } from 'fs';
3
- import { dirname } from 'path';
4
- import { loadNodeSqliteModule } from '../../load-node-sqlite.js';
5
- import { cloneCanonical, runtimeScopeKey, type RuntimeScope } from '../types.js';
6
- import type {
7
- AppendHistoryResult,
8
- AppendStateFrameResult,
9
- HistoryQuery,
10
- HistoryQueryResult,
11
- HistoryScopeRecord,
12
- StateFrameQuery,
13
- StateFrameQueryResult,
14
- StateFrameRecord,
15
- StateHistoryRepository,
16
- StateHistorySnapshot,
17
- StoredStateFrame,
18
- TrajectoryRecord,
19
- TrajectoryRecordKind,
20
- TrajectorySubjectKind,
21
- } from './contracts.js';
22
-
23
- interface StatementLike {
24
- run(...params: unknown[]): { changes: number | bigint };
25
- get(...params: unknown[]): Record<string, unknown> | undefined;
26
- all(...params: unknown[]): Array<Record<string, unknown>>;
27
- }
28
-
29
- interface DatabaseLike {
30
- exec(sql: string): void;
31
- prepare(sql: string): StatementLike;
32
- close(): void;
33
- }
34
-
35
- interface SqliteModuleLike {
36
- DatabaseSync: new (path: string) => DatabaseLike;
37
- }
38
-
39
- const localRequire = createRequire(import.meta.url);
40
- let sqliteModule: SqliteModuleLike | null | undefined;
41
-
42
- function loadNodeSqlite(): SqliteModuleLike | null {
43
- if (sqliteModule !== undefined) return sqliteModule;
44
- try {
45
- const loaded = loadNodeSqliteModule<Partial<SqliteModuleLike>>(localRequire);
46
- sqliteModule = typeof loaded.DatabaseSync === 'function' ? loaded as SqliteModuleLike : null;
47
- } catch {
48
- sqliteModule = null;
49
- }
50
- return sqliteModule;
51
- }
52
-
53
- function numberValue(value: unknown): number {
54
- if (typeof value === 'bigint') return Number(value);
55
- return typeof value === 'number' ? value : Number(value ?? 0);
56
- }
57
-
58
- function nullableJson(value: unknown): string | null {
59
- return value === undefined ? null : JSON.stringify(value);
60
- }
61
-
62
- function sourceSeqValue(value: number | string | undefined): string | null {
63
- return value === undefined ? null : JSON.stringify(value);
64
- }
65
-
66
- function parseJson(value: unknown): unknown {
67
- if (typeof value !== 'string') return undefined;
68
- try { return JSON.parse(value); } catch { return undefined; }
69
- }
70
-
71
- export class SqliteStateHistoryRepository<
72
- TPosition = unknown,
73
- TState = Record<string, unknown>,
74
- > implements StateHistoryRepository<TPosition, TState> {
75
- private readonly db: DatabaseLike;
76
- private readonly recentStateFrames = new Map<string, StoredStateFrame<TState>[]>();
77
-
78
- static isSupported(): boolean {
79
- return loadNodeSqlite() !== null;
80
- }
81
-
82
- constructor(path: string) {
83
- const sqlite = loadNodeSqlite();
84
- if (!sqlite) throw new Error('node:sqlite is unavailable in this Node.js runtime');
85
- if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
86
- this.db = new sqlite.DatabaseSync(path);
87
- this.initialize();
88
- }
89
-
90
- openScope(scope: RuntimeScope, openedAtMs = Date.now(), historyComplete = true): HistoryScopeRecord {
91
- return this.transaction(() => {
92
- this.db.prepare(`
93
- UPDATE history_scopes
94
- SET status = 'SEALED', sealed_at_ms = ?
95
- WHERE adapter_id = ? AND account_id = ? AND status = 'OPEN'
96
- AND NOT (session_id = ? AND segment_id = ?)
97
- `).run(openedAtMs, scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId);
98
- this.db.prepare(`
99
- INSERT INTO history_scopes(
100
- adapter_id, account_id, session_id, segment_id, segment_seq,
101
- status, opened_at_ms, sealed_at_ms, history_complete, history_revision
102
- ) VALUES (?, ?, ?, ?, ?, 'OPEN', ?, NULL, ?, 1)
103
- ON CONFLICT(adapter_id, account_id, session_id, segment_id) DO UPDATE SET
104
- status = 'OPEN',
105
- sealed_at_ms = NULL,
106
- segment_seq = excluded.segment_seq,
107
- history_complete = MIN(history_scopes.history_complete, excluded.history_complete)
108
- `).run(
109
- scope.adapterId,
110
- scope.accountId,
111
- scope.sessionId,
112
- scope.segmentId,
113
- scope.segmentSeq ?? null,
114
- openedAtMs,
115
- historyComplete ? 1 : 0,
116
- );
117
- return this.getScope(scope)!;
118
- });
119
- }
120
-
121
- sealScope(scope: RuntimeScope, sealedAtMs = Date.now()): void {
122
- this.db.prepare(`
123
- UPDATE history_scopes SET status = 'SEALED', sealed_at_ms = ?
124
- WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
125
- `).run(sealedAtMs, scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId);
126
- }
127
-
128
- markScopeIncomplete(scope: RuntimeScope): void {
129
- this.db.prepare(`
130
- UPDATE history_scopes SET history_complete = 0
131
- WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
132
- `).run(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId);
133
- }
134
-
135
- getScope(scope: RuntimeScope): HistoryScopeRecord | null {
136
- const row = this.db.prepare(`
137
- SELECT * FROM history_scopes
138
- WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
139
- `).get(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId);
140
- return row ? this.scopeFromRow(row) : null;
141
- }
142
-
143
- appendStateFrame(frame: StateFrameRecord<TState>): AppendStateFrameResult<TState> {
144
- const result = this.db.prepare(`
145
- INSERT OR IGNORE INTO state_frames(
146
- adapter_id, account_id, session_id, segment_id,
147
- epoch_seq, source_id, connection_id, source_key, source_seq, backend_tick,
148
- observed_at_ms, received_at_ms, state_json
149
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
150
- `).run(
151
- frame.scope.adapterId,
152
- frame.scope.accountId,
153
- frame.scope.sessionId,
154
- frame.scope.segmentId,
155
- frame.epochSeq ?? null,
156
- frame.sourceId ?? null,
157
- frame.connectionId,
158
- frame.sourceKey,
159
- sourceSeqValue(frame.sourceSeq),
160
- frame.backendTick ?? null,
161
- frame.observedAtMs ?? null,
162
- frame.receivedAtMs,
163
- JSON.stringify(frame.state),
164
- );
165
- const row = this.db.prepare(`
166
- SELECT * FROM state_frames
167
- WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
168
- AND source_key = ?
169
- `).get(
170
- frame.scope.adapterId,
171
- frame.scope.accountId,
172
- frame.scope.sessionId,
173
- frame.scope.segmentId,
174
- frame.sourceKey,
175
- );
176
- if (!row) throw new Error(`State frame was not persisted: ${frame.sourceKey}`);
177
- const stored = this.stateFrameFromRow(row);
178
- this.rememberStateFrame(stored);
179
- return {
180
- inserted: numberValue(result.changes) === 1,
181
- frame: cloneCanonical(stored),
182
- };
183
- }
184
-
185
- queryStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState> {
186
- const cached = this.queryRecentStateFrames(query);
187
- if (cached) return cached;
188
-
189
- const order = query.order ?? 'asc';
190
- const limit = Math.max(1, Math.min(query.limit ?? 100, 10_000));
191
- const where = [
192
- 'adapter_id = ?',
193
- 'account_id = ?',
194
- 'session_id = ?',
195
- 'segment_id = ?',
196
- ];
197
- const params: unknown[] = [
198
- query.scope.adapterId,
199
- query.scope.accountId,
200
- query.scope.sessionId,
201
- query.scope.segmentId,
202
- ];
203
- if (query.fromEpochSeq !== undefined) {
204
- where.push('epoch_seq >= ?');
205
- params.push(query.fromEpochSeq);
206
- }
207
- if (query.toEpochSeq !== undefined) {
208
- where.push('epoch_seq <= ?');
209
- params.push(query.toEpochSeq);
210
- }
211
- if (query.afterFrameSeq !== undefined) {
212
- where.push('frame_seq > ?');
213
- params.push(query.afterFrameSeq);
214
- }
215
- if (query.beforeFrameSeq !== undefined) {
216
- where.push('frame_seq < ?');
217
- params.push(query.beforeFrameSeq);
218
- }
219
- if (query.fromBackendTick !== undefined) {
220
- where.push('backend_tick >= ?');
221
- params.push(query.fromBackendTick);
222
- }
223
- if (query.toBackendTick !== undefined) {
224
- where.push('backend_tick <= ?');
225
- params.push(query.toBackendTick);
226
- }
227
- const rows = this.db.prepare(`
228
- SELECT * FROM state_frames
229
- WHERE ${where.join(' AND ')}
230
- ORDER BY frame_seq ${order === 'asc' ? 'ASC' : 'DESC'}
231
- LIMIT ?
232
- `).all(...params, limit + 1);
233
- const hasMore = rows.length > limit;
234
- const frames = rows.slice(0, limit).map((row) => this.stateFrameFromRow(row));
235
- return {
236
- frames,
237
- page: {
238
- order,
239
- limit,
240
- hasMore,
241
- firstFrameSeq: frames[0]?.frameSeq ?? null,
242
- lastFrameSeq: frames.at(-1)?.frameSeq ?? null,
243
- },
244
- };
245
- }
246
-
247
- latestStateFrame(scope: RuntimeScope): StoredStateFrame<TState> | null {
248
- const cached = this.recentStateFrames.get(runtimeScopeKey(scope))?.at(-1);
249
- if (cached) return cloneCanonical(cached);
250
- const stored = this.queryStateFrames({ scope, order: 'desc', limit: 1 }).frames[0] ?? null;
251
- if (stored) this.rememberStateFrame(stored);
252
- return stored ? cloneCanonical(stored) : null;
253
- }
254
-
255
- append(records: TrajectoryRecord<TPosition>[]): AppendHistoryResult {
256
- if (records.length === 0) return { inserted: 0, duplicates: 0 };
257
- return this.transaction(() => {
258
- const statement = this.db.prepare(`
259
- INSERT OR IGNORE INTO trajectory_records(
260
- record_id, adapter_id, account_id, session_id, segment_id,
261
- connection_id, subject_id, subject_kind, record_kind,
262
- source_type, source_key, source_seq, backend_tick,
263
- observed_at_ms, received_at_ms, space_id, area_id,
264
- position_json, attributes_json
265
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
266
- `);
267
- let inserted = 0;
268
- for (const record of records) {
269
- const result = statement.run(
270
- record.recordId,
271
- record.scope.adapterId,
272
- record.scope.accountId,
273
- record.scope.sessionId,
274
- record.scope.segmentId,
275
- record.connectionId ?? null,
276
- record.subjectId,
277
- record.subjectKind,
278
- record.kind,
279
- record.sourceType,
280
- record.sourceKey,
281
- sourceSeqValue(record.sourceSeq),
282
- record.backendTick ?? null,
283
- record.observedAtMs ?? null,
284
- record.receivedAtMs,
285
- record.spaceId ?? null,
286
- record.areaId ?? null,
287
- nullableJson(record.position),
288
- nullableJson(record.attributes),
289
- );
290
- inserted += numberValue(result.changes);
291
- }
292
- return { inserted, duplicates: records.length - inserted };
293
- });
294
- }
295
-
296
- query(query: HistoryQuery): HistoryQueryResult<TPosition> {
297
- const order = query.order ?? 'asc';
298
- const limit = Math.max(1, Math.min(query.limit ?? 100, 1000));
299
- const where = [
300
- 'adapter_id = ?',
301
- 'account_id = ?',
302
- 'session_id = ?',
303
- 'segment_id = ?',
304
- ];
305
- const params: unknown[] = [
306
- query.scope.adapterId,
307
- query.scope.accountId,
308
- query.scope.sessionId,
309
- query.scope.segmentId,
310
- ];
311
- if (query.subjectIds?.length) {
312
- where.push(`subject_id IN (${query.subjectIds.map(() => '?').join(', ')})`);
313
- params.push(...query.subjectIds);
314
- }
315
- if (query.kinds?.length) {
316
- where.push(`record_kind IN (${query.kinds.map(() => '?').join(', ')})`);
317
- params.push(...query.kinds);
318
- }
319
- if (query.afterRecordSeq !== undefined) {
320
- where.push('record_seq > ?');
321
- params.push(query.afterRecordSeq);
322
- }
323
- if (query.beforeRecordSeq !== undefined) {
324
- where.push('record_seq < ?');
325
- params.push(query.beforeRecordSeq);
326
- }
327
- const rows = this.db.prepare(`
328
- SELECT * FROM trajectory_records
329
- WHERE ${where.join(' AND ')}
330
- ORDER BY record_seq ${order === 'asc' ? 'ASC' : 'DESC'}
331
- LIMIT ?
332
- `).all(...params, limit + 1);
333
- const hasMore = rows.length > limit;
334
- const records = rows.slice(0, limit).map((row) => this.recordFromRow(row));
335
- return {
336
- scope: this.getScope(query.scope),
337
- records,
338
- page: {
339
- order,
340
- limit,
341
- hasMore,
342
- firstRecordSeq: records[0]?.recordSeq ?? null,
343
- lastRecordSeq: records.at(-1)?.recordSeq ?? null,
344
- },
345
- };
346
- }
347
-
348
- journalMode(): string | null {
349
- const row = this.db.prepare('PRAGMA journal_mode').get();
350
- const value = row?.journal_mode;
351
- return typeof value === 'string' ? value.toLowerCase() : null;
352
- }
353
-
354
- close(): void {
355
- this.recentStateFrames.clear();
356
- this.db.close();
357
- }
358
-
359
- /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
360
- snapshot(scope?: RuntimeScope | null): StateHistorySnapshot<TPosition, TState> {
361
- const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
362
- : ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
363
- const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
364
- const stateFrames = this.db.prepare(`SELECT * FROM state_frames${where} ORDER BY frame_seq ASC`)
365
- .all(...params).map((row) => this.stateFrameFromRow(row));
366
- const records = this.db.prepare(`SELECT * FROM trajectory_records${where} ORDER BY record_seq ASC`)
367
- .all(...params).map((row) => this.recordFromRow(row));
368
- return {
369
- scopes: this.db.prepare(`SELECT * FROM history_scopes${where}`).all(...params).map((row) => this.scopeFromRow(row)),
370
- stateFrames,
371
- records,
372
- nextFrameSeq: Number(this.db.prepare('SELECT MAX(frame_seq) AS seq FROM state_frames').get()?.seq ?? 0) + 1,
373
- nextRecordSeq: Number(this.db.prepare('SELECT MAX(record_seq) AS seq FROM trajectory_records').get()?.seq ?? 0) + 1,
374
- };
375
- }
376
-
377
- private rememberStateFrame(frame: StoredStateFrame<TState>): void {
378
- const key = runtimeScopeKey(frame.scope);
379
- const recent = this.recentStateFrames.get(key) ?? [];
380
- const existing = recent.findIndex((candidate) => candidate.frameSeq === frame.frameSeq);
381
- if (existing >= 0) recent[existing] = cloneCanonical(frame);
382
- else recent.push(cloneCanonical(frame));
383
- recent.sort((a, b) => a.frameSeq - b.frameSeq);
384
- if (recent.length > 500) recent.splice(0, recent.length - 500);
385
- this.recentStateFrames.set(key, recent);
386
- }
387
-
388
- private queryRecentStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState> | null {
389
- const recent = this.recentStateFrames.get(runtimeScopeKey(query.scope));
390
- if (!recent || recent.length === 0) return null;
391
- const order = query.order ?? 'asc';
392
- const limit = Math.max(1, Math.min(query.limit ?? 100, 10_000));
393
- let selected = recent.filter((frame) => (
394
- (query.fromEpochSeq === undefined
395
- || (frame.epochSeq !== undefined && frame.epochSeq >= query.fromEpochSeq))
396
- && (query.toEpochSeq === undefined
397
- || (frame.epochSeq !== undefined && frame.epochSeq <= query.toEpochSeq))
398
- && (query.afterFrameSeq === undefined || frame.frameSeq > query.afterFrameSeq)
399
- && (query.beforeFrameSeq === undefined || frame.frameSeq < query.beforeFrameSeq)
400
- && (query.fromBackendTick === undefined
401
- || (frame.backendTick !== undefined && frame.backendTick >= query.fromBackendTick))
402
- && (query.toBackendTick === undefined
403
- || (frame.backendTick !== undefined && frame.backendTick <= query.toBackendTick))
404
- ));
405
- selected = selected.sort((a, b) => order === 'asc'
406
- ? a.frameSeq - b.frameSeq
407
- : b.frameSeq - a.frameSeq);
408
-
409
- const coversOldestPossibleMatch = query.afterFrameSeq !== undefined
410
- && query.afterFrameSeq >= recent[0].frameSeq - 1;
411
- const newestPageIsProvable = order === 'desc' && selected.length > limit;
412
- if (!coversOldestPossibleMatch && !newestPageIsProvable) return null;
413
-
414
- const hasMore = selected.length > limit;
415
- const frames = selected.slice(0, limit).map((frame) => cloneCanonical(frame));
416
- return {
417
- frames,
418
- page: {
419
- order,
420
- limit,
421
- hasMore,
422
- firstFrameSeq: frames[0]?.frameSeq ?? null,
423
- lastFrameSeq: frames.at(-1)?.frameSeq ?? null,
424
- },
425
- };
426
- }
427
-
428
- private initialize(): void {
429
- this.db.exec('PRAGMA foreign_keys = ON');
430
- this.db.exec('PRAGMA journal_mode = WAL');
431
- this.db.exec('PRAGMA busy_timeout = 1000');
432
- this.db.exec(`
433
- CREATE TABLE IF NOT EXISTS schema_migrations(
434
- version INTEGER PRIMARY KEY,
435
- applied_at_ms INTEGER NOT NULL
436
- );
437
-
438
- CREATE TABLE IF NOT EXISTS history_scopes(
439
- adapter_id TEXT NOT NULL,
440
- account_id TEXT NOT NULL,
441
- session_id TEXT NOT NULL,
442
- segment_id TEXT NOT NULL,
443
- segment_seq INTEGER,
444
- status TEXT NOT NULL CHECK(status IN ('OPEN', 'SEALED')),
445
- opened_at_ms INTEGER NOT NULL,
446
- sealed_at_ms INTEGER,
447
- history_complete INTEGER NOT NULL CHECK(history_complete IN (0, 1)),
448
- history_revision INTEGER NOT NULL DEFAULT 1 CHECK(history_revision > 0),
449
- PRIMARY KEY(adapter_id, account_id, session_id, segment_id)
450
- );
451
-
452
- CREATE UNIQUE INDEX IF NOT EXISTS one_open_history_scope_per_account
453
- ON history_scopes(adapter_id, account_id)
454
- WHERE status = 'OPEN';
455
-
456
- CREATE TABLE IF NOT EXISTS trajectory_records(
457
- record_seq INTEGER PRIMARY KEY AUTOINCREMENT,
458
- record_id TEXT NOT NULL UNIQUE,
459
- adapter_id TEXT NOT NULL,
460
- account_id TEXT NOT NULL,
461
- session_id TEXT NOT NULL,
462
- segment_id TEXT NOT NULL,
463
- connection_id TEXT,
464
- subject_id TEXT NOT NULL,
465
- subject_kind TEXT NOT NULL CHECK(subject_kind IN ('self', 'player', 'system')),
466
- record_kind TEXT NOT NULL CHECK(record_kind IN (
467
- 'position', 'visibility_gained', 'visibility_lost',
468
- 'stream_gap_started', 'stream_gap_ended',
469
- 'persistence_gap_started', 'persistence_gap_ended',
470
- 'retention_trimmed'
471
- )),
472
- source_type TEXT NOT NULL CHECK(source_type IN ('backend_state', 'canonical_event', 'local_lifecycle')),
473
- source_key TEXT NOT NULL,
474
- source_seq TEXT,
475
- backend_tick INTEGER,
476
- observed_at_ms INTEGER,
477
- received_at_ms INTEGER NOT NULL,
478
- space_id TEXT,
479
- area_id TEXT,
480
- position_json TEXT,
481
- attributes_json TEXT,
482
- UNIQUE(adapter_id, account_id, session_id, segment_id, source_key, subject_id, record_kind),
483
- FOREIGN KEY(adapter_id, account_id, session_id, segment_id)
484
- REFERENCES history_scopes(adapter_id, account_id, session_id, segment_id)
485
- );
486
-
487
- CREATE INDEX IF NOT EXISTS trajectory_scope_seq
488
- ON trajectory_records(adapter_id, account_id, session_id, segment_id, record_seq);
489
-
490
- CREATE INDEX IF NOT EXISTS trajectory_subject_seq
491
- ON trajectory_records(adapter_id, account_id, session_id, segment_id, subject_id, record_seq);
492
-
493
- CREATE TABLE IF NOT EXISTS state_frames(
494
- frame_seq INTEGER PRIMARY KEY AUTOINCREMENT,
495
- epoch_seq INTEGER,
496
- adapter_id TEXT NOT NULL,
497
- account_id TEXT NOT NULL,
498
- session_id TEXT NOT NULL,
499
- segment_id TEXT NOT NULL,
500
- source_id TEXT,
501
- connection_id TEXT NOT NULL,
502
- source_key TEXT NOT NULL,
503
- source_seq TEXT,
504
- backend_tick INTEGER,
505
- observed_at_ms INTEGER,
506
- received_at_ms INTEGER NOT NULL,
507
- state_json TEXT NOT NULL,
508
- UNIQUE(adapter_id, account_id, session_id, segment_id, source_key),
509
- FOREIGN KEY(adapter_id, account_id, session_id, segment_id)
510
- REFERENCES history_scopes(adapter_id, account_id, session_id, segment_id)
511
- );
512
-
513
- CREATE INDEX IF NOT EXISTS state_frames_scope_seq
514
- ON state_frames(adapter_id, account_id, session_id, segment_id, frame_seq);
515
-
516
- CREATE INDEX IF NOT EXISTS state_frames_scope_tick
517
- ON state_frames(adapter_id, account_id, session_id, segment_id, backend_tick, frame_seq);
518
-
519
- INSERT OR IGNORE INTO schema_migrations(version, applied_at_ms)
520
- VALUES (1, unixepoch('subsec') * 1000);
521
-
522
- INSERT OR IGNORE INTO schema_migrations(version, applied_at_ms)
523
- VALUES (2, unixepoch('subsec') * 1000);
524
- `);
525
-
526
- const epochMigration = this.db.prepare(`
527
- SELECT version FROM schema_migrations WHERE version = 3
528
- `).get();
529
- if (!epochMigration) {
530
- this.transaction(() => {
531
- const columns = new Set(
532
- this.db.prepare('PRAGMA table_info(state_frames)')
533
- .all()
534
- .map((row) => String(row.name)),
535
- );
536
- if (!columns.has('epoch_seq')) {
537
- this.db.exec('ALTER TABLE state_frames ADD COLUMN epoch_seq INTEGER');
538
- }
539
- this.db.exec(`
540
- CREATE INDEX IF NOT EXISTS state_frames_scope_epoch
541
- ON state_frames(adapter_id, account_id, session_id, segment_id, epoch_seq)
542
- `);
543
- this.db.prepare(`
544
- INSERT INTO schema_migrations(version, applied_at_ms) VALUES (3, ?)
545
- `).run(Date.now());
546
- });
547
- }
548
- }
549
-
550
- private transaction<T>(run: () => T): T {
551
- this.db.exec('BEGIN IMMEDIATE');
552
- try {
553
- const value = run();
554
- this.db.exec('COMMIT');
555
- return value;
556
- } catch (error) {
557
- try { this.db.exec('ROLLBACK'); } catch {}
558
- throw error;
559
- }
560
- }
561
-
562
- private scopeFromRow(row: Record<string, unknown>): HistoryScopeRecord {
563
- return {
564
- scope: {
565
- adapterId: String(row.adapter_id),
566
- accountId: String(row.account_id),
567
- sessionId: String(row.session_id),
568
- segmentId: String(row.segment_id),
569
- ...(row.segment_seq === null || row.segment_seq === undefined
570
- ? {}
571
- : { segmentSeq: numberValue(row.segment_seq) }),
572
- },
573
- status: row.status === 'SEALED' ? 'SEALED' : 'OPEN',
574
- openedAtMs: numberValue(row.opened_at_ms),
575
- sealedAtMs: row.sealed_at_ms === null || row.sealed_at_ms === undefined
576
- ? null
577
- : numberValue(row.sealed_at_ms),
578
- historyComplete: numberValue(row.history_complete) === 1,
579
- historyRevision: numberValue(row.history_revision),
580
- };
581
- }
582
-
583
- private recordFromRow(row: Record<string, unknown>): TrajectoryRecord<TPosition> & { recordSeq: number } {
584
- const record: TrajectoryRecord<TPosition> & { recordSeq: number } = {
585
- recordId: String(row.record_id),
586
- recordSeq: numberValue(row.record_seq),
587
- scope: {
588
- adapterId: String(row.adapter_id),
589
- accountId: String(row.account_id),
590
- sessionId: String(row.session_id),
591
- segmentId: String(row.segment_id),
592
- },
593
- subjectId: String(row.subject_id),
594
- subjectKind: row.subject_kind as TrajectorySubjectKind,
595
- kind: row.record_kind as TrajectoryRecordKind,
596
- sourceType: row.source_type as TrajectoryRecord['sourceType'],
597
- sourceKey: String(row.source_key),
598
- receivedAtMs: numberValue(row.received_at_ms),
599
- };
600
- if (typeof row.connection_id === 'string') record.connectionId = row.connection_id;
601
- if (typeof row.source_seq === 'string') {
602
- const sourceSeq = parseJson(row.source_seq);
603
- if (typeof sourceSeq === 'number' || typeof sourceSeq === 'string') record.sourceSeq = sourceSeq;
604
- }
605
- if (row.backend_tick !== null && row.backend_tick !== undefined) record.backendTick = numberValue(row.backend_tick);
606
- if (row.observed_at_ms !== null && row.observed_at_ms !== undefined) record.observedAtMs = numberValue(row.observed_at_ms);
607
- if (typeof row.space_id === 'string') record.spaceId = row.space_id;
608
- if (typeof row.area_id === 'string') record.areaId = row.area_id;
609
- const position = parseJson(row.position_json);
610
- if (position !== undefined) record.position = position as TPosition;
611
- const attributes = parseJson(row.attributes_json);
612
- if (attributes && typeof attributes === 'object' && !Array.isArray(attributes)) {
613
- record.attributes = attributes as Record<string, unknown>;
614
- }
615
- return cloneCanonical(record);
616
- }
617
-
618
- private stateFrameFromRow(row: Record<string, unknown>): StoredStateFrame<TState> {
619
- const state = parseJson(row.state_json);
620
- if (!state || typeof state !== 'object' || Array.isArray(state)) {
621
- throw new Error(`Invalid State frame JSON at frame_seq ${String(row.frame_seq)}`);
622
- }
623
- const frame: StoredStateFrame<TState> = {
624
- frameSeq: numberValue(row.frame_seq),
625
- ...(row.epoch_seq === null || row.epoch_seq === undefined
626
- ? {}
627
- : { epochSeq: numberValue(row.epoch_seq) }),
628
- scope: {
629
- adapterId: String(row.adapter_id),
630
- accountId: String(row.account_id),
631
- sessionId: String(row.session_id),
632
- segmentId: String(row.segment_id),
633
- },
634
- connectionId: String(row.connection_id),
635
- sourceKey: String(row.source_key),
636
- receivedAtMs: numberValue(row.received_at_ms),
637
- state: state as TState,
638
- };
639
- if (typeof row.source_id === 'string') frame.sourceId = row.source_id;
640
- if (typeof row.source_seq === 'string') {
641
- const sourceSeq = parseJson(row.source_seq);
642
- if (typeof sourceSeq === 'number' || typeof sourceSeq === 'string') frame.sourceSeq = sourceSeq;
643
- }
644
- if (row.backend_tick !== null && row.backend_tick !== undefined) frame.backendTick = numberValue(row.backend_tick);
645
- if (row.observed_at_ms !== null && row.observed_at_ms !== undefined) frame.observedAtMs = numberValue(row.observed_at_ms);
646
- return cloneCanonical(frame);
647
- }
648
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/state/history/sqlite-state-history-repository.js';