@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.0
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.
- package/README.md +67 -2
- package/dist/framework/action-diagnostics.d.ts +11 -0
- package/dist/framework/action-diagnostics.js +67 -0
- package/dist/framework/capability-registry.d.ts +58 -0
- package/dist/framework/capability-registry.js +325 -0
- package/dist/framework/contracts.d.ts +121 -0
- package/dist/framework/contracts.js +2 -0
- package/dist/framework/control/control-scheduler.d.ts +69 -0
- package/dist/framework/control/control-scheduler.js +1016 -0
- package/dist/framework/control/domain-set.d.ts +18 -0
- package/dist/framework/control/domain-set.js +70 -0
- package/dist/framework/control/index.d.ts +3 -0
- package/dist/framework/control/index.js +3 -0
- package/dist/framework/control/types.d.ts +142 -0
- package/dist/framework/control/types.js +13 -0
- package/dist/framework/control-coordinator.d.ts +7 -0
- package/dist/framework/control-coordinator.js +7 -0
- package/dist/framework/events/event-catalog.d.ts +23 -0
- package/dist/framework/events/event-catalog.js +52 -0
- package/dist/framework/events/event-delivery-service.d.ts +33 -0
- package/dist/framework/events/event-delivery-service.js +165 -0
- package/dist/framework/events/event-ingress.d.ts +28 -0
- package/dist/framework/events/event-ingress.js +76 -0
- package/dist/framework/events/event-repository.d.ts +38 -0
- package/dist/framework/events/event-repository.js +20 -0
- package/dist/framework/events/index.d.ts +7 -0
- package/dist/framework/events/index.js +7 -0
- package/dist/framework/events/memory-event-repository.d.ts +77 -0
- package/dist/framework/events/memory-event-repository.js +909 -0
- package/dist/framework/events/runtime-resume.d.ts +11 -0
- package/dist/framework/events/runtime-resume.js +7 -0
- package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
- package/dist/framework/events/sqlite-event-repository.js +2044 -0
- package/dist/framework/events/store-compatibility.d.ts +17 -0
- package/dist/framework/events/store-compatibility.js +17 -0
- package/dist/framework/events/types.d.ts +242 -0
- package/dist/framework/events/types.js +39 -0
- package/dist/framework/index.d.ts +7 -0
- package/dist/framework/index.js +7 -0
- package/dist/framework/load-node-sqlite.d.ts +5 -0
- package/dist/framework/load-node-sqlite.js +19 -0
- package/dist/framework/mailbox/coalescer.d.ts +30 -0
- package/dist/framework/mailbox/coalescer.js +45 -0
- package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
- package/dist/framework/mailbox/host-notification-sink.js +13 -0
- package/dist/framework/mailbox/identity.d.ts +15 -0
- package/dist/framework/mailbox/identity.js +28 -0
- package/dist/framework/mailbox/index.d.ts +7 -0
- package/dist/framework/mailbox/index.js +7 -0
- package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
- package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
- package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
- package/dist/framework/mailbox/mailbox-repository.js +9 -0
- package/dist/framework/mailbox/notification-projector.d.ts +25 -0
- package/dist/framework/mailbox/notification-projector.js +50 -0
- package/dist/framework/mailbox/types.d.ts +128 -0
- package/dist/framework/mailbox/types.js +1 -0
- package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
- package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
- package/dist/framework/modules/runtime-module-loader.js +64 -0
- package/dist/framework/modules/runtime-module-output.d.ts +7 -0
- package/dist/framework/modules/runtime-module-output.js +15 -0
- package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
- package/dist/framework/participation-manager.d.ts +94 -0
- package/dist/framework/participation-manager.js +185 -0
- package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
- package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
- package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
- package/dist/framework/persistence/memory-first-persistence.js +459 -0
- package/dist/framework/plugins/contracts.d.ts +345 -0
- package/dist/framework/plugins/contracts.js +1 -0
- package/dist/framework/plugins/index.d.ts +4 -0
- package/dist/framework/plugins/index.js +4 -0
- package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
- package/dist/framework/plugins/runtime-event-identity.js +11 -0
- package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
- package/dist/framework/plugins/runtime-input-journal.js +716 -0
- package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
- package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
- package/dist/framework/runtime.d.ts +264 -0
- package/dist/framework/runtime.js +1811 -0
- package/dist/framework/serial-task-queue.d.ts +6 -0
- package/dist/framework/serial-task-queue.js +12 -0
- package/dist/framework/state/contracts.d.ts +30 -0
- package/dist/framework/state/contracts.js +1 -0
- package/dist/framework/state/current-state-store.d.ts +17 -0
- package/dist/framework/state/current-state-store.js +153 -0
- package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
- package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
- package/dist/framework/state/freshness.d.ts +7 -0
- package/dist/framework/state/freshness.js +52 -0
- package/dist/framework/state/history/contracts.d.ts +133 -0
- package/dist/framework/state/history/contracts.js +1 -0
- package/dist/framework/state/history/history-writer.d.ts +55 -0
- package/dist/framework/state/history/history-writer.js +157 -0
- package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
- package/dist/framework/state/history/memory-state-history-repository.js +199 -0
- package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
- package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
- package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
- package/dist/framework/state/history/trajectory-projector.js +130 -0
- package/dist/framework/state/index.d.ts +12 -0
- package/dist/framework/state/index.js +12 -0
- package/dist/framework/state/state-ingress.d.ts +18 -0
- package/dist/framework/state/state-ingress.js +68 -0
- package/dist/framework/state/state-provider.d.ts +11 -0
- package/dist/framework/state/state-provider.js +56 -0
- package/dist/framework/state/types.d.ts +107 -0
- package/dist/framework/state/types.js +19 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
- package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
- package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
- package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
- package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
- package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
- package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
- package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
- package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
- package/dist/mailbox/host-monitor-rate-gate.js +93 -0
- package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
- package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
- package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
- package/dist/mailbox/mailbox-host-relay.js +299 -0
- package/dist/mailbox/mailbox-plugin.d.ts +56 -0
- package/dist/mailbox/mailbox-plugin.js +111 -0
- package/dist/mailbox/mailbox-service.d.ts +128 -0
- package/dist/mailbox/mailbox-service.js +582 -0
- package/dist/memory/contracts.d.ts +12 -0
- package/dist/memory/contracts.js +1 -0
- package/dist/memory/strategy-memory-rpc.d.ts +21 -0
- package/dist/memory/strategy-memory-rpc.js +86 -0
- package/dist/memory/strategy-memory.d.ts +15 -0
- package/dist/memory/strategy-memory.js +95 -0
- package/dist/observability/detail-capture.d.ts +25 -0
- package/dist/observability/detail-capture.js +136 -0
- package/dist/observability/index.d.ts +5 -0
- package/dist/observability/index.js +5 -0
- package/dist/observability/process-timing.d.ts +14 -0
- package/dist/observability/process-timing.js +56 -0
- package/dist/observability/recorder.d.ts +56 -0
- package/dist/observability/recorder.js +202 -0
- package/dist/observability/redaction.d.ts +30 -0
- package/dist/observability/redaction.js +166 -0
- package/dist/observability/reporter.d.ts +32 -0
- package/dist/observability/reporter.js +140 -0
- package/dist/observability/sinks.d.ts +36 -0
- package/dist/observability/sinks.js +121 -0
- package/dist/observability/types.d.ts +81 -0
- package/dist/observability/types.js +1 -0
- package/dist/owner/control-channel.d.ts +42 -0
- package/dist/owner/control-channel.js +188 -0
- package/dist/owner/parent-process-watch.d.ts +15 -0
- package/dist/owner/parent-process-watch.js +40 -0
- package/dist/owner/process-identity.d.ts +10 -0
- package/dist/owner/process-identity.js +65 -0
- package/dist/owner/runtime-lock.d.ts +5 -0
- package/dist/owner/runtime-lock.js +47 -0
- package/dist/perception/binding-resolution.d.ts +9 -0
- package/dist/perception/binding-resolution.js +14 -0
- package/dist/perception/contracts.d.ts +85 -0
- package/dist/perception/contracts.js +1 -0
- package/dist/perception/map-concurrent.d.ts +2 -0
- package/dist/perception/map-concurrent.js +12 -0
- package/dist/perception/perception-host.d.ts +114 -0
- package/dist/perception/perception-host.js +336 -0
- package/dist/perception/perception-worker-host.d.ts +11 -0
- package/dist/perception/perception-worker-host.js +44 -0
- package/dist/perception/perception-worker.d.ts +21 -0
- package/dist/perception/perception-worker.js +77 -0
- package/dist/perception/strategy-names.d.ts +7 -0
- package/dist/perception/strategy-names.js +22 -0
- package/dist/sdk/perception.d.ts +5 -0
- package/dist/sdk/perception.js +6 -0
- package/dist/sdk/strategy.d.ts +6 -0
- package/dist/sdk/strategy.js +3 -0
- package/dist/strategy/activation-manager.d.ts +105 -0
- package/dist/strategy/activation-manager.js +367 -0
- package/dist/strategy/behavior-decision-history.d.ts +20 -0
- package/dist/strategy/behavior-decision-history.js +59 -0
- package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
- package/dist/strategy/behavior-instance-snapshot.js +145 -0
- package/dist/strategy/contracts.d.ts +189 -0
- package/dist/strategy/contracts.js +1 -0
- package/dist/strategy/control-driver.d.ts +25 -0
- package/dist/strategy/control-driver.js +131 -0
- package/dist/strategy/in-process-runner.d.ts +25 -0
- package/dist/strategy/in-process-runner.js +40 -0
- package/dist/strategy/strategy-host.d.ts +165 -0
- package/dist/strategy/strategy-host.js +1456 -0
- package/dist/strategy/strategy-script-runner.d.ts +81 -0
- package/dist/strategy/strategy-script-runner.js +235 -0
- package/dist/strategy/strategy-worker-host.d.ts +27 -0
- package/dist/strategy/strategy-worker-host.js +96 -0
- package/dist/strategy/thread-strategy-executor.d.ts +120 -0
- package/dist/strategy/thread-strategy-executor.js +778 -0
- package/examples/grid-game.mjs +129 -0
- package/examples/grid-perception-worker.mjs +6 -0
- package/examples/grid-perception.mjs +12 -0
- package/examples/grid-strategy-worker.mjs +11 -0
- package/examples/grid-strategy.mjs +13 -0
- package/examples/run-grid-game.mjs +24 -0
- package/package.json +53 -4
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { ObservabilityRedactor } from './redaction.js';
|
|
3
|
+
import { NoopObservabilityReporter } from './reporter.js';
|
|
4
|
+
import { captureSnapshot, detailCategory } from './detail-capture.js';
|
|
5
|
+
import { OBSERVABILITY_SCHEMA, } from './types.js';
|
|
6
|
+
function defaultSeverity(kind) {
|
|
7
|
+
return kind === 'error' ? 'error' : 'info';
|
|
8
|
+
}
|
|
9
|
+
function normalizedError(error) {
|
|
10
|
+
if (error === undefined || error === null)
|
|
11
|
+
return undefined;
|
|
12
|
+
if (error instanceof Error) {
|
|
13
|
+
const code = typeof error.code === 'string' ? error.code : undefined;
|
|
14
|
+
return {
|
|
15
|
+
name: error.name,
|
|
16
|
+
...(code ? { code } : {}),
|
|
17
|
+
message: error.message,
|
|
18
|
+
stack: error.stack,
|
|
19
|
+
cause: error.cause,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
if (typeof error === 'string')
|
|
23
|
+
return { message: error };
|
|
24
|
+
if (typeof error === 'object')
|
|
25
|
+
return error;
|
|
26
|
+
return { message: String(error) };
|
|
27
|
+
}
|
|
28
|
+
function validName(name) {
|
|
29
|
+
const normalized = name.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, '_').slice(0, 120);
|
|
30
|
+
return normalized || 'unnamed';
|
|
31
|
+
}
|
|
32
|
+
function normalizedScope(scope) {
|
|
33
|
+
if (!scope)
|
|
34
|
+
return undefined;
|
|
35
|
+
return {
|
|
36
|
+
...(typeof scope.adapterId === 'string' ? { adapterId: scope.adapterId } : {}),
|
|
37
|
+
...(typeof scope.sessionId === 'string' ? { sessionId: scope.sessionId } : {}),
|
|
38
|
+
...(typeof scope.segmentId === 'string' ? { segmentId: scope.segmentId } : {}),
|
|
39
|
+
...(typeof scope.segmentSeq === 'number' && Number.isFinite(scope.segmentSeq)
|
|
40
|
+
? { segmentSeq: scope.segmentSeq }
|
|
41
|
+
: {}),
|
|
42
|
+
...(typeof scope.connectionId === 'string' ? { connectionId: scope.connectionId } : {}),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Owner-side authority for logs, metrics and error reports. Never throws into gameplay. */
|
|
46
|
+
export class TelemetryRecorder {
|
|
47
|
+
process;
|
|
48
|
+
reporter;
|
|
49
|
+
redactor;
|
|
50
|
+
enabled;
|
|
51
|
+
now;
|
|
52
|
+
idFactory;
|
|
53
|
+
scopeProvider;
|
|
54
|
+
sampler;
|
|
55
|
+
capture;
|
|
56
|
+
detailReporter;
|
|
57
|
+
lastDetailScope;
|
|
58
|
+
constructor(options) {
|
|
59
|
+
this.process = { ...options.process };
|
|
60
|
+
this.reporter = options.reporter ?? new NoopObservabilityReporter();
|
|
61
|
+
this.redactor = options.redactor ?? new ObservabilityRedactor();
|
|
62
|
+
this.enabled = options.enabled !== false;
|
|
63
|
+
this.now = options.now ?? (() => new Date());
|
|
64
|
+
this.idFactory = options.idFactory ?? (() => `obs_${randomUUID()}`);
|
|
65
|
+
this.scopeProvider = options.scopeProvider;
|
|
66
|
+
this.sampler = options.sampler ?? (() => true);
|
|
67
|
+
this.capture = options.capture;
|
|
68
|
+
this.detailReporter = options.detailReporter;
|
|
69
|
+
}
|
|
70
|
+
record(input) {
|
|
71
|
+
if (!this.enabled)
|
|
72
|
+
return null;
|
|
73
|
+
try {
|
|
74
|
+
const category = detailCategory(input.name);
|
|
75
|
+
if (category ? !this.capture?.[category] : !this.sampler(input))
|
|
76
|
+
return null;
|
|
77
|
+
const recordId = this.idFactory();
|
|
78
|
+
const scope = normalizedScope(input.scope ?? this.scopeProvider?.());
|
|
79
|
+
if (category && scope)
|
|
80
|
+
this.lastDetailScope = scope;
|
|
81
|
+
const captured = category ? captureSnapshot(input.attributes ?? {}, this.capture.max_record_bytes - 2048) : undefined;
|
|
82
|
+
const attributes = captured
|
|
83
|
+
? { ...captured.value, capture_truncated: captured.truncated }
|
|
84
|
+
: this.redactor.redactRecord(input.attributes ?? {});
|
|
85
|
+
const correlation = input.correlation
|
|
86
|
+
? this.redactor.redactRecord(input.correlation)
|
|
87
|
+
: undefined;
|
|
88
|
+
const metric = input.metric
|
|
89
|
+
? this.redactor.redactRecord(input.metric)
|
|
90
|
+
: undefined;
|
|
91
|
+
const error = normalizedError(input.error);
|
|
92
|
+
const redactedError = error
|
|
93
|
+
? this.redactor.redactRecord(error)
|
|
94
|
+
: undefined;
|
|
95
|
+
const record = {
|
|
96
|
+
schema: OBSERVABILITY_SCHEMA,
|
|
97
|
+
recordId,
|
|
98
|
+
timestamp: this.now().toISOString(),
|
|
99
|
+
kind: input.kind,
|
|
100
|
+
name: validName(input.name),
|
|
101
|
+
severity: input.severity ?? defaultSeverity(input.kind),
|
|
102
|
+
component: validName(input.component ?? 'runtime'),
|
|
103
|
+
process: { ...this.process },
|
|
104
|
+
...(scope ? { scope } : {}),
|
|
105
|
+
...(correlation ? { correlation } : {}),
|
|
106
|
+
attributes,
|
|
107
|
+
...(metric ? { metric } : {}),
|
|
108
|
+
...(redactedError ? { error: redactedError } : {}),
|
|
109
|
+
};
|
|
110
|
+
return (category ? this.detailReporter ?? this.reporter : this.reporter).enqueue(record) ? recordId : null;
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
log(severity, name, attributes = {}, context = {}) {
|
|
117
|
+
return this.record({ kind: 'log', severity, name, attributes, ...context });
|
|
118
|
+
}
|
|
119
|
+
metric(name, value, options = {}) {
|
|
120
|
+
const { unit, aggregation, ...context } = options;
|
|
121
|
+
return this.record({
|
|
122
|
+
kind: 'metric',
|
|
123
|
+
name,
|
|
124
|
+
...context,
|
|
125
|
+
metric: { value, unit, aggregation },
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
error(name, error, attributes = {}, context = {}) {
|
|
129
|
+
return this.record({ kind: 'error', name, severity: 'error', error, attributes, ...context });
|
|
130
|
+
}
|
|
131
|
+
logger(component, base = {}) {
|
|
132
|
+
return new StructuredLogger(this, component, base);
|
|
133
|
+
}
|
|
134
|
+
captureSummary() {
|
|
135
|
+
if (!this.detailReporter)
|
|
136
|
+
return;
|
|
137
|
+
const category = ['actions', 'behavior_io', 'perception_io'].find(key => this.capture?.[key]);
|
|
138
|
+
if (category)
|
|
139
|
+
this.log('debug', `runtime.detail.${category}.summary`, { reporter: this.detailReporter.stats() }, { component: 'runtime.capture', scope: this.lastDetailScope });
|
|
140
|
+
}
|
|
141
|
+
async flush() {
|
|
142
|
+
await Promise.all([this.reporter.flush(), this.detailReporter?.flush()]);
|
|
143
|
+
this.captureSummary();
|
|
144
|
+
await this.detailReporter?.flush();
|
|
145
|
+
}
|
|
146
|
+
async close() {
|
|
147
|
+
try {
|
|
148
|
+
await this.flush();
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
await Promise.all([this.reporter.close(), this.detailReporter?.close()]);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
flushWithin(timeoutMs) {
|
|
155
|
+
return settleWithin(this.flush(), timeoutMs);
|
|
156
|
+
}
|
|
157
|
+
closeWithin(timeoutMs) {
|
|
158
|
+
return settleWithin(this.close(), timeoutMs);
|
|
159
|
+
}
|
|
160
|
+
stats() { return this.reporter.stats(); }
|
|
161
|
+
detailStats() { return this.detailReporter?.stats(); }
|
|
162
|
+
captureEnabled(category) {
|
|
163
|
+
return this.enabled && this.capture?.[category] === true;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** Stop awaiting diagnostics after a bounded window; gameplay owns hard exit/cancellation. */
|
|
167
|
+
async function settleWithin(operation, timeoutMs) {
|
|
168
|
+
let timer;
|
|
169
|
+
const completed = operation.then(() => true, () => false);
|
|
170
|
+
const timedOut = new Promise((resolve) => {
|
|
171
|
+
timer = setTimeout(() => resolve(false), Math.max(1, timeoutMs));
|
|
172
|
+
});
|
|
173
|
+
try {
|
|
174
|
+
return await Promise.race([completed, timedOut]);
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
if (timer)
|
|
178
|
+
clearTimeout(timer);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
export class StructuredLogger {
|
|
182
|
+
recorder;
|
|
183
|
+
component;
|
|
184
|
+
base;
|
|
185
|
+
constructor(recorder, component, base = {}) {
|
|
186
|
+
this.recorder = recorder;
|
|
187
|
+
this.component = component;
|
|
188
|
+
this.base = base;
|
|
189
|
+
}
|
|
190
|
+
debug(name, attributes = {}) {
|
|
191
|
+
return this.recorder.log('debug', name, { ...this.base, ...attributes }, { component: this.component });
|
|
192
|
+
}
|
|
193
|
+
info(name, attributes = {}) {
|
|
194
|
+
return this.recorder.log('info', name, { ...this.base, ...attributes }, { component: this.component });
|
|
195
|
+
}
|
|
196
|
+
warn(name, attributes = {}) {
|
|
197
|
+
return this.recorder.log('warn', name, { ...this.base, ...attributes }, { component: this.component });
|
|
198
|
+
}
|
|
199
|
+
error(name, error, attributes = {}) {
|
|
200
|
+
return this.recorder.error(name, error, { ...this.base, ...attributes }, { component: this.component });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface RedactionOptions {
|
|
2
|
+
hashSalt?: string;
|
|
3
|
+
maxDepth?: number;
|
|
4
|
+
maxKeys?: number;
|
|
5
|
+
maxArrayItems?: number;
|
|
6
|
+
maxStringLength?: number;
|
|
7
|
+
}
|
|
8
|
+
export interface RedactionSummary {
|
|
9
|
+
redacted: true;
|
|
10
|
+
present: boolean;
|
|
11
|
+
length?: number;
|
|
12
|
+
kind?: 'private_text' | 'raw_payload' | 'local_path';
|
|
13
|
+
extension?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Redacts before persistence. It is deliberately defensive: cycles, deep
|
|
17
|
+
* objects and oversized collections are bounded rather than allowed to break
|
|
18
|
+
* gameplay or turn a diagnostic record into a State/raw-frame dump.
|
|
19
|
+
*/
|
|
20
|
+
export declare class ObservabilityRedactor {
|
|
21
|
+
private readonly salt;
|
|
22
|
+
private readonly maxDepth;
|
|
23
|
+
private readonly maxKeys;
|
|
24
|
+
private readonly maxArrayItems;
|
|
25
|
+
private readonly maxStringLength;
|
|
26
|
+
constructor(options?: RedactionOptions);
|
|
27
|
+
redactRecord(record: Record<string, unknown>): Record<string, unknown>;
|
|
28
|
+
private stableHash;
|
|
29
|
+
private visit;
|
|
30
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'crypto';
|
|
2
|
+
import { extname } from 'path';
|
|
3
|
+
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)?$/;
|
|
4
|
+
const PRIVATE_TEXT_KEY = /(?:^|_)(?:speech|comment|think|thinking|chat|knowledge|persona|prompt)(?:_text|_content|_raw)?$|(?:^|_)(?:source_code|audio|audio_url|avatar|avatar_url)$/;
|
|
5
|
+
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)$/;
|
|
6
|
+
const PATH_KEY = /(?:^|_)(?:path|cwd|workspace|directory|dir|filename|file_path|file_name)$/;
|
|
7
|
+
const IDENTITY_KEY = /(?:^|_)(?:account|account_id|player_name|room_code|agent_name|user_id)$/;
|
|
8
|
+
const DIAGNOSTIC_CODE_KEY = /^(?:code|error_code|.*_error_code)$/;
|
|
9
|
+
const DIAGNOSTIC_CODE = /^[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)+$/;
|
|
10
|
+
const SECRET_CODE_PREFIX = /^(?:claw_|sk[-_]|ghp_|github_pat_|eyj)/i;
|
|
11
|
+
const TOKEN_IN_TEXT = /\b(?:Bearer\s+)?[A-Za-z0-9_-]{24,}\b/g;
|
|
12
|
+
const FILE_URL = /file:\/\/\/?[^"'\r\n<>\)\]]+/gi;
|
|
13
|
+
const WINDOWS_PATH = /\b[A-Za-z]:[\\\/][^"'\r\n<>\)\]]+/g;
|
|
14
|
+
const POSIX_HOME_PATH = /\/(?:home|Users)\/[^"'\r\n<>\)\]]+/g;
|
|
15
|
+
const NETWORK_URL = /\b(?:https?|wss?):\/\/[^\s"'<>\(\)\[\]{}]+/gi;
|
|
16
|
+
function stringLength(value) {
|
|
17
|
+
return typeof value === 'string' || Array.isArray(value) ? value.length : undefined;
|
|
18
|
+
}
|
|
19
|
+
function summarize(value, kind) {
|
|
20
|
+
return {
|
|
21
|
+
redacted: true,
|
|
22
|
+
present: value !== null && value !== undefined && value !== '',
|
|
23
|
+
...(stringLength(value) === undefined ? {} : { length: stringLength(value) }),
|
|
24
|
+
kind,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function pathSummary(value) {
|
|
28
|
+
const extension = typeof value === 'string' ? extname(value).slice(0, 16) : '';
|
|
29
|
+
return {
|
|
30
|
+
...summarize(value, 'local_path'),
|
|
31
|
+
...(extension ? { extension } : {}),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function normalizeUrl(value) {
|
|
35
|
+
try {
|
|
36
|
+
const url = new URL(value);
|
|
37
|
+
const path = url.pathname
|
|
38
|
+
.split('/')
|
|
39
|
+
.map((part) => /^[a-f0-9-]{16,}$/i.test(part) || /^\d{6,}$/.test(part) ? ':id' : part)
|
|
40
|
+
.join('/');
|
|
41
|
+
return `${url.protocol}//${url.host}${path}`;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Make snake_case, kebab-case and camelCase field names share one policy. */
|
|
48
|
+
function normalizeKey(key) {
|
|
49
|
+
return key
|
|
50
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
|
51
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
|
|
52
|
+
.replace(/[^A-Za-z0-9]+/g, '_')
|
|
53
|
+
.replace(/^_+|_+$/g, '')
|
|
54
|
+
.toLowerCase();
|
|
55
|
+
}
|
|
56
|
+
function safeString(value, maxLength) {
|
|
57
|
+
const withoutPaths = value
|
|
58
|
+
.replace(FILE_URL, '[LOCAL_PATH]')
|
|
59
|
+
.replace(WINDOWS_PATH, '[LOCAL_PATH]')
|
|
60
|
+
.replace(POSIX_HOME_PATH, '[LOCAL_PATH]')
|
|
61
|
+
.replace(TOKEN_IN_TEXT, '[REDACTED_TOKEN]');
|
|
62
|
+
const withoutQuery = withoutPaths.replace(NETWORK_URL, (url) => normalizeUrl(url));
|
|
63
|
+
return withoutQuery.length <= maxLength
|
|
64
|
+
? withoutQuery
|
|
65
|
+
: `${withoutQuery.slice(0, maxLength)}...[truncated:${withoutQuery.length}]`;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Preserve bounded semantic codes such as `behavior_activation_superseded`
|
|
69
|
+
* without turning an error-code field into a credential escape hatch. Tokens
|
|
70
|
+
* usually have a known secret prefix or one long high-entropy segment, while
|
|
71
|
+
* Runtime diagnostic codes are made from multiple short semantic segments.
|
|
72
|
+
*/
|
|
73
|
+
function safeDiagnosticCode(value) {
|
|
74
|
+
if (value.length === 0
|
|
75
|
+
|| value.length > 160
|
|
76
|
+
|| value.trim() !== value
|
|
77
|
+
|| !DIAGNOSTIC_CODE.test(value)
|
|
78
|
+
|| SECRET_CODE_PREFIX.test(value)
|
|
79
|
+
|| value.split(/[._-]/).some((segment) => segment.length >= 24))
|
|
80
|
+
return null;
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Redacts before persistence. It is deliberately defensive: cycles, deep
|
|
85
|
+
* objects and oversized collections are bounded rather than allowed to break
|
|
86
|
+
* gameplay or turn a diagnostic record into a State/raw-frame dump.
|
|
87
|
+
*/
|
|
88
|
+
export class ObservabilityRedactor {
|
|
89
|
+
salt;
|
|
90
|
+
maxDepth;
|
|
91
|
+
maxKeys;
|
|
92
|
+
maxArrayItems;
|
|
93
|
+
maxStringLength;
|
|
94
|
+
constructor(options = {}) {
|
|
95
|
+
this.salt = options.hashSalt ?? randomBytes(16).toString('hex');
|
|
96
|
+
this.maxDepth = Math.max(1, options.maxDepth ?? 8);
|
|
97
|
+
this.maxKeys = Math.max(1, options.maxKeys ?? 100);
|
|
98
|
+
this.maxArrayItems = Math.max(1, options.maxArrayItems ?? 50);
|
|
99
|
+
this.maxStringLength = Math.max(32, options.maxStringLength ?? 512);
|
|
100
|
+
}
|
|
101
|
+
redactRecord(record) {
|
|
102
|
+
return this.visit(record, 0, new WeakSet());
|
|
103
|
+
}
|
|
104
|
+
stableHash(value) {
|
|
105
|
+
return `hash:${createHash('sha256').update(this.salt).update(String(value)).digest('hex').slice(0, 16)}`;
|
|
106
|
+
}
|
|
107
|
+
visit(value, depth, seen, key = '') {
|
|
108
|
+
const policyKey = normalizeKey(key);
|
|
109
|
+
if (SECRET_KEY.test(policyKey))
|
|
110
|
+
return '[REDACTED]';
|
|
111
|
+
if (PRIVATE_TEXT_KEY.test(policyKey))
|
|
112
|
+
return summarize(value, 'private_text');
|
|
113
|
+
if (RAW_PAYLOAD_KEY.test(policyKey))
|
|
114
|
+
return summarize(value, 'raw_payload');
|
|
115
|
+
if (PATH_KEY.test(policyKey))
|
|
116
|
+
return pathSummary(value);
|
|
117
|
+
if (IDENTITY_KEY.test(policyKey) && value !== null && value !== undefined)
|
|
118
|
+
return this.stableHash(value);
|
|
119
|
+
if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number')
|
|
120
|
+
return value;
|
|
121
|
+
if (typeof value === 'bigint')
|
|
122
|
+
return value.toString();
|
|
123
|
+
if (typeof value === 'string') {
|
|
124
|
+
if (DIAGNOSTIC_CODE_KEY.test(policyKey)) {
|
|
125
|
+
const code = safeDiagnosticCode(value);
|
|
126
|
+
if (code)
|
|
127
|
+
return code;
|
|
128
|
+
}
|
|
129
|
+
return safeString(value, this.maxStringLength);
|
|
130
|
+
}
|
|
131
|
+
if (depth >= this.maxDepth)
|
|
132
|
+
return '[MAX_DEPTH]';
|
|
133
|
+
if (value instanceof Error) {
|
|
134
|
+
return this.visit({
|
|
135
|
+
name: value.name,
|
|
136
|
+
message: value.message,
|
|
137
|
+
stack: value.stack,
|
|
138
|
+
cause: value.cause,
|
|
139
|
+
}, depth + 1, seen);
|
|
140
|
+
}
|
|
141
|
+
if (typeof value !== 'object')
|
|
142
|
+
return String(value);
|
|
143
|
+
if (seen.has(value))
|
|
144
|
+
return '[CIRCULAR]';
|
|
145
|
+
seen.add(value);
|
|
146
|
+
try {
|
|
147
|
+
if (Array.isArray(value)) {
|
|
148
|
+
const out = value.slice(0, this.maxArrayItems).map((item) => this.visit(item, depth + 1, seen));
|
|
149
|
+
if (value.length > this.maxArrayItems)
|
|
150
|
+
out.push(`[TRUNCATED:${value.length - this.maxArrayItems}]`);
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
const entries = Object.entries(value).slice(0, this.maxKeys);
|
|
154
|
+
const out = {};
|
|
155
|
+
for (const [childKey, childValue] of entries) {
|
|
156
|
+
out[childKey] = this.visit(childValue, depth + 1, seen, childKey);
|
|
157
|
+
}
|
|
158
|
+
if (Object.keys(value).length > this.maxKeys)
|
|
159
|
+
out._truncated_keys = true;
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
seen.delete(value);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ObservabilityRecord, ObservabilityReporter, ObservabilityReporterStats, ObservabilitySink } from './types.js';
|
|
2
|
+
export interface BufferedObservabilityReporterOptions {
|
|
3
|
+
maxQueueRecords?: number;
|
|
4
|
+
batchSize?: number;
|
|
5
|
+
flushIntervalMs?: number;
|
|
6
|
+
}
|
|
7
|
+
/** Bounded, best-effort process buffer in front of a durable/local sink. */
|
|
8
|
+
export declare class BufferedObservabilityReporter implements ObservabilityReporter {
|
|
9
|
+
private readonly sink;
|
|
10
|
+
private readonly maxQueueRecords;
|
|
11
|
+
private readonly batchSize;
|
|
12
|
+
private readonly queue;
|
|
13
|
+
private readonly timer?;
|
|
14
|
+
private operation;
|
|
15
|
+
private closed;
|
|
16
|
+
private acceptedCount;
|
|
17
|
+
private droppedCount;
|
|
18
|
+
private flushedCount;
|
|
19
|
+
private failedBatchCount;
|
|
20
|
+
constructor(sink: ObservabilitySink, options?: BufferedObservabilityReporterOptions);
|
|
21
|
+
enqueue(record: ObservabilityRecord): boolean;
|
|
22
|
+
flush(): Promise<void>;
|
|
23
|
+
close(): Promise<void>;
|
|
24
|
+
stats(): ObservabilityReporterStats;
|
|
25
|
+
private restoreFailedBatch;
|
|
26
|
+
}
|
|
27
|
+
export declare class NoopObservabilityReporter implements ObservabilityReporter {
|
|
28
|
+
enqueue(): boolean;
|
|
29
|
+
flush(): Promise<void>;
|
|
30
|
+
close(): Promise<void>;
|
|
31
|
+
stats(): ObservabilityReporterStats;
|
|
32
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
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))$/;
|
|
2
|
+
function recordPriority(record) {
|
|
3
|
+
if (record.kind === 'error'
|
|
4
|
+
|| record.severity === 'error'
|
|
5
|
+
|| record.severity === 'warn'
|
|
6
|
+
|| CRITICAL_LIFECYCLE_RECORD.test(record.name))
|
|
7
|
+
return 2;
|
|
8
|
+
return record.severity === 'debug' ? 0 : 1;
|
|
9
|
+
}
|
|
10
|
+
/** Bounded, best-effort process buffer in front of a durable/local sink. */
|
|
11
|
+
export class BufferedObservabilityReporter {
|
|
12
|
+
sink;
|
|
13
|
+
maxQueueRecords;
|
|
14
|
+
batchSize;
|
|
15
|
+
queue = [];
|
|
16
|
+
timer;
|
|
17
|
+
operation = Promise.resolve();
|
|
18
|
+
closed = false;
|
|
19
|
+
acceptedCount = 0;
|
|
20
|
+
droppedCount = 0;
|
|
21
|
+
flushedCount = 0;
|
|
22
|
+
failedBatchCount = 0;
|
|
23
|
+
constructor(sink, options = {}) {
|
|
24
|
+
this.sink = sink;
|
|
25
|
+
this.maxQueueRecords = Math.max(1, options.maxQueueRecords ?? 5_000);
|
|
26
|
+
this.batchSize = Math.max(1, options.batchSize ?? 100);
|
|
27
|
+
const interval = Math.max(0, options.flushIntervalMs ?? 1_000);
|
|
28
|
+
if (interval > 0) {
|
|
29
|
+
this.timer = setInterval(() => { void this.flush().catch(() => { }); }, interval);
|
|
30
|
+
this.timer.unref?.();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
enqueue(record) {
|
|
34
|
+
if (this.closed) {
|
|
35
|
+
this.droppedCount += 1;
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
if (this.queue.length >= this.maxQueueRecords) {
|
|
39
|
+
const incomingPriority = recordPriority(record);
|
|
40
|
+
let victimIndex = -1;
|
|
41
|
+
let victimPriority = incomingPriority;
|
|
42
|
+
for (let index = 0; index < this.queue.length; index += 1) {
|
|
43
|
+
const priority = recordPriority(this.queue[index]);
|
|
44
|
+
if (priority < victimPriority) {
|
|
45
|
+
victimIndex = index;
|
|
46
|
+
victimPriority = priority;
|
|
47
|
+
if (priority === 0)
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (victimIndex < 0) {
|
|
52
|
+
this.droppedCount += 1;
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
this.queue.splice(victimIndex, 1);
|
|
56
|
+
this.droppedCount += 1;
|
|
57
|
+
}
|
|
58
|
+
this.queue.push(record);
|
|
59
|
+
this.acceptedCount += 1;
|
|
60
|
+
if (this.queue.length >= this.batchSize)
|
|
61
|
+
void this.flush().catch(() => { });
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
flush() {
|
|
65
|
+
const next = this.operation.then(async () => {
|
|
66
|
+
while (this.queue.length > 0) {
|
|
67
|
+
const batch = this.queue.splice(0, this.batchSize);
|
|
68
|
+
try {
|
|
69
|
+
await this.sink.write(batch);
|
|
70
|
+
this.flushedCount += batch.length;
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
this.failedBatchCount += 1;
|
|
74
|
+
this.restoreFailedBatch(batch);
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
this.operation = next.catch(() => { });
|
|
80
|
+
return next;
|
|
81
|
+
}
|
|
82
|
+
async close() {
|
|
83
|
+
if (this.closed)
|
|
84
|
+
return;
|
|
85
|
+
this.closed = true;
|
|
86
|
+
if (this.timer)
|
|
87
|
+
clearInterval(this.timer);
|
|
88
|
+
let flushError;
|
|
89
|
+
try {
|
|
90
|
+
await this.flush();
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
flushError = error;
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
await this.sink.close?.();
|
|
97
|
+
}
|
|
98
|
+
if (flushError)
|
|
99
|
+
throw flushError;
|
|
100
|
+
}
|
|
101
|
+
stats() {
|
|
102
|
+
return {
|
|
103
|
+
accepted: this.acceptedCount,
|
|
104
|
+
dropped: this.droppedCount,
|
|
105
|
+
flushed: this.flushedCount,
|
|
106
|
+
failedBatches: this.failedBatchCount,
|
|
107
|
+
queued: this.queue.length,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
restoreFailedBatch(batch) {
|
|
111
|
+
// The failed batch is older than records accepted while the sink was in
|
|
112
|
+
// flight. Keep chronological order among survivors, but when the combined
|
|
113
|
+
// set exceeds the bound, discard the newest lowest-priority records first.
|
|
114
|
+
const combined = [...batch, ...this.queue];
|
|
115
|
+
while (combined.length > this.maxQueueRecords) {
|
|
116
|
+
let victimIndex = combined.length - 1;
|
|
117
|
+
let victimPriority = Number.POSITIVE_INFINITY;
|
|
118
|
+
for (let index = combined.length - 1; index >= 0; index -= 1) {
|
|
119
|
+
const priority = recordPriority(combined[index]);
|
|
120
|
+
if (priority < victimPriority) {
|
|
121
|
+
victimIndex = index;
|
|
122
|
+
victimPriority = priority;
|
|
123
|
+
if (priority === 0)
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
combined.splice(victimIndex, 1);
|
|
128
|
+
this.droppedCount += 1;
|
|
129
|
+
}
|
|
130
|
+
this.queue.splice(0, this.queue.length, ...combined);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
export class NoopObservabilityReporter {
|
|
134
|
+
enqueue() { return false; }
|
|
135
|
+
async flush() { }
|
|
136
|
+
async close() { }
|
|
137
|
+
stats() {
|
|
138
|
+
return { accepted: 0, dropped: 0, flushed: 0, failedBatches: 0, queued: 0 };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ObservabilityRecord, ObservabilitySink } from './types.js';
|
|
2
|
+
export interface JsonlObservabilitySinkOptions {
|
|
3
|
+
maxFileBytes?: number;
|
|
4
|
+
retainedFiles?: number;
|
|
5
|
+
}
|
|
6
|
+
/** Owner-only local diagnostic journal. Records arrive already redacted. */
|
|
7
|
+
export declare class JsonlObservabilitySink implements ObservabilitySink {
|
|
8
|
+
readonly id = "local-jsonl";
|
|
9
|
+
readonly filePath: string;
|
|
10
|
+
private readonly maxFileBytes;
|
|
11
|
+
private readonly retainedFiles;
|
|
12
|
+
private operation;
|
|
13
|
+
private closed;
|
|
14
|
+
private retentionPrepared;
|
|
15
|
+
constructor(filePath: string, options?: JsonlObservabilitySinkOptions);
|
|
16
|
+
write(records: readonly ObservabilityRecord[]): Promise<void>;
|
|
17
|
+
close(): Promise<void>;
|
|
18
|
+
private rotateIfNeeded;
|
|
19
|
+
private pruneExcessHistory;
|
|
20
|
+
/** Protected seam for platform adapters and deterministic failure tests. */
|
|
21
|
+
protected renameFile(source: string, destination: string): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Fan-out boundary for local storage plus future reporters. A partial sink
|
|
25
|
+
* failure does not make a successful durable sink repeat its records.
|
|
26
|
+
*/
|
|
27
|
+
export declare class CompositeObservabilitySink implements ObservabilitySink {
|
|
28
|
+
readonly id = "composite";
|
|
29
|
+
private readonly sinks;
|
|
30
|
+
private readonly onSinkError?;
|
|
31
|
+
constructor(sinks: Iterable<ObservabilitySink>, options?: {
|
|
32
|
+
onSinkError?: (sinkId: string, error: unknown) => void;
|
|
33
|
+
});
|
|
34
|
+
write(records: readonly ObservabilityRecord[]): Promise<void>;
|
|
35
|
+
close(): Promise<void>;
|
|
36
|
+
}
|