@myclaw163/clawclaw-cli 0.9.2 → 0.10.2
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.md +1 -1
- package/QUICKSTART_OTHER.md +13 -12
- package/README.md +7 -8
- package/bin/clawclaw-channel.mjs +2 -2
- package/bin/clawclaw-cli.mjs +2 -2
- package/docs/configuration.md +27 -101
- 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 +12 -10
- package/docs/desktop-event-push.md +3 -3
- package/docs/runtime/README.md +16 -17
- package/docs/runtime/agent-notifications.md +42 -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 +12 -10
- package/package.json +24 -9
- package/scripts/check-framework-boundaries.mjs +27 -0
- package/scripts/check-skill-command-surface.mjs +20 -23
- package/scripts/enable_ccl_permissions.cjs +4 -0
- package/scripts/install-local-runtime.mjs +35 -0
- package/scripts/postinstall.mjs +1 -1
- package/scripts/qa-install.mjs +105 -0
- package/scripts/sync-bundled-skill.mjs +35 -28
- package/skills/clawclaw/SKILL.md +53 -57
- package/skills/clawclaw/references/BEHAVIORS.md +43 -83
- package/skills/clawclaw/references/CHANNELS.md +2 -2
- package/skills/clawclaw/references/COMMANDS.md +62 -103
- package/skills/clawclaw/references/HUB.md +2 -2
- package/skills/clawclaw/references/STREAM.md +8 -8
- package/skills/clawclaw/references/TACTICS.md +1 -1
- package/skills/clawclaw-creator/SKILL.md +82 -0
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
- package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
- package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
- package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
- package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
- package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
- 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 +17 -14
- package/src/commands/load.ts +5 -3
- package/src/commands/perception.ts +5 -0
- package/src/commands/skill.ts +34 -29
- package/src/commands/strategy.ts +2 -0
- package/src/commands/upgrade.ts +2 -2
- package/src/lib/agent-workspace-skills.ts +20 -13
- package/src/lib/capability-cloud-sync.ts +2 -1
- package/src/lib/capability-discovery.ts +2 -1
- package/src/lib/capability-load-diagnostics.ts +3 -3
- package/src/lib/capability-workspace.ts +2 -1
- package/src/lib/game-client.ts +7 -1
- package/src/lib/package-skills.ts +4 -0
- package/src/lib/perception-config.ts +18 -6
- package/src/lib/runtime-cadence-config.ts +16 -0
- package/src/lib/skill-host.ts +1 -1
- 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 +47 -9
- 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 +27 -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/adapters/game-sync-perception-report-adapter.ts +15 -20
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
- 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/index.ts +1 -0
- 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 +125 -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 +25 -10
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
- package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
- 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/game-sync-ingress-protocol.ts +3 -2
- package/src/runtime/game-sync-ingress-worker.ts +7 -1
- package/src/runtime/game-sync-protocol.ts +64 -4
- 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/runtime/threaded-ws-client.ts +11 -2
- package/src/runtime/ws-client.ts +6 -0
- 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
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
- package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
|
@@ -1,772 +1,69 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
} from '../../../../pipeline/canonical-event-presentation.js';
|
|
1
|
+
import { isClawclawAgentNotification } from '../../notification-policy.js';
|
|
2
|
+
import { presentCanonicalEventForCclEvents, } from '../../../../pipeline/canonical-event-presentation.js';
|
|
4
3
|
import { compactStateForEvents } from '../../../../pipeline/event-format.js';
|
|
5
|
-
import {
|
|
6
|
-
DEFAULT_EVENT_CONSUMER_ID,
|
|
7
|
-
type CanonicalEvent,
|
|
8
|
-
type EventRepository,
|
|
9
|
-
} from '../../../framework/events/index.js';
|
|
10
|
-
import {
|
|
11
|
-
stableMailboxItemId,
|
|
12
|
-
type MailboxRepository,
|
|
13
|
-
} from '../../../framework/mailbox/index.js';
|
|
14
|
-
import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/contracts.js';
|
|
15
|
-
import type { RuntimeReadyView } from '../../../framework/runtime.js';
|
|
4
|
+
import { type CanonicalEvent } from '../../../framework/events/index.js';
|
|
16
5
|
import { clawclawMonitorEventPriority } from '../../agent-event-policy.js';
|
|
17
|
-
import {
|
|
18
|
-
import type
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
} from '
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
clawclawEventRequiresDetails,
|
|
25
|
-
monitorItemPayload,
|
|
26
|
-
partitionClawclawMonitorItems,
|
|
27
|
-
} from './mailbox-presentation.js';
|
|
28
|
-
|
|
29
|
-
const MONITOR_FORMATTER_VERSION = 'clawclaw.monitor.v4';
|
|
30
|
-
const CCL_EVENTS_LEASE_TTL_MS = 30_000;
|
|
31
|
-
const MONITOR_OVERFLOW_LEASE_TTL_MS = 30_000;
|
|
32
|
-
const MONITOR_OVERFLOW_TRANSITION_BATCH_SIZE = 200;
|
|
6
|
+
import { composeClawclawMonitorNotification, clawclawEventRequiresDetails, monitorItemPayload, partitionClawclawMonitorItems, } from './mailbox-presentation.js';
|
|
7
|
+
import { MailboxService, type MailboxServiceOptions } from '@myclaw163/game-agent-runtime/mailbox/mailbox-service.js';
|
|
8
|
+
import type { ClawclawMonitorItemPayload } from './mailbox-presentation.js';
|
|
9
|
+
import { projectClawclawMailboxState } from './agent-mailbox-coordinator.js';
|
|
10
|
+
export { DEFAULT_MONITOR_PENDING_ITEM_LIMIT, DEFAULT_MONITOR_ADMISSION_WINDOW_MS, DEFAULT_MONITOR_ORDINARY_WINDOW_ITEM_BUDGET, DEFAULT_MONITOR_BACKLOG_HINT_WINDOW_ITEM_BUDGET, DEFAULT_MONITOR_VISUAL_MIN_INTERVAL_MS } from '@myclaw163/game-agent-runtime/mailbox/mailbox-service.js';
|
|
11
|
+
export type { PrepareEventsRequest as PrepareClawclawEventsRequest, PreparedEventsResponse as PreparedClawclawEventsResponse } from '@myclaw163/game-agent-runtime/mailbox/mailbox-service.js';
|
|
12
|
+
export type ClawclawMailboxServiceOptions = Omit<MailboxServiceOptions, 'policy'>;
|
|
33
13
|
const MONITOR_PROTECTED_PRIORITY = 80;
|
|
34
|
-
const MONITOR_PRIORITY_BYPASS_ITEM_LIMIT = 4;
|
|
35
|
-
export const DEFAULT_MONITOR_PENDING_ITEM_LIMIT = 10;
|
|
36
|
-
/** Rolling admission window for ordinary Monitor output. */
|
|
37
|
-
export const DEFAULT_MONITOR_ADMISSION_WINDOW_MS = 60_000;
|
|
38
|
-
/** Ordinary short items admitted during one rolling window. */
|
|
39
|
-
export const DEFAULT_MONITOR_ORDINARY_WINDOW_ITEM_BUDGET = 12;
|
|
40
|
-
/** Additional ordinary-only backlog wake-ups admitted during one rolling window. */
|
|
41
|
-
export const DEFAULT_MONITOR_BACKLOG_HINT_WINDOW_ITEM_BUDGET = 4;
|
|
42
|
-
/** Minimum spacing between directly presented visual telemetry items. */
|
|
43
|
-
export const DEFAULT_MONITOR_VISUAL_MIN_INTERVAL_MS = 5_000;
|
|
44
|
-
|
|
45
14
|
const MONITOR_TERMINAL_EVENT_TYPES = new Set([
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
15
|
+
'game_over',
|
|
16
|
+
'exile_game_over',
|
|
17
|
+
'game_over_recovered',
|
|
49
18
|
]);
|
|
50
19
|
const MONITOR_NOISY_VISUAL_EVENT_TYPES = new Set([
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
20
|
+
'visual.player_moved',
|
|
21
|
+
'visual.player_motion_changed',
|
|
22
|
+
'visual.no_significant_stop',
|
|
23
|
+
'visual.player_area_changed',
|
|
24
|
+
'visual.player_position_changed',
|
|
25
|
+
'visual.player_turned',
|
|
26
|
+
'visual.player_reversed',
|
|
27
|
+
'visual.player_wandering',
|
|
28
|
+
'visual.players_moving_together',
|
|
60
29
|
]);
|
|
61
|
-
|
|
62
30
|
function monitorEventMustRemainDirect(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): boolean {
|
|
63
|
-
|
|
64
|
-
|
|
31
|
+
return MONITOR_TERMINAL_EVENT_TYPES.has(event.type)
|
|
32
|
+
|| clawclawMonitorEventPriority(event) >= MONITOR_PROTECTED_PRIORITY;
|
|
65
33
|
}
|
|
66
|
-
|
|
67
34
|
function monitorDirectAdmissionPriority(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): number {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
35
|
+
return MONITOR_TERMINAL_EVENT_TYPES.has(event.type)
|
|
36
|
+
? Number.MAX_SAFE_INTEGER
|
|
37
|
+
: clawclawMonitorEventPriority(event);
|
|
71
38
|
}
|
|
72
|
-
|
|
73
39
|
function ordinaryMonitorRetentionRank(event: Pick<CanonicalEvent, 'type' | 'commitSeq'>): number {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
40
|
+
// Retain decision/lifecycle facts, then visual transitions, before noisy
|
|
41
|
+
// motion/spatial telemetry so route churn is delegated first under pressure.
|
|
42
|
+
if (monitorEventIsNoisyVisual(event))
|
|
43
|
+
return 2;
|
|
44
|
+
return event.type.startsWith('visual.') ? 1 : 0;
|
|
78
45
|
}
|
|
79
|
-
|
|
80
46
|
function monitorEventIsNoisyVisual(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): boolean {
|
|
81
|
-
|
|
47
|
+
return MONITOR_NOISY_VISUAL_EVENT_TYPES.has(event.type);
|
|
82
48
|
}
|
|
83
|
-
|
|
84
|
-
type ClawclawMailboxRepository = EventRepository & MailboxRepository;
|
|
85
|
-
|
|
86
|
-
export interface ClawclawMailboxServiceOptions {
|
|
87
|
-
repository: ClawclawMailboxRepository;
|
|
88
|
-
readyView: () => RuntimeReadyView;
|
|
89
|
-
/** Dedicated ccl-events lane; transport adapters use their own coordinators. */
|
|
90
|
-
agentMailbox?: AgentMailboxCoordinator;
|
|
91
|
-
consumerId?: string;
|
|
92
|
-
/** Disable the legacy short Monitor adapter for this Owner binding. */
|
|
93
|
-
monitorEnabled?: boolean;
|
|
94
|
-
/**
|
|
95
|
-
* Maximum ordinary pending/claimed short items retained before overflow is
|
|
96
|
-
* delegated to `ccl events`. One additional coalesced backlog signal is
|
|
97
|
-
* permitted while the ordinary queue is full.
|
|
98
|
-
*/
|
|
99
|
-
monitorPendingItemLimit?: number;
|
|
100
|
-
/** Durable ordinary short-item admissions allowed in one rolling window. */
|
|
101
|
-
monitorOrdinaryWindowItemBudget?: number;
|
|
102
|
-
/** Extra ordinary-only backlog hint admissions allowed in one rolling window. */
|
|
103
|
-
monitorBacklogHintWindowItemBudget?: number;
|
|
104
|
-
/** Duration of the rolling ordinary/hint admission window. */
|
|
105
|
-
monitorAdmissionWindowMs?: number;
|
|
106
|
-
/** Minimum interval between direct visual telemetry items. */
|
|
107
|
-
monitorVisualMinIntervalMs?: number;
|
|
108
|
-
/** Details consumer that reads overflow delegated by this Monitor lane. */
|
|
109
|
-
delegatedDetailsConsumerId?: string;
|
|
110
|
-
now?: () => number;
|
|
111
|
-
diagnostic?: (
|
|
112
|
-
name: string,
|
|
113
|
-
attributes?: Record<string, unknown>,
|
|
114
|
-
severity?: RuntimeDiagnosticSeverity,
|
|
115
|
-
) => void;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
export interface PrepareClawclawEventsRequest {
|
|
119
|
-
eventType?: string;
|
|
120
|
-
mode?: 'current' | 'backlog';
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export interface PreparedClawclawEventsResponse {
|
|
124
|
-
output: Record<string, unknown>;
|
|
125
|
-
deliveryToken?: string;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function unavailableEventsOutput(): Record<string, unknown> {
|
|
129
|
-
return {
|
|
130
|
-
schema: 'ccl.events.v5',
|
|
131
|
-
state: null,
|
|
132
|
-
events: [],
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
|
|
136
49
|
function cclEventsCompatibilityError(error: unknown): never {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
}
|
|
140
|
-
if (error instanceof Error && error.message === 'agent_mailbox_stopped') {
|
|
141
|
-
throw new Error('clawclaw_mailbox_stopped');
|
|
142
|
-
}
|
|
143
|
-
throw error;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/** Monitor direct-notification and `ccl events` detail adapters over the Agent Mailbox core. */
|
|
147
|
-
export class ClawclawMailboxService implements ClawclawMailboxDriver {
|
|
148
|
-
readonly adapter?: ClawclawMailboxAdapterDescriptor;
|
|
149
|
-
private readonly repository: ClawclawMailboxRepository;
|
|
150
|
-
private readonly readyView: () => RuntimeReadyView;
|
|
151
|
-
private readonly agentMailbox: AgentMailboxCoordinator;
|
|
152
|
-
private readonly ownsAgentMailbox: boolean;
|
|
153
|
-
private readonly consumerId: string;
|
|
154
|
-
private readonly monitorEnabled: boolean;
|
|
155
|
-
private readonly monitorPendingItemLimit: number;
|
|
156
|
-
private readonly monitorOrdinaryWindowItemBudget: number;
|
|
157
|
-
private readonly monitorBacklogHintWindowItemBudget: number;
|
|
158
|
-
private readonly monitorAdmissionWindowMs: number;
|
|
159
|
-
private readonly monitorVisualMinIntervalMs: number;
|
|
160
|
-
private readonly monitorOrdinaryAdmissionTimesMs: number[] = [];
|
|
161
|
-
private readonly monitorBacklogHintAdmissionTimesMs: number[] = [];
|
|
162
|
-
private monitorLastVisualAdmissionAtMs?: number;
|
|
163
|
-
private readonly delegatedDetailsConsumerId: string;
|
|
164
|
-
private readonly now: () => number;
|
|
165
|
-
private readonly diagnostic?: ClawclawMailboxServiceOptions['diagnostic'];
|
|
166
|
-
private lastObservedReadyEpochSeq = 0;
|
|
167
|
-
private backlogHintEventId?: string;
|
|
168
|
-
private stopped = false;
|
|
169
|
-
|
|
170
|
-
constructor(options: ClawclawMailboxServiceOptions) {
|
|
171
|
-
this.repository = options.repository;
|
|
172
|
-
this.readyView = options.readyView;
|
|
173
|
-
this.consumerId = options.consumerId ?? DEFAULT_EVENT_CONSUMER_ID;
|
|
174
|
-
this.monitorEnabled = options.monitorEnabled ?? true;
|
|
175
|
-
this.monitorPendingItemLimit = options.monitorPendingItemLimit
|
|
176
|
-
?? DEFAULT_MONITOR_PENDING_ITEM_LIMIT;
|
|
177
|
-
if (!Number.isInteger(this.monitorPendingItemLimit) || this.monitorPendingItemLimit <= 0) {
|
|
178
|
-
throw new Error('monitor_pending_item_limit_invalid');
|
|
179
|
-
}
|
|
180
|
-
this.monitorOrdinaryWindowItemBudget = options.monitorOrdinaryWindowItemBudget
|
|
181
|
-
?? DEFAULT_MONITOR_ORDINARY_WINDOW_ITEM_BUDGET;
|
|
182
|
-
if (
|
|
183
|
-
!Number.isInteger(this.monitorOrdinaryWindowItemBudget)
|
|
184
|
-
|| this.monitorOrdinaryWindowItemBudget < 0
|
|
185
|
-
) {
|
|
186
|
-
throw new Error('monitor_ordinary_window_item_budget_invalid');
|
|
187
|
-
}
|
|
188
|
-
this.monitorBacklogHintWindowItemBudget = options.monitorBacklogHintWindowItemBudget
|
|
189
|
-
?? DEFAULT_MONITOR_BACKLOG_HINT_WINDOW_ITEM_BUDGET;
|
|
190
|
-
if (
|
|
191
|
-
!Number.isInteger(this.monitorBacklogHintWindowItemBudget)
|
|
192
|
-
|| this.monitorBacklogHintWindowItemBudget < 0
|
|
193
|
-
) {
|
|
194
|
-
throw new Error('monitor_backlog_hint_window_item_budget_invalid');
|
|
195
|
-
}
|
|
196
|
-
this.monitorAdmissionWindowMs = options.monitorAdmissionWindowMs
|
|
197
|
-
?? DEFAULT_MONITOR_ADMISSION_WINDOW_MS;
|
|
198
|
-
if (!Number.isInteger(this.monitorAdmissionWindowMs) || this.monitorAdmissionWindowMs <= 0) {
|
|
199
|
-
throw new Error('monitor_admission_window_ms_invalid');
|
|
200
|
-
}
|
|
201
|
-
this.monitorVisualMinIntervalMs = options.monitorVisualMinIntervalMs
|
|
202
|
-
?? DEFAULT_MONITOR_VISUAL_MIN_INTERVAL_MS;
|
|
203
|
-
if (
|
|
204
|
-
!Number.isInteger(this.monitorVisualMinIntervalMs)
|
|
205
|
-
|| this.monitorVisualMinIntervalMs < 0
|
|
206
|
-
) {
|
|
207
|
-
throw new Error('monitor_visual_min_interval_ms_invalid');
|
|
208
|
-
}
|
|
209
|
-
this.delegatedDetailsConsumerId = options.delegatedDetailsConsumerId ?? this.consumerId;
|
|
210
|
-
this.adapter = this.monitorEnabled ? {
|
|
211
|
-
id: 'clawclaw.mailbox.adapter.monitor',
|
|
212
|
-
acknowledgement: 'explicit',
|
|
213
|
-
consumerId: this.consumerId,
|
|
214
|
-
} : undefined;
|
|
215
|
-
this.now = options.now ?? Date.now;
|
|
216
|
-
this.diagnostic = options.diagnostic;
|
|
217
|
-
this.ownsAgentMailbox = !options.agentMailbox;
|
|
218
|
-
this.agentMailbox = options.agentMailbox ?? new AgentMailboxCoordinator({
|
|
219
|
-
repository: options.repository,
|
|
220
|
-
readyView: options.readyView,
|
|
221
|
-
presentEvent: presentCanonicalEventForCclEvents,
|
|
222
|
-
compactState: compactStateForEvents,
|
|
223
|
-
eventFilter: clawclawEventRequiresDetails,
|
|
224
|
-
delegatedMonitorConsumerId: this.consumerId,
|
|
225
|
-
consumerId: this.consumerId,
|
|
226
|
-
now: this.now,
|
|
227
|
-
diagnostic: this.diagnostic,
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
prepareEvents(
|
|
232
|
-
request: PrepareClawclawEventsRequest = {},
|
|
233
|
-
readyView?: RuntimeReadyView,
|
|
234
|
-
): PreparedClawclawEventsResponse {
|
|
235
|
-
this.assertRunning();
|
|
236
|
-
const ready = this.captureReadyView(readyView);
|
|
237
|
-
if (ready.epochSeq <= 0) return { output: unavailableEventsOutput() };
|
|
238
|
-
|
|
239
|
-
if (request.eventType) {
|
|
240
|
-
const event = this.repository.listCommittedEvents({
|
|
241
|
-
sessionId: ready.scope.sessionId,
|
|
242
|
-
types: [request.eventType],
|
|
243
|
-
maxCommitSeq: ready.eventWatermark,
|
|
244
|
-
maxEpochSeq: ready.epochSeq,
|
|
245
|
-
order: 'desc',
|
|
246
|
-
limit: 1,
|
|
247
|
-
})[0];
|
|
248
|
-
const visible = event?.deliveryClass !== 'internal_only' ? event : undefined;
|
|
249
|
-
const presented = visible
|
|
250
|
-
? presentCanonicalEventForCclEvents(visible, ready.state.state)
|
|
251
|
-
: null;
|
|
252
|
-
return {
|
|
253
|
-
output: {
|
|
254
|
-
schema: 'ccl.events.v5',
|
|
255
|
-
query: { type: request.eventType },
|
|
256
|
-
state: this.agentMailbox.stateForReadyView(ready),
|
|
257
|
-
found: !!presented,
|
|
258
|
-
event: presented,
|
|
259
|
-
},
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
let prepared;
|
|
264
|
-
try {
|
|
265
|
-
prepared = this.agentMailbox.prepareEvents({
|
|
266
|
-
readyView: ready,
|
|
267
|
-
bypassDelay: true,
|
|
268
|
-
deliveryVia: request.mode === 'backlog' ? 'ccl_events_backlog' : 'ccl_events',
|
|
269
|
-
ownerIdPrefix: 'ccl_events',
|
|
270
|
-
leaseTtlMs: CCL_EVENTS_LEASE_TTL_MS,
|
|
271
|
-
});
|
|
272
|
-
} catch (error) {
|
|
273
|
-
return cclEventsCompatibilityError(error);
|
|
50
|
+
if (error instanceof Error && error.message === 'agent_mailbox_delivery_busy') {
|
|
51
|
+
throw new Error('mailbox_events_delivery_busy');
|
|
274
52
|
}
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
schema: 'ccl.events.v5',
|
|
278
|
-
...prepared.batch,
|
|
279
|
-
},
|
|
280
|
-
...(prepared.deliveryToken ? { deliveryToken: prepared.deliveryToken } : {}),
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/** Serializes pull delivery while preserving the caller's immutable Ready View. */
|
|
285
|
-
async prepareEventsWhenAvailable(
|
|
286
|
-
request: PrepareClawclawEventsRequest = {},
|
|
287
|
-
readyView?: RuntimeReadyView,
|
|
288
|
-
timeoutMs = 5_000,
|
|
289
|
-
): Promise<PreparedClawclawEventsResponse> {
|
|
290
|
-
if (request.eventType) return this.prepareEvents(request, readyView);
|
|
291
|
-
this.assertRunning();
|
|
292
|
-
const ready = this.captureReadyView(readyView);
|
|
293
|
-
if (ready.epochSeq <= 0) return { output: unavailableEventsOutput() };
|
|
294
|
-
let prepared;
|
|
295
|
-
try {
|
|
296
|
-
prepared = await this.agentMailbox.prepareEventsWhenAvailable({
|
|
297
|
-
readyView: ready,
|
|
298
|
-
bypassDelay: true,
|
|
299
|
-
deliveryVia: request.mode === 'backlog' ? 'ccl_events_backlog' : 'ccl_events',
|
|
300
|
-
ownerIdPrefix: 'ccl_events',
|
|
301
|
-
leaseTtlMs: CCL_EVENTS_LEASE_TTL_MS,
|
|
302
|
-
}, timeoutMs);
|
|
303
|
-
} catch (error) {
|
|
304
|
-
return cclEventsCompatibilityError(error);
|
|
53
|
+
if (error instanceof Error && error.message === 'agent_mailbox_stopped') {
|
|
54
|
+
throw new Error('clawclaw_mailbox_stopped');
|
|
305
55
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
releaseEvents(deliveryToken: string): boolean {
|
|
320
|
-
return this.agentMailbox.release(deliveryToken);
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
/** Called by the Monitor Driver at its own cadence, never by each epoch. */
|
|
324
|
-
prepareMonitor(_force = false): number {
|
|
325
|
-
this.assertRunning();
|
|
326
|
-
if (!this.monitorEnabled) return 0;
|
|
327
|
-
const ready = this.captureReadyView();
|
|
328
|
-
if (ready.epochSeq <= 0) return 0;
|
|
329
|
-
this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId, ['monitor']);
|
|
330
|
-
const rows = this.repository.listEvents({
|
|
331
|
-
sessionId: ready.scope.sessionId,
|
|
332
|
-
deliveryClasses: ['monitor_and_events'],
|
|
333
|
-
monitorStates: ['pending'],
|
|
334
|
-
maxCommitSeq: ready.eventWatermark,
|
|
335
|
-
maxEpochSeq: ready.epochSeq,
|
|
336
|
-
order: 'asc',
|
|
337
|
-
}, this.consumerId, ['monitor']);
|
|
338
|
-
const unprojected = rows.filter((row) => !this.repository.mailboxItemForEvent(
|
|
339
|
-
this.consumerId,
|
|
340
|
-
row.event.eventId,
|
|
341
|
-
'short',
|
|
342
|
-
));
|
|
343
|
-
if (unprojected.length === 0 || !unprojected.some(({ event }) => event.wakeAgent !== false)) return 0;
|
|
344
|
-
|
|
345
|
-
const nowMs = this.now();
|
|
346
|
-
this.pruneMonitorAdmissionWindows(nowMs);
|
|
347
|
-
const ordinaryWindowItemsRemaining = Math.max(
|
|
348
|
-
0,
|
|
349
|
-
this.monitorOrdinaryWindowItemBudget - this.monitorOrdinaryAdmissionTimesMs.length,
|
|
350
|
-
);
|
|
351
|
-
const backlogHintWindowItemsRemaining = Math.max(
|
|
352
|
-
0,
|
|
353
|
-
this.monitorBacklogHintWindowItemBudget - this.monitorBacklogHintAdmissionTimesMs.length,
|
|
354
|
-
);
|
|
355
|
-
const visualAdmissionAvailable = this.monitorLastVisualAdmissionAtMs === undefined
|
|
356
|
-
|| nowMs - this.monitorLastVisualAdmissionAtMs >= this.monitorVisualMinIntervalMs;
|
|
357
|
-
const queuedItems = this.repository.peekMailbox<Record<string, unknown>>({
|
|
358
|
-
consumerId: this.consumerId,
|
|
359
|
-
sessionId: ready.scope.sessionId,
|
|
360
|
-
modes: ['short'],
|
|
361
|
-
states: ['pending', 'claimed'],
|
|
362
|
-
order: 'asc',
|
|
363
|
-
limit: this.monitorPendingItemLimit + MONITOR_PRIORITY_BYPASS_ITEM_LIMIT + 1,
|
|
364
|
-
});
|
|
365
|
-
const queuedItemCount = queuedItems.length;
|
|
366
|
-
const delegatedUnreadBefore = this.delegatedUnreadCount(ready);
|
|
367
|
-
if (delegatedUnreadBefore === 0) this.backlogHintEventId = undefined;
|
|
368
|
-
const queuedBacklogHint = queuedItems.find((item) => (
|
|
369
|
-
!!item.payload.backlog && typeof item.payload.backlog === 'object'
|
|
370
|
-
));
|
|
371
|
-
if (queuedBacklogHint) this.backlogHintEventId = queuedBacklogHint.eventId;
|
|
372
|
-
const storedBacklogHint = this.backlogHintEventId
|
|
373
|
-
? this.repository.mailboxItemForEvent(
|
|
374
|
-
this.consumerId,
|
|
375
|
-
this.backlogHintEventId,
|
|
376
|
-
'short',
|
|
377
|
-
)
|
|
378
|
-
: null;
|
|
379
|
-
const backlogHintOutstanding = !!queuedBacklogHint || (
|
|
380
|
-
delegatedUnreadBefore > 0
|
|
381
|
-
&& !!storedBacklogHint
|
|
382
|
-
&& storedBacklogHint.state !== 'suppressed'
|
|
383
|
-
);
|
|
384
|
-
const queuedBaseItemCount = queuedItems.filter((item) => (
|
|
385
|
-
!item.payload.backlog || typeof item.payload.backlog !== 'object'
|
|
386
|
-
)).length;
|
|
387
|
-
const availableBaseItemCount = Math.max(
|
|
388
|
-
0,
|
|
389
|
-
this.monitorPendingItemLimit - queuedBaseItemCount,
|
|
390
|
-
);
|
|
391
|
-
const usedPriorityBypassItemCount = Math.max(
|
|
392
|
-
0,
|
|
393
|
-
queuedBaseItemCount - this.monitorPendingItemLimit,
|
|
394
|
-
);
|
|
395
|
-
const availablePriorityBypassItemCount = Math.max(
|
|
396
|
-
0,
|
|
397
|
-
MONITOR_PRIORITY_BYPASS_ITEM_LIMIT - usedPriorityBypassItemCount,
|
|
398
|
-
);
|
|
399
|
-
const protectedEvents = unprojected
|
|
400
|
-
.filter((row) => monitorEventMustRemainDirect(row.event))
|
|
401
|
-
.sort((left, right) => (
|
|
402
|
-
monitorDirectAdmissionPriority(right.event)
|
|
403
|
-
- monitorDirectAdmissionPriority(left.event)
|
|
404
|
-
|| left.event.commitSeq - right.event.commitSeq
|
|
405
|
-
));
|
|
406
|
-
const protectedCapacity = availableBaseItemCount + availablePriorityBypassItemCount;
|
|
407
|
-
const directProtected = protectedEvents.slice(0, protectedCapacity);
|
|
408
|
-
const remainingBaseItemCount = Math.max(
|
|
409
|
-
0,
|
|
410
|
-
availableBaseItemCount - Math.min(directProtected.length, availableBaseItemCount),
|
|
411
|
-
);
|
|
412
|
-
const allOrdinaryEvents = unprojected
|
|
413
|
-
.filter((row) => !monitorEventMustRemainDirect(row.event));
|
|
414
|
-
const noisyVisualEvents = allOrdinaryEvents
|
|
415
|
-
.filter((row) => monitorEventIsNoisyVisual(row.event))
|
|
416
|
-
.sort((left, right) => left.event.commitSeq - right.event.commitSeq);
|
|
417
|
-
const directVisualCandidate = visualAdmissionAvailable ? [...noisyVisualEvents].sort((left, right) => (
|
|
418
|
-
clawclawMonitorEventPriority(right.event) - clawclawMonitorEventPriority(left.event)
|
|
419
|
-
|| right.event.commitSeq - left.event.commitSeq
|
|
420
|
-
))[0] : undefined;
|
|
421
|
-
const coalescedVisualOverflow = directVisualCandidate
|
|
422
|
-
? noisyVisualEvents.filter((row) => row !== directVisualCandidate)
|
|
423
|
-
: noisyVisualEvents;
|
|
424
|
-
const ordinaryEvents = allOrdinaryEvents
|
|
425
|
-
.filter((row) => !monitorEventIsNoisyVisual(row.event))
|
|
426
|
-
.concat(directVisualCandidate ? [directVisualCandidate] : [])
|
|
427
|
-
.sort((left, right) => (
|
|
428
|
-
clawclawMonitorEventPriority(right.event) - clawclawMonitorEventPriority(left.event)
|
|
429
|
-
|| ordinaryMonitorRetentionRank(left.event) - ordinaryMonitorRetentionRank(right.event)
|
|
430
|
-
|| left.event.commitSeq - right.event.commitSeq
|
|
431
|
-
));
|
|
432
|
-
const ordinaryDirectAdmissionCount = Math.min(
|
|
433
|
-
remainingBaseItemCount,
|
|
434
|
-
ordinaryWindowItemsRemaining,
|
|
435
|
-
);
|
|
436
|
-
const directOrdinary = ordinaryEvents.slice(0, ordinaryDirectAdmissionCount);
|
|
437
|
-
const ordinaryBudgetEventIds = new Set(
|
|
438
|
-
directOrdinary.map((row) => row.event.eventId),
|
|
439
|
-
);
|
|
440
|
-
let overflow = [
|
|
441
|
-
...ordinaryEvents.slice(ordinaryDirectAdmissionCount),
|
|
442
|
-
...coalescedVisualOverflow,
|
|
443
|
-
].sort((left, right) => left.event.commitSeq - right.event.commitSeq);
|
|
444
|
-
let direct = [...directProtected, ...directOrdinary]
|
|
445
|
-
.sort((left, right) => (
|
|
446
|
-
monitorDirectAdmissionPriority(right.event) - monitorDirectAdmissionPriority(left.event)
|
|
447
|
-
|| left.event.commitSeq - right.event.commitSeq
|
|
448
|
-
));
|
|
449
|
-
let dedicatedBacklogHintEventId: string | undefined;
|
|
450
|
-
// A full ordinary queue still needs one durable signal. Use the first new
|
|
451
|
-
// Event as that signal's factual anchor and allow one separately-budgeted
|
|
452
|
-
// item. The same bounded hint lane becomes available again as its rolling
|
|
453
|
-
// admission window advances after `ccl events` drains an earlier backlog.
|
|
454
|
-
if (
|
|
455
|
-
direct.length === 0
|
|
456
|
-
&& !backlogHintOutstanding
|
|
457
|
-
&& backlogHintWindowItemsRemaining > 0
|
|
458
|
-
&& (
|
|
459
|
-
queuedBaseItemCount >= this.monitorPendingItemLimit
|
|
460
|
-
|| ordinaryWindowItemsRemaining === 0
|
|
461
|
-
)
|
|
462
|
-
&& (overflow.length > 1 || (overflow.length > 0 && delegatedUnreadBefore > 0))
|
|
463
|
-
) {
|
|
464
|
-
const highestPriority = Math.max(...overflow.map(({ event }) => clawclawMonitorEventPriority(event)));
|
|
465
|
-
const preferred = overflow.filter(({ event }) => clawclawMonitorEventPriority(event) === highestPriority);
|
|
466
|
-
const firstNonVisualIndex = preferred.findIndex((row) => (
|
|
467
|
-
!row.event.type.startsWith('visual.')
|
|
468
|
-
));
|
|
469
|
-
const hintAnchorIndex = firstNonVisualIndex >= 0
|
|
470
|
-
? firstNonVisualIndex
|
|
471
|
-
: preferred.length - 1;
|
|
472
|
-
const hintAnchor = preferred[hintAnchorIndex]!;
|
|
473
|
-
direct = [hintAnchor];
|
|
474
|
-
dedicatedBacklogHintEventId = hintAnchor.event.eventId;
|
|
475
|
-
overflow = overflow.filter((row) => row !== hintAnchor);
|
|
476
|
-
}
|
|
477
|
-
if (direct.length === 0 && overflow.length === 0) return 0;
|
|
478
|
-
// With only one newly blocked Event there is no factual anchor plus
|
|
479
|
-
// durable remainder yet. Keep it pending/unprojected until either the
|
|
480
|
-
// ordinary queue gains capacity or a second Event forms a real backlog.
|
|
481
|
-
// A temporally eligible item blocked only by queue capacity remains
|
|
482
|
-
// pending until a second Event can anchor a durable backlog signal. An
|
|
483
|
-
// exhausted rolling window or visual rate limit recovers only with time,
|
|
484
|
-
// so delegate a quiet tail immediately instead of retaining stale output.
|
|
485
|
-
if (
|
|
486
|
-
direct.length === 0
|
|
487
|
-
&& !backlogHintOutstanding
|
|
488
|
-
&& delegatedUnreadBefore === 0
|
|
489
|
-
&& ordinaryWindowItemsRemaining > 0
|
|
490
|
-
&& ordinaryEvents.length > 0
|
|
491
|
-
) return 0;
|
|
492
|
-
|
|
493
|
-
const coalesceBase = `ready:${ready.scope.sessionId}:${ready.scope.segmentId}:${ready.epochSeq}`;
|
|
494
|
-
const payloads = direct.map((row) => monitorItemPayload(row.event, ready));
|
|
495
|
-
const anticipatedDelegatedUnreadCount = delegatedUnreadBefore + overflow.length;
|
|
496
|
-
const createsBacklogHint = (
|
|
497
|
-
!backlogHintOutstanding
|
|
498
|
-
&& payloads.length > 0
|
|
499
|
-
&& anticipatedDelegatedUnreadCount > 0
|
|
500
|
-
);
|
|
501
|
-
if (createsBacklogHint) {
|
|
502
|
-
payloads[0] = {
|
|
503
|
-
...payloads[0]!,
|
|
504
|
-
backlog: {
|
|
505
|
-
remaining_events: anticipatedDelegatedUnreadCount,
|
|
506
|
-
through_event_commit_seq: ready.eventWatermark,
|
|
507
|
-
command: 'ccl events',
|
|
508
|
-
},
|
|
509
|
-
};
|
|
510
|
-
}
|
|
511
|
-
const chunks = partitionClawclawMonitorItems(payloads);
|
|
512
|
-
const rowByEventId = new Map(direct.map((row) => [row.event.eventId, row]));
|
|
513
|
-
const entries = chunks.flatMap((chunk, chunkIndex) => {
|
|
514
|
-
const coalesceKey = chunks.length === 1
|
|
515
|
-
? coalesceBase
|
|
516
|
-
: `${coalesceBase}:chunk:${chunkIndex}`;
|
|
517
|
-
return chunk.map((payload) => {
|
|
518
|
-
const row = rowByEventId.get(payload.event_id);
|
|
519
|
-
if (!row) throw new Error(`mailbox_monitor_event_missing:${payload.event_id}`);
|
|
520
|
-
return { coalesceKey, payload, row };
|
|
521
|
-
});
|
|
522
|
-
});
|
|
523
|
-
// Reassign only delivery slots within this batch; canonical sequence is unchanged.
|
|
524
|
-
const slots = entries.map(({ row }) => row.event.commitSeq).sort((a, b) => a - b);
|
|
525
|
-
const deliveryOrder = new Map(entries.map((entry, index) => [entry.row.event.eventId, slots[index]!]));
|
|
526
|
-
const enqueue = (entry: typeof entries[number]) => {
|
|
527
|
-
const event = entry.row.event;
|
|
528
|
-
return this.repository.enqueueMailboxItem<Record<string, unknown>>({
|
|
529
|
-
itemId: stableMailboxItemId({
|
|
530
|
-
consumerId: this.consumerId,
|
|
531
|
-
sessionId: event.sessionId,
|
|
532
|
-
eventId: event.eventId,
|
|
533
|
-
mode: 'short',
|
|
534
|
-
}),
|
|
535
|
-
schemaVersion: 1,
|
|
536
|
-
formatterVersion: `${MONITOR_FORMATTER_VERSION}:short`,
|
|
537
|
-
consumerId: this.consumerId,
|
|
538
|
-
sessionId: event.sessionId,
|
|
539
|
-
segmentId: event.segmentId,
|
|
540
|
-
eventId: event.eventId,
|
|
541
|
-
eventCommitSeq: event.commitSeq,
|
|
542
|
-
deliveryOrder: deliveryOrder.get(event.eventId),
|
|
543
|
-
mode: 'short',
|
|
544
|
-
coalesceKey: entry.coalesceKey,
|
|
545
|
-
payload: entry.payload,
|
|
546
|
-
availableAtMs: nowMs,
|
|
547
|
-
createdAt: new Date(nowMs).toISOString(),
|
|
548
|
-
});
|
|
549
|
-
};
|
|
550
|
-
let inserted = 0;
|
|
551
|
-
const accountInserted = (
|
|
552
|
-
entry: typeof entries[number],
|
|
553
|
-
wasInserted: boolean,
|
|
554
|
-
): void => {
|
|
555
|
-
if (!wasInserted) return;
|
|
556
|
-
inserted += 1;
|
|
557
|
-
if (ordinaryBudgetEventIds.has(entry.row.event.eventId)) {
|
|
558
|
-
this.monitorOrdinaryAdmissionTimesMs.push(nowMs);
|
|
559
|
-
}
|
|
560
|
-
if (entry.row.event.eventId === dedicatedBacklogHintEventId) {
|
|
561
|
-
this.monitorBacklogHintAdmissionTimesMs.push(nowMs);
|
|
562
|
-
}
|
|
563
|
-
if (monitorEventIsNoisyVisual(entry.row.event)) {
|
|
564
|
-
this.monitorLastVisualAdmissionAtMs = nowMs;
|
|
565
|
-
}
|
|
566
|
-
};
|
|
567
|
-
let persistedHintEntry: typeof entries[number] | undefined;
|
|
568
|
-
if (createsBacklogHint) {
|
|
569
|
-
const hintEntry = entries.find((entry) => (
|
|
570
|
-
!!entry.payload.backlog && typeof entry.payload.backlog === 'object'
|
|
571
|
-
));
|
|
572
|
-
if (!hintEntry) throw new Error('mailbox_monitor_backlog_hint_missing');
|
|
573
|
-
const result = enqueue(hintEntry);
|
|
574
|
-
const persisted = result.inserted || (
|
|
575
|
-
!!result.item.payload.backlog && typeof result.item.payload.backlog === 'object'
|
|
576
|
-
);
|
|
577
|
-
if (!persisted) return 0;
|
|
578
|
-
accountInserted(hintEntry, result.inserted);
|
|
579
|
-
persistedHintEntry = hintEntry;
|
|
580
|
-
this.backlogHintEventId = hintEntry.row.event.eventId;
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
// The unique hint anchor is now durable (or an older accepted/pending hint
|
|
584
|
-
// is still outstanding), so suppressing the remainder cannot orphan it.
|
|
585
|
-
const delegatedCount = this.delegateMonitorOverflow(
|
|
586
|
-
overflow.map((row) => row.event.eventId),
|
|
587
|
-
nowMs,
|
|
588
|
-
);
|
|
589
|
-
if (createsBacklogHint) {
|
|
590
|
-
const delegatedUnreadCount = this.delegatedUnreadCount(ready);
|
|
591
|
-
this.diagnostic?.('runtime.mailbox.monitor_backlog_delegated', {
|
|
592
|
-
consumer_id: this.consumerId,
|
|
593
|
-
session_id: ready.scope.sessionId,
|
|
594
|
-
segment_id: ready.scope.segmentId,
|
|
595
|
-
ready_epoch_seq: ready.epochSeq,
|
|
596
|
-
event_watermark: ready.eventWatermark,
|
|
597
|
-
pending_item_limit: this.monitorPendingItemLimit,
|
|
598
|
-
queued_item_count: queuedItemCount,
|
|
599
|
-
direct_event_count: direct.length,
|
|
600
|
-
delegated_event_count: delegatedCount,
|
|
601
|
-
unread_delegated_event_count: delegatedUnreadCount,
|
|
602
|
-
}, 'info');
|
|
603
|
-
}
|
|
604
|
-
for (const entry of entries) {
|
|
605
|
-
if (entry === persistedHintEntry) continue;
|
|
606
|
-
const result = enqueue(entry);
|
|
607
|
-
accountInserted(entry, result.inserted);
|
|
608
|
-
}
|
|
609
|
-
if (payloads.length === 0) {
|
|
610
|
-
// This path uses an already durable backlog hint and only delegates new
|
|
611
|
-
// ordinary Events, so there is intentionally no new Mailbox item.
|
|
612
|
-
return 0;
|
|
613
|
-
}
|
|
614
|
-
if (inserted > 0 && chunks.length > 1) {
|
|
615
|
-
const eventTypeCounts: Record<string, number> = {};
|
|
616
|
-
for (const payload of payloads) {
|
|
617
|
-
const type = String(payload.event.type ?? 'event');
|
|
618
|
-
eventTypeCounts[type] = (eventTypeCounts[type] ?? 0) + 1;
|
|
619
|
-
}
|
|
620
|
-
this.diagnostic?.('runtime.mailbox.monitor_batch_split', {
|
|
621
|
-
consumer_id: this.consumerId,
|
|
622
|
-
session_id: ready.scope.sessionId,
|
|
623
|
-
segment_id: ready.scope.segmentId,
|
|
624
|
-
ready_epoch_seq: ready.epochSeq,
|
|
625
|
-
event_watermark: ready.eventWatermark,
|
|
626
|
-
event_count: payloads.length,
|
|
627
|
-
inserted_event_count: inserted,
|
|
628
|
-
notification_count: chunks.length,
|
|
629
|
-
events_per_notification: chunks.map((chunk) => chunk.length),
|
|
630
|
-
notification_char_counts: chunks.map((chunk) => (
|
|
631
|
-
JSON.stringify(composeClawclawMonitorNotification(chunk)).length
|
|
632
|
-
)),
|
|
633
|
-
event_type_counts: eventTypeCounts,
|
|
634
|
-
}, 'info');
|
|
635
|
-
}
|
|
636
|
-
return inserted;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/** Monitor delivery reports every perception covered by the accepted Ready batch.
|
|
640
|
-
* A backlog hint counts as delivery for display; detail ACK is independent.
|
|
641
|
-
*/
|
|
642
|
-
monitorDeliveredEvents(eventIds: readonly string[]): CanonicalEvent[] {
|
|
643
|
-
const bounds = new Map<string, number>();
|
|
644
|
-
for (const id of eventIds) {
|
|
645
|
-
const item = this.repository.mailboxItemForEvent<Record<string, any>>(this.consumerId, id, 'short');
|
|
646
|
-
if (!item || item.state !== 'accepted') continue;
|
|
647
|
-
const through = Number(item.payload.ready?.event_commit_seq ?? item.eventCommitSeq);
|
|
648
|
-
bounds.set(item.sessionId, Math.max(bounds.get(item.sessionId) ?? 0, through));
|
|
649
|
-
}
|
|
650
|
-
const events: CanonicalEvent[] = [];
|
|
651
|
-
for (const [sessionId, through] of bounds) {
|
|
652
|
-
events.push(...this.repository.listCommittedEvents({ sessionId, maxCommitSeq: through, order: 'asc' }));
|
|
653
|
-
}
|
|
654
|
-
return events;
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
composeMonitor(values: readonly Record<string, unknown>[]): Record<string, unknown> {
|
|
658
|
-
const hasBacklog = values.some((value) => (
|
|
659
|
-
!!value.backlog && typeof value.backlog === 'object'
|
|
660
|
-
));
|
|
661
|
-
if (!hasBacklog) return composeClawclawMonitorNotification(values);
|
|
662
|
-
const ready = this.captureReadyView();
|
|
663
|
-
const remainingEvents = this.delegatedUnreadCount(ready);
|
|
664
|
-
const refreshed = values.map((value) => {
|
|
665
|
-
if (!value.backlog || typeof value.backlog !== 'object') return value;
|
|
666
|
-
const { backlog: _backlog, ...withoutBacklog } = value;
|
|
667
|
-
if (remainingEvents === 0) return withoutBacklog;
|
|
668
|
-
return {
|
|
669
|
-
...withoutBacklog,
|
|
670
|
-
backlog: {
|
|
671
|
-
remaining_events: remainingEvents,
|
|
672
|
-
through_event_commit_seq: ready.eventWatermark,
|
|
673
|
-
command: 'ccl events',
|
|
674
|
-
},
|
|
675
|
-
};
|
|
676
|
-
});
|
|
677
|
-
return composeClawclawMonitorNotification(refreshed);
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
async flush(): Promise<void> {
|
|
681
|
-
if (!this.stopped) this.prepareMonitor(true);
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
async stop(): Promise<void> {
|
|
685
|
-
if (this.stopped) return;
|
|
686
|
-
await this.flush();
|
|
687
|
-
this.stopped = true;
|
|
688
|
-
if (this.ownsAgentMailbox) await this.agentMailbox.stop();
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
private delegateMonitorOverflow(eventIds: readonly string[], nowMs: number): number {
|
|
692
|
-
if (eventIds.length === 0) return 0;
|
|
693
|
-
const lease = this.repository.acquireLease({
|
|
694
|
-
consumerId: this.consumerId,
|
|
695
|
-
channel: 'monitor',
|
|
696
|
-
ownerId: `${this.consumerId}:monitor-overflow`,
|
|
697
|
-
ttlMs: MONITOR_OVERFLOW_LEASE_TTL_MS,
|
|
698
|
-
nowMs,
|
|
699
|
-
});
|
|
700
|
-
if (!lease) return 0;
|
|
701
|
-
let changed = 0;
|
|
702
|
-
try {
|
|
703
|
-
for (let offset = 0; offset < eventIds.length; offset += MONITOR_OVERFLOW_TRANSITION_BATCH_SIZE) {
|
|
704
|
-
changed += this.repository.transitionMonitor({
|
|
705
|
-
eventIds: eventIds.slice(offset, offset + MONITOR_OVERFLOW_TRANSITION_BATCH_SIZE),
|
|
706
|
-
consumerId: this.consumerId,
|
|
707
|
-
from: ['pending'],
|
|
708
|
-
to: 'suppressed',
|
|
709
|
-
lease,
|
|
710
|
-
nowMs,
|
|
711
|
-
});
|
|
712
|
-
}
|
|
713
|
-
return changed;
|
|
714
|
-
} finally {
|
|
715
|
-
this.repository.releaseLease(lease);
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
private delegatedUnreadCount(ready: RuntimeReadyView): number {
|
|
720
|
-
const suppressed = this.repository.listEvents({
|
|
721
|
-
sessionId: ready.scope.sessionId,
|
|
722
|
-
deliveryClasses: ['monitor_and_events'],
|
|
723
|
-
monitorStates: ['suppressed'],
|
|
724
|
-
maxCommitSeq: ready.eventWatermark,
|
|
725
|
-
maxEpochSeq: ready.epochSeq,
|
|
726
|
-
order: 'asc',
|
|
727
|
-
}, this.consumerId, ['monitor']);
|
|
728
|
-
if (suppressed.length === 0) return 0;
|
|
729
|
-
this.repository.ensureDeliveries(
|
|
730
|
-
ready.scope.sessionId,
|
|
731
|
-
this.delegatedDetailsConsumerId,
|
|
732
|
-
['details'],
|
|
733
|
-
);
|
|
734
|
-
return suppressed.filter((row) => {
|
|
735
|
-
const state = this.repository.delivery(
|
|
736
|
-
row.event.eventId,
|
|
737
|
-
this.delegatedDetailsConsumerId,
|
|
738
|
-
)?.detailState;
|
|
739
|
-
return state === 'pending' || state === 'deferred';
|
|
740
|
-
}).length;
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
private pruneMonitorAdmissionWindows(nowMs: number): void {
|
|
744
|
-
const cutoffMs = nowMs - this.monitorAdmissionWindowMs;
|
|
745
|
-
while (
|
|
746
|
-
this.monitorOrdinaryAdmissionTimesMs.length > 0
|
|
747
|
-
&& this.monitorOrdinaryAdmissionTimesMs[0]! <= cutoffMs
|
|
748
|
-
) this.monitorOrdinaryAdmissionTimesMs.shift();
|
|
749
|
-
while (
|
|
750
|
-
this.monitorBacklogHintAdmissionTimesMs.length > 0
|
|
751
|
-
&& this.monitorBacklogHintAdmissionTimesMs[0]! <= cutoffMs
|
|
752
|
-
) this.monitorBacklogHintAdmissionTimesMs.shift();
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
private captureReadyView(readyView?: RuntimeReadyView): RuntimeReadyView {
|
|
756
|
-
const ready = structuredClone(readyView ?? this.readyView());
|
|
757
|
-
if (ready.epochSeq > this.lastObservedReadyEpochSeq) {
|
|
758
|
-
this.diagnostic?.('runtime.mailbox.ready_advanced', {
|
|
759
|
-
previous_ready_epoch_seq: this.lastObservedReadyEpochSeq,
|
|
760
|
-
ready_epoch_seq: ready.epochSeq,
|
|
761
|
-
event_commit_seq: ready.eventWatermark,
|
|
762
|
-
frame_seq: ready.frameSeq,
|
|
763
|
-
});
|
|
764
|
-
this.lastObservedReadyEpochSeq = ready.epochSeq;
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
export class ClawclawMailboxService extends MailboxService {
|
|
59
|
+
constructor(options: ClawclawMailboxServiceOptions) {
|
|
60
|
+
super({ ...options, policy: { monitorAdapterId: 'clawclaw.mailbox.adapter.monitor', querySchema: 'ccl.events.v5',
|
|
61
|
+
formatterVersion: 'clawclaw.monitor.v4', detailPrefix: 'ccl_events', detailsCommand: 'ccl events', stoppedError: 'clawclaw_mailbox_stopped',
|
|
62
|
+
admitEvent: isClawclawAgentNotification, presentEvent: presentCanonicalEventForCclEvents,
|
|
63
|
+
compactState: compactStateForEvents, projectState: projectClawclawMailboxState, requiresDetails: clawclawEventRequiresDetails,
|
|
64
|
+
mustRemainDirect: monitorEventMustRemainDirect, admissionPriority: monitorDirectAdmissionPriority, retentionRank: ordinaryMonitorRetentionRank,
|
|
65
|
+
isRateLimited: monitorEventIsNoisyVisual, isTelemetry: event => event.type.startsWith('visual.'), priority: clawclawMonitorEventPriority,
|
|
66
|
+
item: monitorItemPayload, partition: items => partitionClawclawMonitorItems(items as ClawclawMonitorItemPayload[]),
|
|
67
|
+
compose: composeClawclawMonitorNotification, mapError: cclEventsCompatibilityError } });
|
|
765
68
|
}
|
|
766
|
-
return ready;
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
private assertRunning(): void {
|
|
770
|
-
if (this.stopped) throw new Error('clawclaw_mailbox_stopped');
|
|
771
|
-
}
|
|
772
69
|
}
|