@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,123 +1 @@
1
- /**
2
- * Token-bucket mirror of the Claude Code Host Monitor rate limiter.
3
- *
4
- * The Host (Claude Code) gates Monitor stdout delivery with its own token
5
- * bucket: capacity 10, refill 1 token / 2s, one batch per 200ms of flushed
6
- * stdout lines. Sustained output above ~0.5 batches/s silently suppresses
7
- * batches, and a >30s suppression streak kills the Monitor task. CCL cannot
8
- * observe the Host's suppression (the `[N events suppressed]` notice is
9
- * injected by the Host downstream of stdout), so the only way to guarantee
10
- * "what the Monitor pushed actually arrived" is to never write stdout when the
11
- * Host's bucket would be empty.
12
- *
13
- * This class models that exact bucket so the stdout relay can gate writes.
14
- * Constants are reverse-engineered from Claude Code 2.1.223 (see
15
- * docs/claude-code-monitor-truncation-mechanisms-20260605.md). Version upgrades
16
- * of Claude Code MUST re-verify these constants before relying on this mirror.
17
- */
18
- export const HOST_MONITOR_BUCKET_CAPACITY = 10;
19
- export const HOST_MONITOR_BUCKET_REFILL_MS = 2_000;
20
- export const HOST_MONITOR_BUCKET_REFILL_TOKENS = 1;
21
-
22
- export interface TokenBucketOptions {
23
- capacity?: number;
24
- refillEveryMs?: number;
25
- refillTokens?: number;
26
- now?: () => number;
27
- }
28
-
29
- /**
30
- * A token bucket that refills continuously by elapsed time.
31
- *
32
- * `tryConsume()` returns false when the bucket is empty; the relay then knows
33
- * the Host would suppress this write and can hold the batch instead of
34
- * emitting it. Refill is computed lazily on each access, so no timer is needed.
35
- */
36
- export class TokenBucket {
37
- private readonly capacity: number;
38
- private readonly refillEveryMs: number;
39
- private readonly refillTokens: number;
40
- private readonly now: () => number;
41
- private tokens: number;
42
- private lastRefillAtMs: number;
43
-
44
- constructor(options: TokenBucketOptions = {}) {
45
- this.capacity = options.capacity ?? HOST_MONITOR_BUCKET_CAPACITY;
46
- this.refillEveryMs = options.refillEveryMs ?? HOST_MONITOR_BUCKET_REFILL_MS;
47
- this.refillTokens = options.refillTokens ?? HOST_MONITOR_BUCKET_REFILL_TOKENS;
48
- this.now = options.now ?? Date.now;
49
- this.tokens = this.capacity;
50
- this.lastRefillAtMs = this.now();
51
- }
52
-
53
- private refill(): void {
54
- const elapsedMs = this.now() - this.lastRefillAtMs;
55
- if (elapsedMs <= 0) return;
56
- const refills = Math.floor(elapsedMs / this.refillEveryMs);
57
- if (refills > 0) {
58
- this.tokens = Math.min(this.capacity, this.tokens + refills * this.refillTokens);
59
- this.lastRefillAtMs += refills * this.refillEveryMs;
60
- }
61
- }
62
-
63
- /** Attempts to consume one token. Returns false when the bucket is empty. */
64
- tryConsume(): boolean {
65
- this.refill();
66
- if (this.tokens >= 1) {
67
- this.tokens -= 1;
68
- return true;
69
- }
70
- return false;
71
- }
72
-
73
- /** Current token count after refill (for diagnostics/testing). */
74
- current(): number {
75
- this.refill();
76
- return this.tokens;
77
- }
78
- }
79
-
80
- /**
81
- * A Monitor-write gate that mirrors the Host bucket plus a sustained-rate guard.
82
- *
83
- * The Host kills a Monitor after >30s of continuous suppression, which a burst
84
- * of `capacity` immediate writes could not by itself reach. This gate therefore
85
- * also tracks the sustained interval between accepted writes and enforces a
86
- * conservative minimum spacing. It tolerates the Host's own 200ms line buffer:
87
- * two writes closer than `minIntervalMs` would coalesce into one batch (using
88
- * fewer tokens, never more), so jitter can only merge, never split — the safe
89
- * direction.
90
- */
91
- export class HostMonitorWriteGate {
92
- private readonly bucket: TokenBucket;
93
- private readonly minIntervalMs: number;
94
- private readonly now: () => number;
95
- private lastAcceptedAtMs = 0;
96
- private hasAccepted = false;
97
-
98
- constructor(options: TokenBucketOptions & { minIntervalMs?: number } = {}) {
99
- this.bucket = new TokenBucket(options);
100
- this.minIntervalMs = options.minIntervalMs ?? 300;
101
- this.now = options.now ?? Date.now;
102
- }
103
-
104
- /**
105
- * Returns true when the relay may write stdout now.
106
- *
107
- * Both the bucket token AND the sustained-rate spacing must be satisfied.
108
- */
109
- allow(): boolean {
110
- const nowMs = this.now();
111
- const spaced = !this.hasAccepted || (nowMs - this.lastAcceptedAtMs) >= this.minIntervalMs;
112
- if (!spaced || !this.bucket.tryConsume()) return false;
113
- this.lastAcceptedAtMs = nowMs;
114
- this.hasAccepted = true;
115
- return true;
116
- }
117
-
118
- /** Resets the gate (e.g. after a reconnect). */
119
- reset(): void {
120
- this.lastAcceptedAtMs = 0;
121
- this.hasAccepted = false;
122
- }
123
- }
1
+ export * from '@myclaw163/game-agent-runtime/mailbox/host-monitor-rate-gate.js';
@@ -1,326 +1 @@
1
- import { randomUUID } from 'crypto';
2
- import {
3
- DEFAULT_EVENT_CONSUMER_ID,
4
- type EventRepository,
5
- } from './framework/events/index.js';
6
- import type {
7
- MailboxDeliveryMode,
8
- MailboxRepository,
9
- } from './framework/mailbox/index.js';
10
- import type {
11
- OwnerControlRequest,
12
- OwnerControlResponse,
13
- HostRelayOwnerControlType,
14
- } from './owner-control.js';
15
- import type { HostMonitorWriteGate } from './host-monitor-rate-gate.js';
16
-
17
- export const MAILBOX_RELAY_REQUEST_TYPES = [
18
- 'mailbox_claim',
19
- 'mailbox_ack',
20
- 'mailbox_nack',
21
- ] as const;
22
-
23
- export type MailboxRelayRequestType = typeof MAILBOX_RELAY_REQUEST_TYPES[number];
24
-
25
- const RELAY_ID_MAX_CHARS = 200;
26
- const CLAIM_TOKEN_MAX_CHARS = 200;
27
- const DEFAULT_RELAY_LEASE_TTL_MS = 10_000;
28
- const MAX_RELAY_LEASE_TTL_MS = 30_000;
29
- export const DEFAULT_RELAY_POLL_MS = 220;
30
- const DEFAULT_RELAY_BATCH_SIZE = 100;
31
-
32
- function boundedString(value: unknown, maxChars: number): string | undefined {
33
- if (typeof value !== 'string') return undefined;
34
- const trimmed = value.trim();
35
- if (!trimmed || trimmed.length > maxChars) return undefined;
36
- return trimmed;
37
- }
38
-
39
- function boundedLeaseTtl(value: unknown): number {
40
- const numeric = Number(value);
41
- if (!Number.isFinite(numeric)) return DEFAULT_RELAY_LEASE_TTL_MS;
42
- return Math.max(1_000, Math.min(MAX_RELAY_LEASE_TTL_MS, Math.trunc(numeric)));
43
- }
44
-
45
- function isRelayRequestType(value: unknown): value is MailboxRelayRequestType {
46
- return MAILBOX_RELAY_REQUEST_TYPES.includes(value as MailboxRelayRequestType);
47
- }
48
-
49
- /**
50
- * Authenticated Owner-side Mailbox endpoint.
51
- *
52
- * The surrounding owner-control server has already authenticated a local
53
- * master token before this broker is called. Strategy and Perception do not
54
- * receive owner-control credentials: Owner-thread instances are called
55
- * directly, and parallel Worker Threads do not use these request families.
56
- */
57
- export class MailboxRelayBroker<TPayload extends Record<string, unknown> = Record<string, unknown>> {
58
- private lastContactAtMs = 0;
59
-
60
- constructor(
61
- private readonly repository: EventRepository & MailboxRepository,
62
- readonly mode: MailboxDeliveryMode,
63
- private readonly consumerId = DEFAULT_EVENT_CONSUMER_ID,
64
- private readonly maxItems = DEFAULT_RELAY_BATCH_SIZE,
65
- private readonly onDelivered?: (eventIds: readonly string[]) => void,
66
- ) {}
67
-
68
- handle(request: OwnerControlRequest): OwnerControlResponse | undefined {
69
- if (!isRelayRequestType(request.type)) return undefined;
70
- const relayId = boundedString(request.relay_id, RELAY_ID_MAX_CHARS);
71
- if (!relayId) return { ok: false, error: 'invalid_mailbox_relay_id' };
72
- if (request.mode !== this.mode) {
73
- return {
74
- ok: false,
75
- error: 'mailbox_mode_mismatch',
76
- expected_mode: this.mode,
77
- };
78
- }
79
- this.lastContactAtMs = Date.now();
80
-
81
- if (request.type === 'mailbox_claim') {
82
- const scope = this.repository.currentScope();
83
- if (!scope) {
84
- return { ok: true, type: 'mailbox_claim', claim: null, wait_ms: DEFAULT_RELAY_POLL_MS };
85
- }
86
- const next = this.repository.peekMailbox({
87
- consumerId: this.consumerId,
88
- sessionId: scope.session.sessionId,
89
- modes: [this.mode],
90
- states: ['pending', 'claimed'],
91
- order: 'asc',
92
- limit: 1,
93
- })[0];
94
- const segmentId = next?.segmentId ?? scope.segment.segmentId;
95
- const claim = this.repository.claimMailbox<TPayload>({
96
- consumerId: this.consumerId,
97
- sessionId: scope.session.sessionId,
98
- segmentId,
99
- mode: this.mode,
100
- ownerId: relayId,
101
- leaseTtlMs: boundedLeaseTtl(request.lease_ttl_ms),
102
- maxItems: this.maxItems,
103
- });
104
- return {
105
- ok: true,
106
- type: 'mailbox_claim',
107
- scope: {
108
- session_id: scope.session.sessionId,
109
- segment_id: claim?.items[0]?.segmentId ?? segmentId,
110
- },
111
- claim: claim ? {
112
- claim_token: claim.claimToken,
113
- expires_at_ms: claim.claimExpiresAtMs,
114
- items: claim.items.map((item) => ({
115
- item_id: item.itemId,
116
- event_id: item.eventId,
117
- payload: item.payload,
118
- })),
119
- } : null,
120
- wait_ms: DEFAULT_RELAY_POLL_MS,
121
- };
122
- }
123
-
124
- const claimToken = boundedString(request.claim_token, CLAIM_TOKEN_MAX_CHARS);
125
- if (!claimToken) return { ok: false, error: 'invalid_mailbox_claim_token' };
126
- if (request.type === 'mailbox_ack') {
127
- const result = this.repository.ackMailboxClaim({
128
- ownerId: relayId,
129
- claimToken,
130
- acceptedAt: typeof request.accepted_at === 'string'
131
- ? request.accepted_at
132
- : undefined,
133
- acceptanceLevel: 'sink_emitted',
134
- });
135
- if (result.status !== 'claim_lost') {
136
- try { this.onDelivered?.(result.eventIds); } catch { /* Best-effort display only. */ }
137
- }
138
- return { ok: true, type: 'mailbox_ack', result };
139
- }
140
- return {
141
- ok: true,
142
- type: 'mailbox_nack',
143
- result: this.repository.nackMailboxClaim({
144
- ownerId: relayId,
145
- claimToken,
146
- retryAtMs: Number.isFinite(Number(request.retry_at_ms))
147
- ? Math.max(Date.now(), Math.trunc(Number(request.retry_at_ms)))
148
- : Date.now() + DEFAULT_RELAY_POLL_MS,
149
- errorCode: boundedString(request.error_code, 100) ?? 'host_relay_write_failed',
150
- }),
151
- };
152
- }
153
-
154
- hasRecentRelay(withinMs = 2_000, nowMs = Date.now()): boolean {
155
- return this.lastContactAtMs > 0 && nowMs - this.lastContactAtMs <= withinMs;
156
- }
157
-
158
- hasPendingCurrent(): boolean {
159
- const scope = this.repository.currentScope();
160
- if (!scope) return false;
161
- return this.repository.peekMailbox({
162
- consumerId: this.consumerId,
163
- sessionId: scope.session.sessionId,
164
- modes: [this.mode],
165
- states: ['pending', 'claimed'],
166
- order: 'asc',
167
- limit: 1,
168
- }).length > 0;
169
- }
170
- }
171
-
172
- export interface StdoutMailboxRelayOptions {
173
- request: (
174
- type: HostRelayOwnerControlType,
175
- payload: Record<string, unknown>,
176
- timeoutMs?: number,
177
- ) => Promise<OwnerControlResponse | null>;
178
- emit: (payload: Record<string, unknown>) => Promise<void>;
179
- /** Compose one Host wake-up from all items in a coalesced Mailbox claim. */
180
- compose?: (payloads: readonly Record<string, unknown>[]) => Record<string, unknown>;
181
- /**
182
- * Mirror of the Host Monitor rate limiter. When this gate denies a write,
183
- * the claimed batch is nack'ed (released back to pending) instead of emitted,
184
- * so events are never dropped — they either reach the agent via a later
185
- * stdout write, or are pulled by `ccl events`.
186
- */
187
- rateGate?: HostMonitorWriteGate;
188
- isOwnerAlive: () => boolean;
189
- mode: MailboxDeliveryMode;
190
- signal?: AbortSignal;
191
- relayId?: string;
192
- pollMs?: number;
193
- requestTimeoutMs?: number;
194
- sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
195
- }
196
-
197
- function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {
198
- if (signal?.aborted) return Promise.resolve();
199
- return new Promise((resolve) => {
200
- const timer = setTimeout(finish, ms);
201
- const onAbort = (): void => finish();
202
- function finish(): void {
203
- clearTimeout(timer);
204
- signal?.removeEventListener('abort', onAbort);
205
- resolve();
206
- }
207
- signal?.addEventListener('abort', onAbort, { once: true });
208
- });
209
- }
210
-
211
- function relayClaim(value: unknown): {
212
- claimToken: string;
213
- items: Array<{ payload: Record<string, unknown> }>;
214
- } | null {
215
- if (!value || typeof value !== 'object') return null;
216
- const claim = value as Record<string, unknown>;
217
- const claimToken = boundedString(claim.claim_token, CLAIM_TOKEN_MAX_CHARS);
218
- if (!claimToken || !Array.isArray(claim.items) || claim.items.length === 0) return null;
219
- const items = claim.items.map((value) => {
220
- if (!value || typeof value !== 'object') return null;
221
- const payload = (value as Record<string, unknown>).payload;
222
- if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
223
- return { payload: payload as Record<string, unknown> };
224
- });
225
- if (items.some((item) => item === null)) return null;
226
- return { claimToken, items: items as Array<{ payload: Record<string, unknown> }> };
227
- }
228
-
229
- async function acknowledgeWithRetry(
230
- options: StdoutMailboxRelayOptions,
231
- relayId: string,
232
- claimToken: string,
233
- ): Promise<boolean> {
234
- for (let attempt = 0; attempt < 3; attempt += 1) {
235
- try {
236
- const response = await options.request('mailbox_ack', {
237
- relay_id: relayId,
238
- mode: options.mode,
239
- claim_token: claimToken,
240
- accepted_at: new Date().toISOString(),
241
- }, options.requestTimeoutMs);
242
- const status = response?.result?.status;
243
- if (response?.ok && (status === 'accepted' || status === 'already_accepted')) return true;
244
- if (status === 'claim_lost') return false;
245
- } catch {}
246
- if (!options.isOwnerAlive() || options.signal?.aborted) return false;
247
- await (options.sleep ?? defaultSleep)(50 * (attempt + 1), options.signal);
248
- }
249
- return false;
250
- }
251
-
252
- /**
253
- * Disposable Host-side loop. It has no Owner shutdown authority and never sends
254
- * stop/quit when its stdout consumer goes away.
255
- */
256
- export async function runStdoutMailboxRelay(options: StdoutMailboxRelayOptions): Promise<void> {
257
- const relayId = options.relayId ?? `stdout:${process.pid}:${randomUUID()}`;
258
- const sleep = options.sleep ?? defaultSleep;
259
- const pollMs = Math.max(25, Math.trunc(options.pollMs ?? DEFAULT_RELAY_POLL_MS));
260
- while (!options.signal?.aborted) {
261
- if (!options.isOwnerAlive()) return;
262
- let response: OwnerControlResponse | null = null;
263
- try {
264
- response = await options.request('mailbox_claim', {
265
- relay_id: relayId,
266
- mode: options.mode,
267
- lease_ttl_ms: DEFAULT_RELAY_LEASE_TTL_MS,
268
- }, options.requestTimeoutMs);
269
- } catch {
270
- if (!options.isOwnerAlive()) return;
271
- await sleep(pollMs, options.signal);
272
- continue;
273
- }
274
- if (!response) {
275
- if (!options.isOwnerAlive()) return;
276
- await sleep(pollMs, options.signal);
277
- continue;
278
- }
279
- if (!response.ok) {
280
- throw new Error(response.error ?? 'mailbox_relay_rejected');
281
- }
282
- if (!response.claim) {
283
- if (!options.isOwnerAlive()) return;
284
- await sleep(Math.max(25, Number(response.wait_ms) || pollMs), options.signal);
285
- continue;
286
- }
287
- const claim = relayClaim(response.claim);
288
- if (!claim) throw new Error('invalid_mailbox_claim');
289
- // Mirror the Host Monitor token bucket: if the Host would suppress this
290
- // write (bucket empty), do NOT emit. Nack the claim so the batch returns to
291
- // pending — events stay durable and reach the agent on a later poll or via
292
- // `ccl events`. Emitting anyway would be silently dropped by the Host.
293
- if (options.rateGate && !options.rateGate.allow()) {
294
- try {
295
- await options.request('mailbox_nack', {
296
- relay_id: relayId,
297
- mode: options.mode,
298
- claim_token: claim.claimToken,
299
- retry_at_ms: Date.now() + pollMs,
300
- error_code: 'host_rate_limited',
301
- }, options.requestTimeoutMs);
302
- } catch {}
303
- await sleep(Math.max(25, Number(response.wait_ms) || pollMs), options.signal);
304
- continue;
305
- }
306
- try {
307
- if (options.compose) {
308
- await options.emit(options.compose(claim.items.map((item) => item.payload)));
309
- } else {
310
- for (const item of claim.items) await options.emit(item.payload);
311
- }
312
- } catch (error) {
313
- try {
314
- await options.request('mailbox_nack', {
315
- relay_id: relayId,
316
- mode: options.mode,
317
- claim_token: claim.claimToken,
318
- retry_at_ms: Date.now() + pollMs,
319
- error_code: 'stdout_write_failed',
320
- }, options.requestTimeoutMs);
321
- } catch {}
322
- throw error;
323
- }
324
- await acknowledgeWithRetry(options, relayId, claim.claimToken);
325
- }
326
- }
1
+ export * from '@myclaw163/game-agent-runtime/mailbox/mailbox-host-relay.js';
@@ -1,13 +1,6 @@
1
- import { randomUUID } from 'node:crypto';
1
+ import { DetailCapture as CoreDetailCapture, type CaptureCategory, type DetailCaptureConfig } from '@myclaw163/game-agent-runtime/observability/detail-capture.js';
2
2
  import { readDiagnosticsConfig, type DiagnosticsConfig } from '../../lib/diagnostics-config.js';
3
-
4
- export type CaptureCategory = 'actions' | 'behavior_io' | 'perception_io';
5
- export interface DetailCaptureConfig {
6
- actions: boolean;
7
- behavior_io: boolean;
8
- perception_io: boolean;
9
- max_record_bytes: number;
10
- }
3
+ export { captureSnapshot, detailCategory, type CaptureCategory, type DetailCaptureConfig } from '@myclaw163/game-agent-runtime/observability/detail-capture.js';
11
4
  export function resolveDetailCapture(config?: DiagnosticsConfig, env = process.env): DetailCaptureConfig {
12
5
  let selected = config;
13
6
  if (!selected) { try { selected = readDiagnosticsConfig(); } catch { /* fail closed */ } }
@@ -21,103 +14,6 @@ export function resolveDetailCapture(config?: DiagnosticsConfig, env = process.e
21
14
  return { actions: enabled('actions'), behavior_io: enabled('behavior_io'), perception_io: enabled('perception_io'),
22
15
  max_record_bytes: selected?.capture?.max_record_bytes ?? 256 * 1024 };
23
16
  }
24
- export function detailCategory(name: string): CaptureCategory | undefined {
25
- return /^runtime\.detail\.(actions|behavior_io|perception_io)\./.exec(name)?.[1] as CaptureCategory | undefined;
26
- }
27
- type Diagnostic = (name: string, attributes: Readonly<Record<string, unknown>>, severity?: 'debug' | 'info' | 'warn' | 'error') => void;
28
-
29
- /** Opt-in, lazy, Owner-side observer. No module API, gameplay Event or cross-Worker payload is added. */
30
- export class DetailCapture {
31
- readonly enabled: boolean;
32
- constructor(readonly category: CaptureCategory, private readonly diagnostic?: Diagnostic,
33
- config?: DetailCaptureConfig) { this.enabled = !!diagnostic && (config ?? resolveDetailCapture())[category]; }
34
- emit(phase: string, attributes: () => Record<string, unknown>): void {
35
- if (!this.enabled) return;
36
- try { this.diagnostic?.(`runtime.detail.${this.category}.${phase}`, attributes(), 'debug'); } catch { /* observational */ }
37
- }
38
- run<T>(operation: string, metadata: Record<string, unknown>, input: unknown, invoke: () => Promise<T>, signal?: AbortSignal): Promise<T> {
39
- if (!this.enabled) return invoke();
40
- const invocation_id = randomUUID(), started = performance.now();
41
- const base = { ...metadata, invocation_id, operation };
42
- this.emit('input', () => ({ ...base, input, stage: 'requested' }));
43
- let aborted = false;
44
- const onAbort = () => {
45
- aborted = true;
46
- this.emit('cancelled', () => ({ ...base, duration_ms: performance.now() - started,
47
- error: signal?.reason instanceof Error ? signal.reason.message : 'aborted' }));
48
- };
49
- signal?.addEventListener('abort', onAbort, { once: true });
50
- return (async () => {
51
- try {
52
- const output = await invoke();
53
- this.emit('output', () => ({ ...base, output: output ?? null,
54
- stage: aborted ? 'late_result' : 'computed_not_yet_runtime_committed', duration_ms: performance.now() - started }));
55
- return output;
56
- } catch (error) {
57
- this.emit('failed', () => ({ ...base, error: error instanceof Error ? { name: error.name, message: error.message } : String(error),
58
- duration_ms: performance.now() - started }));
59
- throw error;
60
- } finally { signal?.removeEventListener('abort', onAbort); }
61
- })();
62
- }
63
- }
64
-
65
- /** Bounded JSON snapshot: preserves gameplay payloads and IDs, always removes credentials. */
66
- export function captureSnapshot(value: unknown, maxBytes: number): { value: unknown; truncated: boolean } {
67
- let remaining = maxBytes, nodes = 0, truncated = false;
68
- const seen = new WeakSet<object>();
69
- const marker = (): string => { truncated = true; return '[TRUNCATED]'; };
70
- const secret = /(?:^|_)(?:api_key|claw_key|token|access_token|refresh_token|authorization|cookie|password|passwd|secret|private_key|credential|env|environment)(?:_value)?$/i;
71
- const visit = (item: unknown, key = '', depth = 0): unknown => {
72
- if (++nodes > 20000 || remaining <= 0 || depth > 32) return marker();
73
- remaining -= Buffer.byteLength(key) * 6 + 16;
74
- if (secret.test(key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').replace(/[^A-Za-z0-9]+/g, '_'))) return '[REDACTED]';
75
- if (item === null || item === undefined) return item ?? null;
76
- if (typeof item === 'boolean' || typeof item === 'number') return item;
77
- if (typeof item === 'string') {
78
- const limit = Math.max(0, Math.floor(remaining / 6));
79
- const cut = item.length > limit;
80
- const text = item.slice(0, limit)
81
- .replace(/\bBearer\s+[^\s"']+/gi, 'Bearer [REDACTED]')
82
- .replace(/\b(?:sk-|claw_|ghp_|github_pat_)[A-Za-z0-9_-]+/g, '[REDACTED]')
83
- .replace(/([?&](?:token|key|code|api_key|access_token)=)[^&\s"']+/gi, '$1[REDACTED]');
84
- remaining -= text.length * 6;
85
- return cut ? text + marker() : text;
86
- }
87
- if (typeof item !== 'object') return `[${typeof item}_OMITTED]`;
88
- if (item instanceof Error) {
89
- const field = (name: string, fallback: string) => {
90
- const descriptor = Object.getOwnPropertyDescriptor(item, name);
91
- return descriptor ? 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]' : fallback;
92
- };
93
- return visit({ name: field('name', 'Error'), message: field('message', '') }, key, depth + 1);
94
- }
95
- if (seen.has(item)) return '[CIRCULAR]';
96
- if (ArrayBuffer.isView(item) || item instanceof ArrayBuffer) return '[BINARY_OMITTED]';
97
- seen.add(item);
98
- const out: any = Array.isArray(item) ? [] : {};
99
- if (Array.isArray(item)) {
100
- // JSON serializes holes as nulls. Charge them too; copying an isolated
101
- // high index would create an enormous sparse output despite the budget.
102
- for (let index = 0; index < item.length; index += 1) {
103
- if (remaining <= 0 || nodes > 20000) { out.push(marker()); break; }
104
- const descriptor = Object.getOwnPropertyDescriptor(item, String(index));
105
- out.push(visit(descriptor ? 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]' : null, String(index), depth + 1));
106
- }
107
- seen.delete(item);
108
- return out;
109
- }
110
- // Do not enumerate getters or run user-defined toJSON methods while logging.
111
- for (const name in item) {
112
- if (!Object.prototype.hasOwnProperty.call(item, name)) continue;
113
- if (name.length > 1024) { if (Array.isArray(out)) out.push(marker()); else out.__capture_truncated = marker(); break; }
114
- if (remaining <= 0 || nodes > 20000) { if (Array.isArray(out)) out.push(marker()); else out.__capture_truncated = marker(); break; }
115
- const descriptor = Object.getOwnPropertyDescriptor(item, name);
116
- const next = visit(descriptor && 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]', name, depth + 1);
117
- Object.defineProperty(out, name, { value: next, enumerable: true, configurable: true, writable: true });
118
- }
119
- seen.delete(item);
120
- return out;
121
- };
122
- return { value: visit(value), truncated };
17
+ export class DetailCapture extends CoreDetailCapture {
18
+ constructor(category: CaptureCategory, diagnostic?: ConstructorParameters<typeof CoreDetailCapture>[1], config?: DetailCaptureConfig) { super(category, diagnostic, config ?? resolveDetailCapture()); }
123
19
  }
@@ -1,59 +1,2 @@
1
- import { monitorEventLoopDelay, performance, PerformanceObserver } from 'node:perf_hooks';
2
-
3
- /** Full-only process/Owner-loop measurements. Does not retain GC entries or gameplay data. */
4
- export class RuntimeProcessTimingSampler {
5
- private readonly delay = monitorEventLoopDelay({ resolution: 20 });
6
- private readonly observer: PerformanceObserver;
7
- private previousCpu = process.cpuUsage();
8
- private previousLoop = performance.eventLoopUtilization();
9
- private previousAt = performance.now();
10
- private gcCount = 0;
11
- private gcMs = 0;
12
- private stopped = false;
13
-
14
- constructor() {
15
- this.observer = new PerformanceObserver((entries) => {
16
- for (const entry of entries.getEntries()) {
17
- this.gcCount += 1;
18
- this.gcMs += entry.duration;
19
- }
20
- });
21
- this.observer.observe({ entryTypes: ['gc'] });
22
- this.delay.enable();
23
- }
24
-
25
- sample(): Readonly<Record<string, number>> {
26
- const now = performance.now();
27
- const cpu = process.cpuUsage();
28
- const loop = performance.eventLoopUtilization();
29
- const elapsed = now - this.previousAt;
30
- const deltaLoop = performance.eventLoopUtilization(loop, this.previousLoop);
31
- const milliseconds = (ns: number): number => Number.isFinite(ns) ? Math.round(ns / 1_000) / 1_000 : 0;
32
- const result = {
33
- window_ms: Math.round(elapsed),
34
- // process.cpuUsage includes Worker threads; this is not Owner-isolate CPU utilization.
35
- process_cpu_user_ms: (cpu.user - this.previousCpu.user) / 1_000,
36
- process_cpu_system_ms: (cpu.system - this.previousCpu.system) / 1_000,
37
- owner_event_loop_utilization: deltaLoop.utilization,
38
- owner_event_loop_delay_mean_ms: milliseconds(this.delay.mean),
39
- owner_event_loop_delay_p95_ms: milliseconds(this.delay.percentile(95)),
40
- owner_event_loop_delay_max_ms: milliseconds(this.delay.max),
41
- owner_gc_count: this.gcCount,
42
- owner_gc_duration_ms: Math.round(this.gcMs * 1_000) / 1_000,
43
- };
44
- this.previousAt = now;
45
- this.previousCpu = cpu;
46
- this.previousLoop = loop;
47
- this.gcCount = 0;
48
- this.gcMs = 0;
49
- this.delay.reset();
50
- return result;
51
- }
52
-
53
- stop(): void {
54
- if (this.stopped) return;
55
- this.stopped = true;
56
- this.observer.disconnect();
57
- this.delay.disable();
58
- }
59
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/observability/process-timing.js';