@myclaw163/clawclaw-cli 0.9.2 → 0.10.1

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 (197) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +23 -35
  7. package/docs/custom-modules/api-reference.md +95 -273
  8. package/docs/custom-modules/behavior.md +94 -78
  9. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +42 -603
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +16 -17
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +47 -46
  19. package/docs/runtime/components-and-boundaries.md +70 -28
  20. package/docs/runtime/events-and-state.md +41 -18
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +10 -7
  26. package/docs/user-guide/api-reference.md +81 -164
  27. package/docs/user-guide/behavior.md +84 -68
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +42 -586
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +8 -13
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +49 -49
  37. package/skills/clawclaw/references/BEHAVIORS.md +42 -73
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +60 -101
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +94 -78
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +95 -180
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +24 -24
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +42 -608
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +26 -10
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +3 -2
  53. package/src/commands/perception.ts +5 -0
  54. package/src/commands/strategy.ts +2 -0
  55. package/src/lib/capability-load-diagnostics.ts +3 -3
  56. package/src/lib/perception-config.ts +18 -6
  57. package/src/lib/runtime-cadence-config.ts +16 -0
  58. package/src/lib/workspace-runtime-lock.ts +3 -46
  59. package/src/pipeline/canonical-event-presentation.ts +23 -124
  60. package/src/pipeline/event-format.ts +12 -21
  61. package/src/pipeline/event-hints.ts +6 -6
  62. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  63. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  64. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  65. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  66. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  67. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  68. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  69. package/src/runtime/clawclaw/owner.ts +18 -4
  70. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  71. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  72. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  73. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  74. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  75. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  76. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  77. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  78. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  79. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  82. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  83. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  84. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  85. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  86. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +25 -17
  87. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  88. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  89. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  90. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  91. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  92. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  93. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  94. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  95. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  96. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  97. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  98. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  99. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  100. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  101. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +119 -297
  102. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  103. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  104. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +18 -7
  105. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  106. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  107. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  108. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  109. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  110. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  111. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  112. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  113. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  114. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  115. package/src/runtime/clawclaw/runtime.ts +8 -0
  116. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  117. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  118. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  119. package/src/runtime/framework/action-diagnostics.ts +3 -83
  120. package/src/runtime/framework/capability-registry.ts +2 -395
  121. package/src/runtime/framework/contracts.ts +2 -144
  122. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  123. package/src/runtime/framework/control/domain-set.ts +2 -81
  124. package/src/runtime/framework/control/index.ts +1 -3
  125. package/src/runtime/framework/control/types.ts +2 -191
  126. package/src/runtime/framework/control-coordinator.ts +2 -11
  127. package/src/runtime/framework/events/event-catalog.ts +2 -74
  128. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  129. package/src/runtime/framework/events/event-ingress.ts +2 -99
  130. package/src/runtime/framework/events/event-repository.ts +2 -82
  131. package/src/runtime/framework/events/index.ts +2 -7
  132. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  133. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  134. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  135. package/src/runtime/framework/events/test-helpers.ts +1 -1
  136. package/src/runtime/framework/events/types.ts +2 -312
  137. package/src/runtime/framework/index.ts +3 -7
  138. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  139. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  140. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  141. package/src/runtime/framework/mailbox/identity.ts +2 -38
  142. package/src/runtime/framework/mailbox/index.ts +1 -7
  143. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  144. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  145. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  146. package/src/runtime/framework/mailbox/types.ts +2 -145
  147. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  148. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  149. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  150. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  151. package/src/runtime/framework/participation-manager.ts +2 -253
  152. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  153. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  154. package/src/runtime/framework/plugins/contracts.ts +2 -396
  155. package/src/runtime/framework/plugins/index.ts +1 -4
  156. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  157. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  158. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  159. package/src/runtime/framework/runtime.ts +5 -1843
  160. package/src/runtime/framework/serial-task-queue.ts +2 -14
  161. package/src/runtime/framework/state/contracts.ts +2 -49
  162. package/src/runtime/framework/state/current-state-store.ts +2 -184
  163. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  164. package/src/runtime/framework/state/freshness.ts +2 -72
  165. package/src/runtime/framework/state/history/contracts.ts +2 -158
  166. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  167. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  168. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  169. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  170. package/src/runtime/framework/state/index.ts +1 -13
  171. package/src/runtime/framework/state/state-ingress.ts +2 -95
  172. package/src/runtime/framework/state/state-provider.ts +2 -62
  173. package/src/runtime/framework/state/types.ts +2 -155
  174. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  175. package/src/runtime/mailbox-host-relay.ts +1 -326
  176. package/src/runtime/observability/detail-capture.ts +4 -108
  177. package/src/runtime/observability/process-timing.ts +2 -59
  178. package/src/runtime/observability/recorder.ts +2 -238
  179. package/src/runtime/observability/redaction.ts +2 -181
  180. package/src/runtime/observability/reporter.ts +2 -154
  181. package/src/runtime/observability/sinks.ts +2 -135
  182. package/src/runtime/observability/types.ts +2 -92
  183. package/src/runtime/owner-control.ts +45 -320
  184. package/src/runtime/parent-process-watch.ts +1 -51
  185. package/src/runtime/process-identity.ts +1 -72
  186. package/src/sdk/behavior-plugin/index.ts +9 -3
  187. package/src/sdk/index.ts +40 -2
  188. package/src/sdk/module-input/index.ts +5 -0
  189. package/src/sdk/perception-plugin/index.ts +3 -1
  190. package/src/sdk/perception-plugin/module.ts +12 -2
  191. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  192. package/src/sdk/perception-plugin/reminder.ts +2 -1
  193. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  194. package/src/sdk/strategy-memory.ts +1 -12
  195. package/src/sdk/strategy-plugin/index.ts +36 -0
  196. package/src/sdk/trigger-plugin/index.ts +1 -0
  197. package/docs/custom-modules/trigger.md +0 -295
@@ -1,238 +1,2 @@
1
- import { randomUUID } from 'crypto';
2
- import { ObservabilityRedactor } from './redaction.js';
3
- import { NoopObservabilityReporter } from './reporter.js';
4
- import { captureSnapshot, detailCategory, type DetailCaptureConfig } from './detail-capture.js';
5
- import {
6
- OBSERVABILITY_SCHEMA,
7
- type ObservabilityCorrelation,
8
- type ObservabilityError,
9
- type ObservabilityProcess,
10
- type ObservabilityRecord,
11
- type ObservabilityReporter,
12
- type ObservabilityScope,
13
- type ObservabilitySeverity,
14
- type RecordTelemetryInput,
15
- } from './types.js';
16
-
17
- export interface TelemetryRecorderOptions {
18
- process: ObservabilityProcess;
19
- reporter?: ObservabilityReporter;
20
- redactor?: ObservabilityRedactor;
21
- enabled?: boolean;
22
- now?: () => Date;
23
- idFactory?: () => string;
24
- scopeProvider?: () => ObservabilityScope | undefined;
25
- sampler?: (input: Readonly<RecordTelemetryInput>) => boolean;
26
- capture?: DetailCaptureConfig;
27
- detailReporter?: ObservabilityReporter;
28
- }
29
-
30
- function defaultSeverity(kind: RecordTelemetryInput['kind']): ObservabilitySeverity {
31
- return kind === 'error' ? 'error' : 'info';
32
- }
33
-
34
- function normalizedError(error: unknown): ObservabilityError | undefined {
35
- if (error === undefined || error === null) return undefined;
36
- if (error instanceof Error) {
37
- const code = typeof (error as any).code === 'string' ? (error as any).code : undefined;
38
- return {
39
- name: error.name,
40
- ...(code ? { code } : {}),
41
- message: error.message,
42
- stack: error.stack,
43
- cause: error.cause,
44
- };
45
- }
46
- if (typeof error === 'string') return { message: error };
47
- if (typeof error === 'object') return error as ObservabilityError;
48
- return { message: String(error) };
49
- }
50
-
51
- function validName(name: string): string {
52
- const normalized = name.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, '_').slice(0, 120);
53
- return normalized || 'unnamed';
54
- }
55
-
56
- function normalizedScope(scope: ObservabilityScope | undefined): ObservabilityScope | undefined {
57
- if (!scope) return undefined;
58
- return {
59
- ...(typeof scope.adapterId === 'string' ? { adapterId: scope.adapterId } : {}),
60
- ...(typeof scope.sessionId === 'string' ? { sessionId: scope.sessionId } : {}),
61
- ...(typeof scope.segmentId === 'string' ? { segmentId: scope.segmentId } : {}),
62
- ...(typeof scope.segmentSeq === 'number' && Number.isFinite(scope.segmentSeq)
63
- ? { segmentSeq: scope.segmentSeq }
64
- : {}),
65
- ...(typeof scope.connectionId === 'string' ? { connectionId: scope.connectionId } : {}),
66
- };
67
- }
68
-
69
- /** Owner-side authority for logs, metrics and error reports. Never throws into gameplay. */
70
- export class TelemetryRecorder {
71
- private readonly process: ObservabilityProcess;
72
- private readonly reporter: ObservabilityReporter;
73
- private readonly redactor: ObservabilityRedactor;
74
- private readonly enabled: boolean;
75
- private readonly now: () => Date;
76
- private readonly idFactory: () => string;
77
- private readonly scopeProvider?: () => ObservabilityScope | undefined;
78
- private readonly sampler: (input: Readonly<RecordTelemetryInput>) => boolean;
79
- private readonly capture?: DetailCaptureConfig;
80
- private readonly detailReporter?: ObservabilityReporter;
81
- private lastDetailScope?: ObservabilityScope;
82
-
83
- constructor(options: TelemetryRecorderOptions) {
84
- this.process = { ...options.process };
85
- this.reporter = options.reporter ?? new NoopObservabilityReporter();
86
- this.redactor = options.redactor ?? new ObservabilityRedactor();
87
- this.enabled = options.enabled !== false;
88
- this.now = options.now ?? (() => new Date());
89
- this.idFactory = options.idFactory ?? (() => `obs_${randomUUID()}`);
90
- this.scopeProvider = options.scopeProvider;
91
- this.sampler = options.sampler ?? (() => true);
92
- this.capture = options.capture;
93
- this.detailReporter = options.detailReporter;
94
- }
95
-
96
- record(input: RecordTelemetryInput): string | null {
97
- if (!this.enabled) return null;
98
- try {
99
- const category = detailCategory(input.name);
100
- if (category ? !this.capture?.[category] : !this.sampler(input)) return null;
101
- const recordId = this.idFactory();
102
- const scope = normalizedScope(input.scope ?? this.scopeProvider?.());
103
- if (category && scope) this.lastDetailScope = scope;
104
- const captured = category ? captureSnapshot(input.attributes ?? {}, this.capture!.max_record_bytes - 2048) : undefined;
105
- const attributes = captured
106
- ? { ...(captured.value as Record<string, unknown>), capture_truncated: captured.truncated }
107
- : this.redactor.redactRecord(input.attributes ?? {});
108
- const correlation = input.correlation
109
- ? this.redactor.redactRecord(input.correlation as Record<string, unknown>) as ObservabilityCorrelation
110
- : undefined;
111
- const metric = input.metric
112
- ? this.redactor.redactRecord(input.metric as unknown as Record<string, unknown>) as unknown as typeof input.metric
113
- : undefined;
114
- const error = normalizedError(input.error);
115
- const redactedError = error
116
- ? this.redactor.redactRecord(error as Record<string, unknown>) as ObservabilityError
117
- : undefined;
118
- const record: ObservabilityRecord = {
119
- schema: OBSERVABILITY_SCHEMA,
120
- recordId,
121
- timestamp: this.now().toISOString(),
122
- kind: input.kind,
123
- name: validName(input.name),
124
- severity: input.severity ?? defaultSeverity(input.kind),
125
- component: validName(input.component ?? 'runtime'),
126
- process: { ...this.process },
127
- ...(scope ? { scope } : {}),
128
- ...(correlation ? { correlation } : {}),
129
- attributes,
130
- ...(metric ? { metric } : {}),
131
- ...(redactedError ? { error: redactedError } : {}),
132
- };
133
- return (category ? this.detailReporter ?? this.reporter : this.reporter).enqueue(record) ? recordId : null;
134
- } catch {
135
- return null;
136
- }
137
- }
138
-
139
- log(
140
- severity: ObservabilitySeverity,
141
- name: string,
142
- attributes: Record<string, unknown> = {},
143
- context: Pick<RecordTelemetryInput, 'component' | 'scope' | 'correlation'> = {},
144
- ): string | null {
145
- return this.record({ kind: 'log', severity, name, attributes, ...context });
146
- }
147
-
148
- metric(
149
- name: string,
150
- value: number,
151
- options: Pick<RecordTelemetryInput, 'component' | 'scope' | 'correlation' | 'attributes'> & {
152
- unit?: string;
153
- aggregation?: 'counter' | 'gauge' | 'histogram_sample';
154
- } = {},
155
- ): string | null {
156
- const { unit, aggregation, ...context } = options;
157
- return this.record({
158
- kind: 'metric',
159
- name,
160
- ...context,
161
- metric: { value, unit, aggregation },
162
- });
163
- }
164
-
165
- error(
166
- name: string,
167
- error: unknown,
168
- attributes: Record<string, unknown> = {},
169
- context: Pick<RecordTelemetryInput, 'component' | 'scope' | 'correlation'> = {},
170
- ): string | null {
171
- return this.record({ kind: 'error', name, severity: 'error', error, attributes, ...context });
172
- }
173
-
174
- logger(component: string, base: Record<string, unknown> = {}): StructuredLogger {
175
- return new StructuredLogger(this, component, base);
176
- }
177
-
178
- private captureSummary(): void {
179
- if (!this.detailReporter) return;
180
- const category = (['actions', 'behavior_io', 'perception_io'] as const).find(key => this.capture?.[key]);
181
- if (category) this.log('debug', `runtime.detail.${category}.summary`, { reporter: this.detailReporter.stats() },
182
- { component: 'runtime.capture', scope: this.lastDetailScope });
183
- }
184
- async flush(): Promise<void> {
185
- await Promise.all([this.reporter.flush(), this.detailReporter?.flush()]);
186
- this.captureSummary();
187
- await this.detailReporter?.flush();
188
- }
189
- async close(): Promise<void> {
190
- try { await this.flush(); } finally { await Promise.all([this.reporter.close(), this.detailReporter?.close()]); }
191
- }
192
- flushWithin(timeoutMs: number): Promise<boolean> {
193
- return settleWithin(this.flush(), timeoutMs);
194
- }
195
- closeWithin(timeoutMs: number): Promise<boolean> {
196
- return settleWithin(this.close(), timeoutMs);
197
- }
198
- stats() { return this.reporter.stats(); }
199
- detailStats() { return this.detailReporter?.stats(); }
200
- captureEnabled(category: keyof Pick<DetailCaptureConfig, 'actions' | 'behavior_io' | 'perception_io'>): boolean {
201
- return this.enabled && this.capture?.[category] === true;
202
- }
203
- }
204
-
205
- /** Stop awaiting diagnostics after a bounded window; gameplay owns hard exit/cancellation. */
206
- async function settleWithin(operation: Promise<void>, timeoutMs: number): Promise<boolean> {
207
- let timer: ReturnType<typeof setTimeout> | undefined;
208
- const completed = operation.then(() => true, () => false);
209
- const timedOut = new Promise<boolean>((resolve) => {
210
- timer = setTimeout(() => resolve(false), Math.max(1, timeoutMs));
211
- });
212
- try {
213
- return await Promise.race([completed, timedOut]);
214
- } finally {
215
- if (timer) clearTimeout(timer);
216
- }
217
- }
218
-
219
- export class StructuredLogger {
220
- constructor(
221
- private readonly recorder: TelemetryRecorder,
222
- private readonly component: string,
223
- private readonly base: Record<string, unknown> = {},
224
- ) {}
225
-
226
- debug(name: string, attributes: Record<string, unknown> = {}): string | null {
227
- return this.recorder.log('debug', name, { ...this.base, ...attributes }, { component: this.component });
228
- }
229
- info(name: string, attributes: Record<string, unknown> = {}): string | null {
230
- return this.recorder.log('info', name, { ...this.base, ...attributes }, { component: this.component });
231
- }
232
- warn(name: string, attributes: Record<string, unknown> = {}): string | null {
233
- return this.recorder.log('warn', name, { ...this.base, ...attributes }, { component: this.component });
234
- }
235
- error(name: string, error: unknown, attributes: Record<string, unknown> = {}): string | null {
236
- return this.recorder.error(name, error, { ...this.base, ...attributes }, { component: this.component });
237
- }
238
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/observability/recorder.js';
@@ -1,181 +1,2 @@
1
- import { createHash, randomBytes } from 'crypto';
2
- import { extname } from 'path';
3
-
4
- const SECRET_KEY = /(?:^|_)(?:api_key|claw_key|token|access_token|refresh_token|authorization|cookie|cookie_header|password|passwd|secret|secret_key|credential|private_key|invite_code)(?:_value)?$/;
5
- const PRIVATE_TEXT_KEY = /(?:^|_)(?:speech|comment|think|thinking|chat|knowledge|persona|prompt)(?:_text|_content|_raw)?$|(?:^|_)(?:source_code|audio|audio_url|avatar|avatar_url)$/;
6
- const RAW_PAYLOAD_KEY = /(?:^|_)(?:raw|raw_frame|raw_payload|raw_ws|frame|frame_payload|payload|state|game_state|state_payload|room_payload|event_payload|request_body|response_body|environment|env)$/;
7
- const PATH_KEY = /(?:^|_)(?:path|cwd|workspace|directory|dir|filename|file_path|file_name)$/;
8
- const IDENTITY_KEY = /(?:^|_)(?:account|account_id|player_name|room_code|agent_name|user_id)$/;
9
- const DIAGNOSTIC_CODE_KEY = /^(?:code|error_code|.*_error_code)$/;
10
- const DIAGNOSTIC_CODE = /^[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)+$/;
11
- const SECRET_CODE_PREFIX = /^(?:claw_|sk[-_]|ghp_|github_pat_|eyj)/i;
12
- const TOKEN_IN_TEXT = /\b(?:Bearer\s+)?[A-Za-z0-9_-]{24,}\b/g;
13
- const FILE_URL = /file:\/\/\/?[^"'\r\n<>\)\]]+/gi;
14
- const WINDOWS_PATH = /\b[A-Za-z]:[\\\/][^"'\r\n<>\)\]]+/g;
15
- const POSIX_HOME_PATH = /\/(?:home|Users)\/[^"'\r\n<>\)\]]+/g;
16
- const NETWORK_URL = /\b(?:https?|wss?):\/\/[^\s"'<>\(\)\[\]{}]+/gi;
17
-
18
- export interface RedactionOptions {
19
- hashSalt?: string;
20
- maxDepth?: number;
21
- maxKeys?: number;
22
- maxArrayItems?: number;
23
- maxStringLength?: number;
24
- }
25
-
26
- export interface RedactionSummary {
27
- redacted: true;
28
- present: boolean;
29
- length?: number;
30
- kind?: 'private_text' | 'raw_payload' | 'local_path';
31
- extension?: string;
32
- }
33
-
34
- function stringLength(value: unknown): number | undefined {
35
- return typeof value === 'string' || Array.isArray(value) ? value.length : undefined;
36
- }
37
-
38
- function summarize(value: unknown, kind: RedactionSummary['kind']): RedactionSummary {
39
- return {
40
- redacted: true,
41
- present: value !== null && value !== undefined && value !== '',
42
- ...(stringLength(value) === undefined ? {} : { length: stringLength(value) }),
43
- kind,
44
- };
45
- }
46
-
47
- function pathSummary(value: unknown): RedactionSummary {
48
- const extension = typeof value === 'string' ? extname(value).slice(0, 16) : '';
49
- return {
50
- ...summarize(value, 'local_path'),
51
- ...(extension ? { extension } : {}),
52
- };
53
- }
54
-
55
- function normalizeUrl(value: string): string {
56
- try {
57
- const url = new URL(value);
58
- const path = url.pathname
59
- .split('/')
60
- .map((part) => /^[a-f0-9-]{16,}$/i.test(part) || /^\d{6,}$/.test(part) ? ':id' : part)
61
- .join('/');
62
- return `${url.protocol}//${url.host}${path}`;
63
- } catch {
64
- return value;
65
- }
66
- }
67
-
68
- /** Make snake_case, kebab-case and camelCase field names share one policy. */
69
- function normalizeKey(key: string): string {
70
- return key
71
- .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
72
- .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
73
- .replace(/[^A-Za-z0-9]+/g, '_')
74
- .replace(/^_+|_+$/g, '')
75
- .toLowerCase();
76
- }
77
-
78
- function safeString(value: string, maxLength: number): string {
79
- const withoutPaths = value
80
- .replace(FILE_URL, '[LOCAL_PATH]')
81
- .replace(WINDOWS_PATH, '[LOCAL_PATH]')
82
- .replace(POSIX_HOME_PATH, '[LOCAL_PATH]')
83
- .replace(TOKEN_IN_TEXT, '[REDACTED_TOKEN]');
84
- const withoutQuery = withoutPaths.replace(NETWORK_URL, (url) => normalizeUrl(url));
85
- return withoutQuery.length <= maxLength
86
- ? withoutQuery
87
- : `${withoutQuery.slice(0, maxLength)}...[truncated:${withoutQuery.length}]`;
88
- }
89
-
90
- /**
91
- * Preserve bounded semantic codes such as `behavior_activation_superseded`
92
- * without turning an error-code field into a credential escape hatch. Tokens
93
- * usually have a known secret prefix or one long high-entropy segment, while
94
- * Runtime diagnostic codes are made from multiple short semantic segments.
95
- */
96
- function safeDiagnosticCode(value: string): string | null {
97
- if (
98
- value.length === 0
99
- || value.length > 160
100
- || value.trim() !== value
101
- || !DIAGNOSTIC_CODE.test(value)
102
- || SECRET_CODE_PREFIX.test(value)
103
- || value.split(/[._-]/).some((segment) => segment.length >= 24)
104
- ) return null;
105
- return value;
106
- }
107
-
108
- /**
109
- * Redacts before persistence. It is deliberately defensive: cycles, deep
110
- * objects and oversized collections are bounded rather than allowed to break
111
- * gameplay or turn a diagnostic record into a State/raw-frame dump.
112
- */
113
- export class ObservabilityRedactor {
114
- private readonly salt: string;
115
- private readonly maxDepth: number;
116
- private readonly maxKeys: number;
117
- private readonly maxArrayItems: number;
118
- private readonly maxStringLength: number;
119
-
120
- constructor(options: RedactionOptions = {}) {
121
- this.salt = options.hashSalt ?? randomBytes(16).toString('hex');
122
- this.maxDepth = Math.max(1, options.maxDepth ?? 8);
123
- this.maxKeys = Math.max(1, options.maxKeys ?? 100);
124
- this.maxArrayItems = Math.max(1, options.maxArrayItems ?? 50);
125
- this.maxStringLength = Math.max(32, options.maxStringLength ?? 512);
126
- }
127
-
128
- redactRecord(record: Record<string, unknown>): Record<string, unknown> {
129
- return this.visit(record, 0, new WeakSet()) as Record<string, unknown>;
130
- }
131
-
132
- private stableHash(value: unknown): string {
133
- return `hash:${createHash('sha256').update(this.salt).update(String(value)).digest('hex').slice(0, 16)}`;
134
- }
135
-
136
- private visit(value: unknown, depth: number, seen: WeakSet<object>, key = ''): unknown {
137
- const policyKey = normalizeKey(key);
138
- if (SECRET_KEY.test(policyKey)) return '[REDACTED]';
139
- if (PRIVATE_TEXT_KEY.test(policyKey)) return summarize(value, 'private_text');
140
- if (RAW_PAYLOAD_KEY.test(policyKey)) return summarize(value, 'raw_payload');
141
- if (PATH_KEY.test(policyKey)) return pathSummary(value);
142
- if (IDENTITY_KEY.test(policyKey) && value !== null && value !== undefined) return this.stableHash(value);
143
- if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number') return value;
144
- if (typeof value === 'bigint') return value.toString();
145
- if (typeof value === 'string') {
146
- if (DIAGNOSTIC_CODE_KEY.test(policyKey)) {
147
- const code = safeDiagnosticCode(value);
148
- if (code) return code;
149
- }
150
- return safeString(value, this.maxStringLength);
151
- }
152
- if (depth >= this.maxDepth) return '[MAX_DEPTH]';
153
- if (value instanceof Error) {
154
- return this.visit({
155
- name: value.name,
156
- message: value.message,
157
- stack: value.stack,
158
- cause: value.cause,
159
- }, depth + 1, seen);
160
- }
161
- if (typeof value !== 'object') return String(value);
162
- if (seen.has(value)) return '[CIRCULAR]';
163
- seen.add(value);
164
- try {
165
- if (Array.isArray(value)) {
166
- const out = value.slice(0, this.maxArrayItems).map((item) => this.visit(item, depth + 1, seen));
167
- if (value.length > this.maxArrayItems) out.push(`[TRUNCATED:${value.length - this.maxArrayItems}]`);
168
- return out;
169
- }
170
- const entries = Object.entries(value as Record<string, unknown>).slice(0, this.maxKeys);
171
- const out: Record<string, unknown> = {};
172
- for (const [childKey, childValue] of entries) {
173
- out[childKey] = this.visit(childValue, depth + 1, seen, childKey);
174
- }
175
- if (Object.keys(value as object).length > this.maxKeys) out._truncated_keys = true;
176
- return out;
177
- } finally {
178
- seen.delete(value);
179
- }
180
- }
181
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/observability/redaction.js';
@@ -1,154 +1,2 @@
1
- import type {
2
- ObservabilityRecord,
3
- ObservabilityReporter,
4
- ObservabilityReporterStats,
5
- ObservabilitySink,
6
- } from './types.js';
7
-
8
- export interface BufferedObservabilityReporterOptions {
9
- maxQueueRecords?: number;
10
- batchSize?: number;
11
- flushIntervalMs?: number;
12
- }
13
-
14
- const CRITICAL_LIFECYCLE_RECORD = /^(?:runtime\.owner\.(?:started|stopped)|runtime\.scope\.switched|runtime\.persistence\.degraded|owner\.control\.(?:started|stopped)|behavior\.thread(?:_pool)?\.(?:started|stopped|retired|replacement_failed))$/;
15
-
16
- function recordPriority(record: ObservabilityRecord): number {
17
- if (
18
- record.kind === 'error'
19
- || record.severity === 'error'
20
- || record.severity === 'warn'
21
- || CRITICAL_LIFECYCLE_RECORD.test(record.name)
22
- ) return 2;
23
- return record.severity === 'debug' ? 0 : 1;
24
- }
25
-
26
- /** Bounded, best-effort process buffer in front of a durable/local sink. */
27
- export class BufferedObservabilityReporter implements ObservabilityReporter {
28
- private readonly sink: ObservabilitySink;
29
- private readonly maxQueueRecords: number;
30
- private readonly batchSize: number;
31
- private readonly queue: ObservabilityRecord[] = [];
32
- private readonly timer?: ReturnType<typeof setInterval>;
33
- private operation: Promise<void> = Promise.resolve();
34
- private closed = false;
35
- private acceptedCount = 0;
36
- private droppedCount = 0;
37
- private flushedCount = 0;
38
- private failedBatchCount = 0;
39
-
40
- constructor(sink: ObservabilitySink, options: BufferedObservabilityReporterOptions = {}) {
41
- this.sink = sink;
42
- this.maxQueueRecords = Math.max(1, options.maxQueueRecords ?? 5_000);
43
- this.batchSize = Math.max(1, options.batchSize ?? 100);
44
- const interval = Math.max(0, options.flushIntervalMs ?? 1_000);
45
- if (interval > 0) {
46
- this.timer = setInterval(() => { void this.flush().catch(() => {}); }, interval);
47
- this.timer.unref?.();
48
- }
49
- }
50
-
51
- enqueue(record: ObservabilityRecord): boolean {
52
- if (this.closed) {
53
- this.droppedCount += 1;
54
- return false;
55
- }
56
- if (this.queue.length >= this.maxQueueRecords) {
57
- const incomingPriority = recordPriority(record);
58
- let victimIndex = -1;
59
- let victimPriority = incomingPriority;
60
- for (let index = 0; index < this.queue.length; index += 1) {
61
- const priority = recordPriority(this.queue[index]!);
62
- if (priority < victimPriority) {
63
- victimIndex = index;
64
- victimPriority = priority;
65
- if (priority === 0) break;
66
- }
67
- }
68
- if (victimIndex < 0) {
69
- this.droppedCount += 1;
70
- return false;
71
- }
72
- this.queue.splice(victimIndex, 1);
73
- this.droppedCount += 1;
74
- }
75
- this.queue.push(record);
76
- this.acceptedCount += 1;
77
- if (this.queue.length >= this.batchSize) void this.flush().catch(() => {});
78
- return true;
79
- }
80
-
81
- flush(): Promise<void> {
82
- const next = this.operation.then(async () => {
83
- while (this.queue.length > 0) {
84
- const batch = this.queue.splice(0, this.batchSize);
85
- try {
86
- await this.sink.write(batch);
87
- this.flushedCount += batch.length;
88
- } catch (error) {
89
- this.failedBatchCount += 1;
90
- this.restoreFailedBatch(batch);
91
- throw error;
92
- }
93
- }
94
- });
95
- this.operation = next.catch(() => {});
96
- return next;
97
- }
98
-
99
- async close(): Promise<void> {
100
- if (this.closed) return;
101
- this.closed = true;
102
- if (this.timer) clearInterval(this.timer);
103
- let flushError: unknown;
104
- try {
105
- await this.flush();
106
- } catch (error) {
107
- flushError = error;
108
- } finally {
109
- await this.sink.close?.();
110
- }
111
- if (flushError) throw flushError;
112
- }
113
-
114
- stats(): ObservabilityReporterStats {
115
- return {
116
- accepted: this.acceptedCount,
117
- dropped: this.droppedCount,
118
- flushed: this.flushedCount,
119
- failedBatches: this.failedBatchCount,
120
- queued: this.queue.length,
121
- };
122
- }
123
-
124
- private restoreFailedBatch(batch: readonly ObservabilityRecord[]): void {
125
- // The failed batch is older than records accepted while the sink was in
126
- // flight. Keep chronological order among survivors, but when the combined
127
- // set exceeds the bound, discard the newest lowest-priority records first.
128
- const combined = [...batch, ...this.queue];
129
- while (combined.length > this.maxQueueRecords) {
130
- let victimIndex = combined.length - 1;
131
- let victimPriority = Number.POSITIVE_INFINITY;
132
- for (let index = combined.length - 1; index >= 0; index -= 1) {
133
- const priority = recordPriority(combined[index]!);
134
- if (priority < victimPriority) {
135
- victimIndex = index;
136
- victimPriority = priority;
137
- if (priority === 0) break;
138
- }
139
- }
140
- combined.splice(victimIndex, 1);
141
- this.droppedCount += 1;
142
- }
143
- this.queue.splice(0, this.queue.length, ...combined);
144
- }
145
- }
146
-
147
- export class NoopObservabilityReporter implements ObservabilityReporter {
148
- enqueue(): boolean { return false; }
149
- async flush(): Promise<void> {}
150
- async close(): Promise<void> {}
151
- stats(): ObservabilityReporterStats {
152
- return { accepted: 0, dropped: 0, flushed: 0, failedBatches: 0, queued: 0 };
153
- }
154
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/observability/reporter.js';