@myclaw163/clawclaw-cli 0.8.19 → 0.8.21
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/configuration.md +71 -2
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +3 -1
- package/skills/clawclaw/references/COMMANDS.md +2 -0
- package/src/commands/behavior.ts +1 -0
- package/src/commands/capability.ts +1 -0
- package/src/commands/data.ts +1 -0
- package/src/commands/load.ts +31 -2
- package/src/lib/agent-workspace-client.ts +1 -0
- package/src/lib/agent-workspace-runtime.ts +6 -0
- package/src/lib/agent-workspace-sync.ts +117 -6
- package/src/lib/capability-cloud-refresh.ts +7 -0
- package/src/lib/capability-cloud-sync.ts +11 -3
- package/src/lib/capability-workspace.ts +3 -0
- package/src/lib/diagnostics-config.ts +26 -1
- package/src/lib/hub-client.ts +6 -0
- package/src/lib/persona.ts +2 -0
- package/src/runtime/clawclaw/owner.ts +2 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +21 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +8 -1
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +19 -1
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +36 -0
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +13 -0
- package/src/runtime/clawclaw/runtime-data-export.ts +9 -0
- package/src/runtime/clawclaw/runtime.ts +8 -0
- package/src/runtime/framework/events/memory-event-repository.ts +24 -1
- package/src/runtime/framework/events/runtime-resume.ts +20 -0
- package/src/runtime/framework/events/sqlite-event-repository.ts +32 -8
- package/src/runtime/framework/participation-manager.ts +10 -1
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +20 -1
- package/src/runtime/framework/persistence/memory-first-persistence.ts +116 -13
- package/src/runtime/framework/plugins/runtime-input-journal.ts +13 -8
- package/src/runtime/framework/runtime.ts +19 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +11 -8
- package/src/runtime/observability/detail-capture.ts +123 -0
- package/src/runtime/observability/factory.ts +13 -0
- package/src/runtime/observability/recorder.ts +34 -5
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'crypto';
|
|
2
|
+
import { statSync } from 'fs';
|
|
3
|
+
import { getHeapStatistics } from 'v8';
|
|
4
|
+
import { canReuseParticipationSegment } from '../participation-manager.js';
|
|
2
5
|
import { createRequire } from 'module';
|
|
3
6
|
import { pathToFileURL } from 'url';
|
|
4
7
|
import { Worker } from 'worker_threads';
|
|
@@ -13,6 +16,7 @@ import type {
|
|
|
13
16
|
} from '../mailbox/types.js';
|
|
14
17
|
import { MemoryEventRepository } from '../events/memory-event-repository.js';
|
|
15
18
|
import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
|
|
19
|
+
import { canResumeRuntimeScope, type RuntimeResumeSelection } from '../events/runtime-resume.js';
|
|
16
20
|
import type { EventRepository } from '../events/event-repository.js';
|
|
17
21
|
import type {
|
|
18
22
|
AcquireLeaseRequest,
|
|
@@ -58,6 +62,8 @@ export interface MemoryFirstPersistenceOptions {
|
|
|
58
62
|
maxPendingOperations?: number;
|
|
59
63
|
batchSize?: number;
|
|
60
64
|
flushIntervalMs?: number;
|
|
65
|
+
recovery?: RuntimeResumeSelection & { account: EventAccountScope };
|
|
66
|
+
onDiagnostic?: (name: string, attributes: Readonly<Record<string, unknown>>) => void;
|
|
61
67
|
onDegraded?: (error: Error, health: AsyncPersistenceHealth) => void;
|
|
62
68
|
}
|
|
63
69
|
|
|
@@ -69,6 +75,7 @@ interface ResolvedMemoryFirstPersistenceOptions {
|
|
|
69
75
|
batchSize: number;
|
|
70
76
|
flushIntervalMs: number;
|
|
71
77
|
onDegraded?: MemoryFirstPersistenceOptions['onDegraded'];
|
|
78
|
+
onDiagnostic?: MemoryFirstPersistenceOptions['onDiagnostic'];
|
|
72
79
|
}
|
|
73
80
|
|
|
74
81
|
export interface AsyncPersistenceHealth {
|
|
@@ -77,6 +84,21 @@ export interface AsyncPersistenceHealth {
|
|
|
77
84
|
droppedOperations: number;
|
|
78
85
|
degraded: boolean;
|
|
79
86
|
error?: string;
|
|
87
|
+
workerMemory?: Readonly<Record<string, number>>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function memorySample(): Readonly<Record<string, number>> {
|
|
91
|
+
const memory = process.memoryUsage();
|
|
92
|
+
return {
|
|
93
|
+
sampled_at_ms: Date.now(), rss_bytes: memory.rss,
|
|
94
|
+
heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
|
|
95
|
+
external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
|
|
96
|
+
heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function databaseBytes(path: string): number {
|
|
101
|
+
try { return statSync(path).size; } catch { return 0; }
|
|
80
102
|
}
|
|
81
103
|
|
|
82
104
|
class AsyncSqliteMirror {
|
|
@@ -92,6 +114,7 @@ class AsyncSqliteMirror {
|
|
|
92
114
|
private degradedError?: Error;
|
|
93
115
|
private closing?: Promise<void>;
|
|
94
116
|
private references = 3;
|
|
117
|
+
private workerMemory?: Readonly<Record<string, number>>;
|
|
95
118
|
|
|
96
119
|
constructor(private readonly options: ResolvedMemoryFirstPersistenceOptions) {
|
|
97
120
|
const workerUrl = new URL('./async-sqlite-persistence-worker.ts', import.meta.url).href;
|
|
@@ -109,9 +132,15 @@ class AsyncSqliteMirror {
|
|
|
109
132
|
eventLedgerPath: options.eventLedgerPath,
|
|
110
133
|
stateHistoryPath: options.stateHistoryPath,
|
|
111
134
|
inputJournalPath: options.inputJournalPath,
|
|
135
|
+
diagnostics: !!options.onDiagnostic,
|
|
112
136
|
},
|
|
113
137
|
});
|
|
114
|
-
this.worker.on('message', (message: { type: string; id: number; error?: string }) => {
|
|
138
|
+
this.worker.on('message', (message: { type: string; id: number; error?: string; memory?: Readonly<Record<string, number>> }) => {
|
|
139
|
+
if (message.type === 'diagnostics') {
|
|
140
|
+
this.workerMemory = message.memory;
|
|
141
|
+
try { this.options.onDiagnostic?.('runtime.persistence.worker_memory', { worker_memory: message.memory }); } catch { /* observational */ }
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
115
144
|
if (message.type === 'ack') {
|
|
116
145
|
this.acknowledgedOperations += this.batchSizes.get(message.id) ?? 0;
|
|
117
146
|
this.batchSizes.delete(message.id);
|
|
@@ -155,6 +184,7 @@ class AsyncSqliteMirror {
|
|
|
155
184
|
droppedOperations: this.droppedOperations,
|
|
156
185
|
degraded: !!this.degradedError,
|
|
157
186
|
...(this.degradedError ? { error: this.degradedError.message } : {}),
|
|
187
|
+
...(this.workerMemory ? { workerMemory: this.workerMemory } : {}),
|
|
158
188
|
};
|
|
159
189
|
}
|
|
160
190
|
|
|
@@ -231,7 +261,11 @@ abstract class MirroredStore {
|
|
|
231
261
|
}
|
|
232
262
|
|
|
233
263
|
class MemoryFirstEventRepository extends MirroredStore implements EventRepository, MailboxRepository {
|
|
234
|
-
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository
|
|
264
|
+
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository,
|
|
265
|
+
private readonly closeArchive: () => void) { super(mirror); }
|
|
266
|
+
override async close(): Promise<void> {
|
|
267
|
+
try { await super.close(); } finally { this.closeArchive(); }
|
|
268
|
+
}
|
|
235
269
|
diagnosticCounts() { return this.memory.diagnosticCounts(); }
|
|
236
270
|
saveSession(value: PlaySessionRecord): void { this.memory.saveSession(value); this.persist('events', 'saveSession', value); }
|
|
237
271
|
saveSegment(value: EventSegmentRecord): void { this.memory.saveSegment(value); this.persist('events', 'saveSegment', value); }
|
|
@@ -351,21 +385,79 @@ export function createMemoryFirstPersistence<
|
|
|
351
385
|
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
352
386
|
TEvent extends Record<string, unknown> = Record<string, unknown>,
|
|
353
387
|
>(options: MemoryFirstPersistenceOptions): MemoryFirstPersistence<TPosition, TState, TEvent> {
|
|
388
|
+
const startedAt = performance.now();
|
|
389
|
+
const diagnostic = (stage: string, attributes: Record<string, unknown> = {}): void => {
|
|
390
|
+
if (!options.onDiagnostic) return;
|
|
391
|
+
try {
|
|
392
|
+
options.onDiagnostic('runtime.persistence.hydration', {
|
|
393
|
+
stage, elapsed_ms: performance.now() - startedAt,
|
|
394
|
+
process_memory: memorySample(), ...attributes,
|
|
395
|
+
});
|
|
396
|
+
} catch { /* Diagnostics must not prevent startup. */ }
|
|
397
|
+
};
|
|
398
|
+
diagnostic('started', {
|
|
399
|
+
event_db_bytes: databaseBytes(options.eventLedgerPath),
|
|
400
|
+
event_wal_bytes: databaseBytes(`${options.eventLedgerPath}-wal`),
|
|
401
|
+
history_db_bytes: databaseBytes(options.stateHistoryPath),
|
|
402
|
+
history_wal_bytes: databaseBytes(`${options.stateHistoryPath}-wal`),
|
|
403
|
+
input_db_bytes: databaseBytes(options.inputJournalPath),
|
|
404
|
+
input_wal_bytes: databaseBytes(`${options.inputJournalPath}-wal`),
|
|
405
|
+
});
|
|
354
406
|
const eventSqlite = SqliteEventRepository.open(options.eventLedgerPath);
|
|
355
|
-
if (!eventSqlite.ok)
|
|
356
|
-
|
|
357
|
-
|
|
407
|
+
if (!eventSqlite.ok) {
|
|
408
|
+
diagnostic('failed', { error_name: eventSqlite.unavailable.code });
|
|
409
|
+
throw new Error(`${eventSqlite.unavailable.code}: ${eventSqlite.unavailable.message}`);
|
|
410
|
+
}
|
|
411
|
+
let historySqlite: SqliteStateHistoryRepository<TPosition, TState> | undefined;
|
|
412
|
+
let inputSqlite: SqliteRuntimeInputJournal<TState, TEvent> | undefined;
|
|
358
413
|
let eventMemory: MemoryEventRepository;
|
|
359
414
|
let historyMemory: MemoryStateHistoryRepository<TPosition, TState>;
|
|
360
415
|
let inputMemory: MemoryRuntimeInputJournal<TState, TEvent>;
|
|
416
|
+
let hydrated = false;
|
|
361
417
|
try {
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
418
|
+
historySqlite = new SqliteStateHistoryRepository<TPosition, TState>(options.stateHistoryPath);
|
|
419
|
+
inputSqlite = new SqliteRuntimeInputJournal<TState, TEvent>(options.inputJournalPath);
|
|
420
|
+
const current = eventSqlite.repository.currentScope(options.recovery?.account);
|
|
421
|
+
const restore = options.recovery
|
|
422
|
+
? canResumeRuntimeScope(current, options.recovery)
|
|
423
|
+
: current?.session.status === 'open';
|
|
424
|
+
const sessionId = restore && current ? current.session.sessionId : null;
|
|
425
|
+
const reuseSegment = !options.recovery || (current && current.segment.status === 'open'
|
|
426
|
+
&& canReuseParticipationSegment({ kind: current.segment.kind, identity: current.segment.scopeRef },
|
|
427
|
+
options.recovery.initialSegment.kind, options.recovery.initialSegment.identity));
|
|
428
|
+
const scope: RuntimeScope | null = restore && current && reuseSegment ? {
|
|
429
|
+
adapterId: current.session.adapterId, accountId: current.session.accountId,
|
|
430
|
+
sessionId: current.session.sessionId, segmentId: current.segment.segmentId,
|
|
431
|
+
segmentSeq: current.segment.sequence,
|
|
432
|
+
} : null;
|
|
433
|
+
diagnostic('selected', {
|
|
434
|
+
restore_session: !!sessionId, event_selection: sessionId ? 'current_session' : 'metadata_only',
|
|
435
|
+
state_selection: scope ? 'current_segment' : 'none',
|
|
436
|
+
});
|
|
437
|
+
// Event consumers can still own pending deliveries in earlier segments of
|
|
438
|
+
// the same session. State/plugin recovery, however, reads the active scope only.
|
|
439
|
+
const events = eventSqlite.repository.snapshot(sessionId);
|
|
440
|
+
if (!sessionId && current) {
|
|
441
|
+
// Runtime must still seal the previous durable scope on a fresh start.
|
|
442
|
+
events.sessions = [current.session];
|
|
443
|
+
events.segments = [current.segment];
|
|
444
|
+
}
|
|
445
|
+
const archiveThrough = events.nextCommitSeq - 1;
|
|
446
|
+
eventMemory = new MemoryEventRepository(events, (event) =>
|
|
447
|
+
eventSqlite.repository.archivedEventIdentities(event, sessionId, archiveThrough));
|
|
448
|
+
diagnostic('events_loaded', { loaded_records: eventMemory.diagnosticCounts() });
|
|
449
|
+
historyMemory = new MemoryStateHistoryRepository(historySqlite.snapshot(scope));
|
|
450
|
+
diagnostic('history_loaded', { loaded_records: historyMemory.diagnosticCounts() });
|
|
451
|
+
inputMemory = new MemoryRuntimeInputJournal(inputSqlite.snapshot(scope));
|
|
452
|
+
diagnostic('input_loaded', { loaded_records: inputMemory.diagnosticCounts() });
|
|
453
|
+
hydrated = true;
|
|
454
|
+
} catch (error) {
|
|
455
|
+
diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
|
|
456
|
+
throw error;
|
|
365
457
|
} finally {
|
|
366
|
-
eventSqlite.repository.close();
|
|
367
|
-
historySqlite
|
|
368
|
-
inputSqlite
|
|
458
|
+
if (!hydrated) eventSqlite.repository.close();
|
|
459
|
+
historySqlite?.close();
|
|
460
|
+
inputSqlite?.close();
|
|
369
461
|
}
|
|
370
462
|
const required: ResolvedMemoryFirstPersistenceOptions = {
|
|
371
463
|
...options,
|
|
@@ -373,9 +465,20 @@ export function createMemoryFirstPersistence<
|
|
|
373
465
|
batchSize: options.batchSize ?? 128,
|
|
374
466
|
flushIntervalMs: options.flushIntervalMs ?? 8,
|
|
375
467
|
};
|
|
376
|
-
|
|
468
|
+
let mirror: AsyncSqliteMirror;
|
|
469
|
+
try { mirror = new AsyncSqliteMirror(required); }
|
|
470
|
+
catch (error) {
|
|
471
|
+
eventSqlite.repository.close();
|
|
472
|
+
diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
|
|
473
|
+
throw error;
|
|
474
|
+
}
|
|
475
|
+
diagnostic('completed', {
|
|
476
|
+
loaded_records: {
|
|
477
|
+
events: eventMemory.diagnosticCounts(), history: historyMemory.diagnosticCounts(), input: inputMemory.diagnosticCounts(),
|
|
478
|
+
},
|
|
479
|
+
});
|
|
377
480
|
return {
|
|
378
|
-
eventRepository: new MemoryFirstEventRepository(mirror, eventMemory),
|
|
481
|
+
eventRepository: new MemoryFirstEventRepository(mirror, eventMemory, () => eventSqlite.repository.close()),
|
|
379
482
|
stateHistoryRepository: new MemoryFirstStateHistory(mirror, historyMemory),
|
|
380
483
|
inputJournal: new MemoryFirstInputJournal(mirror, inputMemory),
|
|
381
484
|
health: () => mirror.health(),
|
|
@@ -668,15 +668,18 @@ implements RuntimePersistenceStore<TState, TEvent> {
|
|
|
668
668
|
}
|
|
669
669
|
|
|
670
670
|
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
671
|
-
snapshot(): RuntimeInputJournalSnapshot<TState, TEvent> {
|
|
672
|
-
const
|
|
671
|
+
snapshot(scope?: RuntimeScope | null): RuntimeInputJournalSnapshot<TState, TEvent> {
|
|
672
|
+
const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
|
|
673
|
+
: ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
|
|
674
|
+
const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
|
|
675
|
+
const epochRows = this.db.prepare(`SELECT * FROM runtime_epochs${where} ORDER BY epoch_seq ASC`).all(...params);
|
|
673
676
|
const epochs = epochRows.map((row) => ({
|
|
674
677
|
epoch: this.fromRow(row),
|
|
675
678
|
closed: row.status === 'closed',
|
|
676
679
|
inputEventsCommitted: typeof row.input_events_committed_at === 'string',
|
|
677
680
|
eventWatermark: numberValue(row.event_commit_watermark),
|
|
678
681
|
}));
|
|
679
|
-
const pluginProgress = this.db.prepare(
|
|
682
|
+
const pluginProgress = this.db.prepare(`SELECT * FROM runtime_plugin_progress${where}`).all(...params).map((row) => ({
|
|
680
683
|
scope: {
|
|
681
684
|
adapterId: String(row.adapter_id),
|
|
682
685
|
accountId: String(row.account_id),
|
|
@@ -691,8 +694,9 @@ implements RuntimePersistenceStore<TState, TEvent> {
|
|
|
691
694
|
updatedAt: String(row.updated_at),
|
|
692
695
|
},
|
|
693
696
|
}));
|
|
694
|
-
const pluginRecords = this.db.prepare(
|
|
695
|
-
|
|
697
|
+
const pluginRecords = this.db.prepare(`SELECT * FROM runtime_plugin_outcomes
|
|
698
|
+
WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id`)
|
|
699
|
+
.all(...params).map((row) => ({
|
|
696
700
|
epochSeq: numberValue(row.epoch_seq),
|
|
697
701
|
pluginId: String(row.plugin_id),
|
|
698
702
|
invocationId: String(row.invocation_id),
|
|
@@ -705,8 +709,9 @@ implements RuntimePersistenceStore<TState, TEvent> {
|
|
|
705
709
|
eventCursorAfter: numberValue(row.event_cursor_after),
|
|
706
710
|
recordedAt: String(row.recorded_at),
|
|
707
711
|
}));
|
|
708
|
-
const states = this.db.prepare(
|
|
709
|
-
|
|
712
|
+
const states = this.db.prepare(`SELECT * FROM runtime_plugin_states
|
|
713
|
+
WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id, topic`)
|
|
714
|
+
.all(...params).map((row) => ({
|
|
710
715
|
epochSeq: numberValue(row.epoch_seq),
|
|
711
716
|
pluginId: String(row.plugin_id),
|
|
712
717
|
topic: String(row.topic),
|
|
@@ -717,7 +722,7 @@ implements RuntimePersistenceStore<TState, TEvent> {
|
|
|
717
722
|
pluginProgress,
|
|
718
723
|
pluginRecords,
|
|
719
724
|
states,
|
|
720
|
-
nextEpochSeq: (
|
|
725
|
+
nextEpochSeq: numberValue(this.db.prepare('SELECT MAX(epoch_seq) AS seq FROM runtime_epochs').get()?.seq) + 1,
|
|
721
726
|
};
|
|
722
727
|
}
|
|
723
728
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { canResumeRuntimeScope } from './events/runtime-resume.js';
|
|
2
|
+
import { randomUUID as captureId } from 'node:crypto';
|
|
1
3
|
import {
|
|
2
4
|
ActionRegistry,
|
|
3
5
|
ObservationRegistry,
|
|
@@ -502,13 +504,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
502
504
|
const durableCurrent = this.repository.currentScope(accountScope);
|
|
503
505
|
const resumesBySessionKey = options.resumeKey !== undefined
|
|
504
506
|
&& durableCurrent?.session.resumeKey === options.resumeKey;
|
|
505
|
-
const
|
|
506
|
-
&& durableCurrent?.segment.kind === options.initialSegment.kind
|
|
507
|
-
&& durableCurrent.segment.scopeRef === options.initialSegment.identity;
|
|
508
|
-
const canResume = !!options.resume
|
|
509
|
-
&& !!durableCurrent
|
|
510
|
-
&& durableCurrent.session.status === 'open'
|
|
511
|
-
&& (resumesBySessionKey || resumesByCurrentSegment);
|
|
507
|
+
const canResume = canResumeRuntimeScope(durableCurrent, options);
|
|
512
508
|
if (!canResume && durableCurrent) this.sealDurableScope(durableCurrent);
|
|
513
509
|
|
|
514
510
|
this.participation = new ParticipationManager({
|
|
@@ -626,6 +622,11 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
626
622
|
};
|
|
627
623
|
}
|
|
628
624
|
|
|
625
|
+
runtimePersistenceDiagnostics(): Readonly<Record<string, unknown>> {
|
|
626
|
+
return (this.repository as { persistenceHealth?: () => Readonly<Record<string, unknown>> })
|
|
627
|
+
.persistenceHealth?.() ?? {};
|
|
628
|
+
}
|
|
629
|
+
|
|
629
630
|
runtimePluginDescriptors(): RuntimePluginDescriptor[] {
|
|
630
631
|
return [
|
|
631
632
|
...[...this.sourcePlugins.values()].map(({ plugin }) => ({
|
|
@@ -962,11 +963,19 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
962
963
|
): Promise<ActionResult<R>> {
|
|
963
964
|
const scope = this.assertExpectedScope(expectedScope);
|
|
964
965
|
const startedAt = Date.now();
|
|
966
|
+
const detailId = this.observability?.captureEnabled('actions') ? captureId() : undefined;
|
|
967
|
+
if (detailId) this.observability?.log('debug', 'runtime.detail.actions.requested', {
|
|
968
|
+
request_id: detailId, capability, caller, request: action,
|
|
969
|
+
}, { component: 'runtime.actions', scope });
|
|
965
970
|
try {
|
|
966
971
|
const result = await this.actions.perform<A, R>(capability, action, scope, caller, {
|
|
967
972
|
...admission,
|
|
968
973
|
latestAcceptedState: () => this.latestAcceptedActionState(scope),
|
|
969
974
|
});
|
|
975
|
+
if (detailId) this.observability?.log('debug', 'runtime.detail.actions.receipt', {
|
|
976
|
+
request_id: detailId, capability, caller, action_id: result.actionId, result,
|
|
977
|
+
duration_ms: Date.now() - startedAt,
|
|
978
|
+
}, { component: 'runtime.actions', scope });
|
|
970
979
|
const attributes = {
|
|
971
980
|
capability,
|
|
972
981
|
caller_kind: caller.kind,
|
|
@@ -1026,6 +1035,9 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
1026
1035
|
return result;
|
|
1027
1036
|
} catch (error) {
|
|
1028
1037
|
const summary = summarizeActionError(error);
|
|
1038
|
+
if (detailId) this.observability?.log('debug', 'runtime.detail.actions.failed', {
|
|
1039
|
+
request_id: detailId, capability, caller, error, duration_ms: Date.now() - startedAt,
|
|
1040
|
+
}, { component: 'runtime.actions', scope });
|
|
1029
1041
|
this.observability?.error('runtime.action.failed', {
|
|
1030
1042
|
name: error instanceof Error ? error.name : 'ActionFailure',
|
|
1031
1043
|
...(summary.code ? { code: summary.code } : {}),
|
|
@@ -357,17 +357,20 @@ export class SqliteStateHistoryRepository<
|
|
|
357
357
|
}
|
|
358
358
|
|
|
359
359
|
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
360
|
-
snapshot(): StateHistorySnapshot<TPosition, TState> {
|
|
361
|
-
const
|
|
362
|
-
|
|
363
|
-
const
|
|
364
|
-
|
|
360
|
+
snapshot(scope?: RuntimeScope | null): StateHistorySnapshot<TPosition, TState> {
|
|
361
|
+
const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
|
|
362
|
+
: ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
|
|
363
|
+
const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
|
|
364
|
+
const stateFrames = this.db.prepare(`SELECT * FROM state_frames${where} ORDER BY frame_seq ASC`)
|
|
365
|
+
.all(...params).map((row) => this.stateFrameFromRow(row));
|
|
366
|
+
const records = this.db.prepare(`SELECT * FROM trajectory_records${where} ORDER BY record_seq ASC`)
|
|
367
|
+
.all(...params).map((row) => this.recordFromRow(row));
|
|
365
368
|
return {
|
|
366
|
-
scopes: this.db.prepare(
|
|
369
|
+
scopes: this.db.prepare(`SELECT * FROM history_scopes${where}`).all(...params).map((row) => this.scopeFromRow(row)),
|
|
367
370
|
stateFrames,
|
|
368
371
|
records,
|
|
369
|
-
nextFrameSeq: (
|
|
370
|
-
nextRecordSeq: (
|
|
372
|
+
nextFrameSeq: Number(this.db.prepare('SELECT MAX(frame_seq) AS seq FROM state_frames').get()?.seq ?? 0) + 1,
|
|
373
|
+
nextRecordSeq: Number(this.db.prepare('SELECT MAX(record_seq) AS seq FROM trajectory_records').get()?.seq ?? 0) + 1,
|
|
371
374
|
};
|
|
372
375
|
}
|
|
373
376
|
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { readDiagnosticsConfig, type DiagnosticsConfig } from '../../lib/diagnostics-config.js';
|
|
3
|
+
|
|
4
|
+
export type CaptureCategory = 'actions' | 'behavior_io' | 'perception_io';
|
|
5
|
+
export interface DetailCaptureConfig {
|
|
6
|
+
actions: boolean;
|
|
7
|
+
behavior_io: boolean;
|
|
8
|
+
perception_io: boolean;
|
|
9
|
+
max_record_bytes: number;
|
|
10
|
+
}
|
|
11
|
+
export function resolveDetailCapture(config?: DiagnosticsConfig, env = process.env): DetailCaptureConfig {
|
|
12
|
+
let selected = config;
|
|
13
|
+
if (!selected) { try { selected = readDiagnosticsConfig(); } catch { /* fail closed */ } }
|
|
14
|
+
const requestedLevel = env.CLAWCLAW_OBSERVABILITY_LEVEL?.trim().toLowerCase();
|
|
15
|
+
const full = (requestedLevel && ['errors', 'telemetry', 'full'].includes(requestedLevel)
|
|
16
|
+
? requestedLevel : selected?.level) === 'full';
|
|
17
|
+
const enabled = (key: CaptureCategory): boolean => {
|
|
18
|
+
const value = env[`CLAWCLAW_CAPTURE_${key.toUpperCase()}`];
|
|
19
|
+
return value === undefined ? selected?.capture?.[key] ?? full : value.trim() === '1';
|
|
20
|
+
};
|
|
21
|
+
return { actions: enabled('actions'), behavior_io: enabled('behavior_io'), perception_io: enabled('perception_io'),
|
|
22
|
+
max_record_bytes: selected?.capture?.max_record_bytes ?? 256 * 1024 };
|
|
23
|
+
}
|
|
24
|
+
export function detailCategory(name: string): CaptureCategory | undefined {
|
|
25
|
+
return /^runtime\.detail\.(actions|behavior_io|perception_io)\./.exec(name)?.[1] as CaptureCategory | undefined;
|
|
26
|
+
}
|
|
27
|
+
type Diagnostic = (name: string, attributes: Readonly<Record<string, unknown>>, severity?: 'debug' | 'info' | 'warn' | 'error') => void;
|
|
28
|
+
|
|
29
|
+
/** Opt-in, lazy, Owner-side observer. No module API, gameplay Event or cross-Worker payload is added. */
|
|
30
|
+
export class DetailCapture {
|
|
31
|
+
readonly enabled: boolean;
|
|
32
|
+
constructor(readonly category: CaptureCategory, private readonly diagnostic?: Diagnostic,
|
|
33
|
+
config?: DetailCaptureConfig) { this.enabled = !!diagnostic && (config ?? resolveDetailCapture())[category]; }
|
|
34
|
+
emit(phase: string, attributes: () => Record<string, unknown>): void {
|
|
35
|
+
if (!this.enabled) return;
|
|
36
|
+
try { this.diagnostic?.(`runtime.detail.${this.category}.${phase}`, attributes(), 'debug'); } catch { /* observational */ }
|
|
37
|
+
}
|
|
38
|
+
run<T>(operation: string, metadata: Record<string, unknown>, input: unknown, invoke: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
39
|
+
if (!this.enabled) return invoke();
|
|
40
|
+
const invocation_id = randomUUID(), started = performance.now();
|
|
41
|
+
const base = { ...metadata, invocation_id, operation };
|
|
42
|
+
this.emit('input', () => ({ ...base, input, stage: 'requested' }));
|
|
43
|
+
let aborted = false;
|
|
44
|
+
const onAbort = () => {
|
|
45
|
+
aborted = true;
|
|
46
|
+
this.emit('cancelled', () => ({ ...base, duration_ms: performance.now() - started,
|
|
47
|
+
error: signal?.reason instanceof Error ? signal.reason.message : 'aborted' }));
|
|
48
|
+
};
|
|
49
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
50
|
+
return (async () => {
|
|
51
|
+
try {
|
|
52
|
+
const output = await invoke();
|
|
53
|
+
this.emit('output', () => ({ ...base, output: output ?? null,
|
|
54
|
+
stage: aborted ? 'late_result' : 'computed_not_yet_runtime_committed', duration_ms: performance.now() - started }));
|
|
55
|
+
return output;
|
|
56
|
+
} catch (error) {
|
|
57
|
+
this.emit('failed', () => ({ ...base, error: error instanceof Error ? { name: error.name, message: error.message } : String(error),
|
|
58
|
+
duration_ms: performance.now() - started }));
|
|
59
|
+
throw error;
|
|
60
|
+
} finally { signal?.removeEventListener('abort', onAbort); }
|
|
61
|
+
})();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Bounded JSON snapshot: preserves gameplay payloads and IDs, always removes credentials. */
|
|
66
|
+
export function captureSnapshot(value: unknown, maxBytes: number): { value: unknown; truncated: boolean } {
|
|
67
|
+
let remaining = maxBytes, nodes = 0, truncated = false;
|
|
68
|
+
const seen = new WeakSet<object>();
|
|
69
|
+
const marker = (): string => { truncated = true; return '[TRUNCATED]'; };
|
|
70
|
+
const secret = /(?:^|_)(?:api_key|claw_key|token|access_token|refresh_token|authorization|cookie|password|passwd|secret|private_key|credential|env|environment)(?:_value)?$/i;
|
|
71
|
+
const visit = (item: unknown, key = '', depth = 0): unknown => {
|
|
72
|
+
if (++nodes > 20000 || remaining <= 0 || depth > 32) return marker();
|
|
73
|
+
remaining -= Buffer.byteLength(key) * 6 + 16;
|
|
74
|
+
if (secret.test(key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').replace(/[^A-Za-z0-9]+/g, '_'))) return '[REDACTED]';
|
|
75
|
+
if (item === null || item === undefined) return item ?? null;
|
|
76
|
+
if (typeof item === 'boolean' || typeof item === 'number') return item;
|
|
77
|
+
if (typeof item === 'string') {
|
|
78
|
+
const limit = Math.max(0, Math.floor(remaining / 6));
|
|
79
|
+
const cut = item.length > limit;
|
|
80
|
+
const text = item.slice(0, limit)
|
|
81
|
+
.replace(/\bBearer\s+[^\s"']+/gi, 'Bearer [REDACTED]')
|
|
82
|
+
.replace(/\b(?:sk-|claw_|ghp_|github_pat_)[A-Za-z0-9_-]+/g, '[REDACTED]')
|
|
83
|
+
.replace(/([?&](?:token|key|code|api_key|access_token)=)[^&\s"']+/gi, '$1[REDACTED]');
|
|
84
|
+
remaining -= text.length * 6;
|
|
85
|
+
return cut ? text + marker() : text;
|
|
86
|
+
}
|
|
87
|
+
if (typeof item !== 'object') return `[${typeof item}_OMITTED]`;
|
|
88
|
+
if (item instanceof Error) {
|
|
89
|
+
const field = (name: string, fallback: string) => {
|
|
90
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, name);
|
|
91
|
+
return descriptor ? 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]' : fallback;
|
|
92
|
+
};
|
|
93
|
+
return visit({ name: field('name', 'Error'), message: field('message', '') }, key, depth + 1);
|
|
94
|
+
}
|
|
95
|
+
if (seen.has(item)) return '[CIRCULAR]';
|
|
96
|
+
if (ArrayBuffer.isView(item) || item instanceof ArrayBuffer) return '[BINARY_OMITTED]';
|
|
97
|
+
seen.add(item);
|
|
98
|
+
const out: any = Array.isArray(item) ? [] : {};
|
|
99
|
+
if (Array.isArray(item)) {
|
|
100
|
+
// JSON serializes holes as nulls. Charge them too; copying an isolated
|
|
101
|
+
// high index would create an enormous sparse output despite the budget.
|
|
102
|
+
for (let index = 0; index < item.length; index += 1) {
|
|
103
|
+
if (remaining <= 0 || nodes > 20000) { out.push(marker()); break; }
|
|
104
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, String(index));
|
|
105
|
+
out.push(visit(descriptor ? 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]' : null, String(index), depth + 1));
|
|
106
|
+
}
|
|
107
|
+
seen.delete(item);
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
// Do not enumerate getters or run user-defined toJSON methods while logging.
|
|
111
|
+
for (const name in item) {
|
|
112
|
+
if (!Object.prototype.hasOwnProperty.call(item, name)) continue;
|
|
113
|
+
if (name.length > 1024) { if (Array.isArray(out)) out.push(marker()); else out.__capture_truncated = marker(); break; }
|
|
114
|
+
if (remaining <= 0 || nodes > 20000) { if (Array.isArray(out)) out.push(marker()); else out.__capture_truncated = marker(); break; }
|
|
115
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, name);
|
|
116
|
+
const next = visit(descriptor && 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]', name, depth + 1);
|
|
117
|
+
Object.defineProperty(out, name, { value: next, enumerable: true, configurable: true, writable: true });
|
|
118
|
+
}
|
|
119
|
+
seen.delete(item);
|
|
120
|
+
return out;
|
|
121
|
+
};
|
|
122
|
+
return { value: visit(value), truncated };
|
|
123
|
+
}
|
|
@@ -10,6 +10,7 @@ import { getProfileRuntimeStateDir, getRuntimeAccountId } from '../../lib/init-c
|
|
|
10
10
|
import { ObservabilityRedactor } from './redaction.js';
|
|
11
11
|
import { BufferedObservabilityReporter } from './reporter.js';
|
|
12
12
|
import { TelemetryRecorder } from './recorder.js';
|
|
13
|
+
import { resolveDetailCapture } from './detail-capture.js';
|
|
13
14
|
import { JsonlObservabilitySink } from './sinks.js';
|
|
14
15
|
import type { RecordTelemetryInput } from './types.js';
|
|
15
16
|
|
|
@@ -159,6 +160,9 @@ export function createOwnerTelemetryRecorder(
|
|
|
159
160
|
config = defaultDiagnosticsConfig();
|
|
160
161
|
}
|
|
161
162
|
const level = observabilityLevel(config, env);
|
|
163
|
+
const capture = resolveDetailCapture(config, env);
|
|
164
|
+
// A two-record batch must fit the configured file rotation budget.
|
|
165
|
+
capture.max_record_bytes = Math.min(capture.max_record_bytes, Math.floor(observabilityRetention(env).maxFileBytes / 2));
|
|
162
166
|
const runtimeAccountId = getRuntimeAccountId(profile);
|
|
163
167
|
const redactor = new ObservabilityRedactor({ hashSalt: runtimeAccountId });
|
|
164
168
|
const sink = new JsonlObservabilitySink(
|
|
@@ -168,12 +172,21 @@ export function createOwnerTelemetryRecorder(
|
|
|
168
172
|
const reporter = new BufferedObservabilityReporter(sink, {
|
|
169
173
|
flushIntervalMs: options.flushIntervalMs,
|
|
170
174
|
});
|
|
175
|
+
const detailReporter = capture.actions || capture.behavior_io || capture.perception_io
|
|
176
|
+
? new BufferedObservabilityReporter(new JsonlObservabilitySink(
|
|
177
|
+
join(options.runtimeStateDir ?? getProfileRuntimeStateDir(profile), 'observability', 'owner-detail.jsonl'),
|
|
178
|
+
observabilityRetention(env),
|
|
179
|
+
), { maxQueueRecords: Math.max(2, Math.floor(8 * 1024 * 1024 / capture.max_record_bytes)),
|
|
180
|
+
batchSize: 2, flushIntervalMs: 100 })
|
|
181
|
+
: undefined;
|
|
171
182
|
const recorder = new TelemetryRecorder({
|
|
172
183
|
enabled: true,
|
|
173
184
|
process: { role: 'owner', pid: process.pid },
|
|
174
185
|
reporter,
|
|
175
186
|
redactor,
|
|
176
187
|
sampler: (input) => observabilityInputEnabled(level, input),
|
|
188
|
+
capture,
|
|
189
|
+
detailReporter,
|
|
177
190
|
});
|
|
178
191
|
if (configError) {
|
|
179
192
|
recorder.error('observability.config.invalid', configError, {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'crypto';
|
|
2
2
|
import { ObservabilityRedactor } from './redaction.js';
|
|
3
3
|
import { NoopObservabilityReporter } from './reporter.js';
|
|
4
|
+
import { captureSnapshot, detailCategory, type DetailCaptureConfig } from './detail-capture.js';
|
|
4
5
|
import {
|
|
5
6
|
OBSERVABILITY_SCHEMA,
|
|
6
7
|
type ObservabilityCorrelation,
|
|
@@ -22,6 +23,8 @@ export interface TelemetryRecorderOptions {
|
|
|
22
23
|
idFactory?: () => string;
|
|
23
24
|
scopeProvider?: () => ObservabilityScope | undefined;
|
|
24
25
|
sampler?: (input: Readonly<RecordTelemetryInput>) => boolean;
|
|
26
|
+
capture?: DetailCaptureConfig;
|
|
27
|
+
detailReporter?: ObservabilityReporter;
|
|
25
28
|
}
|
|
26
29
|
|
|
27
30
|
function defaultSeverity(kind: RecordTelemetryInput['kind']): ObservabilitySeverity {
|
|
@@ -73,6 +76,9 @@ export class TelemetryRecorder {
|
|
|
73
76
|
private readonly idFactory: () => string;
|
|
74
77
|
private readonly scopeProvider?: () => ObservabilityScope | undefined;
|
|
75
78
|
private readonly sampler: (input: Readonly<RecordTelemetryInput>) => boolean;
|
|
79
|
+
private readonly capture?: DetailCaptureConfig;
|
|
80
|
+
private readonly detailReporter?: ObservabilityReporter;
|
|
81
|
+
private lastDetailScope?: ObservabilityScope;
|
|
76
82
|
|
|
77
83
|
constructor(options: TelemetryRecorderOptions) {
|
|
78
84
|
this.process = { ...options.process };
|
|
@@ -83,15 +89,22 @@ export class TelemetryRecorder {
|
|
|
83
89
|
this.idFactory = options.idFactory ?? (() => `obs_${randomUUID()}`);
|
|
84
90
|
this.scopeProvider = options.scopeProvider;
|
|
85
91
|
this.sampler = options.sampler ?? (() => true);
|
|
92
|
+
this.capture = options.capture;
|
|
93
|
+
this.detailReporter = options.detailReporter;
|
|
86
94
|
}
|
|
87
95
|
|
|
88
96
|
record(input: RecordTelemetryInput): string | null {
|
|
89
97
|
if (!this.enabled) return null;
|
|
90
98
|
try {
|
|
91
|
-
|
|
99
|
+
const category = detailCategory(input.name);
|
|
100
|
+
if (category ? !this.capture?.[category] : !this.sampler(input)) return null;
|
|
92
101
|
const recordId = this.idFactory();
|
|
93
102
|
const scope = normalizedScope(input.scope ?? this.scopeProvider?.());
|
|
94
|
-
|
|
103
|
+
if (category && scope) this.lastDetailScope = scope;
|
|
104
|
+
const captured = category ? captureSnapshot(input.attributes ?? {}, this.capture!.max_record_bytes - 2048) : undefined;
|
|
105
|
+
const attributes = captured
|
|
106
|
+
? { ...(captured.value as Record<string, unknown>), capture_truncated: captured.truncated }
|
|
107
|
+
: this.redactor.redactRecord(input.attributes ?? {});
|
|
95
108
|
const correlation = input.correlation
|
|
96
109
|
? this.redactor.redactRecord(input.correlation as Record<string, unknown>) as ObservabilityCorrelation
|
|
97
110
|
: undefined;
|
|
@@ -117,7 +130,7 @@ export class TelemetryRecorder {
|
|
|
117
130
|
...(metric ? { metric } : {}),
|
|
118
131
|
...(redactedError ? { error: redactedError } : {}),
|
|
119
132
|
};
|
|
120
|
-
return this.reporter.enqueue(record) ? recordId : null;
|
|
133
|
+
return (category ? this.detailReporter ?? this.reporter : this.reporter).enqueue(record) ? recordId : null;
|
|
121
134
|
} catch {
|
|
122
135
|
return null;
|
|
123
136
|
}
|
|
@@ -162,8 +175,20 @@ export class TelemetryRecorder {
|
|
|
162
175
|
return new StructuredLogger(this, component, base);
|
|
163
176
|
}
|
|
164
177
|
|
|
165
|
-
|
|
166
|
-
|
|
178
|
+
private captureSummary(): void {
|
|
179
|
+
if (!this.detailReporter) return;
|
|
180
|
+
const category = (['actions', 'behavior_io', 'perception_io'] as const).find(key => this.capture?.[key]);
|
|
181
|
+
if (category) this.log('debug', `runtime.detail.${category}.summary`, { reporter: this.detailReporter.stats() },
|
|
182
|
+
{ component: 'runtime.capture', scope: this.lastDetailScope });
|
|
183
|
+
}
|
|
184
|
+
async flush(): Promise<void> {
|
|
185
|
+
await Promise.all([this.reporter.flush(), this.detailReporter?.flush()]);
|
|
186
|
+
this.captureSummary();
|
|
187
|
+
await this.detailReporter?.flush();
|
|
188
|
+
}
|
|
189
|
+
async close(): Promise<void> {
|
|
190
|
+
try { await this.flush(); } finally { await Promise.all([this.reporter.close(), this.detailReporter?.close()]); }
|
|
191
|
+
}
|
|
167
192
|
flushWithin(timeoutMs: number): Promise<boolean> {
|
|
168
193
|
return settleWithin(this.flush(), timeoutMs);
|
|
169
194
|
}
|
|
@@ -171,6 +196,10 @@ export class TelemetryRecorder {
|
|
|
171
196
|
return settleWithin(this.close(), timeoutMs);
|
|
172
197
|
}
|
|
173
198
|
stats() { return this.reporter.stats(); }
|
|
199
|
+
detailStats() { return this.detailReporter?.stats(); }
|
|
200
|
+
captureEnabled(category: keyof Pick<DetailCaptureConfig, 'actions' | 'behavior_io' | 'perception_io'>): boolean {
|
|
201
|
+
return this.enabled && this.capture?.[category] === true;
|
|
202
|
+
}
|
|
174
203
|
}
|
|
175
204
|
|
|
176
205
|
/** Stop awaiting diagnostics after a bounded window; gameplay owns hard exit/cancellation. */
|