@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,14 +1,2 @@
1
- /** Serializes compatibility ingress tasks without participating in epoch scheduling. */
2
- export class SerialTaskQueue {
3
- private tail: Promise<void> = Promise.resolve();
4
-
5
- run<T>(task: () => T | Promise<T>): Promise<T> {
6
- const result = this.tail.then(task, task);
7
- this.tail = result.then(() => undefined, () => undefined);
8
- return result;
9
- }
10
-
11
- async flush(): Promise<void> {
12
- await this.tail;
13
- }
14
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/serial-task-queue.js';
@@ -1,49 +1,2 @@
1
- import type {
2
- ApplyStateResult,
3
- CurrentStateSnapshot,
4
- RuntimeConnectionState,
5
- RuntimeScope,
6
- StateFactPatch,
7
- StateFrameEnvelope,
8
- } from './types.js';
9
-
10
- export interface CurrentStateReader<TState = unknown> {
11
- snapshot(): CurrentStateSnapshot<TState>;
12
- }
13
-
14
- export interface CurrentStateWriter<TState = unknown> extends CurrentStateReader<TState> {
15
- openScope(scope: RuntimeScope, atMs?: number): CurrentStateSnapshot<TState>;
16
- openConnection(connectionId: string, atMs?: number): CurrentStateSnapshot<TState>;
17
- markConnectionState(
18
- connectionId: string,
19
- state: RuntimeConnectionState,
20
- atMs?: number,
21
- ): CurrentStateSnapshot<TState>;
22
- markLiveness(connectionId: string, atMs?: number): boolean;
23
- applyFacts(patches: StateFactPatch[], atMs?: number): CurrentStateSnapshot<TState>;
24
- applyBackendState(frame: StateFrameEnvelope<TState>): ApplyStateResult<TState>;
25
- clear(): void;
26
- }
27
-
28
- export interface StateIngressObserver<TState = unknown> {
29
- onFrameAccepted?(frame: StateFrameEnvelope<TState>, result: Extract<ApplyStateResult<TState>, { accepted: true }>): void | Promise<void>;
30
- onConnectionChanged?(
31
- scope: RuntimeScope | null,
32
- connectionId: string,
33
- state: RuntimeConnectionState,
34
- atMs: number,
35
- ): void | Promise<void>;
36
- onObserverError?(error: unknown): void;
37
- }
38
-
39
- /**
40
- * Optional lifecycle hooks for observers that buffer durable side effects.
41
- * State ingestion never waits for disk I/O, while the owner can still flush
42
- * the last accepted frame before it exits.
43
- */
44
- export interface FlushableStateIngressObserver<TState = unknown> extends StateIngressObserver<TState> {
45
- flush?(): Promise<void>;
46
- close?(): Promise<void>;
47
- }
48
-
49
- export type StateViewProjector<TState, TView> = (snapshot: CurrentStateSnapshot<TState>) => TView;
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/state/contracts.js';
@@ -1,184 +1,2 @@
1
- import type { CurrentStateWriter } from './contracts.js';
2
- import {
3
- cloneCanonical,
4
- sameRuntimeScope,
5
- sameRuntimeSession,
6
- type ApplyStateResult,
7
- type CurrentStateMeta,
8
- type CurrentStateSnapshot,
9
- type RuntimeConnectionState,
10
- type RuntimeScope,
11
- type StateFactPatch,
12
- type StateFrameEnvelope,
13
- type StoredStateFact,
14
- } from './types.js';
15
-
16
- function emptyMeta(): CurrentStateMeta {
17
- return {
18
- sourceId: null,
19
- connectionId: null,
20
- connectionState: 'disconnected',
21
- awaitingFirstFrame: true,
22
- receiveSeq: 0,
23
- lastSourceSeq: null,
24
- backendTick: null,
25
- lastStateSourceKey: null,
26
- lastStateReceivedAtMs: null,
27
- lastStateReceivedMonotonicMs: null,
28
- lastLivenessAtMs: null,
29
- gapSinceMs: null,
30
- };
31
- }
32
-
33
- function copyFactMap(source: Map<string, StoredStateFact>): Record<string, StoredStateFact> {
34
- return Object.fromEntries(
35
- Array.from(source.entries(), ([key, value]) => [key, cloneCanonical(value)]),
36
- );
37
- }
38
-
39
- export class CurrentStateStore<TState = unknown> implements CurrentStateWriter<TState> {
40
- private currentScope: RuntimeScope | null = null;
41
- private backendState: TState | null = null;
42
- private readonly sessionFacts = new Map<string, StoredStateFact>();
43
- private readonly segmentFacts = new Map<string, StoredStateFact>();
44
- private meta: CurrentStateMeta = emptyMeta();
45
-
46
- openScope(scope: RuntimeScope, _atMs = Date.now()): CurrentStateSnapshot<TState> {
47
- if (sameRuntimeScope(this.currentScope, scope)) return this.snapshot();
48
-
49
- const sameSession = sameRuntimeSession(this.currentScope, scope);
50
- if (!sameSession) this.sessionFacts.clear();
51
- this.segmentFacts.clear();
52
- this.currentScope = cloneCanonical(scope);
53
- this.backendState = null;
54
- this.meta = emptyMeta();
55
- return this.snapshot();
56
- }
57
-
58
- openConnection(connectionId: string, atMs = Date.now()): CurrentStateSnapshot<TState> {
59
- if (!this.currentScope) throw new Error('Cannot open a connection before opening a scope');
60
- if (!connectionId) throw new Error('connectionId is required');
61
- const isNewConnection = this.meta.connectionId !== connectionId;
62
- if (isNewConnection) {
63
- this.meta.connectionId = connectionId;
64
- this.meta.receiveSeq = 0;
65
- this.meta.lastSourceSeq = null;
66
- this.meta.awaitingFirstFrame = true;
67
- if (this.backendState !== null || this.meta.lastStateReceivedAtMs !== null) {
68
- this.meta.gapSinceMs ??= atMs;
69
- }
70
- }
71
- this.meta.connectionState = 'connected';
72
- this.meta.lastLivenessAtMs = atMs;
73
- return this.snapshot();
74
- }
75
-
76
- markConnectionState(
77
- connectionId: string,
78
- state: RuntimeConnectionState,
79
- atMs = Date.now(),
80
- ): CurrentStateSnapshot<TState> {
81
- if (!this.meta.connectionId || this.meta.connectionId !== connectionId) return this.snapshot();
82
- this.meta.connectionState = state;
83
- if (state !== 'connected') {
84
- this.meta.gapSinceMs ??= atMs;
85
- this.meta.awaitingFirstFrame = true;
86
- }
87
- return this.snapshot();
88
- }
89
-
90
- markLiveness(connectionId: string, atMs = Date.now()): boolean {
91
- if (!this.meta.connectionId || this.meta.connectionId !== connectionId) return false;
92
- this.meta.lastLivenessAtMs = atMs;
93
- return true;
94
- }
95
-
96
- applyFacts(patches: StateFactPatch[], atMs = Date.now()): CurrentStateSnapshot<TState> {
97
- if (!this.currentScope) throw new Error('Cannot apply facts before opening a scope');
98
- for (const patch of patches) {
99
- if (!patch.key) throw new Error('State fact key is required');
100
- const target = patch.lifetime === 'session' ? this.sessionFacts : this.segmentFacts;
101
- const other = patch.lifetime === 'session' ? this.segmentFacts : this.sessionFacts;
102
- other.delete(patch.key);
103
- target.set(patch.key, {
104
- ...cloneCanonical(patch),
105
- updatedAtMs: atMs,
106
- });
107
- }
108
- return this.snapshot();
109
- }
110
-
111
- applyBackendState(frame: StateFrameEnvelope<TState>): ApplyStateResult<TState> {
112
- if (!this.currentScope) {
113
- return { accepted: false, reason: 'scope_not_open', snapshot: this.snapshot() };
114
- }
115
- if (!sameRuntimeScope(this.currentScope, frame.scope)) {
116
- return { accepted: false, reason: 'scope_mismatch', snapshot: this.snapshot() };
117
- }
118
- if (!this.meta.connectionId) {
119
- return { accepted: false, reason: 'connection_not_open', snapshot: this.snapshot() };
120
- }
121
- if (this.meta.connectionId !== frame.connectionId) {
122
- return { accepted: false, reason: 'stale_connection', snapshot: this.snapshot() };
123
- }
124
- if (
125
- frame.sourceSeq !== undefined
126
- && this.meta.lastSourceSeq !== null
127
- && (
128
- frame.sourceSeq === this.meta.lastSourceSeq
129
- || (
130
- typeof frame.sourceSeq === 'number'
131
- && typeof this.meta.lastSourceSeq === 'number'
132
- && frame.sourceSeq < this.meta.lastSourceSeq
133
- )
134
- )
135
- ) {
136
- return { accepted: false, reason: 'duplicate_or_out_of_order', snapshot: this.snapshot() };
137
- }
138
-
139
- const firstFrameAfterConnect = this.meta.awaitingFirstFrame;
140
- this.backendState = cloneCanonical(frame.payload);
141
- this.meta.sourceId = frame.sourceId ?? this.meta.sourceId;
142
- this.meta.receiveSeq += 1;
143
- this.meta.lastSourceSeq = frame.sourceSeq ?? this.meta.lastSourceSeq;
144
- this.meta.backendTick = frame.backendTick ?? null;
145
- this.meta.lastStateSourceKey = frame.sourceKey;
146
- this.meta.lastStateReceivedAtMs = frame.receivedAtMs;
147
- this.meta.lastStateReceivedMonotonicMs = frame.receivedMonotonicMs ?? null;
148
- this.meta.lastLivenessAtMs = frame.receivedAtMs;
149
- this.meta.connectionState = 'connected';
150
- this.meta.awaitingFirstFrame = false;
151
- this.meta.gapSinceMs = null;
152
-
153
- return {
154
- accepted: true,
155
- receiveSeq: this.meta.receiveSeq,
156
- firstFrameAfterConnect,
157
- snapshot: this.snapshot(),
158
- };
159
- }
160
-
161
- snapshot(): CurrentStateSnapshot<TState> {
162
- const session = copyFactMap(this.sessionFacts);
163
- const segment = copyFactMap(this.segmentFacts);
164
- const globalFacts: Record<string, unknown> = {};
165
- for (const [key, fact] of [...Object.entries(session), ...Object.entries(segment)]) {
166
- globalFacts[key] = cloneCanonical(fact.value);
167
- }
168
- return {
169
- scope: this.currentScope ? cloneCanonical(this.currentScope) : null,
170
- backendState: this.backendState === null ? null : cloneCanonical(this.backendState),
171
- globalFacts,
172
- facts: { session, segment },
173
- meta: cloneCanonical(this.meta),
174
- };
175
- }
176
-
177
- clear(): void {
178
- this.currentScope = null;
179
- this.backendState = null;
180
- this.sessionFacts.clear();
181
- this.segmentFacts.clear();
182
- this.meta = emptyMeta();
183
- }
184
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/state/current-state-store.js';
@@ -1,209 +1,2 @@
1
- import { randomUUID } from 'crypto';
2
- import { mkdir, readFile, rename, rm, writeFile } from 'fs/promises';
3
- import { basename, dirname, join } from 'path';
4
- import type { FlushableStateIngressObserver } from './contracts.js';
5
- import { StateFreshnessEvaluator } from './freshness.js';
6
- import {
7
- cloneCanonical,
8
- sameRuntimeScope,
9
- type ApplyStateResult,
10
- type RuntimeScope,
11
- type StateFrameEnvelope,
12
- type StateFreshnessPolicy,
13
- type StateFreshnessPolicyResolver,
14
- type StateStatus,
15
- } from './types.js';
16
-
17
- export const DURABLE_AGENT_STATE_SNAPSHOT_FILE = 'last-agent-state.json';
18
- export const DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA = 'ccl.last-agent-state.v1';
19
-
20
- export interface DurableAgentStateSnapshot<TState = unknown> {
21
- schema: typeof DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA;
22
- scope: RuntimeScope;
23
- state: TState;
24
- stateStatus: StateStatus;
25
- receivedAt: string;
26
- }
27
-
28
- export interface OfflineAgentStateSnapshot<TState = unknown> {
29
- state: TState;
30
- stateStatus: StateStatus;
31
- scope: Omit<RuntimeScope, 'accountId'>;
32
- }
33
-
34
- export interface DurableAgentStateSnapshotObserverOptions<TState> {
35
- freshnessPolicy?: StateFreshnessPolicy;
36
- freshnessPolicyResolver?: StateFreshnessPolicyResolver;
37
- isTerminal?: (state: TState) => boolean;
38
- }
39
-
40
- export function durableAgentStateSnapshotPath(stateDir: string): string {
41
- return join(stateDir, DURABLE_AGENT_STATE_SNAPSHOT_FILE);
42
- }
43
-
44
- function publicScope(scope: RuntimeScope): Omit<RuntimeScope, 'accountId'> {
45
- const { accountId: _accountId, ...safe } = scope;
46
- return safe;
47
- }
48
-
49
- function isRuntimeScope(value: unknown): value is RuntimeScope {
50
- if (!value || typeof value !== 'object') return false;
51
- const scope = value as Record<string, unknown>;
52
- return ['adapterId', 'accountId', 'sessionId', 'segmentId']
53
- .every((key) => typeof scope[key] === 'string' && scope[key] !== '');
54
- }
55
-
56
- function isSnapshot<TState>(value: unknown): value is DurableAgentStateSnapshot<TState> {
57
- if (!value || typeof value !== 'object') return false;
58
- const row = value as Record<string, unknown>;
59
- return row.schema === DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA
60
- && isRuntimeScope(row.scope)
61
- && Object.prototype.hasOwnProperty.call(row, 'state')
62
- && !!row.stateStatus
63
- && typeof row.stateStatus === 'object'
64
- && typeof row.receivedAt === 'string'
65
- && Number.isFinite(Date.parse(row.receivedAt));
66
- }
67
-
68
- /**
69
- * A one-row durable cache. Writes are serialized and coalesced: transports do
70
- * not block on disk, and flush() guarantees the newest accepted State reached
71
- * an atomically replaced JSON file before owner shutdown completes.
72
- */
73
- export class AtomicJsonAgentStateSnapshotStore<TState = unknown> {
74
- private pending: DurableAgentStateSnapshot<TState> | null = null;
75
- private draining: Promise<void> | null = null;
76
- private lastErrorValue: unknown = null;
77
-
78
- constructor(readonly path: string) {}
79
-
80
- enqueue(snapshot: DurableAgentStateSnapshot<TState>): void {
81
- this.pending = cloneCanonical(snapshot);
82
- this.schedule();
83
- }
84
-
85
- async flush(): Promise<void> {
86
- while (this.pending || this.draining) {
87
- this.schedule();
88
- if (this.draining) await this.draining;
89
- }
90
- }
91
-
92
- lastError(): unknown {
93
- return this.lastErrorValue;
94
- }
95
-
96
- async read(expectedScope?: RuntimeScope): Promise<DurableAgentStateSnapshot<TState> | null> {
97
- try {
98
- const parsed: unknown = JSON.parse(await readFile(this.path, 'utf8'));
99
- if (!isSnapshot<TState>(parsed)) return null;
100
- if (expectedScope && !sameRuntimeScope(parsed.scope, expectedScope)) return null;
101
- return cloneCanonical(parsed);
102
- } catch {
103
- return null;
104
- }
105
- }
106
-
107
- private schedule(): void {
108
- if (this.draining || !this.pending) return;
109
- this.draining = this.drain().finally(() => {
110
- this.draining = null;
111
- if (this.pending) this.schedule();
112
- });
113
- }
114
-
115
- private async drain(): Promise<void> {
116
- while (this.pending) {
117
- const snapshot = this.pending;
118
- this.pending = null;
119
- try {
120
- await this.writeAtomic(snapshot);
121
- this.lastErrorValue = null;
122
- } catch (error) {
123
- // Current State remains available in owner memory. Persistence failure
124
- // is observable but must never roll back or block State ingestion.
125
- this.lastErrorValue = error;
126
- }
127
- }
128
- }
129
-
130
- private async writeAtomic(snapshot: DurableAgentStateSnapshot<TState>): Promise<void> {
131
- const directory = dirname(this.path);
132
- const temporary = join(
133
- directory,
134
- `.${basename(this.path)}.${process.pid}.${randomUUID()}.tmp`,
135
- );
136
- await mkdir(directory, { recursive: true });
137
- try {
138
- await writeFile(temporary, `${JSON.stringify(snapshot)}\n`, 'utf8');
139
- await rename(temporary, this.path);
140
- } finally {
141
- await rm(temporary, { force: true }).catch(() => undefined);
142
- }
143
- }
144
- }
145
-
146
- /** Writes only accepted State frames; rejected/mismatched frames never replace the cache. */
147
- export class DurableAgentStateSnapshotObserver<TState = unknown>
148
- implements FlushableStateIngressObserver<TState> {
149
- private readonly freshness: StateFreshnessEvaluator;
150
-
151
- constructor(
152
- private readonly store: AtomicJsonAgentStateSnapshotStore<TState>,
153
- private readonly options: DurableAgentStateSnapshotObserverOptions<TState> = {},
154
- ) {
155
- this.freshness = new StateFreshnessEvaluator(
156
- options.freshnessPolicy,
157
- options.freshnessPolicyResolver,
158
- );
159
- }
160
-
161
- onFrameAccepted(
162
- frame: StateFrameEnvelope<TState>,
163
- result: Extract<ApplyStateResult<TState>, { accepted: true }>,
164
- ): void {
165
- const stateStatus = this.freshness.evaluate(result.snapshot, frame.scope, frame.receivedAtMs);
166
- if (this.options.isTerminal?.(frame.payload)) stateStatus.terminal = true;
167
- this.store.enqueue({
168
- schema: DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA,
169
- scope: cloneCanonical(frame.scope),
170
- state: cloneCanonical(frame.payload),
171
- stateStatus,
172
- receivedAt: new Date(frame.receivedAtMs).toISOString(),
173
- });
174
- }
175
-
176
- flush(): Promise<void> {
177
- return this.store.flush();
178
- }
179
- }
180
-
181
- /**
182
- * Converts a same-scope durable row into an Agent-safe offline view. Internal
183
- * account identity remains available for validation on disk and is removed at
184
- * this single output boundary.
185
- */
186
- export function offlineAgentStateSnapshot<TState>(
187
- snapshot: DurableAgentStateSnapshot<TState>,
188
- options: { terminal?: boolean; nowMs?: number } = {},
189
- ): OfflineAgentStateSnapshot<TState> {
190
- const terminal = options.terminal === true || snapshot.stateStatus.terminal === true;
191
- const nowMs = options.nowMs ?? Date.now();
192
- const receivedAtMs = Date.parse(snapshot.receivedAt);
193
- const scope = publicScope(snapshot.scope);
194
- return {
195
- state: cloneCanonical(snapshot.state),
196
- scope,
197
- stateStatus: {
198
- ...cloneCanonical(snapshot.stateStatus),
199
- status: 'stale',
200
- source: 'durable_snapshot',
201
- scope: scope as RuntimeScope,
202
- connectionState: 'owner_unavailable',
203
- receivedAtMs: Number.isFinite(receivedAtMs) ? receivedAtMs : snapshot.stateStatus.receivedAtMs,
204
- ageMs: Number.isFinite(receivedAtMs) ? Math.max(0, nowMs - receivedAtMs) : null,
205
- reason: terminal ? 'terminal_snapshot' : 'owner_offline',
206
- terminal,
207
- },
208
- };
209
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/state/durable-agent-state-snapshot.js';
@@ -1,72 +1,2 @@
1
- import {
2
- sameRuntimeScope,
3
- type CurrentStateSnapshot,
4
- type RuntimeScope,
5
- type StateFreshnessPolicy,
6
- type StateFreshnessPolicyResolver,
7
- type StateStatus,
8
- } from './types.js';
9
-
10
- export class StateFreshnessEvaluator {
11
- constructor(
12
- private readonly policy: StateFreshnessPolicy = {},
13
- private readonly resolvePolicy?: StateFreshnessPolicyResolver,
14
- ) {}
15
-
16
- evaluate(
17
- snapshot: CurrentStateSnapshot,
18
- expectedScope?: RuntimeScope | null,
19
- nowMs = Date.now(),
20
- ): StateStatus {
21
- const base = {
22
- semantics: 'latest_received' as const,
23
- scope: snapshot.scope,
24
- connectionId: snapshot.meta.connectionId,
25
- connectionState: snapshot.meta.connectionState,
26
- receivedAtMs: snapshot.meta.lastStateReceivedAtMs,
27
- ageMs: snapshot.meta.lastStateReceivedAtMs === null
28
- ? null
29
- : Math.max(0, nowMs - snapshot.meta.lastStateReceivedAtMs),
30
- backendTick: snapshot.meta.backendTick,
31
- };
32
-
33
- if (!snapshot.scope) {
34
- return { ...base, status: 'unavailable', source: null, reason: 'scope_not_open' };
35
- }
36
- if (expectedScope && !sameRuntimeScope(snapshot.scope, expectedScope)) {
37
- return { ...base, status: 'unavailable', source: null, reason: 'scope_mismatch' };
38
- }
39
- if (snapshot.backendState === null || snapshot.meta.lastStateReceivedAtMs === null) {
40
- return { ...base, status: 'unavailable', source: null, reason: 'state_not_received' };
41
- }
42
- if (snapshot.meta.connectionState !== 'connected') {
43
- return { ...base, status: 'stale', source: 'owner_memory', reason: `connection_${snapshot.meta.connectionState}` };
44
- }
45
- if (snapshot.meta.awaitingFirstFrame) {
46
- return { ...base, status: 'stale', source: 'owner_memory', reason: 'awaiting_first_frame' };
47
- }
48
- if (snapshot.meta.gapSinceMs !== null) {
49
- return { ...base, status: 'stale', source: 'owner_memory', reason: 'stream_gap' };
50
- }
51
-
52
- const effectivePolicy = this.resolvePolicy?.(snapshot.meta.sourceId, snapshot) ?? this.policy;
53
- const { maxLivenessSilenceMs, maxStateSilenceMs } = effectivePolicy;
54
- if (
55
- maxLivenessSilenceMs !== undefined
56
- && (
57
- snapshot.meta.lastLivenessAtMs === null
58
- || nowMs - snapshot.meta.lastLivenessAtMs > maxLivenessSilenceMs
59
- )
60
- ) {
61
- return { ...base, status: 'stale', source: 'owner_memory', reason: 'liveness_timeout' };
62
- }
63
- if (
64
- maxStateSilenceMs !== undefined
65
- && nowMs - snapshot.meta.lastStateReceivedAtMs > maxStateSilenceMs
66
- ) {
67
- return { ...base, status: 'stale', source: 'owner_memory', reason: 'state_silence_timeout' };
68
- }
69
-
70
- return { ...base, status: 'fresh', source: 'owner_memory', reason: null };
71
- }
72
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/state/freshness.js';