@myclaw163/clawclaw-cli 0.8.20 → 0.8.22
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 +57 -2
- package/docs/custom-modules/api-reference.md +2 -0
- package/docs/custom-modules/perception.md +25 -0
- package/docs/runtime/official-perception-modules.md +23 -0
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +3 -1
- package/skills/clawclaw/references/COMMANDS.md +2 -0
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +2 -0
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +25 -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/agent-event-policy.ts +7 -0
- package/src/runtime/clawclaw/owner.ts +17 -10
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +21 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +26 -12
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +19 -1
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +2 -0
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +10 -1
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +17 -1
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +5 -2
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +46 -15
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +36 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +2 -1
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +13 -0
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +4 -0
- package/src/runtime/clawclaw/runtime-data-export.ts +9 -0
- package/src/runtime/framework/events/event-ingress.ts +1 -0
- package/src/runtime/framework/events/memory-event-repository.ts +5 -4
- package/src/runtime/framework/events/sqlite-event-repository.ts +36 -9
- package/src/runtime/framework/events/types.ts +4 -0
- package/src/runtime/framework/mailbox/types.ts +4 -0
- package/src/runtime/framework/plugins/contracts.ts +2 -0
- package/src/runtime/framework/runtime.ts +13 -0
- package/src/runtime/mailbox-host-relay.ts +13 -12
- 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
- package/src/sdk/perception-plugin/index.ts +4 -0
|
@@ -642,6 +642,7 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
642
642
|
segmentId: request.segmentId,
|
|
643
643
|
eventId: request.eventId,
|
|
644
644
|
eventCommitSeq: request.eventCommitSeq,
|
|
645
|
+
...(request.deliveryOrder === undefined ? {} : { deliveryOrder: request.deliveryOrder }),
|
|
645
646
|
mode: request.mode,
|
|
646
647
|
coalesceKey: request.coalesceKey,
|
|
647
648
|
payload: cloneRecord(request.payload),
|
|
@@ -688,9 +689,9 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
688
689
|
rows.sort((a, b) => {
|
|
689
690
|
const direction = filter.order === 'desc' ? -1 : 1;
|
|
690
691
|
return direction * (
|
|
691
|
-
a.eventCommitSeq === b.eventCommitSeq
|
|
692
|
+
(a.deliveryOrder ?? a.eventCommitSeq) === (b.deliveryOrder ?? b.eventCommitSeq)
|
|
692
693
|
? a.itemId.localeCompare(b.itemId)
|
|
693
|
-
: a.eventCommitSeq - b.eventCommitSeq
|
|
694
|
+
: (a.deliveryOrder ?? a.eventCommitSeq) - (b.deliveryOrder ?? b.eventCommitSeq)
|
|
694
695
|
);
|
|
695
696
|
});
|
|
696
697
|
const limit = filter.limit === undefined
|
|
@@ -713,9 +714,9 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
713
714
|
&& (item.state === 'pending' || item.state === 'claimed')
|
|
714
715
|
))
|
|
715
716
|
.sort((a, b) => (
|
|
716
|
-
a.eventCommitSeq === b.eventCommitSeq
|
|
717
|
+
(a.deliveryOrder ?? a.eventCommitSeq) === (b.deliveryOrder ?? b.eventCommitSeq)
|
|
717
718
|
? a.itemId.localeCompare(b.itemId)
|
|
718
|
-
: a.eventCommitSeq - b.eventCommitSeq
|
|
719
|
+
: (a.deliveryOrder ?? a.eventCommitSeq) - (b.deliveryOrder ?? b.eventCommitSeq)
|
|
719
720
|
));
|
|
720
721
|
const activeRows: MailboxItem[] = [];
|
|
721
722
|
for (const item of rows) {
|
|
@@ -158,6 +158,7 @@ function segmentFromRow(row: Record<string, unknown>): EventSegmentRecord {
|
|
|
158
158
|
function eventFromRow(row: Record<string, unknown>): CanonicalEvent {
|
|
159
159
|
const payload = JSON.parse(String(row.payload_json)) as Record<string, unknown>;
|
|
160
160
|
return {
|
|
161
|
+
...(row.wake_agent === null || row.wake_agent === undefined ? {} : { wakeAgent: numberValue(row.wake_agent) !== 0 }),
|
|
161
162
|
commitSeq: numberValue(row.commit_seq),
|
|
162
163
|
...(row.epoch_seq === null || row.epoch_seq === undefined
|
|
163
164
|
? {}
|
|
@@ -223,6 +224,7 @@ function mailboxItemFromRow<T = unknown>(row: Record<string, unknown>): MailboxI
|
|
|
223
224
|
segmentId: String(row.segment_id),
|
|
224
225
|
eventId: String(row.event_id),
|
|
225
226
|
eventCommitSeq: numberValue(row.event_commit_seq),
|
|
227
|
+
...(row.delivery_order == null ? {} : { deliveryOrder: numberValue(row.delivery_order) }),
|
|
226
228
|
// New runtime code only creates short notifications. The SQLite schema
|
|
227
229
|
// still accepts historical full rows so existing ledgers open in place.
|
|
228
230
|
mode: 'short',
|
|
@@ -572,8 +574,8 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
572
574
|
event_id, epoch_seq, session_id, segment_id, type, producer,
|
|
573
575
|
producer_plugin_id, producer_output_index, delivery_class,
|
|
574
576
|
occurred_at, received_at, payload_json, source_id, source_event_id,
|
|
575
|
-
source_sequence, connection_id, replayed
|
|
576
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
577
|
+
source_sequence, connection_id, replayed, wake_agent
|
|
578
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
577
579
|
`).run(
|
|
578
580
|
request.event.eventId,
|
|
579
581
|
request.event.epochSeq ?? null,
|
|
@@ -592,6 +594,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
592
594
|
request.event.sourceSequence ?? null,
|
|
593
595
|
request.event.connectionId ?? null,
|
|
594
596
|
booleanInt(request.event.replayed),
|
|
597
|
+
request.event.wakeAgent === undefined ? null : booleanInt(request.event.wakeAgent),
|
|
595
598
|
);
|
|
596
599
|
const event: CanonicalEvent = {
|
|
597
600
|
...cloneRecord(request.event),
|
|
@@ -948,8 +951,8 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
948
951
|
INSERT INTO mailbox_items(
|
|
949
952
|
item_id, schema_version, formatter_version, consumer_id, session_id,
|
|
950
953
|
segment_id, event_id, event_commit_seq, mode, coalesce_key,
|
|
951
|
-
payload_json, state, attempt_count, available_at, created_at, updated_at
|
|
952
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
|
|
954
|
+
payload_json, state, attempt_count, available_at, created_at, updated_at, delivery_order
|
|
955
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)
|
|
953
956
|
`).run(
|
|
954
957
|
request.itemId,
|
|
955
958
|
request.schemaVersion ?? 1,
|
|
@@ -966,6 +969,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
966
969
|
request.availableAtMs ?? 0,
|
|
967
970
|
createdAt,
|
|
968
971
|
createdAt,
|
|
972
|
+
request.deliveryOrder ?? null,
|
|
969
973
|
);
|
|
970
974
|
const inserted = this.db.prepare('SELECT * FROM mailbox_items WHERE item_id = ?')
|
|
971
975
|
.get(request.itemId);
|
|
@@ -1012,7 +1016,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1012
1016
|
return this.db.prepare(`
|
|
1013
1017
|
SELECT * FROM mailbox_items
|
|
1014
1018
|
WHERE ${clauses.join(' AND ')}
|
|
1015
|
-
ORDER BY event_commit_seq ${order}, item_id ${order}${limit}
|
|
1019
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ${order}, item_id ${order}${limit}
|
|
1016
1020
|
`).all(...params).map((row) => mailboxItemFromRow<T>(row));
|
|
1017
1021
|
}
|
|
1018
1022
|
|
|
@@ -1032,7 +1036,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1032
1036
|
AND m.segment_id = ?
|
|
1033
1037
|
AND m.mode = ?
|
|
1034
1038
|
AND m.state IN ('pending', 'claimed')
|
|
1035
|
-
ORDER BY m.event_commit_seq ASC, m.item_id ASC
|
|
1039
|
+
ORDER BY COALESCE(m.delivery_order, m.event_commit_seq) ASC, m.item_id ASC
|
|
1036
1040
|
`).all(request.consumerId, request.sessionId, request.segmentId, request.mode);
|
|
1037
1041
|
|
|
1038
1042
|
const activeRows: Array<Record<string, unknown>> = [];
|
|
@@ -1098,7 +1102,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1098
1102
|
const claimedRows = this.db.prepare(`
|
|
1099
1103
|
SELECT * FROM mailbox_items
|
|
1100
1104
|
WHERE item_id IN (${placeholders(itemIds.length)})
|
|
1101
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1105
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1102
1106
|
`).all(...itemIds);
|
|
1103
1107
|
return {
|
|
1104
1108
|
ownerId: request.ownerId,
|
|
@@ -1115,7 +1119,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1115
1119
|
const rows = this.db.prepare(`
|
|
1116
1120
|
SELECT * FROM mailbox_items
|
|
1117
1121
|
WHERE claim_owner = ? AND claim_token = ?
|
|
1118
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1122
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1119
1123
|
`).all(request.ownerId, request.claimToken);
|
|
1120
1124
|
if (rows.length === 0) return { status: 'claim_lost', itemIds: [], eventIds: [] };
|
|
1121
1125
|
const itemIds = rows.map((row) => String(row.item_id));
|
|
@@ -1158,7 +1162,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1158
1162
|
const rows = this.db.prepare(`
|
|
1159
1163
|
SELECT * FROM mailbox_items
|
|
1160
1164
|
WHERE claim_owner = ? AND claim_token = ? AND state = 'claimed'
|
|
1161
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1165
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1162
1166
|
`).all(request.ownerId, request.claimToken);
|
|
1163
1167
|
if (
|
|
1164
1168
|
rows.length === 0
|
|
@@ -1669,6 +1673,29 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1669
1673
|
`).run(new Date().toISOString());
|
|
1670
1674
|
});
|
|
1671
1675
|
}
|
|
1676
|
+
const wakeMigration = this.db.prepare('SELECT version FROM schema_migrations WHERE version = 11').get();
|
|
1677
|
+
if (!wakeMigration) {
|
|
1678
|
+
this.transaction(() => {
|
|
1679
|
+
const columns = this.db.prepare('PRAGMA table_info(events)').all();
|
|
1680
|
+
if (!columns.some((row) => row.name === 'wake_agent')) {
|
|
1681
|
+
this.db.exec('ALTER TABLE events ADD COLUMN wake_agent INTEGER CHECK(wake_agent IN (0, 1))');
|
|
1682
|
+
}
|
|
1683
|
+
this.db.prepare('INSERT INTO schema_migrations(version, applied_at) VALUES (11, ?)')
|
|
1684
|
+
.run(new Date().toISOString());
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
if (!this.db.prepare('SELECT version FROM schema_migrations WHERE version = 12').get()) {
|
|
1689
|
+
this.transaction(() => {
|
|
1690
|
+
const columns = this.db.prepare('PRAGMA table_info(mailbox_items)').all();
|
|
1691
|
+
if (!columns.some((row) => row.name === 'delivery_order')) {
|
|
1692
|
+
this.db.exec('ALTER TABLE mailbox_items ADD COLUMN delivery_order INTEGER');
|
|
1693
|
+
}
|
|
1694
|
+
this.db.prepare('INSERT INTO schema_migrations(version, applied_at) VALUES (12, ?)')
|
|
1695
|
+
.run(new Date().toISOString());
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1672
1699
|
}
|
|
1673
1700
|
|
|
1674
1701
|
/**
|
|
@@ -85,6 +85,8 @@ export interface EventSourceRef {
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
export interface PublishEventInput {
|
|
88
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
89
|
+
readonly wakeAgent?: boolean;
|
|
88
90
|
/** Runtime epoch that admitted or derived this Event. */
|
|
89
91
|
epochSeq?: number;
|
|
90
92
|
type: string;
|
|
@@ -103,6 +105,8 @@ export interface PublishEventInput {
|
|
|
103
105
|
}
|
|
104
106
|
|
|
105
107
|
export interface CanonicalEvent {
|
|
108
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
109
|
+
readonly wakeAgent?: boolean;
|
|
106
110
|
commitSeq: number;
|
|
107
111
|
/** Absent only for records written before the epoch runtime migration. */
|
|
108
112
|
epochSeq?: number;
|
|
@@ -24,6 +24,8 @@ export interface MailboxItem<T = unknown> {
|
|
|
24
24
|
segmentId: string;
|
|
25
25
|
eventId: string;
|
|
26
26
|
eventCommitSeq: number;
|
|
27
|
+
/** Optional stable delivery position; canonical event sequence remains unchanged. */
|
|
28
|
+
deliveryOrder?: number;
|
|
27
29
|
mode: MailboxDeliveryMode;
|
|
28
30
|
coalesceKey: string;
|
|
29
31
|
payload: T;
|
|
@@ -51,6 +53,8 @@ export interface EnqueueMailboxItem<T = unknown> {
|
|
|
51
53
|
segmentId: string;
|
|
52
54
|
eventId: string;
|
|
53
55
|
eventCommitSeq: number;
|
|
56
|
+
/** Optional stable delivery position; canonical event sequence remains unchanged. */
|
|
57
|
+
deliveryOrder?: number;
|
|
54
58
|
mode: MailboxDeliveryMode;
|
|
55
59
|
coalesceKey: string;
|
|
56
60
|
payload: T;
|
|
@@ -115,6 +115,8 @@ export interface RuntimeStateProposal<T = unknown> {
|
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
export interface RuntimeEventProposal {
|
|
118
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
119
|
+
readonly wakeAgent?: boolean;
|
|
118
120
|
readonly type: string;
|
|
119
121
|
readonly dedupeKey: string;
|
|
120
122
|
readonly dedupeScope?: 'segment' | 'session';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { canResumeRuntimeScope } from './events/runtime-resume.js';
|
|
2
|
+
import { randomUUID as captureId } from 'node:crypto';
|
|
2
3
|
import {
|
|
3
4
|
ActionRegistry,
|
|
4
5
|
ObservationRegistry,
|
|
@@ -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 } : {}),
|
|
@@ -1246,6 +1258,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
1246
1258
|
producerOutputIndex: proposalIndex,
|
|
1247
1259
|
sessionId: epoch.scope.sessionId,
|
|
1248
1260
|
segmentId: epoch.scope.segmentId,
|
|
1261
|
+
wakeAgent: proposal.wakeAgent,
|
|
1249
1262
|
payload: proposal.payload,
|
|
1250
1263
|
occurredAt: proposal.occurredAt,
|
|
1251
1264
|
receivedAt: new Date().toISOString(),
|
|
@@ -62,6 +62,7 @@ export class MailboxRelayBroker<TPayload extends Record<string, unknown> = Recor
|
|
|
62
62
|
readonly mode: MailboxDeliveryMode,
|
|
63
63
|
private readonly consumerId = DEFAULT_EVENT_CONSUMER_ID,
|
|
64
64
|
private readonly maxItems = DEFAULT_RELAY_BATCH_SIZE,
|
|
65
|
+
private readonly onDelivered?: (eventIds: readonly string[]) => void,
|
|
65
66
|
) {}
|
|
66
67
|
|
|
67
68
|
handle(request: OwnerControlRequest): OwnerControlResponse | undefined {
|
|
@@ -123,18 +124,18 @@ export class MailboxRelayBroker<TPayload extends Record<string, unknown> = Recor
|
|
|
123
124
|
const claimToken = boundedString(request.claim_token, CLAIM_TOKEN_MAX_CHARS);
|
|
124
125
|
if (!claimToken) return { ok: false, error: 'invalid_mailbox_claim_token' };
|
|
125
126
|
if (request.type === 'mailbox_ack') {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
};
|
|
127
|
+
const result = this.repository.ackMailboxClaim({
|
|
128
|
+
ownerId: relayId,
|
|
129
|
+
claimToken,
|
|
130
|
+
acceptedAt: typeof request.accepted_at === 'string'
|
|
131
|
+
? request.accepted_at
|
|
132
|
+
: undefined,
|
|
133
|
+
acceptanceLevel: 'sink_emitted',
|
|
134
|
+
});
|
|
135
|
+
if (result.status !== 'claim_lost') {
|
|
136
|
+
try { this.onDelivered?.(result.eventIds); } catch { /* Best-effort display only. */ }
|
|
137
|
+
}
|
|
138
|
+
return { ok: true, type: 'mailbox_ack', result };
|
|
138
139
|
}
|
|
139
140
|
return {
|
|
140
141
|
ok: true,
|
|
@@ -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. */
|
|
@@ -107,6 +107,8 @@ export interface PerceptionBoundary {
|
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
export interface PerceptionEventProposal {
|
|
110
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
111
|
+
readonly wakeAgent?: boolean;
|
|
110
112
|
readonly type: string;
|
|
111
113
|
/** Stable identity of this semantic slice within the current segment. */
|
|
112
114
|
readonly dedupeKey: string;
|
|
@@ -116,6 +118,8 @@ export interface PerceptionEventProposal {
|
|
|
116
118
|
}
|
|
117
119
|
|
|
118
120
|
export interface ClawclawPerceptionManifest {
|
|
121
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
122
|
+
readonly wakeAgent?: boolean;
|
|
119
123
|
readonly apiVersion: typeof PERCEPTION_PLUGIN_API_VERSION;
|
|
120
124
|
readonly id: string;
|
|
121
125
|
readonly name: string;
|