@myclaw163/clawclaw-cli 0.9.2 → 0.10.1
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/QUICKSTART_OTHER.md +5 -5
- package/README.md +7 -8
- package/bin/clawclaw-channel.mjs +2 -2
- package/bin/clawclaw-cli.mjs +2 -2
- package/docs/configuration.md +25 -99
- package/docs/custom-modules/README.md +23 -35
- package/docs/custom-modules/api-reference.md +95 -273
- package/docs/custom-modules/behavior.md +94 -78
- package/docs/custom-modules/examples/auto-escape.ts +5 -5
- package/docs/custom-modules/examples/go-to-point.ts +11 -11
- package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
- package/docs/custom-modules/examples/task-reminder.ts +4 -5
- package/docs/custom-modules/perception.md +42 -603
- package/docs/custom-modules/skill.md +1 -1
- package/docs/desktop-event-push.md +3 -3
- package/docs/runtime/README.md +16 -17
- package/docs/runtime/agent-notifications.md +31 -12
- package/docs/runtime/behavior-runtime.md +47 -46
- package/docs/runtime/components-and-boundaries.md +70 -28
- package/docs/runtime/events-and-state.md +41 -18
- package/docs/runtime/framework-package.md +73 -0
- package/docs/runtime/official-perception-modules.md +5 -5
- package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
- package/docs/runtime/short-commands-and-capabilities.md +8 -9
- package/docs/user-guide/README.md +10 -7
- package/docs/user-guide/api-reference.md +81 -164
- package/docs/user-guide/behavior.md +84 -68
- package/docs/user-guide/installation.md +7 -7
- package/docs/user-guide/perception.md +42 -586
- package/docs/user-guide/skill.md +1 -1
- package/package.json +24 -9
- package/scripts/check-framework-boundaries.mjs +27 -0
- package/scripts/check-skill-command-surface.mjs +8 -13
- package/scripts/install-local-runtime.mjs +35 -0
- package/scripts/qa-install.mjs +105 -0
- package/skills/clawclaw/SKILL.md +49 -49
- package/skills/clawclaw/references/BEHAVIORS.md +42 -73
- package/skills/clawclaw/references/CHANNELS.md +2 -2
- package/skills/clawclaw/references/COMMANDS.md +60 -101
- package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +94 -78
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +95 -180
- package/skills/clawclaw/references/CUSTOM-MODULES.md +24 -24
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +42 -608
- package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
- package/skills/clawclaw/references/HUB.md +1 -1
- package/skills/clawclaw/references/STREAM.md +8 -8
- package/skills/clawclaw/references/TACTICS.md +1 -1
- package/src/channel/claude-channel-ipc-server.ts +1 -0
- package/src/cli.ts +4 -2
- package/src/commands/behavior.ts +26 -10
- package/src/commands/capability.ts +3 -3
- package/src/commands/load.ts +3 -2
- package/src/commands/perception.ts +5 -0
- package/src/commands/strategy.ts +2 -0
- package/src/lib/capability-load-diagnostics.ts +3 -3
- package/src/lib/perception-config.ts +18 -6
- package/src/lib/runtime-cadence-config.ts +16 -0
- package/src/lib/workspace-runtime-lock.ts +3 -46
- package/src/pipeline/canonical-event-presentation.ts +23 -124
- package/src/pipeline/event-format.ts +12 -21
- package/src/pipeline/event-hints.ts +6 -6
- package/src/pipeline/game-sync-event-normalization.ts +57 -63
- package/src/runtime/clawclaw/behavior-decision.ts +7 -3
- package/src/runtime/clawclaw/behavior-input.ts +8 -4
- package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
- package/src/runtime/clawclaw/notification-policy.ts +42 -0
- package/src/runtime/clawclaw/notification-turn.ts +19 -0
- package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
- package/src/runtime/clawclaw/owner.ts +18 -4
- package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
- package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
- package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
- package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
- package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
- package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
- package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +25 -17
- package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
- package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
- package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
- package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +119 -297
- package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
- package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +18 -7
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
- package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
- package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
- package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
- package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
- package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
- package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
- package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
- package/src/runtime/clawclaw/runtime-state.ts +11 -0
- package/src/runtime/clawclaw/runtime.ts +8 -0
- package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
- package/src/runtime/clawclaw/strategy-memory.ts +1 -77
- package/src/runtime/clawclaw-event-catalog.ts +12 -12
- package/src/runtime/framework/action-diagnostics.ts +3 -83
- package/src/runtime/framework/capability-registry.ts +2 -395
- package/src/runtime/framework/contracts.ts +2 -144
- package/src/runtime/framework/control/control-scheduler.ts +2 -1268
- package/src/runtime/framework/control/domain-set.ts +2 -81
- package/src/runtime/framework/control/index.ts +1 -3
- package/src/runtime/framework/control/types.ts +2 -191
- package/src/runtime/framework/control-coordinator.ts +2 -11
- package/src/runtime/framework/events/event-catalog.ts +2 -74
- package/src/runtime/framework/events/event-delivery-service.ts +2 -200
- package/src/runtime/framework/events/event-ingress.ts +2 -99
- package/src/runtime/framework/events/event-repository.ts +2 -82
- package/src/runtime/framework/events/index.ts +2 -7
- package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
- package/src/runtime/framework/events/runtime-resume.ts +2 -20
- package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
- package/src/runtime/framework/events/test-helpers.ts +1 -1
- package/src/runtime/framework/events/types.ts +2 -312
- package/src/runtime/framework/index.ts +3 -7
- package/src/runtime/framework/load-node-sqlite.ts +2 -17
- package/src/runtime/framework/mailbox/coalescer.ts +2 -83
- package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
- package/src/runtime/framework/mailbox/identity.ts +2 -38
- package/src/runtime/framework/mailbox/index.ts +1 -7
- package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
- package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
- package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
- package/src/runtime/framework/mailbox/types.ts +2 -145
- package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
- package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
- package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
- package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
- package/src/runtime/framework/participation-manager.ts +2 -253
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
- package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
- package/src/runtime/framework/plugins/contracts.ts +2 -396
- package/src/runtime/framework/plugins/index.ts +1 -4
- package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
- package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
- package/src/runtime/framework/runtime.ts +5 -1843
- package/src/runtime/framework/serial-task-queue.ts +2 -14
- package/src/runtime/framework/state/contracts.ts +2 -49
- package/src/runtime/framework/state/current-state-store.ts +2 -184
- package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
- package/src/runtime/framework/state/freshness.ts +2 -72
- package/src/runtime/framework/state/history/contracts.ts +2 -158
- package/src/runtime/framework/state/history/history-writer.ts +2 -194
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
- package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
- package/src/runtime/framework/state/index.ts +1 -13
- package/src/runtime/framework/state/state-ingress.ts +2 -95
- package/src/runtime/framework/state/state-provider.ts +2 -62
- package/src/runtime/framework/state/types.ts +2 -155
- package/src/runtime/host-monitor-rate-gate.ts +1 -123
- package/src/runtime/mailbox-host-relay.ts +1 -326
- package/src/runtime/observability/detail-capture.ts +4 -108
- package/src/runtime/observability/process-timing.ts +2 -59
- package/src/runtime/observability/recorder.ts +2 -238
- package/src/runtime/observability/redaction.ts +2 -181
- package/src/runtime/observability/reporter.ts +2 -154
- package/src/runtime/observability/sinks.ts +2 -135
- package/src/runtime/observability/types.ts +2 -92
- package/src/runtime/owner-control.ts +45 -320
- package/src/runtime/parent-process-watch.ts +1 -51
- package/src/runtime/process-identity.ts +1 -72
- package/src/sdk/behavior-plugin/index.ts +9 -3
- package/src/sdk/index.ts +40 -2
- package/src/sdk/module-input/index.ts +5 -0
- package/src/sdk/perception-plugin/index.ts +3 -1
- package/src/sdk/perception-plugin/module.ts +12 -2
- package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
- package/src/sdk/perception-plugin/reminder.ts +2 -1
- package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
- package/src/sdk/strategy-memory.ts +1 -12
- package/src/sdk/strategy-plugin/index.ts +36 -0
- package/src/sdk/trigger-plugin/index.ts +1 -0
- package/docs/custom-modules/trigger.md +0 -295
|
@@ -1,326 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
DEFAULT_EVENT_CONSUMER_ID,
|
|
4
|
-
type EventRepository,
|
|
5
|
-
} from './framework/events/index.js';
|
|
6
|
-
import type {
|
|
7
|
-
MailboxDeliveryMode,
|
|
8
|
-
MailboxRepository,
|
|
9
|
-
} from './framework/mailbox/index.js';
|
|
10
|
-
import type {
|
|
11
|
-
OwnerControlRequest,
|
|
12
|
-
OwnerControlResponse,
|
|
13
|
-
HostRelayOwnerControlType,
|
|
14
|
-
} from './owner-control.js';
|
|
15
|
-
import type { HostMonitorWriteGate } from './host-monitor-rate-gate.js';
|
|
16
|
-
|
|
17
|
-
export const MAILBOX_RELAY_REQUEST_TYPES = [
|
|
18
|
-
'mailbox_claim',
|
|
19
|
-
'mailbox_ack',
|
|
20
|
-
'mailbox_nack',
|
|
21
|
-
] as const;
|
|
22
|
-
|
|
23
|
-
export type MailboxRelayRequestType = typeof MAILBOX_RELAY_REQUEST_TYPES[number];
|
|
24
|
-
|
|
25
|
-
const RELAY_ID_MAX_CHARS = 200;
|
|
26
|
-
const CLAIM_TOKEN_MAX_CHARS = 200;
|
|
27
|
-
const DEFAULT_RELAY_LEASE_TTL_MS = 10_000;
|
|
28
|
-
const MAX_RELAY_LEASE_TTL_MS = 30_000;
|
|
29
|
-
export const DEFAULT_RELAY_POLL_MS = 220;
|
|
30
|
-
const DEFAULT_RELAY_BATCH_SIZE = 100;
|
|
31
|
-
|
|
32
|
-
function boundedString(value: unknown, maxChars: number): string | undefined {
|
|
33
|
-
if (typeof value !== 'string') return undefined;
|
|
34
|
-
const trimmed = value.trim();
|
|
35
|
-
if (!trimmed || trimmed.length > maxChars) return undefined;
|
|
36
|
-
return trimmed;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function boundedLeaseTtl(value: unknown): number {
|
|
40
|
-
const numeric = Number(value);
|
|
41
|
-
if (!Number.isFinite(numeric)) return DEFAULT_RELAY_LEASE_TTL_MS;
|
|
42
|
-
return Math.max(1_000, Math.min(MAX_RELAY_LEASE_TTL_MS, Math.trunc(numeric)));
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function isRelayRequestType(value: unknown): value is MailboxRelayRequestType {
|
|
46
|
-
return MAILBOX_RELAY_REQUEST_TYPES.includes(value as MailboxRelayRequestType);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Authenticated Owner-side Mailbox endpoint.
|
|
51
|
-
*
|
|
52
|
-
* The surrounding owner-control server has already authenticated a local
|
|
53
|
-
* master token before this broker is called. Strategy and Perception do not
|
|
54
|
-
* receive owner-control credentials: Owner-thread instances are called
|
|
55
|
-
* directly, and parallel Worker Threads do not use these request families.
|
|
56
|
-
*/
|
|
57
|
-
export class MailboxRelayBroker<TPayload extends Record<string, unknown> = Record<string, unknown>> {
|
|
58
|
-
private lastContactAtMs = 0;
|
|
59
|
-
|
|
60
|
-
constructor(
|
|
61
|
-
private readonly repository: EventRepository & MailboxRepository,
|
|
62
|
-
readonly mode: MailboxDeliveryMode,
|
|
63
|
-
private readonly consumerId = DEFAULT_EVENT_CONSUMER_ID,
|
|
64
|
-
private readonly maxItems = DEFAULT_RELAY_BATCH_SIZE,
|
|
65
|
-
private readonly onDelivered?: (eventIds: readonly string[]) => void,
|
|
66
|
-
) {}
|
|
67
|
-
|
|
68
|
-
handle(request: OwnerControlRequest): OwnerControlResponse | undefined {
|
|
69
|
-
if (!isRelayRequestType(request.type)) return undefined;
|
|
70
|
-
const relayId = boundedString(request.relay_id, RELAY_ID_MAX_CHARS);
|
|
71
|
-
if (!relayId) return { ok: false, error: 'invalid_mailbox_relay_id' };
|
|
72
|
-
if (request.mode !== this.mode) {
|
|
73
|
-
return {
|
|
74
|
-
ok: false,
|
|
75
|
-
error: 'mailbox_mode_mismatch',
|
|
76
|
-
expected_mode: this.mode,
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
this.lastContactAtMs = Date.now();
|
|
80
|
-
|
|
81
|
-
if (request.type === 'mailbox_claim') {
|
|
82
|
-
const scope = this.repository.currentScope();
|
|
83
|
-
if (!scope) {
|
|
84
|
-
return { ok: true, type: 'mailbox_claim', claim: null, wait_ms: DEFAULT_RELAY_POLL_MS };
|
|
85
|
-
}
|
|
86
|
-
const next = this.repository.peekMailbox({
|
|
87
|
-
consumerId: this.consumerId,
|
|
88
|
-
sessionId: scope.session.sessionId,
|
|
89
|
-
modes: [this.mode],
|
|
90
|
-
states: ['pending', 'claimed'],
|
|
91
|
-
order: 'asc',
|
|
92
|
-
limit: 1,
|
|
93
|
-
})[0];
|
|
94
|
-
const segmentId = next?.segmentId ?? scope.segment.segmentId;
|
|
95
|
-
const claim = this.repository.claimMailbox<TPayload>({
|
|
96
|
-
consumerId: this.consumerId,
|
|
97
|
-
sessionId: scope.session.sessionId,
|
|
98
|
-
segmentId,
|
|
99
|
-
mode: this.mode,
|
|
100
|
-
ownerId: relayId,
|
|
101
|
-
leaseTtlMs: boundedLeaseTtl(request.lease_ttl_ms),
|
|
102
|
-
maxItems: this.maxItems,
|
|
103
|
-
});
|
|
104
|
-
return {
|
|
105
|
-
ok: true,
|
|
106
|
-
type: 'mailbox_claim',
|
|
107
|
-
scope: {
|
|
108
|
-
session_id: scope.session.sessionId,
|
|
109
|
-
segment_id: claim?.items[0]?.segmentId ?? segmentId,
|
|
110
|
-
},
|
|
111
|
-
claim: claim ? {
|
|
112
|
-
claim_token: claim.claimToken,
|
|
113
|
-
expires_at_ms: claim.claimExpiresAtMs,
|
|
114
|
-
items: claim.items.map((item) => ({
|
|
115
|
-
item_id: item.itemId,
|
|
116
|
-
event_id: item.eventId,
|
|
117
|
-
payload: item.payload,
|
|
118
|
-
})),
|
|
119
|
-
} : null,
|
|
120
|
-
wait_ms: DEFAULT_RELAY_POLL_MS,
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const claimToken = boundedString(request.claim_token, CLAIM_TOKEN_MAX_CHARS);
|
|
125
|
-
if (!claimToken) return { ok: false, error: 'invalid_mailbox_claim_token' };
|
|
126
|
-
if (request.type === 'mailbox_ack') {
|
|
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 };
|
|
139
|
-
}
|
|
140
|
-
return {
|
|
141
|
-
ok: true,
|
|
142
|
-
type: 'mailbox_nack',
|
|
143
|
-
result: this.repository.nackMailboxClaim({
|
|
144
|
-
ownerId: relayId,
|
|
145
|
-
claimToken,
|
|
146
|
-
retryAtMs: Number.isFinite(Number(request.retry_at_ms))
|
|
147
|
-
? Math.max(Date.now(), Math.trunc(Number(request.retry_at_ms)))
|
|
148
|
-
: Date.now() + DEFAULT_RELAY_POLL_MS,
|
|
149
|
-
errorCode: boundedString(request.error_code, 100) ?? 'host_relay_write_failed',
|
|
150
|
-
}),
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
hasRecentRelay(withinMs = 2_000, nowMs = Date.now()): boolean {
|
|
155
|
-
return this.lastContactAtMs > 0 && nowMs - this.lastContactAtMs <= withinMs;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
hasPendingCurrent(): boolean {
|
|
159
|
-
const scope = this.repository.currentScope();
|
|
160
|
-
if (!scope) return false;
|
|
161
|
-
return this.repository.peekMailbox({
|
|
162
|
-
consumerId: this.consumerId,
|
|
163
|
-
sessionId: scope.session.sessionId,
|
|
164
|
-
modes: [this.mode],
|
|
165
|
-
states: ['pending', 'claimed'],
|
|
166
|
-
order: 'asc',
|
|
167
|
-
limit: 1,
|
|
168
|
-
}).length > 0;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
export interface StdoutMailboxRelayOptions {
|
|
173
|
-
request: (
|
|
174
|
-
type: HostRelayOwnerControlType,
|
|
175
|
-
payload: Record<string, unknown>,
|
|
176
|
-
timeoutMs?: number,
|
|
177
|
-
) => Promise<OwnerControlResponse | null>;
|
|
178
|
-
emit: (payload: Record<string, unknown>) => Promise<void>;
|
|
179
|
-
/** Compose one Host wake-up from all items in a coalesced Mailbox claim. */
|
|
180
|
-
compose?: (payloads: readonly Record<string, unknown>[]) => Record<string, unknown>;
|
|
181
|
-
/**
|
|
182
|
-
* Mirror of the Host Monitor rate limiter. When this gate denies a write,
|
|
183
|
-
* the claimed batch is nack'ed (released back to pending) instead of emitted,
|
|
184
|
-
* so events are never dropped — they either reach the agent via a later
|
|
185
|
-
* stdout write, or are pulled by `ccl events`.
|
|
186
|
-
*/
|
|
187
|
-
rateGate?: HostMonitorWriteGate;
|
|
188
|
-
isOwnerAlive: () => boolean;
|
|
189
|
-
mode: MailboxDeliveryMode;
|
|
190
|
-
signal?: AbortSignal;
|
|
191
|
-
relayId?: string;
|
|
192
|
-
pollMs?: number;
|
|
193
|
-
requestTimeoutMs?: number;
|
|
194
|
-
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
198
|
-
if (signal?.aborted) return Promise.resolve();
|
|
199
|
-
return new Promise((resolve) => {
|
|
200
|
-
const timer = setTimeout(finish, ms);
|
|
201
|
-
const onAbort = (): void => finish();
|
|
202
|
-
function finish(): void {
|
|
203
|
-
clearTimeout(timer);
|
|
204
|
-
signal?.removeEventListener('abort', onAbort);
|
|
205
|
-
resolve();
|
|
206
|
-
}
|
|
207
|
-
signal?.addEventListener('abort', onAbort, { once: true });
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
function relayClaim(value: unknown): {
|
|
212
|
-
claimToken: string;
|
|
213
|
-
items: Array<{ payload: Record<string, unknown> }>;
|
|
214
|
-
} | null {
|
|
215
|
-
if (!value || typeof value !== 'object') return null;
|
|
216
|
-
const claim = value as Record<string, unknown>;
|
|
217
|
-
const claimToken = boundedString(claim.claim_token, CLAIM_TOKEN_MAX_CHARS);
|
|
218
|
-
if (!claimToken || !Array.isArray(claim.items) || claim.items.length === 0) return null;
|
|
219
|
-
const items = claim.items.map((value) => {
|
|
220
|
-
if (!value || typeof value !== 'object') return null;
|
|
221
|
-
const payload = (value as Record<string, unknown>).payload;
|
|
222
|
-
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
|
|
223
|
-
return { payload: payload as Record<string, unknown> };
|
|
224
|
-
});
|
|
225
|
-
if (items.some((item) => item === null)) return null;
|
|
226
|
-
return { claimToken, items: items as Array<{ payload: Record<string, unknown> }> };
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
async function acknowledgeWithRetry(
|
|
230
|
-
options: StdoutMailboxRelayOptions,
|
|
231
|
-
relayId: string,
|
|
232
|
-
claimToken: string,
|
|
233
|
-
): Promise<boolean> {
|
|
234
|
-
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
235
|
-
try {
|
|
236
|
-
const response = await options.request('mailbox_ack', {
|
|
237
|
-
relay_id: relayId,
|
|
238
|
-
mode: options.mode,
|
|
239
|
-
claim_token: claimToken,
|
|
240
|
-
accepted_at: new Date().toISOString(),
|
|
241
|
-
}, options.requestTimeoutMs);
|
|
242
|
-
const status = response?.result?.status;
|
|
243
|
-
if (response?.ok && (status === 'accepted' || status === 'already_accepted')) return true;
|
|
244
|
-
if (status === 'claim_lost') return false;
|
|
245
|
-
} catch {}
|
|
246
|
-
if (!options.isOwnerAlive() || options.signal?.aborted) return false;
|
|
247
|
-
await (options.sleep ?? defaultSleep)(50 * (attempt + 1), options.signal);
|
|
248
|
-
}
|
|
249
|
-
return false;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* Disposable Host-side loop. It has no Owner shutdown authority and never sends
|
|
254
|
-
* stop/quit when its stdout consumer goes away.
|
|
255
|
-
*/
|
|
256
|
-
export async function runStdoutMailboxRelay(options: StdoutMailboxRelayOptions): Promise<void> {
|
|
257
|
-
const relayId = options.relayId ?? `stdout:${process.pid}:${randomUUID()}`;
|
|
258
|
-
const sleep = options.sleep ?? defaultSleep;
|
|
259
|
-
const pollMs = Math.max(25, Math.trunc(options.pollMs ?? DEFAULT_RELAY_POLL_MS));
|
|
260
|
-
while (!options.signal?.aborted) {
|
|
261
|
-
if (!options.isOwnerAlive()) return;
|
|
262
|
-
let response: OwnerControlResponse | null = null;
|
|
263
|
-
try {
|
|
264
|
-
response = await options.request('mailbox_claim', {
|
|
265
|
-
relay_id: relayId,
|
|
266
|
-
mode: options.mode,
|
|
267
|
-
lease_ttl_ms: DEFAULT_RELAY_LEASE_TTL_MS,
|
|
268
|
-
}, options.requestTimeoutMs);
|
|
269
|
-
} catch {
|
|
270
|
-
if (!options.isOwnerAlive()) return;
|
|
271
|
-
await sleep(pollMs, options.signal);
|
|
272
|
-
continue;
|
|
273
|
-
}
|
|
274
|
-
if (!response) {
|
|
275
|
-
if (!options.isOwnerAlive()) return;
|
|
276
|
-
await sleep(pollMs, options.signal);
|
|
277
|
-
continue;
|
|
278
|
-
}
|
|
279
|
-
if (!response.ok) {
|
|
280
|
-
throw new Error(response.error ?? 'mailbox_relay_rejected');
|
|
281
|
-
}
|
|
282
|
-
if (!response.claim) {
|
|
283
|
-
if (!options.isOwnerAlive()) return;
|
|
284
|
-
await sleep(Math.max(25, Number(response.wait_ms) || pollMs), options.signal);
|
|
285
|
-
continue;
|
|
286
|
-
}
|
|
287
|
-
const claim = relayClaim(response.claim);
|
|
288
|
-
if (!claim) throw new Error('invalid_mailbox_claim');
|
|
289
|
-
// Mirror the Host Monitor token bucket: if the Host would suppress this
|
|
290
|
-
// write (bucket empty), do NOT emit. Nack the claim so the batch returns to
|
|
291
|
-
// pending — events stay durable and reach the agent on a later poll or via
|
|
292
|
-
// `ccl events`. Emitting anyway would be silently dropped by the Host.
|
|
293
|
-
if (options.rateGate && !options.rateGate.allow()) {
|
|
294
|
-
try {
|
|
295
|
-
await options.request('mailbox_nack', {
|
|
296
|
-
relay_id: relayId,
|
|
297
|
-
mode: options.mode,
|
|
298
|
-
claim_token: claim.claimToken,
|
|
299
|
-
retry_at_ms: Date.now() + pollMs,
|
|
300
|
-
error_code: 'host_rate_limited',
|
|
301
|
-
}, options.requestTimeoutMs);
|
|
302
|
-
} catch {}
|
|
303
|
-
await sleep(Math.max(25, Number(response.wait_ms) || pollMs), options.signal);
|
|
304
|
-
continue;
|
|
305
|
-
}
|
|
306
|
-
try {
|
|
307
|
-
if (options.compose) {
|
|
308
|
-
await options.emit(options.compose(claim.items.map((item) => item.payload)));
|
|
309
|
-
} else {
|
|
310
|
-
for (const item of claim.items) await options.emit(item.payload);
|
|
311
|
-
}
|
|
312
|
-
} catch (error) {
|
|
313
|
-
try {
|
|
314
|
-
await options.request('mailbox_nack', {
|
|
315
|
-
relay_id: relayId,
|
|
316
|
-
mode: options.mode,
|
|
317
|
-
claim_token: claim.claimToken,
|
|
318
|
-
retry_at_ms: Date.now() + pollMs,
|
|
319
|
-
error_code: 'stdout_write_failed',
|
|
320
|
-
}, options.requestTimeoutMs);
|
|
321
|
-
} catch {}
|
|
322
|
-
throw error;
|
|
323
|
-
}
|
|
324
|
-
await acknowledgeWithRetry(options, relayId, claim.claimToken);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
1
|
+
export * from '@myclaw163/game-agent-runtime/mailbox/mailbox-host-relay.js';
|
|
@@ -1,13 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { DetailCapture as CoreDetailCapture, type CaptureCategory, type DetailCaptureConfig } from '@myclaw163/game-agent-runtime/observability/detail-capture.js';
|
|
2
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
|
-
}
|
|
3
|
+
export { captureSnapshot, detailCategory, type CaptureCategory, type DetailCaptureConfig } from '@myclaw163/game-agent-runtime/observability/detail-capture.js';
|
|
11
4
|
export function resolveDetailCapture(config?: DiagnosticsConfig, env = process.env): DetailCaptureConfig {
|
|
12
5
|
let selected = config;
|
|
13
6
|
if (!selected) { try { selected = readDiagnosticsConfig(); } catch { /* fail closed */ } }
|
|
@@ -21,103 +14,6 @@ export function resolveDetailCapture(config?: DiagnosticsConfig, env = process.e
|
|
|
21
14
|
return { actions: enabled('actions'), behavior_io: enabled('behavior_io'), perception_io: enabled('perception_io'),
|
|
22
15
|
max_record_bytes: selected?.capture?.max_record_bytes ?? 256 * 1024 };
|
|
23
16
|
}
|
|
24
|
-
export
|
|
25
|
-
|
|
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 };
|
|
17
|
+
export class DetailCapture extends CoreDetailCapture {
|
|
18
|
+
constructor(category: CaptureCategory, diagnostic?: ConstructorParameters<typeof CoreDetailCapture>[1], config?: DetailCaptureConfig) { super(category, diagnostic, config ?? resolveDetailCapture()); }
|
|
123
19
|
}
|
|
@@ -1,59 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
/** Full-only process/Owner-loop measurements. Does not retain GC entries or gameplay data. */
|
|
4
|
-
export class RuntimeProcessTimingSampler {
|
|
5
|
-
private readonly delay = monitorEventLoopDelay({ resolution: 20 });
|
|
6
|
-
private readonly observer: PerformanceObserver;
|
|
7
|
-
private previousCpu = process.cpuUsage();
|
|
8
|
-
private previousLoop = performance.eventLoopUtilization();
|
|
9
|
-
private previousAt = performance.now();
|
|
10
|
-
private gcCount = 0;
|
|
11
|
-
private gcMs = 0;
|
|
12
|
-
private stopped = false;
|
|
13
|
-
|
|
14
|
-
constructor() {
|
|
15
|
-
this.observer = new PerformanceObserver((entries) => {
|
|
16
|
-
for (const entry of entries.getEntries()) {
|
|
17
|
-
this.gcCount += 1;
|
|
18
|
-
this.gcMs += entry.duration;
|
|
19
|
-
}
|
|
20
|
-
});
|
|
21
|
-
this.observer.observe({ entryTypes: ['gc'] });
|
|
22
|
-
this.delay.enable();
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
sample(): Readonly<Record<string, number>> {
|
|
26
|
-
const now = performance.now();
|
|
27
|
-
const cpu = process.cpuUsage();
|
|
28
|
-
const loop = performance.eventLoopUtilization();
|
|
29
|
-
const elapsed = now - this.previousAt;
|
|
30
|
-
const deltaLoop = performance.eventLoopUtilization(loop, this.previousLoop);
|
|
31
|
-
const milliseconds = (ns: number): number => Number.isFinite(ns) ? Math.round(ns / 1_000) / 1_000 : 0;
|
|
32
|
-
const result = {
|
|
33
|
-
window_ms: Math.round(elapsed),
|
|
34
|
-
// process.cpuUsage includes Worker threads; this is not Owner-isolate CPU utilization.
|
|
35
|
-
process_cpu_user_ms: (cpu.user - this.previousCpu.user) / 1_000,
|
|
36
|
-
process_cpu_system_ms: (cpu.system - this.previousCpu.system) / 1_000,
|
|
37
|
-
owner_event_loop_utilization: deltaLoop.utilization,
|
|
38
|
-
owner_event_loop_delay_mean_ms: milliseconds(this.delay.mean),
|
|
39
|
-
owner_event_loop_delay_p95_ms: milliseconds(this.delay.percentile(95)),
|
|
40
|
-
owner_event_loop_delay_max_ms: milliseconds(this.delay.max),
|
|
41
|
-
owner_gc_count: this.gcCount,
|
|
42
|
-
owner_gc_duration_ms: Math.round(this.gcMs * 1_000) / 1_000,
|
|
43
|
-
};
|
|
44
|
-
this.previousAt = now;
|
|
45
|
-
this.previousCpu = cpu;
|
|
46
|
-
this.previousLoop = loop;
|
|
47
|
-
this.gcCount = 0;
|
|
48
|
-
this.gcMs = 0;
|
|
49
|
-
this.delay.reset();
|
|
50
|
-
return result;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
stop(): void {
|
|
54
|
-
if (this.stopped) return;
|
|
55
|
-
this.stopped = true;
|
|
56
|
-
this.observer.disconnect();
|
|
57
|
-
this.delay.disable();
|
|
58
|
-
}
|
|
59
|
-
}
|
|
1
|
+
// Compatibility facade; implementation lives in the game-neutral runtime package.
|
|
2
|
+
export * from '@myclaw163/game-agent-runtime/observability/process-timing.js';
|