@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,86 @@
|
|
|
1
|
+
import { validateStrategyMemoryValue } from './strategy-memory.js';
|
|
2
|
+
export const unavailableStrategyMemory = {
|
|
3
|
+
get: async () => { throw Error('strategy_memory_unavailable'); },
|
|
4
|
+
set: async () => { throw Error('strategy_memory_unavailable'); },
|
|
5
|
+
delete: async () => { throw Error('strategy_memory_unavailable'); },
|
|
6
|
+
};
|
|
7
|
+
/** Replies are handled outside the computation queue, so an awaited memory call cannot deadlock it. */
|
|
8
|
+
export class StrategyMemoryRpcClient {
|
|
9
|
+
send;
|
|
10
|
+
sequence = 0;
|
|
11
|
+
pending = new Map();
|
|
12
|
+
constructor(send) {
|
|
13
|
+
this.send = send;
|
|
14
|
+
}
|
|
15
|
+
receive(message) {
|
|
16
|
+
if (message?.type !== 'strategy_memory_result')
|
|
17
|
+
return false;
|
|
18
|
+
const pending = this.pending.get(message.memoryRequestId);
|
|
19
|
+
if (!pending || pending.requestId !== message.requestId)
|
|
20
|
+
return true;
|
|
21
|
+
this.pending.delete(message.memoryRequestId);
|
|
22
|
+
clearTimeout(pending.timer);
|
|
23
|
+
if (message.error)
|
|
24
|
+
pending.reject(Error(String(message.error)));
|
|
25
|
+
else
|
|
26
|
+
pending.resolve(message.value);
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
bind(requestId, isActive) {
|
|
30
|
+
const call = (operation, key, value) => {
|
|
31
|
+
if (!isActive())
|
|
32
|
+
return Promise.reject(Error('strategy_memory_inactive'));
|
|
33
|
+
if (this.pending.size >= 64)
|
|
34
|
+
return Promise.reject(Error('strategy_memory_request_limit'));
|
|
35
|
+
if (operation === 'set') {
|
|
36
|
+
try {
|
|
37
|
+
validateStrategyMemoryValue(value);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
return Promise.reject(error);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const memoryRequestId = ++this.sequence;
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const timer = setTimeout(() => { this.pending.delete(memoryRequestId); reject(Error('strategy_memory_timeout')); }, 5000);
|
|
46
|
+
timer.unref?.();
|
|
47
|
+
this.pending.set(memoryRequestId, { requestId, resolve, reject, timer });
|
|
48
|
+
try {
|
|
49
|
+
this.send({ type: 'strategy_memory', requestId, memoryRequestId, operation, key, ...(operation === 'set' ? { value } : {}) });
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
this.pending.delete(memoryRequestId);
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
reject(error);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
return Object.freeze({ get: (key) => call('get', key),
|
|
59
|
+
set: (key, value) => call('set', key, value), delete: (key) => call('delete', key) });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** The parent supplies an already-bound capability; messages cannot choose another resource or scope. */
|
|
63
|
+
export async function serveStrategyMemoryRequest(message, binding, send) {
|
|
64
|
+
let value, error;
|
|
65
|
+
try {
|
|
66
|
+
const memory = typeof binding === 'function' ? binding() : binding;
|
|
67
|
+
if (!Number.isSafeInteger(message.memoryRequestId) || typeof message.key !== 'string')
|
|
68
|
+
throw Error('strategy_memory_request_invalid');
|
|
69
|
+
if (message.operation === 'get')
|
|
70
|
+
value = await memory.get(message.key);
|
|
71
|
+
else if (message.operation === 'set')
|
|
72
|
+
await memory.set(message.key, message.value);
|
|
73
|
+
else if (message.operation === 'delete')
|
|
74
|
+
await memory.delete(message.key);
|
|
75
|
+
else
|
|
76
|
+
throw Error('strategy_memory_request_invalid');
|
|
77
|
+
}
|
|
78
|
+
catch (failure) {
|
|
79
|
+
error = failure instanceof Error ? failure.message : 'strategy_memory_failed';
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
send({ type: 'strategy_memory_result', requestId: message.requestId, memoryRequestId: message.memoryRequestId,
|
|
83
|
+
...(error ? { error } : { value }) });
|
|
84
|
+
}
|
|
85
|
+
catch { /* the requesting Worker may have stopped */ }
|
|
86
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { StrategyMemory, StrategyMemoryValue } from './contracts.js';
|
|
2
|
+
export declare const STRATEGY_MEMORY_MAX_BYTES: number;
|
|
3
|
+
type Scope = Readonly<{
|
|
4
|
+
sessionId: string;
|
|
5
|
+
segmentId: string;
|
|
6
|
+
}>;
|
|
7
|
+
export declare function validateStrategyMemoryValue(value: unknown): asserts value is StrategyMemoryValue;
|
|
8
|
+
/** One explicitly assembled Owner-local store. Never persisted or shared with another account/Owner. */
|
|
9
|
+
export declare class StrategyMemoryStore {
|
|
10
|
+
private readonly segments;
|
|
11
|
+
open(scope: Scope): void;
|
|
12
|
+
close(scope: Scope): void;
|
|
13
|
+
bind(scope: Scope, namespace: string, isActive: () => boolean): StrategyMemory;
|
|
14
|
+
}
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
export const STRATEGY_MEMORY_MAX_BYTES = 64 * 1024;
|
|
2
|
+
const MAX_KEYS = 256, MAX_SCOPE_BYTES = 4 * 1024 * 1024;
|
|
3
|
+
const scopeKey = (scope) => JSON.stringify([scope.sessionId, scope.segmentId]);
|
|
4
|
+
function keySize(key) {
|
|
5
|
+
if (typeof key !== 'string' || !key || Buffer.byteLength(key) > 256)
|
|
6
|
+
throw Error('strategy_memory_key_invalid');
|
|
7
|
+
return Buffer.byteLength(key);
|
|
8
|
+
}
|
|
9
|
+
export function validateStrategyMemoryValue(value) {
|
|
10
|
+
const seen = new Set();
|
|
11
|
+
const visit = (entry, depth) => {
|
|
12
|
+
if (depth > 32)
|
|
13
|
+
throw Error('strategy_memory_value_invalid');
|
|
14
|
+
if (entry === null || typeof entry === 'boolean' || typeof entry === 'string')
|
|
15
|
+
return;
|
|
16
|
+
if (typeof entry === 'number' && Number.isFinite(entry))
|
|
17
|
+
return;
|
|
18
|
+
if (!entry || typeof entry !== 'object' || seen.has(entry))
|
|
19
|
+
throw Error('strategy_memory_value_invalid');
|
|
20
|
+
const prototype = Object.getPrototypeOf(entry);
|
|
21
|
+
if (!Array.isArray(entry) && prototype !== Object.prototype && prototype !== null)
|
|
22
|
+
throw Error('strategy_memory_value_invalid');
|
|
23
|
+
seen.add(entry);
|
|
24
|
+
for (const descriptor of Object.values(Object.getOwnPropertyDescriptors(entry))) {
|
|
25
|
+
if (!('value' in descriptor))
|
|
26
|
+
throw Error('strategy_memory_value_invalid');
|
|
27
|
+
// Array length is a finite number and is harmless to validate as well.
|
|
28
|
+
visit(descriptor.value, depth + 1);
|
|
29
|
+
}
|
|
30
|
+
if (Object.getOwnPropertySymbols(entry).length)
|
|
31
|
+
throw Error('strategy_memory_value_invalid');
|
|
32
|
+
seen.delete(entry);
|
|
33
|
+
};
|
|
34
|
+
visit(value, 0);
|
|
35
|
+
if (Buffer.byteLength(JSON.stringify(value)) > STRATEGY_MEMORY_MAX_BYTES)
|
|
36
|
+
throw Error('strategy_memory_limit_exceeded');
|
|
37
|
+
}
|
|
38
|
+
/** One explicitly assembled Owner-local store. Never persisted or shared with another account/Owner. */
|
|
39
|
+
export class StrategyMemoryStore {
|
|
40
|
+
segments = new Map();
|
|
41
|
+
open(scope) {
|
|
42
|
+
const key = scopeKey(scope);
|
|
43
|
+
if (!this.segments.has(key))
|
|
44
|
+
this.segments.set(key, { namespaces: new Map(), bytes: 0 });
|
|
45
|
+
}
|
|
46
|
+
close(scope) {
|
|
47
|
+
const key = scopeKey(scope), segment = this.segments.get(key);
|
|
48
|
+
if (segment) {
|
|
49
|
+
segment.namespaces.clear();
|
|
50
|
+
segment.bytes = 0;
|
|
51
|
+
this.segments.delete(key);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
bind(scope, namespace, isActive) {
|
|
55
|
+
const key = scopeKey(scope), segment = this.segments.get(key);
|
|
56
|
+
const check = () => {
|
|
57
|
+
if (!segment || this.segments.get(key) !== segment || !isActive())
|
|
58
|
+
throw Error('strategy_memory_inactive');
|
|
59
|
+
return segment;
|
|
60
|
+
};
|
|
61
|
+
return Object.freeze({
|
|
62
|
+
get: async (name) => {
|
|
63
|
+
keySize(name);
|
|
64
|
+
const current = check();
|
|
65
|
+
const value = current.namespaces.get(namespace)?.values.get(name)?.value;
|
|
66
|
+
return value === undefined ? undefined : structuredClone(value);
|
|
67
|
+
},
|
|
68
|
+
set: async (name, value) => {
|
|
69
|
+
const keyBytes = keySize(name);
|
|
70
|
+
const current = check();
|
|
71
|
+
validateStrategyMemoryValue(value);
|
|
72
|
+
const size = keyBytes + Buffer.byteLength(JSON.stringify(value));
|
|
73
|
+
const target = current.namespaces.get(namespace) ?? { values: new Map(), bytes: 0 };
|
|
74
|
+
const old = target.values.get(name)?.bytes ?? 0, delta = size - old;
|
|
75
|
+
if ((!target.values.has(name) && target.values.size >= MAX_KEYS)
|
|
76
|
+
|| target.bytes + delta > STRATEGY_MEMORY_MAX_BYTES || current.bytes + delta > MAX_SCOPE_BYTES) {
|
|
77
|
+
throw Error('strategy_memory_limit_exceeded');
|
|
78
|
+
}
|
|
79
|
+
target.values.set(name, { value: structuredClone(value), bytes: size });
|
|
80
|
+
target.bytes += delta;
|
|
81
|
+
current.bytes += delta;
|
|
82
|
+
current.namespaces.set(namespace, target);
|
|
83
|
+
},
|
|
84
|
+
delete: async (name) => {
|
|
85
|
+
keySize(name);
|
|
86
|
+
const current = check(), target = current.namespaces.get(namespace), entry = target?.values.get(name);
|
|
87
|
+
if (target && entry) {
|
|
88
|
+
target.values.delete(name);
|
|
89
|
+
target.bytes -= entry.bytes;
|
|
90
|
+
current.bytes -= entry.bytes;
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export type CaptureCategory = 'actions' | 'behavior_io' | 'perception_io';
|
|
2
|
+
export interface DetailCaptureConfig {
|
|
3
|
+
actions: boolean;
|
|
4
|
+
behavior_io: boolean;
|
|
5
|
+
perception_io: boolean;
|
|
6
|
+
max_record_bytes: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function resolveDetailCapture(): DetailCaptureConfig;
|
|
9
|
+
export declare function detailCategory(name: string): CaptureCategory | undefined;
|
|
10
|
+
type Diagnostic = (name: string, attributes: Readonly<Record<string, unknown>>, severity?: 'debug' | 'info' | 'warn' | 'error') => void;
|
|
11
|
+
/** Opt-in, lazy, Owner-side observer. No module API, gameplay Event or cross-Worker payload is added. */
|
|
12
|
+
export declare class DetailCapture {
|
|
13
|
+
readonly category: CaptureCategory;
|
|
14
|
+
private readonly diagnostic?;
|
|
15
|
+
readonly enabled: boolean;
|
|
16
|
+
constructor(category: CaptureCategory, diagnostic?: Diagnostic | undefined, config?: DetailCaptureConfig);
|
|
17
|
+
emit(phase: string, attributes: () => Record<string, unknown>): void;
|
|
18
|
+
run<T>(operation: string, metadata: Record<string, unknown>, input: unknown, invoke: () => Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
19
|
+
}
|
|
20
|
+
/** Bounded JSON snapshot: preserves gameplay payloads and IDs, always removes credentials. */
|
|
21
|
+
export declare function captureSnapshot(value: unknown, maxBytes: number): {
|
|
22
|
+
value: unknown;
|
|
23
|
+
truncated: boolean;
|
|
24
|
+
};
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
export function resolveDetailCapture() { return { actions: false, behavior_io: false, perception_io: false, max_record_bytes: 256 * 1024 }; }
|
|
3
|
+
export function detailCategory(name) {
|
|
4
|
+
return /^runtime\.detail\.(actions|behavior_io|perception_io)\./.exec(name)?.[1];
|
|
5
|
+
}
|
|
6
|
+
/** Opt-in, lazy, Owner-side observer. No module API, gameplay Event or cross-Worker payload is added. */
|
|
7
|
+
export class DetailCapture {
|
|
8
|
+
category;
|
|
9
|
+
diagnostic;
|
|
10
|
+
enabled;
|
|
11
|
+
constructor(category, diagnostic, config) {
|
|
12
|
+
this.category = category;
|
|
13
|
+
this.diagnostic = diagnostic;
|
|
14
|
+
this.enabled = !!diagnostic && (config ?? resolveDetailCapture())[category];
|
|
15
|
+
}
|
|
16
|
+
emit(phase, attributes) {
|
|
17
|
+
if (!this.enabled)
|
|
18
|
+
return;
|
|
19
|
+
try {
|
|
20
|
+
this.diagnostic?.(`runtime.detail.${this.category}.${phase}`, attributes(), 'debug');
|
|
21
|
+
}
|
|
22
|
+
catch { /* observational */ }
|
|
23
|
+
}
|
|
24
|
+
run(operation, metadata, input, invoke, signal) {
|
|
25
|
+
if (!this.enabled)
|
|
26
|
+
return invoke();
|
|
27
|
+
const invocation_id = randomUUID(), started = performance.now();
|
|
28
|
+
const base = { ...metadata, invocation_id, operation };
|
|
29
|
+
this.emit('input', () => ({ ...base, input, stage: 'requested' }));
|
|
30
|
+
let aborted = false;
|
|
31
|
+
const onAbort = () => {
|
|
32
|
+
aborted = true;
|
|
33
|
+
this.emit('cancelled', () => ({ ...base, duration_ms: performance.now() - started,
|
|
34
|
+
error: signal?.reason instanceof Error ? signal.reason.message : 'aborted' }));
|
|
35
|
+
};
|
|
36
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
37
|
+
return (async () => {
|
|
38
|
+
try {
|
|
39
|
+
const output = await invoke();
|
|
40
|
+
this.emit('output', () => ({ ...base, output: output ?? null,
|
|
41
|
+
stage: aborted ? 'late_result' : 'computed_not_yet_runtime_committed', duration_ms: performance.now() - started }));
|
|
42
|
+
return output;
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
this.emit('failed', () => ({ ...base, error: error instanceof Error ? { name: error.name, message: error.message } : String(error),
|
|
46
|
+
duration_ms: performance.now() - started }));
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
signal?.removeEventListener('abort', onAbort);
|
|
51
|
+
}
|
|
52
|
+
})();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Bounded JSON snapshot: preserves gameplay payloads and IDs, always removes credentials. */
|
|
56
|
+
export function captureSnapshot(value, maxBytes) {
|
|
57
|
+
let remaining = maxBytes, nodes = 0, truncated = false;
|
|
58
|
+
const seen = new WeakSet();
|
|
59
|
+
const marker = () => { truncated = true; return '[TRUNCATED]'; };
|
|
60
|
+
const secret = /(?:^|_)(?:api_key|claw_key|token|access_token|refresh_token|authorization|cookie|password|passwd|secret|private_key|credential|env|environment)(?:_value)?$/i;
|
|
61
|
+
const visit = (item, key = '', depth = 0) => {
|
|
62
|
+
if (++nodes > 20000 || remaining <= 0 || depth > 32)
|
|
63
|
+
return marker();
|
|
64
|
+
remaining -= Buffer.byteLength(key) * 6 + 16;
|
|
65
|
+
if (secret.test(key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').replace(/[^A-Za-z0-9]+/g, '_')))
|
|
66
|
+
return '[REDACTED]';
|
|
67
|
+
if (item === null || item === undefined)
|
|
68
|
+
return item ?? null;
|
|
69
|
+
if (typeof item === 'boolean' || typeof item === 'number')
|
|
70
|
+
return item;
|
|
71
|
+
if (typeof item === 'string') {
|
|
72
|
+
const limit = Math.max(0, Math.floor(remaining / 6));
|
|
73
|
+
const cut = item.length > limit;
|
|
74
|
+
const text = item.slice(0, limit)
|
|
75
|
+
.replace(/\bBearer\s+[^\s"']+/gi, 'Bearer [REDACTED]')
|
|
76
|
+
.replace(/\b(?:sk-|claw_|ghp_|github_pat_)[A-Za-z0-9_-]+/g, '[REDACTED]')
|
|
77
|
+
.replace(/([?&](?:token|key|code|api_key|access_token)=)[^&\s"']+/gi, '$1[REDACTED]');
|
|
78
|
+
remaining -= text.length * 6;
|
|
79
|
+
return cut ? text + marker() : text;
|
|
80
|
+
}
|
|
81
|
+
if (typeof item !== 'object')
|
|
82
|
+
return `[${typeof item}_OMITTED]`;
|
|
83
|
+
if (item instanceof Error) {
|
|
84
|
+
const field = (name, fallback) => {
|
|
85
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, name);
|
|
86
|
+
return descriptor ? 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]' : fallback;
|
|
87
|
+
};
|
|
88
|
+
return visit({ name: field('name', 'Error'), message: field('message', '') }, key, depth + 1);
|
|
89
|
+
}
|
|
90
|
+
if (seen.has(item))
|
|
91
|
+
return '[CIRCULAR]';
|
|
92
|
+
if (ArrayBuffer.isView(item) || item instanceof ArrayBuffer)
|
|
93
|
+
return '[BINARY_OMITTED]';
|
|
94
|
+
seen.add(item);
|
|
95
|
+
const out = Array.isArray(item) ? [] : {};
|
|
96
|
+
if (Array.isArray(item)) {
|
|
97
|
+
// JSON serializes holes as nulls. Charge them too; copying an isolated
|
|
98
|
+
// high index would create an enormous sparse output despite the budget.
|
|
99
|
+
for (let index = 0; index < item.length; index += 1) {
|
|
100
|
+
if (remaining <= 0 || nodes > 20000) {
|
|
101
|
+
out.push(marker());
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
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))
|
|
113
|
+
continue;
|
|
114
|
+
if (name.length > 1024) {
|
|
115
|
+
if (Array.isArray(out))
|
|
116
|
+
out.push(marker());
|
|
117
|
+
else
|
|
118
|
+
out.__capture_truncated = marker();
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
if (remaining <= 0 || nodes > 20000) {
|
|
122
|
+
if (Array.isArray(out))
|
|
123
|
+
out.push(marker());
|
|
124
|
+
else
|
|
125
|
+
out.__capture_truncated = marker();
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, name);
|
|
129
|
+
const next = visit(descriptor && 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]', name, depth + 1);
|
|
130
|
+
Object.defineProperty(out, name, { value: next, enumerable: true, configurable: true, writable: true });
|
|
131
|
+
}
|
|
132
|
+
seen.delete(item);
|
|
133
|
+
return out;
|
|
134
|
+
};
|
|
135
|
+
return { value: visit(value), truncated };
|
|
136
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Full-only process/Owner-loop measurements. Does not retain GC entries or gameplay data. */
|
|
2
|
+
export declare class RuntimeProcessTimingSampler {
|
|
3
|
+
private readonly delay;
|
|
4
|
+
private readonly observer;
|
|
5
|
+
private previousCpu;
|
|
6
|
+
private previousLoop;
|
|
7
|
+
private previousAt;
|
|
8
|
+
private gcCount;
|
|
9
|
+
private gcMs;
|
|
10
|
+
private stopped;
|
|
11
|
+
constructor();
|
|
12
|
+
sample(): Readonly<Record<string, number>>;
|
|
13
|
+
stop(): void;
|
|
14
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { monitorEventLoopDelay, performance, PerformanceObserver } from 'node:perf_hooks';
|
|
2
|
+
/** Full-only process/Owner-loop measurements. Does not retain GC entries or gameplay data. */
|
|
3
|
+
export class RuntimeProcessTimingSampler {
|
|
4
|
+
delay = monitorEventLoopDelay({ resolution: 20 });
|
|
5
|
+
observer;
|
|
6
|
+
previousCpu = process.cpuUsage();
|
|
7
|
+
previousLoop = performance.eventLoopUtilization();
|
|
8
|
+
previousAt = performance.now();
|
|
9
|
+
gcCount = 0;
|
|
10
|
+
gcMs = 0;
|
|
11
|
+
stopped = false;
|
|
12
|
+
constructor() {
|
|
13
|
+
this.observer = new PerformanceObserver((entries) => {
|
|
14
|
+
for (const entry of entries.getEntries()) {
|
|
15
|
+
this.gcCount += 1;
|
|
16
|
+
this.gcMs += entry.duration;
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
this.observer.observe({ entryTypes: ['gc'] });
|
|
20
|
+
this.delay.enable();
|
|
21
|
+
}
|
|
22
|
+
sample() {
|
|
23
|
+
const now = performance.now();
|
|
24
|
+
const cpu = process.cpuUsage();
|
|
25
|
+
const loop = performance.eventLoopUtilization();
|
|
26
|
+
const elapsed = now - this.previousAt;
|
|
27
|
+
const deltaLoop = performance.eventLoopUtilization(loop, this.previousLoop);
|
|
28
|
+
const milliseconds = (ns) => Number.isFinite(ns) ? Math.round(ns / 1_000) / 1_000 : 0;
|
|
29
|
+
const result = {
|
|
30
|
+
window_ms: Math.round(elapsed),
|
|
31
|
+
// process.cpuUsage includes Worker threads; this is not Owner-isolate CPU utilization.
|
|
32
|
+
process_cpu_user_ms: (cpu.user - this.previousCpu.user) / 1_000,
|
|
33
|
+
process_cpu_system_ms: (cpu.system - this.previousCpu.system) / 1_000,
|
|
34
|
+
owner_event_loop_utilization: deltaLoop.utilization,
|
|
35
|
+
owner_event_loop_delay_mean_ms: milliseconds(this.delay.mean),
|
|
36
|
+
owner_event_loop_delay_p95_ms: milliseconds(this.delay.percentile(95)),
|
|
37
|
+
owner_event_loop_delay_max_ms: milliseconds(this.delay.max),
|
|
38
|
+
owner_gc_count: this.gcCount,
|
|
39
|
+
owner_gc_duration_ms: Math.round(this.gcMs * 1_000) / 1_000,
|
|
40
|
+
};
|
|
41
|
+
this.previousAt = now;
|
|
42
|
+
this.previousCpu = cpu;
|
|
43
|
+
this.previousLoop = loop;
|
|
44
|
+
this.gcCount = 0;
|
|
45
|
+
this.gcMs = 0;
|
|
46
|
+
this.delay.reset();
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
stop() {
|
|
50
|
+
if (this.stopped)
|
|
51
|
+
return;
|
|
52
|
+
this.stopped = true;
|
|
53
|
+
this.observer.disconnect();
|
|
54
|
+
this.delay.disable();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { ObservabilityRedactor } from './redaction.js';
|
|
2
|
+
import { type DetailCaptureConfig } from './detail-capture.js';
|
|
3
|
+
import { type ObservabilityProcess, type ObservabilityReporter, type ObservabilityScope, type ObservabilitySeverity, type RecordTelemetryInput } from './types.js';
|
|
4
|
+
export interface TelemetryRecorderOptions {
|
|
5
|
+
process: ObservabilityProcess;
|
|
6
|
+
reporter?: ObservabilityReporter;
|
|
7
|
+
redactor?: ObservabilityRedactor;
|
|
8
|
+
enabled?: boolean;
|
|
9
|
+
now?: () => Date;
|
|
10
|
+
idFactory?: () => string;
|
|
11
|
+
scopeProvider?: () => ObservabilityScope | undefined;
|
|
12
|
+
sampler?: (input: Readonly<RecordTelemetryInput>) => boolean;
|
|
13
|
+
capture?: DetailCaptureConfig;
|
|
14
|
+
detailReporter?: ObservabilityReporter;
|
|
15
|
+
}
|
|
16
|
+
/** Owner-side authority for logs, metrics and error reports. Never throws into gameplay. */
|
|
17
|
+
export declare class TelemetryRecorder {
|
|
18
|
+
private readonly process;
|
|
19
|
+
private readonly reporter;
|
|
20
|
+
private readonly redactor;
|
|
21
|
+
private readonly enabled;
|
|
22
|
+
private readonly now;
|
|
23
|
+
private readonly idFactory;
|
|
24
|
+
private readonly scopeProvider?;
|
|
25
|
+
private readonly sampler;
|
|
26
|
+
private readonly capture?;
|
|
27
|
+
private readonly detailReporter?;
|
|
28
|
+
private lastDetailScope?;
|
|
29
|
+
constructor(options: TelemetryRecorderOptions);
|
|
30
|
+
record(input: RecordTelemetryInput): string | null;
|
|
31
|
+
log(severity: ObservabilitySeverity, name: string, attributes?: Record<string, unknown>, context?: Pick<RecordTelemetryInput, 'component' | 'scope' | 'correlation'>): string | null;
|
|
32
|
+
metric(name: string, value: number, options?: Pick<RecordTelemetryInput, 'component' | 'scope' | 'correlation' | 'attributes'> & {
|
|
33
|
+
unit?: string;
|
|
34
|
+
aggregation?: 'counter' | 'gauge' | 'histogram_sample';
|
|
35
|
+
}): string | null;
|
|
36
|
+
error(name: string, error: unknown, attributes?: Record<string, unknown>, context?: Pick<RecordTelemetryInput, 'component' | 'scope' | 'correlation'>): string | null;
|
|
37
|
+
logger(component: string, base?: Record<string, unknown>): StructuredLogger;
|
|
38
|
+
private captureSummary;
|
|
39
|
+
flush(): Promise<void>;
|
|
40
|
+
close(): Promise<void>;
|
|
41
|
+
flushWithin(timeoutMs: number): Promise<boolean>;
|
|
42
|
+
closeWithin(timeoutMs: number): Promise<boolean>;
|
|
43
|
+
stats(): import("./types.js").ObservabilityReporterStats;
|
|
44
|
+
detailStats(): import("./types.js").ObservabilityReporterStats | undefined;
|
|
45
|
+
captureEnabled(category: keyof Pick<DetailCaptureConfig, 'actions' | 'behavior_io' | 'perception_io'>): boolean;
|
|
46
|
+
}
|
|
47
|
+
export declare class StructuredLogger {
|
|
48
|
+
private readonly recorder;
|
|
49
|
+
private readonly component;
|
|
50
|
+
private readonly base;
|
|
51
|
+
constructor(recorder: TelemetryRecorder, component: string, base?: Record<string, unknown>);
|
|
52
|
+
debug(name: string, attributes?: Record<string, unknown>): string | null;
|
|
53
|
+
info(name: string, attributes?: Record<string, unknown>): string | null;
|
|
54
|
+
warn(name: string, attributes?: Record<string, unknown>): string | null;
|
|
55
|
+
error(name: string, error: unknown, attributes?: Record<string, unknown>): string | null;
|
|
56
|
+
}
|