@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.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/README.md +67 -2
- package/dist/framework/action-diagnostics.d.ts +11 -0
- package/dist/framework/action-diagnostics.js +67 -0
- package/dist/framework/capability-registry.d.ts +58 -0
- package/dist/framework/capability-registry.js +325 -0
- package/dist/framework/contracts.d.ts +121 -0
- package/dist/framework/contracts.js +2 -0
- package/dist/framework/control/control-scheduler.d.ts +69 -0
- package/dist/framework/control/control-scheduler.js +1016 -0
- package/dist/framework/control/domain-set.d.ts +18 -0
- package/dist/framework/control/domain-set.js +70 -0
- package/dist/framework/control/index.d.ts +3 -0
- package/dist/framework/control/index.js +3 -0
- package/dist/framework/control/types.d.ts +142 -0
- package/dist/framework/control/types.js +13 -0
- package/dist/framework/control-coordinator.d.ts +7 -0
- package/dist/framework/control-coordinator.js +7 -0
- package/dist/framework/events/event-catalog.d.ts +23 -0
- package/dist/framework/events/event-catalog.js +52 -0
- package/dist/framework/events/event-delivery-service.d.ts +33 -0
- package/dist/framework/events/event-delivery-service.js +165 -0
- package/dist/framework/events/event-ingress.d.ts +28 -0
- package/dist/framework/events/event-ingress.js +76 -0
- package/dist/framework/events/event-repository.d.ts +38 -0
- package/dist/framework/events/event-repository.js +20 -0
- package/dist/framework/events/index.d.ts +7 -0
- package/dist/framework/events/index.js +7 -0
- package/dist/framework/events/memory-event-repository.d.ts +77 -0
- package/dist/framework/events/memory-event-repository.js +909 -0
- package/dist/framework/events/runtime-resume.d.ts +11 -0
- package/dist/framework/events/runtime-resume.js +7 -0
- package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
- package/dist/framework/events/sqlite-event-repository.js +2044 -0
- package/dist/framework/events/store-compatibility.d.ts +17 -0
- package/dist/framework/events/store-compatibility.js +17 -0
- package/dist/framework/events/types.d.ts +244 -0
- package/dist/framework/events/types.js +39 -0
- package/dist/framework/index.d.ts +7 -0
- package/dist/framework/index.js +7 -0
- package/dist/framework/load-node-sqlite.d.ts +5 -0
- package/dist/framework/load-node-sqlite.js +19 -0
- package/dist/framework/mailbox/coalescer.d.ts +30 -0
- package/dist/framework/mailbox/coalescer.js +45 -0
- package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
- package/dist/framework/mailbox/host-notification-sink.js +13 -0
- package/dist/framework/mailbox/identity.d.ts +15 -0
- package/dist/framework/mailbox/identity.js +28 -0
- package/dist/framework/mailbox/index.d.ts +7 -0
- package/dist/framework/mailbox/index.js +7 -0
- package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
- package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
- package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
- package/dist/framework/mailbox/mailbox-repository.js +9 -0
- package/dist/framework/mailbox/notification-projector.d.ts +25 -0
- package/dist/framework/mailbox/notification-projector.js +50 -0
- package/dist/framework/mailbox/types.d.ts +128 -0
- package/dist/framework/mailbox/types.js +1 -0
- package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
- package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
- package/dist/framework/modules/runtime-module-loader.js +64 -0
- package/dist/framework/modules/runtime-module-output.d.ts +7 -0
- package/dist/framework/modules/runtime-module-output.js +15 -0
- package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
- package/dist/framework/participation-manager.d.ts +94 -0
- package/dist/framework/participation-manager.js +185 -0
- package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
- package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
- package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
- package/dist/framework/persistence/memory-first-persistence.js +459 -0
- package/dist/framework/plugins/contracts.d.ts +345 -0
- package/dist/framework/plugins/contracts.js +1 -0
- package/dist/framework/plugins/index.d.ts +4 -0
- package/dist/framework/plugins/index.js +4 -0
- package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
- package/dist/framework/plugins/runtime-event-identity.js +11 -0
- package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
- package/dist/framework/plugins/runtime-input-journal.js +716 -0
- package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
- package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
- package/dist/framework/runtime.d.ts +264 -0
- package/dist/framework/runtime.js +1811 -0
- package/dist/framework/serial-task-queue.d.ts +6 -0
- package/dist/framework/serial-task-queue.js +12 -0
- package/dist/framework/state/contracts.d.ts +30 -0
- package/dist/framework/state/contracts.js +1 -0
- package/dist/framework/state/current-state-store.d.ts +17 -0
- package/dist/framework/state/current-state-store.js +153 -0
- package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
- package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
- package/dist/framework/state/freshness.d.ts +7 -0
- package/dist/framework/state/freshness.js +52 -0
- package/dist/framework/state/history/contracts.d.ts +133 -0
- package/dist/framework/state/history/contracts.js +1 -0
- package/dist/framework/state/history/history-writer.d.ts +55 -0
- package/dist/framework/state/history/history-writer.js +157 -0
- package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
- package/dist/framework/state/history/memory-state-history-repository.js +199 -0
- package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
- package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
- package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
- package/dist/framework/state/history/trajectory-projector.js +130 -0
- package/dist/framework/state/index.d.ts +12 -0
- package/dist/framework/state/index.js +12 -0
- package/dist/framework/state/state-ingress.d.ts +18 -0
- package/dist/framework/state/state-ingress.js +68 -0
- package/dist/framework/state/state-provider.d.ts +11 -0
- package/dist/framework/state/state-provider.js +56 -0
- package/dist/framework/state/types.d.ts +107 -0
- package/dist/framework/state/types.js +19 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
- package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
- package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
- package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
- package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
- package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
- package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
- package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
- package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
- package/dist/mailbox/host-monitor-rate-gate.js +93 -0
- package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
- package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
- package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
- package/dist/mailbox/mailbox-host-relay.js +299 -0
- package/dist/mailbox/mailbox-plugin.d.ts +58 -0
- package/dist/mailbox/mailbox-plugin.js +128 -0
- package/dist/mailbox/mailbox-service.d.ts +128 -0
- package/dist/mailbox/mailbox-service.js +582 -0
- package/dist/memory/contracts.d.ts +12 -0
- package/dist/memory/contracts.js +1 -0
- package/dist/memory/strategy-memory-rpc.d.ts +21 -0
- package/dist/memory/strategy-memory-rpc.js +86 -0
- package/dist/memory/strategy-memory.d.ts +15 -0
- package/dist/memory/strategy-memory.js +95 -0
- package/dist/observability/detail-capture.d.ts +25 -0
- package/dist/observability/detail-capture.js +136 -0
- package/dist/observability/index.d.ts +5 -0
- package/dist/observability/index.js +5 -0
- package/dist/observability/process-timing.d.ts +14 -0
- package/dist/observability/process-timing.js +56 -0
- package/dist/observability/recorder.d.ts +56 -0
- package/dist/observability/recorder.js +202 -0
- package/dist/observability/redaction.d.ts +30 -0
- package/dist/observability/redaction.js +166 -0
- package/dist/observability/reporter.d.ts +32 -0
- package/dist/observability/reporter.js +140 -0
- package/dist/observability/sinks.d.ts +36 -0
- package/dist/observability/sinks.js +121 -0
- package/dist/observability/types.d.ts +81 -0
- package/dist/observability/types.js +1 -0
- package/dist/owner/control-channel.d.ts +42 -0
- package/dist/owner/control-channel.js +188 -0
- package/dist/owner/parent-process-watch.d.ts +15 -0
- package/dist/owner/parent-process-watch.js +40 -0
- package/dist/owner/process-identity.d.ts +10 -0
- package/dist/owner/process-identity.js +65 -0
- package/dist/owner/runtime-lock.d.ts +5 -0
- package/dist/owner/runtime-lock.js +47 -0
- package/dist/perception/binding-resolution.d.ts +9 -0
- package/dist/perception/binding-resolution.js +14 -0
- package/dist/perception/contracts.d.ts +85 -0
- package/dist/perception/contracts.js +1 -0
- package/dist/perception/map-concurrent.d.ts +2 -0
- package/dist/perception/map-concurrent.js +12 -0
- package/dist/perception/perception-host.d.ts +114 -0
- package/dist/perception/perception-host.js +338 -0
- package/dist/perception/perception-worker-host.d.ts +11 -0
- package/dist/perception/perception-worker-host.js +44 -0
- package/dist/perception/perception-worker.d.ts +21 -0
- package/dist/perception/perception-worker.js +77 -0
- package/dist/perception/strategy-names.d.ts +7 -0
- package/dist/perception/strategy-names.js +22 -0
- package/dist/sdk/perception.d.ts +5 -0
- package/dist/sdk/perception.js +6 -0
- package/dist/sdk/strategy.d.ts +6 -0
- package/dist/sdk/strategy.js +3 -0
- package/dist/strategy/activation-manager.d.ts +105 -0
- package/dist/strategy/activation-manager.js +367 -0
- package/dist/strategy/behavior-decision-history.d.ts +20 -0
- package/dist/strategy/behavior-decision-history.js +59 -0
- package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
- package/dist/strategy/behavior-instance-snapshot.js +145 -0
- package/dist/strategy/contracts.d.ts +189 -0
- package/dist/strategy/contracts.js +1 -0
- package/dist/strategy/control-driver.d.ts +25 -0
- package/dist/strategy/control-driver.js +131 -0
- package/dist/strategy/in-process-runner.d.ts +25 -0
- package/dist/strategy/in-process-runner.js +40 -0
- package/dist/strategy/strategy-host.d.ts +165 -0
- package/dist/strategy/strategy-host.js +1456 -0
- package/dist/strategy/strategy-script-runner.d.ts +81 -0
- package/dist/strategy/strategy-script-runner.js +235 -0
- package/dist/strategy/strategy-worker-host.d.ts +27 -0
- package/dist/strategy/strategy-worker-host.js +96 -0
- package/dist/strategy/thread-strategy-executor.d.ts +120 -0
- package/dist/strategy/thread-strategy-executor.js +778 -0
- package/examples/grid-game.mjs +129 -0
- package/examples/grid-perception-worker.mjs +6 -0
- package/examples/grid-perception.mjs +12 -0
- package/examples/grid-strategy-worker.mjs +11 -0
- package/examples/grid-strategy.mjs +13 -0
- package/examples/run-grid-game.mjs +24 -0
- package/package.json +53 -4
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { type CanonicalEvent, type DetailDeliveryVia, type EventRepository } from '../framework/events/index.js';
|
|
2
|
+
import type { RuntimeReadyView } from '../framework/runtime.js';
|
|
3
|
+
import type { MailboxAdapterDescriptor } from './mailbox-plugin.js';
|
|
4
|
+
export declare const AGENT_MAILBOX_COALESCE_MS = 220;
|
|
5
|
+
export type AgentMailboxDeliveryVia = DetailDeliveryVia;
|
|
6
|
+
export interface AgentMailboxBatch {
|
|
7
|
+
state: Record<string, unknown> | null;
|
|
8
|
+
events: Array<Record<string, unknown> | string>;
|
|
9
|
+
}
|
|
10
|
+
export interface PreparedAgentMailboxBatch {
|
|
11
|
+
batch: AgentMailboxBatch;
|
|
12
|
+
deliveryToken?: string;
|
|
13
|
+
readyEpochSeq: number;
|
|
14
|
+
/** Earliest useful retry when the coalescing or Ready View boundary is pending. */
|
|
15
|
+
nextAttemptAtMs?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface PrepareAgentMailboxBatchOptions {
|
|
18
|
+
readyView?: RuntimeReadyView;
|
|
19
|
+
/** Pull adapters use an explicit query boundary and do not need push coalescing. */
|
|
20
|
+
bypassDelay?: boolean;
|
|
21
|
+
deliveryVia?: AgentMailboxDeliveryVia;
|
|
22
|
+
ownerIdPrefix?: string;
|
|
23
|
+
/** Adapter-specific lease lifetime; omitted adapters use the Mailbox default. */
|
|
24
|
+
leaseTtlMs?: number;
|
|
25
|
+
}
|
|
26
|
+
export interface AgentMailboxCoordinatorOptions {
|
|
27
|
+
projectState?: (state: Record<string, any>, ready: RuntimeReadyView) => Record<string, any>;
|
|
28
|
+
repository: EventRepository;
|
|
29
|
+
readyView: () => RuntimeReadyView;
|
|
30
|
+
presentEvent: (event: CanonicalEvent, state: Record<string, any> | null | undefined) => Record<string, unknown> | string;
|
|
31
|
+
compactState: (state: Record<string, any> | null | undefined, events?: Array<Record<string, any>>) => Record<string, any> | null;
|
|
32
|
+
/** Best-effort observer after this consumer accepts a batch. */
|
|
33
|
+
onDelivered?: (events: readonly CanonicalEvent[]) => void;
|
|
34
|
+
/** Mandatory admission gate, applied before every adapter selection or backlog rule. */
|
|
35
|
+
admitEvent?: (event: CanonicalEvent) => boolean;
|
|
36
|
+
/** Adapter-specific selection; omitted adapters receive every Agent-visible Event. */
|
|
37
|
+
eventFilter?: (event: CanonicalEvent, state: Record<string, any> | null | undefined) => boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Also pull Events deliberately delegated by a Monitor lane. This is used
|
|
40
|
+
* when a bounded short-notification queue suppresses its overflow and tells
|
|
41
|
+
* the Agent to read the durable remainder with the explicit event query.
|
|
42
|
+
*/
|
|
43
|
+
delegatedMonitorConsumerId?: string;
|
|
44
|
+
consumerId?: string;
|
|
45
|
+
/** Declares this coordinator when it is itself a complete output adapter. */
|
|
46
|
+
adapter?: MailboxAdapterDescriptor;
|
|
47
|
+
coalesceMs?: number;
|
|
48
|
+
leaseTtlMs?: number;
|
|
49
|
+
now?: () => number;
|
|
50
|
+
diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Durable Agent communication core owned by the Mailbox Plugin.
|
|
54
|
+
*
|
|
55
|
+
* One instance owns exactly one output consumer: Ready View selection, full
|
|
56
|
+
* Agent presentation, coalescing and its details lease. Desktop IPC, Claude
|
|
57
|
+
* Channels and legacy pull commands use separate instances so every output
|
|
58
|
+
* advances only its own ACK state.
|
|
59
|
+
*/
|
|
60
|
+
export declare class AgentMailboxCoordinator {
|
|
61
|
+
readonly adapter?: MailboxAdapterDescriptor;
|
|
62
|
+
private readonly onDelivered?;
|
|
63
|
+
private readonly repository;
|
|
64
|
+
private readonly readyView;
|
|
65
|
+
private readonly presentEvent;
|
|
66
|
+
private readonly projectState?;
|
|
67
|
+
private readonly compactState;
|
|
68
|
+
private readonly eventFilter;
|
|
69
|
+
private readonly admitEvent;
|
|
70
|
+
private readonly delegatedMonitorConsumerId?;
|
|
71
|
+
private readonly consumerId;
|
|
72
|
+
private readonly coalesceMs;
|
|
73
|
+
private readonly leaseTtlMs;
|
|
74
|
+
private readonly now;
|
|
75
|
+
private readonly diagnostic?;
|
|
76
|
+
private readonly prepared;
|
|
77
|
+
private readonly preparedSlotWaiters;
|
|
78
|
+
private prepareTail;
|
|
79
|
+
private delayWindow?;
|
|
80
|
+
private lastObservedReadyEpochSeq;
|
|
81
|
+
private stopped;
|
|
82
|
+
constructor(options: AgentMailboxCoordinatorOptions);
|
|
83
|
+
prepare(options?: PrepareAgentMailboxBatchOptions): PreparedAgentMailboxBatch;
|
|
84
|
+
/** Selects and projects one durable Agent-facing Event batch. */
|
|
85
|
+
prepareEvents(options?: PrepareAgentMailboxBatchOptions): PreparedAgentMailboxBatch;
|
|
86
|
+
prepareWhenAvailable(options?: PrepareAgentMailboxBatchOptions, timeoutMs?: number): Promise<PreparedAgentMailboxBatch>;
|
|
87
|
+
prepareEventsWhenAvailable(options?: PrepareAgentMailboxBatchOptions, timeoutMs?: number): Promise<PreparedAgentMailboxBatch>;
|
|
88
|
+
stateForReadyView(readyView?: RuntimeReadyView): Record<string, any> | null;
|
|
89
|
+
ack(deliveryToken: string, acceptanceLevel?: import('../framework/mailbox/types.js').MailboxAcceptanceLevel): boolean;
|
|
90
|
+
renew(deliveryToken: string): boolean;
|
|
91
|
+
release(deliveryToken: string): boolean;
|
|
92
|
+
observeEvents(events: readonly CanonicalEvent[]): void;
|
|
93
|
+
flush(): Promise<void>;
|
|
94
|
+
waitForDrain(shouldAbort?: () => boolean): Promise<boolean>;
|
|
95
|
+
stop(): Promise<void>;
|
|
96
|
+
private selectsEvent;
|
|
97
|
+
private captureReadyView;
|
|
98
|
+
private compactReadyState;
|
|
99
|
+
private releaseExpiredPrepared;
|
|
100
|
+
private renewPreparedLease;
|
|
101
|
+
private waitForPreparedSlot;
|
|
102
|
+
private notifyPreparedSlotAvailable;
|
|
103
|
+
private assertRunning;
|
|
104
|
+
}
|
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { DEFAULT_EVENT_CONSUMER_ID, validateDetailDeliveryVia, } from '../framework/events/index.js';
|
|
3
|
+
export const AGENT_MAILBOX_COALESCE_MS = 220;
|
|
4
|
+
const AGENT_MAILBOX_LEASE_TTL_MS = 5 * 60_000;
|
|
5
|
+
const AGENT_MAILBOX_PREPARE_WAIT_MS = 5_000;
|
|
6
|
+
const READY_VIEW_RETRY_MS = 25;
|
|
7
|
+
function emptyBatch(state = null) {
|
|
8
|
+
return { state, events: [] };
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Durable Agent communication core owned by the Mailbox Plugin.
|
|
12
|
+
*
|
|
13
|
+
* One instance owns exactly one output consumer: Ready View selection, full
|
|
14
|
+
* Agent presentation, coalescing and its details lease. Desktop IPC, Claude
|
|
15
|
+
* Channels and legacy pull commands use separate instances so every output
|
|
16
|
+
* advances only its own ACK state.
|
|
17
|
+
*/
|
|
18
|
+
export class AgentMailboxCoordinator {
|
|
19
|
+
adapter;
|
|
20
|
+
onDelivered;
|
|
21
|
+
repository;
|
|
22
|
+
readyView;
|
|
23
|
+
presentEvent;
|
|
24
|
+
projectState;
|
|
25
|
+
compactState;
|
|
26
|
+
eventFilter;
|
|
27
|
+
admitEvent;
|
|
28
|
+
delegatedMonitorConsumerId;
|
|
29
|
+
consumerId;
|
|
30
|
+
coalesceMs;
|
|
31
|
+
leaseTtlMs;
|
|
32
|
+
now;
|
|
33
|
+
diagnostic;
|
|
34
|
+
prepared = new Map();
|
|
35
|
+
preparedSlotWaiters = new Set();
|
|
36
|
+
prepareTail = Promise.resolve();
|
|
37
|
+
delayWindow;
|
|
38
|
+
lastObservedReadyEpochSeq = 0;
|
|
39
|
+
stopped = false;
|
|
40
|
+
constructor(options) {
|
|
41
|
+
this.onDelivered = options.onDelivered;
|
|
42
|
+
this.repository = options.repository;
|
|
43
|
+
this.readyView = options.readyView;
|
|
44
|
+
this.presentEvent = options.presentEvent;
|
|
45
|
+
this.compactState = options.compactState;
|
|
46
|
+
this.projectState = options.projectState;
|
|
47
|
+
this.eventFilter = options.eventFilter ?? (() => true);
|
|
48
|
+
this.admitEvent = options.admitEvent ?? (() => true);
|
|
49
|
+
this.delegatedMonitorConsumerId = options.delegatedMonitorConsumerId;
|
|
50
|
+
this.consumerId = options.consumerId ?? DEFAULT_EVENT_CONSUMER_ID;
|
|
51
|
+
this.adapter = options.adapter;
|
|
52
|
+
this.coalesceMs = options.coalesceMs ?? AGENT_MAILBOX_COALESCE_MS;
|
|
53
|
+
this.leaseTtlMs = options.leaseTtlMs ?? AGENT_MAILBOX_LEASE_TTL_MS;
|
|
54
|
+
this.now = options.now ?? Date.now;
|
|
55
|
+
this.diagnostic = options.diagnostic;
|
|
56
|
+
if (this.adapter?.acknowledgement === 'none') {
|
|
57
|
+
throw new Error('A durable Agent Mailbox coordinator cannot use acknowledgement none.');
|
|
58
|
+
}
|
|
59
|
+
if (this.adapter && this.adapter.consumerId !== this.consumerId) {
|
|
60
|
+
throw new Error(`Mailbox adapter '${this.adapter.id}' must use coordinator consumerId '${this.consumerId}'.`);
|
|
61
|
+
}
|
|
62
|
+
if (!Number.isFinite(this.coalesceMs) || this.coalesceMs < 0) {
|
|
63
|
+
throw new Error('Agent Mailbox coalesceMs must be non-negative.');
|
|
64
|
+
}
|
|
65
|
+
if (!Number.isFinite(this.leaseTtlMs) || this.leaseTtlMs <= 0) {
|
|
66
|
+
throw new Error('Agent Mailbox leaseTtlMs must be positive.');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
prepare(options = {}) {
|
|
70
|
+
return this.prepareEvents(options);
|
|
71
|
+
}
|
|
72
|
+
/** Selects and projects one durable Agent-facing Event batch. */
|
|
73
|
+
prepareEvents(options = {}) {
|
|
74
|
+
this.assertRunning();
|
|
75
|
+
this.releaseExpiredPrepared();
|
|
76
|
+
if (this.prepared.size > 0)
|
|
77
|
+
throw new Error('agent_mailbox_delivery_busy');
|
|
78
|
+
const ready = this.captureReadyView(options.readyView);
|
|
79
|
+
if (ready.epochSeq <= 0) {
|
|
80
|
+
return {
|
|
81
|
+
batch: emptyBatch(),
|
|
82
|
+
readyEpochSeq: 0,
|
|
83
|
+
...(this.delayWindow ? { nextAttemptAtMs: this.now() + READY_VIEW_RETRY_MS } : {}),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
const state = this.compactReadyState(ready);
|
|
87
|
+
this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId, ['details']);
|
|
88
|
+
const pending = this.repository.listEvents({
|
|
89
|
+
sessionId: ready.scope.sessionId,
|
|
90
|
+
detailStates: ['pending', 'deferred'],
|
|
91
|
+
maxCommitSeq: ready.eventWatermark,
|
|
92
|
+
maxEpochSeq: ready.epochSeq,
|
|
93
|
+
order: 'asc',
|
|
94
|
+
}, this.consumerId, ['details']).filter((row) => ((options.bypassDelay || row.event.deliveryClass === 'monitor_and_events')
|
|
95
|
+
&& this.selectsEvent(row.event, ready.state.state)));
|
|
96
|
+
if (pending.length === 0) {
|
|
97
|
+
const eventIsBeyondReadyBoundary = this.delayWindow?.sessionId === ready.scope.sessionId
|
|
98
|
+
&& this.delayWindow.firstCommitSeq > ready.eventWatermark;
|
|
99
|
+
if (eventIsBeyondReadyBoundary) {
|
|
100
|
+
return {
|
|
101
|
+
batch: emptyBatch(state),
|
|
102
|
+
readyEpochSeq: ready.epochSeq,
|
|
103
|
+
nextAttemptAtMs: this.now() + READY_VIEW_RETRY_MS,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
this.delayWindow = undefined;
|
|
107
|
+
return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
|
|
108
|
+
}
|
|
109
|
+
if (!options.bypassDelay && !pending.some(({ event }) => event.wakeAgent !== false)) {
|
|
110
|
+
this.delayWindow = undefined;
|
|
111
|
+
return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
|
|
112
|
+
}
|
|
113
|
+
if (this.delayWindow?.sessionId !== ready.scope.sessionId) {
|
|
114
|
+
this.delayWindow = {
|
|
115
|
+
sessionId: ready.scope.sessionId,
|
|
116
|
+
firstCommitSeq: pending[0].event.commitSeq,
|
|
117
|
+
deadlineMs: this.now() + this.coalesceMs,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
if (!options.bypassDelay && this.now() < this.delayWindow.deadlineMs) {
|
|
121
|
+
return {
|
|
122
|
+
batch: emptyBatch(state),
|
|
123
|
+
readyEpochSeq: ready.epochSeq,
|
|
124
|
+
nextAttemptAtMs: this.delayWindow.deadlineMs,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
const deliveryVia = validateDetailDeliveryVia(options.deliveryVia ?? 'mailbox_full');
|
|
128
|
+
const leaseTtlMs = options.leaseTtlMs ?? this.leaseTtlMs;
|
|
129
|
+
if (!Number.isFinite(leaseTtlMs) || leaseTtlMs <= 0) {
|
|
130
|
+
throw new Error('Agent Mailbox leaseTtlMs must be positive.');
|
|
131
|
+
}
|
|
132
|
+
const lease = this.repository.acquireLease({
|
|
133
|
+
consumerId: this.consumerId,
|
|
134
|
+
channel: 'details',
|
|
135
|
+
ownerId: `${options.ownerIdPrefix ?? 'agent_mailbox'}:${randomUUID()}`,
|
|
136
|
+
ttlMs: leaseTtlMs,
|
|
137
|
+
nowMs: this.now(),
|
|
138
|
+
});
|
|
139
|
+
if (!lease)
|
|
140
|
+
throw new Error('agent_mailbox_delivery_busy');
|
|
141
|
+
try {
|
|
142
|
+
const candidates = this.repository.listEvents({
|
|
143
|
+
sessionId: ready.scope.sessionId,
|
|
144
|
+
detailStates: ['pending', 'deferred'],
|
|
145
|
+
maxCommitSeq: ready.eventWatermark,
|
|
146
|
+
maxEpochSeq: ready.epochSeq,
|
|
147
|
+
order: 'desc',
|
|
148
|
+
}, this.consumerId, ['details']).filter((row) => ((options.bypassDelay || row.event.deliveryClass === 'monitor_and_events')
|
|
149
|
+
&& this.selectsEvent(row.event, ready.state.state)));
|
|
150
|
+
if (candidates.length === 0) {
|
|
151
|
+
this.delayWindow = undefined;
|
|
152
|
+
this.repository.releaseLease(lease);
|
|
153
|
+
return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
|
|
154
|
+
}
|
|
155
|
+
const deliveryToken = randomUUID();
|
|
156
|
+
const segmentIds = [...new Set(candidates.map((row) => row.event.segmentId))];
|
|
157
|
+
this.prepared.set(deliveryToken, {
|
|
158
|
+
lease,
|
|
159
|
+
leaseTtlMs,
|
|
160
|
+
eventIds: candidates.map((row) => row.event.eventId),
|
|
161
|
+
readyEpochSeq: ready.epochSeq,
|
|
162
|
+
sessionId: ready.scope.sessionId,
|
|
163
|
+
segmentIds,
|
|
164
|
+
deliveryVia,
|
|
165
|
+
});
|
|
166
|
+
this.delayWindow = undefined;
|
|
167
|
+
this.diagnostic?.('runtime.agent_mailbox.delivery_prepared', {
|
|
168
|
+
consumer: this.consumerId,
|
|
169
|
+
delivery_token: deliveryToken,
|
|
170
|
+
delivery_via: deliveryVia,
|
|
171
|
+
session_id: ready.scope.sessionId,
|
|
172
|
+
segment_ids: segmentIds,
|
|
173
|
+
ready_epoch_seq: ready.epochSeq,
|
|
174
|
+
event_count: candidates.length,
|
|
175
|
+
});
|
|
176
|
+
return {
|
|
177
|
+
batch: {
|
|
178
|
+
state,
|
|
179
|
+
events: candidates.map((row) => this.presentEvent(row.event, ready.state.state)),
|
|
180
|
+
},
|
|
181
|
+
deliveryToken,
|
|
182
|
+
readyEpochSeq: ready.epochSeq,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
this.repository.releaseLease(lease);
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
prepareWhenAvailable(options = {}, timeoutMs = AGENT_MAILBOX_PREPARE_WAIT_MS) {
|
|
191
|
+
return this.prepareEventsWhenAvailable(options, timeoutMs);
|
|
192
|
+
}
|
|
193
|
+
prepareEventsWhenAvailable(options = {}, timeoutMs = AGENT_MAILBOX_PREPARE_WAIT_MS) {
|
|
194
|
+
const operation = this.prepareTail.then(async () => {
|
|
195
|
+
await this.waitForPreparedSlot(timeoutMs);
|
|
196
|
+
return this.prepareEvents(options);
|
|
197
|
+
});
|
|
198
|
+
this.prepareTail = operation.then(() => undefined, () => undefined);
|
|
199
|
+
return operation;
|
|
200
|
+
}
|
|
201
|
+
stateForReadyView(readyView) {
|
|
202
|
+
this.assertRunning();
|
|
203
|
+
return this.compactReadyState(this.captureReadyView(readyView));
|
|
204
|
+
}
|
|
205
|
+
ack(deliveryToken, acceptanceLevel = 'sink_emitted') {
|
|
206
|
+
const prepared = this.prepared.get(deliveryToken);
|
|
207
|
+
if (!prepared || !this.renewPreparedLease(prepared))
|
|
208
|
+
return false;
|
|
209
|
+
const nowMs = this.now();
|
|
210
|
+
const transition = {
|
|
211
|
+
eventIds: prepared.eventIds,
|
|
212
|
+
consumerId: this.consumerId,
|
|
213
|
+
from: ['pending', 'deferred'],
|
|
214
|
+
to: 'delivered',
|
|
215
|
+
deliveredAt: new Date(nowMs).toISOString(),
|
|
216
|
+
deliveryVia: prepared.deliveryVia,
|
|
217
|
+
acceptanceLevel,
|
|
218
|
+
lease: prepared.lease,
|
|
219
|
+
nowMs,
|
|
220
|
+
};
|
|
221
|
+
const changed = this.repository.transitionDetails(transition);
|
|
222
|
+
if (changed !== prepared.eventIds.length)
|
|
223
|
+
return false;
|
|
224
|
+
try {
|
|
225
|
+
this.onDelivered?.(prepared.eventIds.flatMap((id) => {
|
|
226
|
+
const event = this.repository.eventById(id);
|
|
227
|
+
return event ? [event] : [];
|
|
228
|
+
}));
|
|
229
|
+
}
|
|
230
|
+
catch { /* Display reporting must not affect delivery ACK. */ }
|
|
231
|
+
this.prepared.delete(deliveryToken);
|
|
232
|
+
this.repository.releaseLease(prepared.lease);
|
|
233
|
+
this.notifyPreparedSlotAvailable();
|
|
234
|
+
this.diagnostic?.('runtime.agent_mailbox.delivery_acked', {
|
|
235
|
+
acceptance_level: acceptanceLevel,
|
|
236
|
+
consumer: this.consumerId,
|
|
237
|
+
delivery_token: deliveryToken,
|
|
238
|
+
delivery_via: prepared.deliveryVia,
|
|
239
|
+
session_id: prepared.sessionId,
|
|
240
|
+
segment_ids: prepared.segmentIds,
|
|
241
|
+
ready_epoch_seq: prepared.readyEpochSeq,
|
|
242
|
+
event_count: prepared.eventIds.length,
|
|
243
|
+
});
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
renew(deliveryToken) {
|
|
247
|
+
const prepared = this.prepared.get(deliveryToken);
|
|
248
|
+
return prepared ? this.renewPreparedLease(prepared) : false;
|
|
249
|
+
}
|
|
250
|
+
release(deliveryToken) {
|
|
251
|
+
const prepared = this.prepared.get(deliveryToken);
|
|
252
|
+
if (!prepared)
|
|
253
|
+
return false;
|
|
254
|
+
this.prepared.delete(deliveryToken);
|
|
255
|
+
const released = this.repository.releaseLease(prepared.lease);
|
|
256
|
+
this.delayWindow = {
|
|
257
|
+
sessionId: prepared.sessionId,
|
|
258
|
+
firstCommitSeq: 0,
|
|
259
|
+
deadlineMs: this.now(),
|
|
260
|
+
};
|
|
261
|
+
this.notifyPreparedSlotAvailable();
|
|
262
|
+
this.diagnostic?.('runtime.agent_mailbox.delivery_released', {
|
|
263
|
+
consumer: this.consumerId,
|
|
264
|
+
delivery_token: deliveryToken,
|
|
265
|
+
delivery_via: prepared.deliveryVia,
|
|
266
|
+
session_id: prepared.sessionId,
|
|
267
|
+
segment_ids: prepared.segmentIds,
|
|
268
|
+
ready_epoch_seq: prepared.readyEpochSeq,
|
|
269
|
+
event_count: prepared.eventIds.length,
|
|
270
|
+
released,
|
|
271
|
+
});
|
|
272
|
+
return released;
|
|
273
|
+
}
|
|
274
|
+
observeEvents(events) {
|
|
275
|
+
const first = events
|
|
276
|
+
.filter((event) => (event.deliveryClass === 'monitor_and_events'
|
|
277
|
+
&& this.selectsEvent(event, undefined)))
|
|
278
|
+
.sort((left, right) => left.commitSeq - right.commitSeq)[0];
|
|
279
|
+
if (!first || this.delayWindow?.sessionId === first.sessionId)
|
|
280
|
+
return;
|
|
281
|
+
this.delayWindow = {
|
|
282
|
+
sessionId: first.sessionId,
|
|
283
|
+
firstCommitSeq: first.commitSeq,
|
|
284
|
+
deadlineMs: this.now() + this.coalesceMs,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
async flush() {
|
|
288
|
+
if (this.delayWindow)
|
|
289
|
+
this.delayWindow.deadlineMs = this.now();
|
|
290
|
+
}
|
|
291
|
+
async waitForDrain(shouldAbort = () => false) {
|
|
292
|
+
while (!shouldAbort()) {
|
|
293
|
+
const ready = this.captureReadyView();
|
|
294
|
+
if (ready.epochSeq <= 0)
|
|
295
|
+
return this.prepared.size === 0;
|
|
296
|
+
this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId, ['details']);
|
|
297
|
+
const pending = this.repository.listEvents({
|
|
298
|
+
sessionId: ready.scope.sessionId,
|
|
299
|
+
deliveryClasses: ['monitor_and_events'],
|
|
300
|
+
detailStates: ['pending', 'deferred'],
|
|
301
|
+
maxCommitSeq: ready.eventWatermark,
|
|
302
|
+
maxEpochSeq: ready.epochSeq,
|
|
303
|
+
order: 'asc',
|
|
304
|
+
}, this.consumerId, ['details']).filter((row) => (this.selectsEvent(row.event, ready.state.state)));
|
|
305
|
+
if (!pending.some(({ event }) => event.wakeAgent !== false) && this.prepared.size === 0)
|
|
306
|
+
return true;
|
|
307
|
+
await new Promise((resolve) => {
|
|
308
|
+
const timer = setTimeout(resolve, READY_VIEW_RETRY_MS);
|
|
309
|
+
timer.unref?.();
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
async stop() {
|
|
315
|
+
if (this.stopped)
|
|
316
|
+
return;
|
|
317
|
+
this.stopped = true;
|
|
318
|
+
for (const token of [...this.prepared.keys()])
|
|
319
|
+
this.release(token);
|
|
320
|
+
}
|
|
321
|
+
selectsEvent(event, state) {
|
|
322
|
+
if (event.deliveryClass !== 'monitor_and_events' || !this.admitEvent(event))
|
|
323
|
+
return false;
|
|
324
|
+
if (this.delegatedMonitorConsumerId && event.wakeAgent === false)
|
|
325
|
+
return true;
|
|
326
|
+
if (this.eventFilter(event, state))
|
|
327
|
+
return true;
|
|
328
|
+
if (!this.delegatedMonitorConsumerId)
|
|
329
|
+
return false;
|
|
330
|
+
return this.repository.delivery(event.eventId, this.delegatedMonitorConsumerId)
|
|
331
|
+
?.monitorState === 'suppressed';
|
|
332
|
+
}
|
|
333
|
+
captureReadyView(readyView) {
|
|
334
|
+
const ready = structuredClone(readyView ?? this.readyView());
|
|
335
|
+
if (ready.epochSeq > this.lastObservedReadyEpochSeq) {
|
|
336
|
+
this.diagnostic?.('runtime.agent_mailbox.ready_advanced', {
|
|
337
|
+
previous_ready_epoch_seq: this.lastObservedReadyEpochSeq,
|
|
338
|
+
ready_epoch_seq: ready.epochSeq,
|
|
339
|
+
event_commit_seq: ready.eventWatermark,
|
|
340
|
+
frame_seq: ready.frameSeq,
|
|
341
|
+
});
|
|
342
|
+
this.lastObservedReadyEpochSeq = ready.epochSeq;
|
|
343
|
+
}
|
|
344
|
+
return ready;
|
|
345
|
+
}
|
|
346
|
+
compactReadyState(ready) {
|
|
347
|
+
if (!ready.state.state)
|
|
348
|
+
return null;
|
|
349
|
+
const state = this.compactState(ready.state.state);
|
|
350
|
+
if (!state)
|
|
351
|
+
return null;
|
|
352
|
+
return this.projectState?.(state, ready) ?? state;
|
|
353
|
+
}
|
|
354
|
+
releaseExpiredPrepared() {
|
|
355
|
+
const nowMs = this.now();
|
|
356
|
+
for (const [token, prepared] of this.prepared) {
|
|
357
|
+
if (prepared.lease.expiresAt > nowMs)
|
|
358
|
+
continue;
|
|
359
|
+
this.prepared.delete(token);
|
|
360
|
+
this.repository.releaseLease(prepared.lease);
|
|
361
|
+
}
|
|
362
|
+
this.notifyPreparedSlotAvailable();
|
|
363
|
+
}
|
|
364
|
+
renewPreparedLease(prepared) {
|
|
365
|
+
const renewed = this.repository.acquireLease({
|
|
366
|
+
consumerId: prepared.lease.consumerId,
|
|
367
|
+
channel: prepared.lease.channel,
|
|
368
|
+
ownerId: prepared.lease.ownerId,
|
|
369
|
+
ttlMs: prepared.leaseTtlMs,
|
|
370
|
+
nowMs: this.now(),
|
|
371
|
+
});
|
|
372
|
+
if (!renewed)
|
|
373
|
+
return false;
|
|
374
|
+
prepared.lease = renewed;
|
|
375
|
+
return true;
|
|
376
|
+
}
|
|
377
|
+
waitForPreparedSlot(timeoutMs) {
|
|
378
|
+
this.assertRunning();
|
|
379
|
+
this.releaseExpiredPrepared();
|
|
380
|
+
if (this.prepared.size === 0)
|
|
381
|
+
return Promise.resolve();
|
|
382
|
+
const boundedTimeoutMs = Math.max(1, Math.trunc(timeoutMs));
|
|
383
|
+
return new Promise((resolve, reject) => {
|
|
384
|
+
let timer;
|
|
385
|
+
const cleanup = () => {
|
|
386
|
+
if (timer)
|
|
387
|
+
clearTimeout(timer);
|
|
388
|
+
this.preparedSlotWaiters.delete(available);
|
|
389
|
+
};
|
|
390
|
+
const available = () => {
|
|
391
|
+
cleanup();
|
|
392
|
+
resolve();
|
|
393
|
+
};
|
|
394
|
+
this.preparedSlotWaiters.add(available);
|
|
395
|
+
timer = setTimeout(() => {
|
|
396
|
+
cleanup();
|
|
397
|
+
reject(new Error('agent_mailbox_delivery_busy'));
|
|
398
|
+
}, boundedTimeoutMs);
|
|
399
|
+
timer.unref?.();
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
notifyPreparedSlotAvailable() {
|
|
403
|
+
if (this.prepared.size > 0)
|
|
404
|
+
return;
|
|
405
|
+
for (const waiter of [...this.preparedSlotWaiters])
|
|
406
|
+
waiter();
|
|
407
|
+
}
|
|
408
|
+
assertRunning() {
|
|
409
|
+
if (this.stopped)
|
|
410
|
+
throw new Error('agent_mailbox_stopped');
|
|
411
|
+
}
|
|
412
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** Compatibility defaults for the existing Claude Monitor integration. Host-specific budgets remain configurable; this is not a delivery guarantee for arbitrary host versions. */
|
|
2
|
+
export declare const HOST_MONITOR_BUCKET_CAPACITY = 10;
|
|
3
|
+
export declare const HOST_MONITOR_BUCKET_REFILL_MS = 2000;
|
|
4
|
+
export declare const HOST_MONITOR_BUCKET_REFILL_TOKENS = 1;
|
|
5
|
+
export interface TokenBucketOptions {
|
|
6
|
+
capacity?: number;
|
|
7
|
+
refillEveryMs?: number;
|
|
8
|
+
refillTokens?: number;
|
|
9
|
+
now?: () => number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A token bucket that refills continuously by elapsed time.
|
|
13
|
+
*
|
|
14
|
+
* `tryConsume()` returns false when the bucket is empty; the relay then knows
|
|
15
|
+
* the Host would suppress this write and can hold the batch instead of
|
|
16
|
+
* emitting it. Refill is computed lazily on each access, so no timer is needed.
|
|
17
|
+
*/
|
|
18
|
+
export declare class TokenBucket {
|
|
19
|
+
private readonly capacity;
|
|
20
|
+
private readonly refillEveryMs;
|
|
21
|
+
private readonly refillTokens;
|
|
22
|
+
private readonly now;
|
|
23
|
+
private tokens;
|
|
24
|
+
private lastRefillAtMs;
|
|
25
|
+
constructor(options?: TokenBucketOptions);
|
|
26
|
+
private refill;
|
|
27
|
+
/** Attempts to consume one token. Returns false when the bucket is empty. */
|
|
28
|
+
tryConsume(): boolean;
|
|
29
|
+
/** Current token count after refill (for diagnostics/testing). */
|
|
30
|
+
current(): number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A Monitor-write gate that mirrors the Host bucket plus a sustained-rate guard.
|
|
34
|
+
*
|
|
35
|
+
* The Host kills a Monitor after >30s of continuous suppression, which a burst
|
|
36
|
+
* of `capacity` immediate writes could not by itself reach. This gate therefore
|
|
37
|
+
* also tracks the sustained interval between accepted writes and enforces a
|
|
38
|
+
* conservative minimum spacing. It tolerates the Host's own 200ms line buffer:
|
|
39
|
+
* two writes closer than `minIntervalMs` would coalesce into one batch (using
|
|
40
|
+
* fewer tokens, never more), so jitter can only merge, never split — the safe
|
|
41
|
+
* direction.
|
|
42
|
+
*/
|
|
43
|
+
export declare class HostMonitorWriteGate {
|
|
44
|
+
private readonly bucket;
|
|
45
|
+
private readonly minIntervalMs;
|
|
46
|
+
private readonly now;
|
|
47
|
+
private lastAcceptedAtMs;
|
|
48
|
+
private hasAccepted;
|
|
49
|
+
constructor(options?: TokenBucketOptions & {
|
|
50
|
+
minIntervalMs?: number;
|
|
51
|
+
});
|
|
52
|
+
/**
|
|
53
|
+
* Returns true when the relay may write stdout now.
|
|
54
|
+
*
|
|
55
|
+
* Both the bucket token AND the sustained-rate spacing must be satisfied.
|
|
56
|
+
*/
|
|
57
|
+
allow(): boolean;
|
|
58
|
+
/** Resets the gate (e.g. after a reconnect). */
|
|
59
|
+
reset(): void;
|
|
60
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/** Compatibility defaults for the existing Claude Monitor integration. Host-specific budgets remain configurable; this is not a delivery guarantee for arbitrary host versions. */
|
|
2
|
+
export const HOST_MONITOR_BUCKET_CAPACITY = 10;
|
|
3
|
+
export const HOST_MONITOR_BUCKET_REFILL_MS = 2_000;
|
|
4
|
+
export const HOST_MONITOR_BUCKET_REFILL_TOKENS = 1;
|
|
5
|
+
/**
|
|
6
|
+
* A token bucket that refills continuously by elapsed time.
|
|
7
|
+
*
|
|
8
|
+
* `tryConsume()` returns false when the bucket is empty; the relay then knows
|
|
9
|
+
* the Host would suppress this write and can hold the batch instead of
|
|
10
|
+
* emitting it. Refill is computed lazily on each access, so no timer is needed.
|
|
11
|
+
*/
|
|
12
|
+
export class TokenBucket {
|
|
13
|
+
capacity;
|
|
14
|
+
refillEveryMs;
|
|
15
|
+
refillTokens;
|
|
16
|
+
now;
|
|
17
|
+
tokens;
|
|
18
|
+
lastRefillAtMs;
|
|
19
|
+
constructor(options = {}) {
|
|
20
|
+
this.capacity = options.capacity ?? HOST_MONITOR_BUCKET_CAPACITY;
|
|
21
|
+
this.refillEveryMs = options.refillEveryMs ?? HOST_MONITOR_BUCKET_REFILL_MS;
|
|
22
|
+
this.refillTokens = options.refillTokens ?? HOST_MONITOR_BUCKET_REFILL_TOKENS;
|
|
23
|
+
this.now = options.now ?? Date.now;
|
|
24
|
+
this.tokens = this.capacity;
|
|
25
|
+
this.lastRefillAtMs = this.now();
|
|
26
|
+
}
|
|
27
|
+
refill() {
|
|
28
|
+
const elapsedMs = this.now() - this.lastRefillAtMs;
|
|
29
|
+
if (elapsedMs <= 0)
|
|
30
|
+
return;
|
|
31
|
+
const refills = Math.floor(elapsedMs / this.refillEveryMs);
|
|
32
|
+
if (refills > 0) {
|
|
33
|
+
this.tokens = Math.min(this.capacity, this.tokens + refills * this.refillTokens);
|
|
34
|
+
this.lastRefillAtMs += refills * this.refillEveryMs;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** Attempts to consume one token. Returns false when the bucket is empty. */
|
|
38
|
+
tryConsume() {
|
|
39
|
+
this.refill();
|
|
40
|
+
if (this.tokens >= 1) {
|
|
41
|
+
this.tokens -= 1;
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
/** Current token count after refill (for diagnostics/testing). */
|
|
47
|
+
current() {
|
|
48
|
+
this.refill();
|
|
49
|
+
return this.tokens;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A Monitor-write gate that mirrors the Host bucket plus a sustained-rate guard.
|
|
54
|
+
*
|
|
55
|
+
* The Host kills a Monitor after >30s of continuous suppression, which a burst
|
|
56
|
+
* of `capacity` immediate writes could not by itself reach. This gate therefore
|
|
57
|
+
* also tracks the sustained interval between accepted writes and enforces a
|
|
58
|
+
* conservative minimum spacing. It tolerates the Host's own 200ms line buffer:
|
|
59
|
+
* two writes closer than `minIntervalMs` would coalesce into one batch (using
|
|
60
|
+
* fewer tokens, never more), so jitter can only merge, never split — the safe
|
|
61
|
+
* direction.
|
|
62
|
+
*/
|
|
63
|
+
export class HostMonitorWriteGate {
|
|
64
|
+
bucket;
|
|
65
|
+
minIntervalMs;
|
|
66
|
+
now;
|
|
67
|
+
lastAcceptedAtMs = 0;
|
|
68
|
+
hasAccepted = false;
|
|
69
|
+
constructor(options = {}) {
|
|
70
|
+
this.bucket = new TokenBucket(options);
|
|
71
|
+
this.minIntervalMs = options.minIntervalMs ?? 300;
|
|
72
|
+
this.now = options.now ?? Date.now;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Returns true when the relay may write stdout now.
|
|
76
|
+
*
|
|
77
|
+
* Both the bucket token AND the sustained-rate spacing must be satisfied.
|
|
78
|
+
*/
|
|
79
|
+
allow() {
|
|
80
|
+
const nowMs = this.now();
|
|
81
|
+
const spaced = !this.hasAccepted || (nowMs - this.lastAcceptedAtMs) >= this.minIntervalMs;
|
|
82
|
+
if (!spaced || !this.bucket.tryConsume())
|
|
83
|
+
return false;
|
|
84
|
+
this.lastAcceptedAtMs = nowMs;
|
|
85
|
+
this.hasAccepted = true;
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
/** Resets the gate (e.g. after a reconnect). */
|
|
89
|
+
reset() {
|
|
90
|
+
this.lastAcceptedAtMs = 0;
|
|
91
|
+
this.hasAccepted = false;
|
|
92
|
+
}
|
|
93
|
+
}
|