@myclaw163/clawclaw-cli 0.8.13 → 0.8.15
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/docs/custom-modules/perception.md +4 -4
- package/docs/runtime/README.md +1 -1
- package/docs/runtime/behavior-runtime.md +1 -1
- package/docs/runtime/official-perception-modules.md +23 -30
- package/docs/runtime/perception-replay.md +1 -1
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +8 -4
- package/skills/clawclaw/references/BEHAVIORS.md +16 -1
- package/skills/clawclaw/references/CHANNELS.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +2 -2
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
- package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
- package/skills/clawclaw/references/STREAM.md +4 -2
- package/src/lib/game-client.ts +12 -4
- package/src/pipeline/event-format.ts +5 -0
- package/src/pipeline/event-hints.ts +10 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
- package/src/runtime/clawclaw/behavior-decision.ts +4 -1
- package/src/runtime/clawclaw/behavior-input.ts +5 -0
- package/src/runtime/clawclaw/owner.ts +64 -1
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
- package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
- package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +201 -43
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +45 -9
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +170 -8
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
- package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +33 -9
- package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
- package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +327 -23
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
- package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
- package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
- package/src/runtime/clawclaw/runtime.ts +31 -3
- package/src/runtime/clawclaw-event-catalog.ts +3 -0
- package/src/runtime/framework/events/event-repository.ts +1 -1
- package/src/runtime/framework/events/memory-event-repository.ts +71 -1
- package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
- package/src/runtime/framework/mailbox/types.ts +2 -0
- package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +383 -0
- package/src/runtime/framework/plugins/contracts.ts +5 -2
- package/src/runtime/framework/plugins/runtime-input-journal.ts +185 -17
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +173 -34
- package/src/runtime/framework/runtime.ts +75 -4
- package/src/runtime/framework/state/history/contracts.ts +9 -1
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +59 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
- package/src/runtime/observability/redaction.ts +28 -1
- package/src/sdk/behavior-plugin/index.ts +5 -24
- package/src/sdk/module-input/index.ts +47 -0
- package/src/sdk/perception-plugin/index.ts +13 -8
|
@@ -73,6 +73,7 @@ import {
|
|
|
73
73
|
type StateProviderResult,
|
|
74
74
|
type TrajectoryRecord,
|
|
75
75
|
} from './state/index.js';
|
|
76
|
+
import { performance } from 'node:perf_hooks';
|
|
76
77
|
import { randomUUID } from 'crypto';
|
|
77
78
|
import type { TelemetryRecorder } from '../observability/index.js';
|
|
78
79
|
|
|
@@ -323,6 +324,13 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
323
324
|
StateProviderResult<Record<string, any> | null>
|
|
324
325
|
>();
|
|
325
326
|
private readonly epochCompletions = new Map<number, Promise<RuntimeEpochExecutionResult>>();
|
|
327
|
+
private readonly epochIntakeTimings = new Map<number, {
|
|
328
|
+
startedAtMs: number;
|
|
329
|
+
journalMs: number;
|
|
330
|
+
historyMs: number;
|
|
331
|
+
stateProjectionMs: number;
|
|
332
|
+
intakeTotalMs: number;
|
|
333
|
+
}>();
|
|
326
334
|
private readonly closedReadyAnchors = new Map<
|
|
327
335
|
number,
|
|
328
336
|
RuntimeReadyAnchor<Record<string, any> | null>
|
|
@@ -360,6 +368,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
360
368
|
if (options.stateHistoryRepository) {
|
|
361
369
|
this.stateHistoryRepository = options.stateHistoryRepository;
|
|
362
370
|
historyPersistence = options.stateHistoryRepository instanceof SqliteStateHistoryRepository
|
|
371
|
+
|| (options.stateHistoryRepository as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
|
|
363
372
|
? 'sqlite'
|
|
364
373
|
: 'memory';
|
|
365
374
|
} else if (options.stateHistoryPath) {
|
|
@@ -377,6 +386,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
377
386
|
if (options.inputJournal) {
|
|
378
387
|
this.inputJournal = options.inputJournal;
|
|
379
388
|
inputJournalPersistence = options.inputJournal instanceof SqliteRuntimeInputJournal
|
|
389
|
+
|| (options.inputJournal as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
|
|
380
390
|
? 'sqlite'
|
|
381
391
|
: 'memory';
|
|
382
392
|
} else if (options.inputJournalPath) {
|
|
@@ -385,7 +395,10 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
385
395
|
} else {
|
|
386
396
|
this.inputJournal = new MemoryRuntimeInputJournal();
|
|
387
397
|
}
|
|
388
|
-
const eventPersistence = this.repository instanceof SqliteEventRepository
|
|
398
|
+
const eventPersistence = this.repository instanceof SqliteEventRepository
|
|
399
|
+
|| (this.repository as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
|
|
400
|
+
? 'sqlite'
|
|
401
|
+
: 'memory';
|
|
389
402
|
this.persistenceBase = {
|
|
390
403
|
events: eventPersistence,
|
|
391
404
|
stateHistory: historyPersistence,
|
|
@@ -595,6 +608,24 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
595
608
|
return this.pluginScheduler.descriptors();
|
|
596
609
|
}
|
|
597
610
|
|
|
611
|
+
/** Full-diagnostic, on-demand scheduler state; never sampled by default. */
|
|
612
|
+
runtimeEpochDiagnosticSnapshot(): ReturnType<RuntimePluginScheduler['diagnosticSnapshot']> {
|
|
613
|
+
return this.pluginScheduler.diagnosticSnapshot(this.scope());
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** Full-only retained row counts; implementations without a hot cache report an empty object. */
|
|
617
|
+
runtimeRetainedRecordCounts(): Readonly<Record<string, unknown>> {
|
|
618
|
+
const counts = (value: unknown): Readonly<Record<string, number>> => (
|
|
619
|
+
(value as { diagnosticCounts?: () => Readonly<Record<string, number>> })
|
|
620
|
+
?.diagnosticCounts?.() ?? {}
|
|
621
|
+
);
|
|
622
|
+
return {
|
|
623
|
+
event_repository: counts(this.repository),
|
|
624
|
+
state_history: counts(this.stateHistoryRepository),
|
|
625
|
+
input_journal: counts(this.inputJournal),
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
|
|
598
629
|
runtimePluginDescriptors(): RuntimePluginDescriptor[] {
|
|
599
630
|
return [
|
|
600
631
|
...[...this.sourcePlugins.values()].map(({ plugin }) => ({
|
|
@@ -774,6 +805,8 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
774
805
|
batch: RuntimeInputBatch<Record<string, any>, Record<string, unknown>>,
|
|
775
806
|
): Promise<RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>> {
|
|
776
807
|
this.assertSourceInputOpen();
|
|
808
|
+
const intakeStartedAtMs = performance.now();
|
|
809
|
+
const journalStartedAtMs = performance.now();
|
|
777
810
|
let acceptance: RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>;
|
|
778
811
|
try {
|
|
779
812
|
assertRuntimeInputBatch(batch);
|
|
@@ -789,6 +822,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
789
822
|
}, { component: 'runtime.input', scope: this.publicScope() });
|
|
790
823
|
throw error;
|
|
791
824
|
}
|
|
825
|
+
const journalMs = Math.max(0, performance.now() - journalStartedAtMs);
|
|
792
826
|
if (!acceptance.inserted) {
|
|
793
827
|
this.observability?.log('debug', 'runtime.input.duplicate', {
|
|
794
828
|
source_id: batch.sourceId,
|
|
@@ -800,6 +834,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
800
834
|
|
|
801
835
|
const epoch = acceptance.epoch;
|
|
802
836
|
this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, epoch.epochSeq);
|
|
837
|
+
const historyStartedAtMs = performance.now();
|
|
803
838
|
const previousFrame = this.stateHistoryRepository.latestStateFrame(epoch.scope);
|
|
804
839
|
const frame = this.stateHistoryRepository.appendStateFrame({
|
|
805
840
|
epochSeq: epoch.epochSeq,
|
|
@@ -813,7 +848,9 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
813
848
|
receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
|
|
814
849
|
state: epoch.state,
|
|
815
850
|
}).frame;
|
|
851
|
+
const historyMs = Math.max(0, performance.now() - historyStartedAtMs);
|
|
816
852
|
|
|
853
|
+
const stateProjectionStartedAtMs = performance.now();
|
|
817
854
|
const projectedState = this.currentStateFromRuntimeState(epoch.state);
|
|
818
855
|
if (projectedState !== null) {
|
|
819
856
|
const current = this.stateIngress.snapshot();
|
|
@@ -840,6 +877,15 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
840
877
|
}
|
|
841
878
|
const currentState = this.readAgentState();
|
|
842
879
|
this.acceptedAgentStateByEpoch.set(epoch.epochSeq, structuredClone(currentState));
|
|
880
|
+
const stateProjectionMs = Math.max(0, performance.now() - stateProjectionStartedAtMs);
|
|
881
|
+
const intakeTotalMs = Math.max(0, performance.now() - intakeStartedAtMs);
|
|
882
|
+
this.epochIntakeTimings.set(epoch.epochSeq, {
|
|
883
|
+
startedAtMs: intakeStartedAtMs,
|
|
884
|
+
journalMs,
|
|
885
|
+
historyMs,
|
|
886
|
+
stateProjectionMs,
|
|
887
|
+
intakeTotalMs,
|
|
888
|
+
});
|
|
843
889
|
|
|
844
890
|
this.observability?.log('debug', 'runtime.input.accepted', {
|
|
845
891
|
source_id: epoch.sourceId,
|
|
@@ -854,6 +900,10 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
854
900
|
cause: typeof epoch.state.cause === 'string' ? epoch.state.cause : undefined,
|
|
855
901
|
connection: typeof epoch.state.connection === 'string' ? epoch.state.connection : undefined,
|
|
856
902
|
game_snapshot_status: epoch.state.game_snapshot?.status,
|
|
903
|
+
journal_ms: Math.round(journalMs * 1_000) / 1_000,
|
|
904
|
+
state_history_ms: Math.round(historyMs * 1_000) / 1_000,
|
|
905
|
+
state_projection_ms: Math.round(stateProjectionMs * 1_000) / 1_000,
|
|
906
|
+
intake_total_ms: Math.round(intakeTotalMs * 1_000) / 1_000,
|
|
857
907
|
}, { component: 'runtime.input', scope: this.publicScope() });
|
|
858
908
|
|
|
859
909
|
const completion = this.pluginScheduler.enqueue({
|
|
@@ -1137,9 +1187,9 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
1137
1187
|
this.sourceInputOpen = false;
|
|
1138
1188
|
this.closing = false;
|
|
1139
1189
|
this.closed = true;
|
|
1140
|
-
this.stateHistoryRepository.close?.();
|
|
1141
|
-
this.inputJournal.close?.();
|
|
1142
|
-
this.repository.close?.();
|
|
1190
|
+
await this.stateHistoryRepository.close?.();
|
|
1191
|
+
await this.inputJournal.close?.();
|
|
1192
|
+
await this.repository.close?.();
|
|
1143
1193
|
this.observability?.log('info', 'runtime.owner.stopped', {
|
|
1144
1194
|
event_repository: this.persistence.events,
|
|
1145
1195
|
state_history_repository: this.persistence.stateHistory,
|
|
@@ -1372,6 +1422,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
1372
1422
|
frameSeq: number,
|
|
1373
1423
|
result: RuntimeEpochExecutionResult,
|
|
1374
1424
|
): Promise<void> {
|
|
1425
|
+
const finalizeStartedAtMs = performance.now();
|
|
1375
1426
|
const isCurrentScope = sameScope(epoch.scope, this.scope());
|
|
1376
1427
|
const acceptedState = this.acceptedAgentStateByEpoch.get(epoch.epochSeq)
|
|
1377
1428
|
?? this.recoveredAgentState(epoch);
|
|
@@ -1435,6 +1486,16 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
1435
1486
|
for (const acceptedEpochSeq of this.acceptedAgentStateByEpoch.keys()) {
|
|
1436
1487
|
if (acceptedEpochSeq <= epoch.epochSeq) this.acceptedAgentStateByEpoch.delete(acceptedEpochSeq);
|
|
1437
1488
|
}
|
|
1489
|
+
const intakeTiming = this.epochIntakeTimings.get(epoch.epochSeq);
|
|
1490
|
+
this.epochIntakeTimings.delete(epoch.epochSeq);
|
|
1491
|
+
const finalizeMs = Math.max(0, performance.now() - finalizeStartedAtMs);
|
|
1492
|
+
const totalMs = intakeTiming
|
|
1493
|
+
? Math.max(0, performance.now() - intakeTiming.startedAtMs)
|
|
1494
|
+
: result.durationMs + finalizeMs;
|
|
1495
|
+
const longestPlugin = [...result.outcomes].sort((left, right) => right.durationMs - left.durationMs)[0];
|
|
1496
|
+
const persistenceHealth = (
|
|
1497
|
+
this.repository as { persistenceHealth?: () => Record<string, unknown> }
|
|
1498
|
+
).persistenceHealth?.();
|
|
1438
1499
|
this.observability?.log('debug', 'runtime.view.ready', {
|
|
1439
1500
|
epoch_seq: epoch.epochSeq,
|
|
1440
1501
|
latest_epoch_seq: this.latestAcceptedEpochSeq,
|
|
@@ -1442,6 +1503,16 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
1442
1503
|
frame_seq: frameSeq,
|
|
1443
1504
|
event_watermark: result.eventWatermark,
|
|
1444
1505
|
current_scope: isCurrentScope,
|
|
1506
|
+
total_duration_ms: Math.round(totalMs * 1_000) / 1_000,
|
|
1507
|
+
intake_duration_ms: Math.round((intakeTiming?.intakeTotalMs ?? 0) * 1_000) / 1_000,
|
|
1508
|
+
scheduler_duration_ms: Math.round(result.durationMs * 1_000) / 1_000,
|
|
1509
|
+
ready_view_finalize_ms: Math.round(finalizeMs * 1_000) / 1_000,
|
|
1510
|
+
longest_plugin_id: longestPlugin?.pluginId,
|
|
1511
|
+
longest_plugin_duration_ms: longestPlugin
|
|
1512
|
+
? Math.round(longestPlugin.durationMs * 1_000) / 1_000
|
|
1513
|
+
: 0,
|
|
1514
|
+
persistence_pending_operations: persistenceHealth?.pendingOperations,
|
|
1515
|
+
persistence_degraded: persistenceHealth?.degraded,
|
|
1445
1516
|
}, { component: 'runtime.view', scope: this.publicScope() });
|
|
1446
1517
|
}
|
|
1447
1518
|
|
|
@@ -118,6 +118,14 @@ export interface AppendStateFrameResult<TState = Record<string, unknown>> {
|
|
|
118
118
|
frame: StoredStateFrame<TState>;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
+
export interface StateHistorySnapshot<TPosition = unknown, TState = Record<string, unknown>> {
|
|
122
|
+
scopes: HistoryScopeRecord[];
|
|
123
|
+
stateFrames: StoredStateFrame<TState>[];
|
|
124
|
+
records: Array<TrajectoryRecord<TPosition> & { recordSeq: number }>;
|
|
125
|
+
nextFrameSeq: number;
|
|
126
|
+
nextRecordSeq: number;
|
|
127
|
+
}
|
|
128
|
+
|
|
121
129
|
export interface StateFrameHistoryReader<TState = Record<string, unknown>> {
|
|
122
130
|
/** Reads the canonical accepted State journal. Implementations may use a hot cache. */
|
|
123
131
|
queryStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState>;
|
|
@@ -135,7 +143,7 @@ export interface StateJournal<TState = Record<string, unknown>>
|
|
|
135
143
|
markScopeIncomplete(scope: RuntimeScope): void;
|
|
136
144
|
getScope(scope: RuntimeScope): HistoryScopeRecord | null;
|
|
137
145
|
appendStateFrame(frame: StateFrameRecord<TState>): AppendStateFrameResult<TState>;
|
|
138
|
-
close?(): void
|
|
146
|
+
close?(): void | Promise<void>;
|
|
139
147
|
}
|
|
140
148
|
|
|
141
149
|
/** Sparse records used by transport-gap diagnostics and adapters that explicitly project them. */
|
|
@@ -9,6 +9,7 @@ import type {
|
|
|
9
9
|
StateFrameQueryResult,
|
|
10
10
|
StateFrameRecord,
|
|
11
11
|
StateHistoryRepository,
|
|
12
|
+
StateHistorySnapshot,
|
|
12
13
|
StoredStateFrame,
|
|
13
14
|
TrajectoryRecord,
|
|
14
15
|
} from './contracts.js';
|
|
@@ -23,12 +24,57 @@ export class MemoryStateHistoryRepository<
|
|
|
23
24
|
> implements StateHistoryRepository<TPosition, TState> {
|
|
24
25
|
private readonly scopes = new Map<string, HistoryScopeRecord>();
|
|
25
26
|
private readonly stateFrames: StoredStateFrame<TState>[] = [];
|
|
27
|
+
private readonly stateFramesByScope = new Map<string, StoredStateFrame<TState>[]>();
|
|
26
28
|
private readonly stateFrameDedupe = new Map<string, StoredStateFrame<TState>>();
|
|
27
29
|
private readonly records: Array<TrajectoryRecord<TPosition> & { recordSeq: number }> = [];
|
|
30
|
+
private readonly recordsByScope = new Map<string, Array<TrajectoryRecord<TPosition> & { recordSeq: number }>>();
|
|
28
31
|
private readonly dedupe = new Set<string>();
|
|
32
|
+
|
|
33
|
+
diagnosticCounts(): Readonly<Record<string, number>> {
|
|
34
|
+
return {
|
|
35
|
+
scopes: this.scopes.size,
|
|
36
|
+
state_frames: this.stateFrames.length,
|
|
37
|
+
trajectory_records: this.records.length,
|
|
38
|
+
state_frame_dedupe_keys: this.stateFrameDedupe.size,
|
|
39
|
+
trajectory_dedupe_keys: this.dedupe.size,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
29
42
|
private nextFrameSeq = 1;
|
|
30
43
|
private nextRecordSeq = 1;
|
|
31
44
|
|
|
45
|
+
constructor(snapshot?: StateHistorySnapshot<TPosition, TState>) {
|
|
46
|
+
if (!snapshot) return;
|
|
47
|
+
for (const scope of snapshot.scopes) this.scopes.set(runtimeScopeKey(scope.scope), cloneCanonical(scope));
|
|
48
|
+
for (const frame of snapshot.stateFrames) {
|
|
49
|
+
const stored = cloneCanonical(frame);
|
|
50
|
+
this.stateFrames.push(stored);
|
|
51
|
+
const scoped = this.stateFramesByScope.get(runtimeScopeKey(frame.scope)) ?? [];
|
|
52
|
+
scoped.push(stored);
|
|
53
|
+
this.stateFramesByScope.set(runtimeScopeKey(frame.scope), scoped);
|
|
54
|
+
this.stateFrameDedupe.set(`${runtimeScopeKey(frame.scope)}\u001f${frame.sourceKey}`, stored);
|
|
55
|
+
}
|
|
56
|
+
for (const record of snapshot.records) {
|
|
57
|
+
const stored = cloneCanonical(record);
|
|
58
|
+
this.records.push(stored);
|
|
59
|
+
const scoped = this.recordsByScope.get(runtimeScopeKey(record.scope)) ?? [];
|
|
60
|
+
scoped.push(stored);
|
|
61
|
+
this.recordsByScope.set(runtimeScopeKey(record.scope), scoped);
|
|
62
|
+
this.dedupe.add(dedupeKey(stored));
|
|
63
|
+
}
|
|
64
|
+
this.nextFrameSeq = Math.max(snapshot.nextFrameSeq, 1);
|
|
65
|
+
this.nextRecordSeq = Math.max(snapshot.nextRecordSeq, 1);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
snapshot(): StateHistorySnapshot<TPosition, TState> {
|
|
69
|
+
return cloneCanonical({
|
|
70
|
+
scopes: [...this.scopes.values()],
|
|
71
|
+
stateFrames: this.stateFrames,
|
|
72
|
+
records: this.records,
|
|
73
|
+
nextFrameSeq: this.nextFrameSeq,
|
|
74
|
+
nextRecordSeq: this.nextRecordSeq,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
32
78
|
openScope(scope: RuntimeScope, openedAtMs = Date.now(), historyComplete = true): HistoryScopeRecord {
|
|
33
79
|
for (const stored of this.scopes.values()) {
|
|
34
80
|
if (
|
|
@@ -88,6 +134,9 @@ export class MemoryStateHistoryRepository<
|
|
|
88
134
|
frameSeq: this.nextFrameSeq++,
|
|
89
135
|
};
|
|
90
136
|
this.stateFrames.push(stored);
|
|
137
|
+
const scopedFrames = this.stateFramesByScope.get(scopeKey) ?? [];
|
|
138
|
+
scopedFrames.push(stored);
|
|
139
|
+
this.stateFramesByScope.set(scopeKey, scopedFrames);
|
|
91
140
|
this.stateFrameDedupe.set(dedupe, stored);
|
|
92
141
|
return { inserted: true, frame: cloneCanonical(stored) };
|
|
93
142
|
}
|
|
@@ -95,9 +144,8 @@ export class MemoryStateHistoryRepository<
|
|
|
95
144
|
queryStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState> {
|
|
96
145
|
const order = query.order ?? 'asc';
|
|
97
146
|
const limit = Math.max(1, Math.min(query.limit ?? 100, 10_000));
|
|
98
|
-
let selected = this.
|
|
99
|
-
|
|
100
|
-
&& (query.fromEpochSeq === undefined
|
|
147
|
+
let selected = (this.stateFramesByScope.get(runtimeScopeKey(query.scope)) ?? []).filter((frame) => (
|
|
148
|
+
(query.fromEpochSeq === undefined
|
|
101
149
|
|| (frame.epochSeq !== undefined && frame.epochSeq >= query.fromEpochSeq))
|
|
102
150
|
&& (query.toEpochSeq === undefined
|
|
103
151
|
|| (frame.epochSeq !== undefined && frame.epochSeq <= query.toEpochSeq))
|
|
@@ -142,7 +190,12 @@ export class MemoryStateHistoryRepository<
|
|
|
142
190
|
continue;
|
|
143
191
|
}
|
|
144
192
|
this.dedupe.add(key);
|
|
145
|
-
|
|
193
|
+
const stored = { ...cloneCanonical(record), recordSeq: this.nextRecordSeq++ };
|
|
194
|
+
this.records.push(stored);
|
|
195
|
+
const scopeKey = runtimeScopeKey(record.scope);
|
|
196
|
+
const scoped = this.recordsByScope.get(scopeKey) ?? [];
|
|
197
|
+
scoped.push(stored);
|
|
198
|
+
this.recordsByScope.set(scopeKey, scoped);
|
|
146
199
|
inserted += 1;
|
|
147
200
|
}
|
|
148
201
|
return { inserted, duplicates };
|
|
@@ -153,9 +206,8 @@ export class MemoryStateHistoryRepository<
|
|
|
153
206
|
const limit = Math.max(1, Math.min(query.limit ?? 100, 1000));
|
|
154
207
|
const subjectSet = query.subjectIds ? new Set(query.subjectIds) : null;
|
|
155
208
|
const kindSet = query.kinds ? new Set(query.kinds) : null;
|
|
156
|
-
let selected = this.
|
|
157
|
-
|
|
158
|
-
&& (!subjectSet || subjectSet.has(record.subjectId))
|
|
209
|
+
let selected = (this.recordsByScope.get(runtimeScopeKey(query.scope)) ?? []).filter((record) => (
|
|
210
|
+
(!subjectSet || subjectSet.has(record.subjectId))
|
|
159
211
|
&& (!kindSet || kindSet.has(record.kind))
|
|
160
212
|
&& (query.afterRecordSeq === undefined || record.recordSeq > query.afterRecordSeq)
|
|
161
213
|
&& (query.beforeRecordSeq === undefined || record.recordSeq < query.beforeRecordSeq)
|
|
@@ -13,6 +13,7 @@ import type {
|
|
|
13
13
|
StateFrameQueryResult,
|
|
14
14
|
StateFrameRecord,
|
|
15
15
|
StateHistoryRepository,
|
|
16
|
+
StateHistorySnapshot,
|
|
16
17
|
StoredStateFrame,
|
|
17
18
|
TrajectoryRecord,
|
|
18
19
|
TrajectoryRecordKind,
|
|
@@ -355,6 +356,21 @@ export class SqliteStateHistoryRepository<
|
|
|
355
356
|
this.db.close();
|
|
356
357
|
}
|
|
357
358
|
|
|
359
|
+
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
360
|
+
snapshot(): StateHistorySnapshot<TPosition, TState> {
|
|
361
|
+
const stateFrames = this.db.prepare('SELECT * FROM state_frames ORDER BY frame_seq ASC')
|
|
362
|
+
.all().map((row) => this.stateFrameFromRow(row));
|
|
363
|
+
const records = this.db.prepare('SELECT * FROM trajectory_records ORDER BY record_seq ASC')
|
|
364
|
+
.all().map((row) => this.recordFromRow(row));
|
|
365
|
+
return {
|
|
366
|
+
scopes: this.db.prepare('SELECT * FROM history_scopes').all().map((row) => this.scopeFromRow(row)),
|
|
367
|
+
stateFrames,
|
|
368
|
+
records,
|
|
369
|
+
nextFrameSeq: (stateFrames.at(-1)?.frameSeq ?? 0) + 1,
|
|
370
|
+
nextRecordSeq: (records.at(-1)?.recordSeq ?? 0) + 1,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
358
374
|
private rememberStateFrame(frame: StoredStateFrame<TState>): void {
|
|
359
375
|
const key = runtimeScopeKey(frame.scope);
|
|
360
376
|
const recent = this.recentStateFrames.get(key) ?? [];
|
|
@@ -6,6 +6,9 @@ const PRIVATE_TEXT_KEY = /(?:^|_)(?:speech|comment|think|thinking|chat|knowledge
|
|
|
6
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
7
|
const PATH_KEY = /(?:^|_)(?:path|cwd|workspace|directory|dir|filename|file_path|file_name)$/;
|
|
8
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;
|
|
9
12
|
const TOKEN_IN_TEXT = /\b(?:Bearer\s+)?[A-Za-z0-9_-]{24,}\b/g;
|
|
10
13
|
const FILE_URL = /file:\/\/\/?[^"'\r\n<>\)\]]+/gi;
|
|
11
14
|
const WINDOWS_PATH = /\b[A-Za-z]:[\\\/][^"'\r\n<>\)\]]+/g;
|
|
@@ -84,6 +87,24 @@ function safeString(value: string, maxLength: number): string {
|
|
|
84
87
|
: `${withoutQuery.slice(0, maxLength)}...[truncated:${withoutQuery.length}]`;
|
|
85
88
|
}
|
|
86
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
|
+
|
|
87
108
|
/**
|
|
88
109
|
* Redacts before persistence. It is deliberately defensive: cycles, deep
|
|
89
110
|
* objects and oversized collections are bounded rather than allowed to break
|
|
@@ -121,7 +142,13 @@ export class ObservabilityRedactor {
|
|
|
121
142
|
if (IDENTITY_KEY.test(policyKey) && value !== null && value !== undefined) return this.stableHash(value);
|
|
122
143
|
if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number') return value;
|
|
123
144
|
if (typeof value === 'bigint') return value.toString();
|
|
124
|
-
if (typeof value === 'string')
|
|
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
|
+
}
|
|
125
152
|
if (depth >= this.maxDepth) return '[MAX_DEPTH]';
|
|
126
153
|
if (value instanceof Error) {
|
|
127
154
|
return this.visit({
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
BehaviorInput,
|
|
3
|
+
BehaviorDecisionAction,
|
|
3
4
|
Position,
|
|
4
5
|
} from '../module-input/index.js';
|
|
5
6
|
import type { ClawclawResourceLocalizations } from '../resource-metadata.js';
|
|
@@ -19,6 +20,9 @@ export type {
|
|
|
19
20
|
|
|
20
21
|
export type {
|
|
21
22
|
BehaviorContinuation,
|
|
23
|
+
BehaviorDecisionAction,
|
|
24
|
+
BehaviorDecisionFrame,
|
|
25
|
+
BehaviorDecisionFrameStatus,
|
|
22
26
|
BehaviorDelegatedBehaviorResult,
|
|
23
27
|
BehaviorInput,
|
|
24
28
|
BehaviorScope,
|
|
@@ -180,31 +184,8 @@ export interface BehaviorReadApi {
|
|
|
180
184
|
};
|
|
181
185
|
}
|
|
182
186
|
|
|
183
|
-
interface GameActionBase {
|
|
184
|
-
readonly thinking_content?: string;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
187
|
/** The one typed Action union accepted from finite and continuous Behaviors. */
|
|
188
|
-
export type GameAction =
|
|
189
|
-
| (GameActionBase & {
|
|
190
|
-
readonly action: 'move';
|
|
191
|
-
readonly target: string;
|
|
192
|
-
readonly target_x?: never;
|
|
193
|
-
readonly target_y?: never;
|
|
194
|
-
readonly stop_on_player?: boolean;
|
|
195
|
-
})
|
|
196
|
-
| (GameActionBase & {
|
|
197
|
-
readonly action: 'move';
|
|
198
|
-
readonly target?: never;
|
|
199
|
-
readonly target_x: number;
|
|
200
|
-
readonly target_y: number;
|
|
201
|
-
readonly stop_on_player?: boolean;
|
|
202
|
-
})
|
|
203
|
-
| (GameActionBase & { readonly action: 'kill'; readonly target_seat: number })
|
|
204
|
-
| (GameActionBase & { readonly action: 'speech'; readonly text: string })
|
|
205
|
-
| (GameActionBase & { readonly action: 'task'; readonly task_name?: string })
|
|
206
|
-
| (GameActionBase & { readonly action: 'report' })
|
|
207
|
-
| (GameActionBase & { readonly action: 'think' });
|
|
188
|
+
export type GameAction = BehaviorDecisionAction;
|
|
208
189
|
|
|
209
190
|
/** Module status published beside Game State; it never patches authoritative Game State. */
|
|
210
191
|
export interface BehaviorStatus {
|
|
@@ -227,6 +227,48 @@ export interface BehaviorContinuation {
|
|
|
227
227
|
readonly delegatedBehavior: Readonly<BehaviorDelegatedBehaviorResult>;
|
|
228
228
|
}
|
|
229
229
|
|
|
230
|
+
interface BehaviorDecisionActionBase {
|
|
231
|
+
readonly thinking_content?: string;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** One credential-free Action proposed by a Behavior Decision. */
|
|
235
|
+
export type BehaviorDecisionAction =
|
|
236
|
+
| (BehaviorDecisionActionBase & {
|
|
237
|
+
readonly action: 'move';
|
|
238
|
+
readonly target: string;
|
|
239
|
+
readonly target_x?: never;
|
|
240
|
+
readonly target_y?: never;
|
|
241
|
+
readonly stop_on_player?: boolean;
|
|
242
|
+
})
|
|
243
|
+
| (BehaviorDecisionActionBase & {
|
|
244
|
+
readonly action: 'move';
|
|
245
|
+
readonly target?: never;
|
|
246
|
+
readonly target_x: number;
|
|
247
|
+
readonly target_y: number;
|
|
248
|
+
readonly stop_on_player?: boolean;
|
|
249
|
+
})
|
|
250
|
+
| (BehaviorDecisionActionBase & { readonly action: 'kill'; readonly target_seat: number })
|
|
251
|
+
| (BehaviorDecisionActionBase & { readonly action: 'speech'; readonly text: string })
|
|
252
|
+
| (BehaviorDecisionActionBase & { readonly action: 'task'; readonly task_name?: string })
|
|
253
|
+
| (BehaviorDecisionActionBase & { readonly action: 'report' })
|
|
254
|
+
| (BehaviorDecisionActionBase & { readonly action: 'think' });
|
|
255
|
+
|
|
256
|
+
export type BehaviorDecisionFrameStatus = 'pending' | 'completed' | 'not_computed' | 'failed';
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* One activation-local Runtime frame and the Decision result known so far.
|
|
260
|
+
* `actions` is an array for a completed Decision (including an empty array)
|
|
261
|
+
* and null when no Decision result exists.
|
|
262
|
+
*/
|
|
263
|
+
export interface BehaviorDecisionFrame {
|
|
264
|
+
readonly epochId: number;
|
|
265
|
+
readonly tick: number;
|
|
266
|
+
readonly instanceGeneration: number;
|
|
267
|
+
readonly status: BehaviorDecisionFrameStatus;
|
|
268
|
+
readonly actions: readonly Readonly<BehaviorDecisionAction>[] | null;
|
|
269
|
+
readonly reason?: string;
|
|
270
|
+
}
|
|
271
|
+
|
|
230
272
|
/** The input envelope shared by finite and continuous Behaviors. */
|
|
231
273
|
export interface BehaviorInput<
|
|
232
274
|
TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
|
|
@@ -238,6 +280,11 @@ export interface BehaviorInput<
|
|
|
238
280
|
readonly gameState: Readonly<GameState>;
|
|
239
281
|
readonly events: readonly Readonly<GameEvent>[];
|
|
240
282
|
readonly input: Readonly<TInput>;
|
|
283
|
+
/**
|
|
284
|
+
* One immutable snapshot of the current Activation's latest 100 Decision frames.
|
|
285
|
+
* Current Runtime owners always provide it; optional keeps older author test fixtures source-compatible.
|
|
286
|
+
*/
|
|
287
|
+
readonly decisionHistory?: readonly Readonly<BehaviorDecisionFrame>[];
|
|
241
288
|
/** Present for the first committed decision after delegated short work ends. */
|
|
242
289
|
readonly continuation?: Readonly<BehaviorContinuation>;
|
|
243
290
|
}
|
|
@@ -102,6 +102,8 @@ export interface PerceptionBoundary {
|
|
|
102
102
|
readonly mode: 'snapshot' | 'close';
|
|
103
103
|
/** Last visual frame the module may include in this output. */
|
|
104
104
|
readonly through: Readonly<PerceptionFrame> | null;
|
|
105
|
+
/** First frame after a close boundary, when one exists; never part of the closing slice. */
|
|
106
|
+
readonly next?: Readonly<PerceptionFrame> | null;
|
|
105
107
|
}
|
|
106
108
|
|
|
107
109
|
export interface PerceptionEventProposal {
|
|
@@ -125,9 +127,10 @@ export interface ClawclawPerceptionManifest {
|
|
|
125
127
|
/** Optional display metadata for every Event in `produces`. */
|
|
126
128
|
readonly eventMetadata?: Readonly<Record<string, ClawclawPerceptionEventMetadata>>;
|
|
127
129
|
/**
|
|
128
|
-
* Omit for the
|
|
130
|
+
* Omit for the persistent, ordered `update()` contract.
|
|
129
131
|
* `parallel_analysis` batches every enabled parallel module for one frame on
|
|
130
|
-
*
|
|
132
|
+
* reusable analysis Workers, then applies each persistent reducer in order
|
|
133
|
+
* on its reducer Worker lane.
|
|
131
134
|
*/
|
|
132
135
|
readonly execution?: 'parallel_analysis';
|
|
133
136
|
/**
|
|
@@ -142,9 +145,10 @@ export interface ClawclawPerceptionManifest {
|
|
|
142
145
|
/**
|
|
143
146
|
* Canonical authoring surface for one independent perception module.
|
|
144
147
|
*
|
|
145
|
-
* CCL
|
|
146
|
-
* one persistent instance runs `update()`
|
|
147
|
-
*
|
|
148
|
+
* CCL imports this local code inside a memory-bounded Worker lane. Without
|
|
149
|
+
* `parallel_analysis`, one persistent instance runs `update()` in frame order.
|
|
150
|
+
* A slow call can be terminated without blocking the Runtime Owner, but authors
|
|
151
|
+
* should still keep each call short so the module can keep up with live frames.
|
|
148
152
|
*/
|
|
149
153
|
export abstract class ClawclawPerception {
|
|
150
154
|
static readonly manifest?: ClawclawPerceptionManifest;
|
|
@@ -179,8 +183,8 @@ export abstract class ClawclawPerception {
|
|
|
179
183
|
* instance for every module/frame job, so `analyze()` must depend only on its
|
|
180
184
|
* arguments and cannot rely on an earlier instance having run.
|
|
181
185
|
*
|
|
182
|
-
* A separate long-lived reducer instance lives on
|
|
183
|
-
* receives successful analysis values through `commit()` in frame order.
|
|
186
|
+
* A separate long-lived reducer instance lives on a memory-bounded Worker lane
|
|
187
|
+
* and receives successful analysis values through `commit()` in frame order.
|
|
184
188
|
* `commit()` is the only place this module may mutate cross-frame state or emit
|
|
185
189
|
* Events and must remain short. A completed analysis is still only a proposal:
|
|
186
190
|
* when the 1-10 frame window is exhausted, CCL may discard it before `commit()`.
|
|
@@ -190,7 +194,8 @@ export abstract class ClawclawPerception {
|
|
|
190
194
|
*
|
|
191
195
|
* Analysis values cross the Worker boundary and therefore must be supported by
|
|
192
196
|
* `structuredClone`. CCL rejects a value that cannot be cloned. Worker Threads
|
|
193
|
-
*
|
|
197
|
+
* isolate failures and bound V8 old-generation memory, but are not an
|
|
198
|
+
* operating-system security sandbox; load only trusted code.
|
|
194
199
|
*/
|
|
195
200
|
export abstract class ClawclawParallelPerception<TAnalysis = unknown>
|
|
196
201
|
extends ClawclawPerception {
|