@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,282 +1,2 @@
1
- import type { MailboxCoalescer } from './coalescer.js';
2
- import { IdentityMailboxCoalescer } from './coalescer.js';
3
- import {
4
- HostNotificationDeliveryError,
5
- type HostNotificationSink,
6
- } from './host-notification-sink.js';
7
- import type { MailboxRepository } from './mailbox-repository.js';
8
- import type { MailboxDeliveryMode, MailboxItem } from './types.js';
9
-
10
- const DEFAULT_LEASE_TTL_MS = 30_000;
11
- const DEFAULT_RETRY_BASE_MS = 250;
12
- const DEFAULT_RETRY_MAX_MS = 30_000;
13
-
14
- export interface MailboxDispatcherScope {
15
- consumerId: string;
16
- sessionId: string;
17
- segmentId: string;
18
- mode: MailboxDeliveryMode;
19
- }
20
-
21
- export interface MailboxRetryContext<TPayload = unknown> {
22
- attemptCount: number;
23
- error: unknown;
24
- items: readonly MailboxItem<TPayload>[];
25
- nowMs: number;
26
- }
27
-
28
- export type MailboxRetryAt<TPayload = unknown> = (
29
- context: MailboxRetryContext<TPayload>,
30
- ) => number;
31
-
32
- export interface MailboxDispatcherOptions<TItemPayload = unknown, TNotificationPayload = TItemPayload> {
33
- repository: MailboxRepository;
34
- /** null means there is currently no foreground game scope; park until notified. */
35
- scope: MailboxDispatcherScope | (() => MailboxDispatcherScope | null);
36
- ownerId: string;
37
- sink: HostNotificationSink<TNotificationPayload>;
38
- coalescer?: MailboxCoalescer<TItemPayload, TNotificationPayload>;
39
- leaseTtlMs?: number;
40
- retryAt?: MailboxRetryAt<TItemPayload>;
41
- now?: () => number;
42
- onAttempt?: (items: readonly MailboxItem<TItemPayload>[]) => void;
43
- onError?: (error: unknown, items?: readonly MailboxItem<TItemPayload>[]) => void;
44
- }
45
-
46
- function defaultRetryAt(context: MailboxRetryContext): number {
47
- const exponent = Math.max(0, Math.min(16, context.attemptCount - 1));
48
- const delay = Math.min(DEFAULT_RETRY_MAX_MS, DEFAULT_RETRY_BASE_MS * (2 ** exponent));
49
- return context.nowMs + delay;
50
- }
51
-
52
- function errorCode(error: unknown): string {
53
- if (error instanceof HostNotificationDeliveryError) return error.code.slice(0, 100);
54
- if (error instanceof Error && error.name.trim().length > 0) {
55
- return error.name.trim().slice(0, 100);
56
- }
57
- return 'HostNotificationDeliveryError';
58
- }
59
-
60
- /**
61
- * Pumps one durable Mailbox scope into one Host Adapter.
62
- *
63
- * It intentionally knows nothing about Agent active/idle state or game Event
64
- * types. notifyAvailable always attempts immediately; retry timing is persisted
65
- * by Repository.nackMailboxClaim through retryAtMs.
66
- */
67
- export class MailboxDispatcher<TItemPayload = unknown, TNotificationPayload = TItemPayload> {
68
- private readonly repository: MailboxRepository;
69
- private readonly resolveScope: () => MailboxDispatcherScope | null;
70
- private readonly ownerId: string;
71
- private readonly sink: HostNotificationSink<TNotificationPayload>;
72
- private readonly coalescer: MailboxCoalescer<TItemPayload, TNotificationPayload>;
73
- private readonly leaseTtlMs: number;
74
- private readonly retryAt: MailboxRetryAt<TItemPayload>;
75
- private readonly now: () => number;
76
- private readonly onAttempt?: (items: readonly MailboxItem<TItemPayload>[]) => void;
77
- private readonly onError?: (error: unknown, items?: readonly MailboxItem<TItemPayload>[]) => void;
78
-
79
- private stopped = false;
80
- private pumpRequested = false;
81
- private pumpPromise: Promise<void> | null = null;
82
- private retryTimer: ReturnType<typeof setTimeout> | null = null;
83
-
84
- constructor(options: MailboxDispatcherOptions<TItemPayload, TNotificationPayload>) {
85
- this.repository = options.repository;
86
- const configuredScope = options.scope;
87
- this.resolveScope = typeof configuredScope === 'function' ? configuredScope : () => configuredScope;
88
- this.ownerId = options.ownerId;
89
- this.sink = options.sink;
90
- this.coalescer = options.coalescer ?? new IdentityMailboxCoalescer<TItemPayload>() as unknown as MailboxCoalescer<
91
- TItemPayload,
92
- TNotificationPayload
93
- >;
94
- this.leaseTtlMs = options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;
95
- this.retryAt = options.retryAt ?? defaultRetryAt;
96
- this.now = options.now ?? Date.now;
97
- this.onAttempt = options.onAttempt;
98
- this.onError = options.onError;
99
-
100
- if (!this.ownerId) throw new Error('MailboxDispatcher ownerId is required.');
101
- if (!Number.isFinite(this.leaseTtlMs) || this.leaseTtlMs <= 0) {
102
- throw new Error('MailboxDispatcher leaseTtlMs must be positive.');
103
- }
104
- if (!Number.isInteger(this.coalescer.maxItems) || this.coalescer.maxItems <= 0) {
105
- throw new Error('MailboxCoalescer maxItems must be a positive integer.');
106
- }
107
- }
108
-
109
- /** Signals new work without waiting for Host delivery. */
110
- notifyAvailable(): void {
111
- if (this.stopped) return;
112
- this.pumpRequested = true;
113
- this.clearRetryTimer();
114
- this.ensurePump();
115
- }
116
-
117
- /** Drains work available now, but never waits for a future retry timer. */
118
- async flush(): Promise<void> {
119
- if (this.stopped) {
120
- await this.pumpPromise;
121
- return;
122
- }
123
- this.notifyAvailable();
124
- while (this.pumpPromise) await this.pumpPromise;
125
- }
126
-
127
- /** Stops future retries, while allowing an in-flight Host acceptance to settle. */
128
- async stop(): Promise<void> {
129
- if (this.stopped) {
130
- await this.pumpPromise;
131
- return;
132
- }
133
- this.stopped = true;
134
- this.pumpRequested = false;
135
- this.clearRetryTimer();
136
- await this.pumpPromise;
137
- }
138
-
139
- private ensurePump(): void {
140
- if (this.stopped || this.pumpPromise) return;
141
- this.pumpPromise = this.pump()
142
- .catch((error) => {
143
- try { this.onError?.(error); } catch {}
144
- // A transient scope/repository failure happens before any item can be
145
- // claimed and therefore has no persisted item retryAt. Still retry the
146
- // pump itself so one SQLite busy/read error cannot strand durable work
147
- // until an unrelated future Event happens to arrive.
148
- this.scheduleAt(this.now() + DEFAULT_RETRY_BASE_MS);
149
- })
150
- .finally(() => {
151
- this.pumpPromise = null;
152
- if (this.pumpRequested && !this.stopped) this.ensurePump();
153
- });
154
- }
155
-
156
- private async pump(): Promise<void> {
157
- while (!this.stopped) {
158
- this.pumpRequested = false;
159
- const nowMs = this.now();
160
- const scope = this.resolveScope();
161
- if (!scope) return;
162
- const claim = this.repository.claimMailbox<TItemPayload>({
163
- ...scope,
164
- ownerId: this.ownerId,
165
- leaseTtlMs: this.leaseTtlMs,
166
- nowMs,
167
- maxItems: this.coalescer.maxItems,
168
- });
169
-
170
- if (!claim) {
171
- this.scheduleHead();
172
- if (this.pumpRequested) continue;
173
- return;
174
- }
175
-
176
- const controller = new AbortController();
177
- try {
178
- try {
179
- this.onAttempt?.(claim.items);
180
- } catch (error) {
181
- this.onError?.(error, claim.items);
182
- }
183
- const notification = this.coalescer.coalesce(claim.items);
184
- const acceptance = await this.sink.deliver(notification, controller.signal);
185
- const acknowledged = this.repository.ackMailboxClaim({
186
- ownerId: this.ownerId,
187
- claimToken: claim.claimToken,
188
- acceptedAt: acceptance.acceptedAt,
189
- acceptanceLevel: acceptance.acceptanceLevel ?? 'sink_emitted',
190
- receiptId: acceptance.receiptId,
191
- nowMs: this.now(),
192
- });
193
- if (acknowledged.status === 'claim_lost') {
194
- this.onError?.(
195
- new Error(`Mailbox claim ${claim.claimToken} was lost before acknowledgement.`),
196
- claim.items,
197
- );
198
- this.scheduleHead();
199
- return;
200
- }
201
- } catch (error) {
202
- const failedAtMs = this.now();
203
- const terminal = error instanceof HostNotificationDeliveryError && !error.retryable;
204
- const attemptCount = Math.max(1, ...claim.items.map((item) => item.attemptCount));
205
- const retryAtMs = terminal || this.stopped
206
- ? failedAtMs
207
- : Math.max(failedAtMs, this.retryAt({
208
- attemptCount,
209
- error,
210
- items: claim.items,
211
- nowMs: failedAtMs,
212
- }));
213
- const released = this.repository.nackMailboxClaim({
214
- ownerId: this.ownerId,
215
- claimToken: claim.claimToken,
216
- retryAtMs,
217
- errorCode: errorCode(error),
218
- nowMs: failedAtMs,
219
- });
220
- this.onError?.(error, claim.items);
221
- if (terminal && released.status === 'released') {
222
- // A malformed envelope, stale credential, or identity conflict will
223
- // not heal through backoff. Remove it from the active-notification
224
- // FIFO while leaving the underlying Event detail pullable via
225
- // `ccl events`, and surface the typed error through onError/logging.
226
- this.repository.suppressMailboxItems({
227
- consumerId: scope.consumerId,
228
- sessionId: scope.sessionId,
229
- segmentId: scope.segmentId,
230
- eventIds: claim.items.map((item) => item.eventId),
231
- modes: [scope.mode],
232
- nowMs: failedAtMs,
233
- });
234
- this.pumpRequested = true;
235
- continue;
236
- }
237
- if (!this.stopped) {
238
- if (released.status === 'released') this.scheduleAt(retryAtMs);
239
- else if (released.status === 'claim_lost') this.scheduleHead();
240
- }
241
- return;
242
- }
243
- }
244
- }
245
-
246
- private scheduleHead(): void {
247
- const scope = this.resolveScope();
248
- if (!scope) return;
249
- const [head] = this.repository.peekMailbox<TItemPayload>({
250
- consumerId: scope.consumerId,
251
- sessionId: scope.sessionId,
252
- segmentId: scope.segmentId,
253
- modes: [scope.mode],
254
- states: ['pending', 'claimed'],
255
- order: 'asc',
256
- limit: 1,
257
- });
258
- if (!head) return;
259
- const wakeAt = head.state === 'claimed'
260
- ? head.claimExpiresAtMs ?? this.now()
261
- : head.availableAtMs;
262
- this.scheduleAt(wakeAt);
263
- }
264
-
265
- private scheduleAt(wakeAtMs: number): void {
266
- if (this.stopped) return;
267
- const delay = Math.max(0, wakeAtMs - this.now());
268
- if (this.retryTimer) return;
269
- const timer = setTimeout(() => {
270
- this.retryTimer = null;
271
- this.notifyAvailable();
272
- }, delay);
273
- if (typeof timer === 'object' && 'unref' in timer) timer.unref();
274
- this.retryTimer = timer;
275
- }
276
-
277
- private clearRetryTimer(): void {
278
- if (!this.retryTimer) return;
279
- clearTimeout(this.retryTimer);
280
- this.retryTimer = null;
281
- }
282
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/mailbox/mailbox-dispatcher.js';
@@ -1,44 +1,2 @@
1
- import type {
2
- AckMailboxClaimRequest,
3
- AckMailboxClaimResult,
4
- ClaimMailboxItemsRequest,
5
- EnqueueMailboxItem,
6
- EnqueueMailboxResult,
7
- MailboxClaim,
8
- MailboxDeliveryMode,
9
- MailboxItem,
10
- MailboxPeekFilter,
11
- NackMailboxClaimRequest,
12
- NackMailboxClaimResult,
13
- SuppressMailboxItemsFilter,
14
- } from './types.js';
15
-
16
- /**
17
- * Mutable notification delivery storage. It is deliberately separate from
18
- * EventRepository even when both interfaces share one SQLite connection.
19
- */
20
- export interface MailboxRepository {
21
- enqueueMailboxItem<T = unknown>(request: EnqueueMailboxItem<T>): EnqueueMailboxResult<T>;
22
- mailboxItem<T = unknown>(itemId: string): MailboxItem<T> | null;
23
- mailboxItemForEvent<T = unknown>(
24
- consumerId: string,
25
- eventId: string,
26
- mode: MailboxDeliveryMode,
27
- ): MailboxItem<T> | null;
28
- peekMailbox<T = unknown>(filter: MailboxPeekFilter): MailboxItem<T>[];
29
- claimMailbox<T = unknown>(request: ClaimMailboxItemsRequest): MailboxClaim<T> | null;
30
- ackMailboxClaim(request: AckMailboxClaimRequest): AckMailboxClaimResult;
31
- nackMailboxClaim(request: NackMailboxClaimRequest): NackMailboxClaimResult;
32
- suppressMailboxItems(filter: SuppressMailboxItemsFilter): number;
33
- }
34
-
35
- export type RuntimeEventRepository<TEventRepository> = TEventRepository & MailboxRepository;
36
-
37
- export function isMailboxRepository(value: unknown): value is MailboxRepository {
38
- if (!value || typeof value !== 'object') return false;
39
- const candidate = value as Partial<Record<keyof MailboxRepository, unknown>>;
40
- return typeof candidate.enqueueMailboxItem === 'function'
41
- && typeof candidate.claimMailbox === 'function'
42
- && typeof candidate.ackMailboxClaim === 'function'
43
- && typeof candidate.nackMailboxClaim === 'function';
44
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/mailbox/mailbox-repository.js';
@@ -1,65 +1,2 @@
1
- import type { CanonicalEvent } from '../events/index.js';
2
- import { stableMailboxItemId } from './identity.js';
3
- import type { MailboxRepository } from './mailbox-repository.js';
4
- import type { MailboxDeliveryMode, MailboxItem } from './types.js';
5
-
6
- export interface NotificationProjectorOptions<TPayload> {
7
- repository: MailboxRepository;
8
- consumerId: string;
9
- mode: MailboxDeliveryMode;
10
- formatterVersion: string;
11
- present(event: CanonicalEvent): TPayload;
12
- /** A batching hint only. It never decides whether the Event is eligible. */
13
- coalesceKey?: (event: CanonicalEvent) => string;
14
- now?: () => number;
15
- }
16
-
17
- /**
18
- * Materializes an immutable notification envelope from a committed Event.
19
- * Re-running projection after a crash is idempotent and never mutates an
20
- * existing payload, even if the installed formatter version has changed.
21
- */
22
- export class NotificationProjector<TPayload = unknown> {
23
- private readonly now: () => number;
24
-
25
- constructor(private readonly options: NotificationProjectorOptions<TPayload>) {
26
- this.now = options.now ?? Date.now;
27
- if (!options.consumerId) throw new Error('NotificationProjector consumerId is required.');
28
- if (!options.formatterVersion) {
29
- throw new Error('NotificationProjector formatterVersion is required.');
30
- }
31
- }
32
-
33
- project(event: CanonicalEvent): MailboxItem<TPayload> {
34
- const itemId = stableMailboxItemId({
35
- consumerId: this.options.consumerId,
36
- sessionId: event.sessionId,
37
- eventId: event.eventId,
38
- mode: this.options.mode,
39
- });
40
- const existing = this.options.repository.mailboxItem<TPayload>(itemId);
41
- if (existing) return existing;
42
-
43
- const nowMs = this.now();
44
- const createdAt = new Date(nowMs).toISOString();
45
- return this.options.repository.enqueueMailboxItem<TPayload>({
46
- itemId,
47
- schemaVersion: 1,
48
- formatterVersion: this.options.formatterVersion,
49
- consumerId: this.options.consumerId,
50
- sessionId: event.sessionId,
51
- segmentId: event.segmentId,
52
- eventId: event.eventId,
53
- eventCommitSeq: event.commitSeq,
54
- mode: this.options.mode,
55
- coalesceKey: this.options.coalesceKey?.(event) ?? event.type,
56
- payload: this.options.present(event),
57
- availableAtMs: nowMs,
58
- createdAt,
59
- }).item;
60
- }
61
-
62
- projectAll(events: readonly CanonicalEvent[]): MailboxItem<TPayload>[] {
63
- return events.map((event) => this.project(event));
64
- }
65
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/mailbox/notification-projector.js';
@@ -1,145 +1,2 @@
1
- export type MailboxDeliveryMode = 'short';
2
-
3
- export type MailboxItemState =
4
- | 'pending'
5
- | 'claimed'
6
- | 'accepted'
7
- | 'suppressed';
8
-
9
- /** CCL cannot generally observe whether a model actually saw a notification. */
10
- export type MailboxAcceptanceLevel = 'sink_emitted' | 'host_accepted';
11
-
12
- /**
13
- * A durable, already-presented notification envelope.
14
- *
15
- * The canonical Event remains the game fact. A Mailbox item is only a mutable
16
- * delivery record for one logical Agent consumer.
17
- */
18
- export interface MailboxItem<T = unknown> {
19
- itemId: string;
20
- schemaVersion: number;
21
- formatterVersion: string;
22
- consumerId: string;
23
- sessionId: string;
24
- segmentId: string;
25
- eventId: string;
26
- eventCommitSeq: number;
27
- /** Optional stable delivery position; canonical event sequence remains unchanged. */
28
- deliveryOrder?: number;
29
- mode: MailboxDeliveryMode;
30
- coalesceKey: string;
31
- payload: T;
32
- state: MailboxItemState;
33
- attemptCount: number;
34
- availableAtMs: number;
35
- createdAt: string;
36
- updatedAt: string;
37
- lastAttemptAt?: string;
38
- claimOwner?: string;
39
- claimToken?: string;
40
- claimExpiresAtMs?: number;
41
- acceptedAt?: string;
42
- acceptanceLevel?: MailboxAcceptanceLevel;
43
- receiptId?: string;
44
- lastErrorCode?: string;
45
- }
46
-
47
- export interface EnqueueMailboxItem<T = unknown> {
48
- itemId: string;
49
- schemaVersion?: number;
50
- formatterVersion: string;
51
- consumerId: string;
52
- sessionId: string;
53
- segmentId: string;
54
- eventId: string;
55
- eventCommitSeq: number;
56
- /** Optional stable delivery position; canonical event sequence remains unchanged. */
57
- deliveryOrder?: number;
58
- mode: MailboxDeliveryMode;
59
- coalesceKey: string;
60
- payload: T;
61
- availableAtMs?: number;
62
- createdAt?: string;
63
- }
64
-
65
- export interface EnqueueMailboxResult<T = unknown> {
66
- inserted: boolean;
67
- item: MailboxItem<T>;
68
- }
69
-
70
- export interface MailboxPeekFilter {
71
- consumerId: string;
72
- sessionId?: string;
73
- segmentId?: string;
74
- eventIds?: string[];
75
- modes?: MailboxDeliveryMode[];
76
- states?: MailboxItemState[];
77
- /** Pure read bound; it never changes attempts, leases, or delivery state. */
78
- limit?: number;
79
- order?: 'asc' | 'desc';
80
- }
81
-
82
- export interface ClaimMailboxItemsRequest {
83
- consumerId: string;
84
- sessionId: string;
85
- segmentId: string;
86
- mode: MailboxDeliveryMode;
87
- ownerId: string;
88
- leaseTtlMs: number;
89
- nowMs?: number;
90
- /**
91
- * Claims a FIFO prefix. Items after the first are included only while their
92
- * coalesceKey matches, so batching never lets a later topic overtake one.
93
- */
94
- maxItems?: number;
95
- /** Internal deterministic token used by mirrored persistence stores. */
96
- claimToken?: string;
97
- }
98
-
99
- export interface MailboxClaim<T = unknown> {
100
- ownerId: string;
101
- claimToken: string;
102
- claimExpiresAtMs: number;
103
- items: MailboxItem<T>[];
104
- }
105
-
106
- export interface AckMailboxClaimRequest {
107
- ownerId: string;
108
- claimToken: string;
109
- acceptedAt?: string;
110
- /** Defaults to sink_emitted for legacy stdout transports. */
111
- acceptanceLevel?: MailboxAcceptanceLevel;
112
- receiptId?: string;
113
- nowMs?: number;
114
- }
115
-
116
- export interface AckMailboxClaimResult {
117
- status: 'accepted' | 'already_accepted' | 'claim_lost';
118
- itemIds: string[];
119
- eventIds: string[];
120
- }
121
-
122
- export interface NackMailboxClaimRequest {
123
- ownerId: string;
124
- claimToken: string;
125
- retryAtMs: number;
126
- errorCode?: string;
127
- nowMs?: number;
128
- }
129
-
130
- export interface NackMailboxClaimResult {
131
- status: 'released' | 'suppressed' | 'claim_lost';
132
- itemIds: string[];
133
- }
134
-
135
- export interface SuppressMailboxItemsFilter {
136
- consumerId: string;
137
- sessionId?: string;
138
- segmentId?: string;
139
- excludeSegmentId?: string;
140
- eventIds?: string[];
141
- modes?: MailboxDeliveryMode[];
142
- /** Claimed items are in flight and are not suppressed by default. */
143
- includeExpiredClaims?: boolean;
144
- nowMs?: number;
145
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/mailbox/types.js';
@@ -1,154 +1,2 @@
1
- import { accessSync, readFileSync } from 'node:fs';
2
- import { transformSync } from 'amaro';
3
-
4
- let sdkAliases = Object.create(null);
5
- let nativeTypeScript = false;
6
- const esmModuleRoots = new Set();
7
-
8
- function addEsmRoot(root) {
9
- if (typeof root !== 'string') return;
10
- try {
11
- const url = new URL(root);
12
- if (url.protocol !== 'file:') return;
13
- url.search = '';
14
- url.hash = '';
15
- esmModuleRoots.add(url.href.endsWith('/') ? url.href : `${url.href}/`);
16
- } catch {
17
- // Invalid roots never broaden the loader scope.
18
- }
19
- }
20
-
21
- export function initialize(data) {
22
- sdkAliases = data?.sdkAliases ?? Object.create(null);
23
- nativeTypeScript = data?.nativeTypeScript === true;
24
- esmModuleRoots.clear();
25
- for (const root of data?.esmModuleRoots ?? []) addEsmRoot(root);
26
- }
27
-
28
- export function addEsmModuleRoot(root) {
29
- addEsmRoot(root);
30
- }
31
-
32
- function isTypeScriptUrl(url) {
33
- return /\.(?:ts|tsx)(?:\?|$)/i.test(url);
34
- }
35
-
36
- function withNativeTypeScriptFormat(result) {
37
- if (!nativeTypeScript || !isTypeScriptUrl(result.url)) return result;
38
- return { ...result, format: 'module' };
39
- }
40
-
41
- function userTypeScriptUrl(specifier, parentURL) {
42
- if (!nativeTypeScript || typeof specifier !== 'string') return undefined;
43
- let url;
44
- try {
45
- url = new URL(specifier, parentURL);
46
- } catch {
47
- return undefined;
48
- }
49
- if (url.protocol !== 'file:' || !isTypeScriptUrl(url.href)) return undefined;
50
-
51
- // Compare only the physical file location. Query strings are deliberately
52
- // retained on the returned URL because Runtime uses them to isolate module
53
- // state between lifecycles.
54
- const physicalUrl = new URL(url.href);
55
- physicalUrl.search = '';
56
- physicalUrl.hash = '';
57
- if (![...esmModuleRoots].some((root) => physicalUrl.href.startsWith(root))) {
58
- return undefined;
59
- }
60
- return url.href;
61
- }
62
-
63
- function isUserEsmJavaScript(url) {
64
- if (!/\.js(?:\?|$)/i.test(url)) return false;
65
- return [...esmModuleRoots].some((root) => {
66
- if (!url.startsWith(root)) return false;
67
- const relative = url.slice(root.length).split(/[?#]/, 1)[0].toLowerCase();
68
- return relative !== 'node_modules' && !relative.startsWith('node_modules/')
69
- && !relative.includes('/node_modules/');
70
- });
71
- }
72
-
73
- function sourceFallbackUrl(specifier, parentURL) {
74
- if (typeof specifier !== 'string' || !parentURL) return undefined;
75
- if (!specifier.startsWith('.') && !specifier.startsWith('/') && !specifier.startsWith('file:')) {
76
- return undefined;
77
- }
78
- let url;
79
- try {
80
- url = new URL(specifier, parentURL);
81
- } catch {
82
- return undefined;
83
- }
84
- if (url.protocol !== 'file:') return undefined;
85
- const match = /\.(js|jsx)(\?.*)?$/i.exec(url.href);
86
- if (!match) return undefined;
87
- const extension = match[1].toLowerCase() === 'jsx' ? 'tsx' : 'ts';
88
- return new URL(url.href.slice(0, match.index) + `.${extension}${match[2] ?? ''}`);
89
- }
90
-
91
- export function resolve(specifier, context, nextResolve) {
92
- const target = sdkAliases[specifier];
93
- if (typeof target === 'string') {
94
- return withNativeTypeScriptFormat({
95
- shortCircuit: true,
96
- url: target,
97
- });
98
- }
99
- // The CLI registers tsx before this hook. Letting tsx resolve a queried
100
- // user .ts/.tsx entry can percent-encode the query into a CommonJS virtual
101
- // URL, which then turns public SDK imports into unresolved require() calls.
102
- // Claim only registered user-module roots here so package resolution and
103
- // node_modules continue through the normal loader chain.
104
- const directUserTypeScriptUrl = userTypeScriptUrl(specifier, context.parentURL);
105
- if (directUserTypeScriptUrl) {
106
- return {
107
- format: 'module',
108
- shortCircuit: true,
109
- url: directUserTypeScriptUrl,
110
- };
111
- }
112
- try {
113
- return withNativeTypeScriptFormat(nextResolve(specifier, context));
114
- } catch (error) {
115
- const fallback = sourceFallbackUrl(specifier, context.parentURL);
116
- if (!fallback) throw error;
117
- try {
118
- accessSync(fallback);
119
- } catch {
120
- throw error;
121
- }
122
- return withNativeTypeScriptFormat({
123
- shortCircuit: true,
124
- url: fallback.href,
125
- });
126
- }
127
- }
128
-
129
- export function load(url, context, nextLoad) {
130
- // User data directories do not need their own package.json merely to make a
131
- // Strategy/Perception/Intent .ts file ESM. Owner and Worker Threads share the same
132
- // in-process transform semantics without starting a compiler service.
133
- if (/\.(?:ts|tsx)(?:\?|$)/i.test(url)) {
134
- if (nativeTypeScript) {
135
- const source = readFileSync(new URL(url), 'utf8');
136
- return {
137
- format: 'module',
138
- shortCircuit: true,
139
- source: transformSync(source, {
140
- filename: new URL(url).pathname,
141
- mode: 'transform',
142
- }).code,
143
- };
144
- }
145
- return nextLoad(url, {
146
- ...context,
147
- format: 'module',
148
- });
149
- }
150
- if (isUserEsmJavaScript(url)) {
151
- return nextLoad(url, { ...context, format: 'module' });
152
- }
153
- return nextLoad(url, context);
154
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/modules/runtime-module-loader-hooks.mjs';