@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.0
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 +242 -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 +56 -0
- package/dist/mailbox/mailbox-plugin.js +111 -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 +336 -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,73 @@
|
|
|
1
|
+
import type { CanonicalEvent } from '../framework/events/index.js';
|
|
2
|
+
import type { AgentMailboxBatch, PreparedAgentMailboxBatch } from './agent-mailbox-coordinator.js';
|
|
3
|
+
import type { MailboxAdapterDescriptor } from './mailbox-plugin.js';
|
|
4
|
+
import type { MailboxAcceptanceLevel } from '../framework/mailbox/types.js';
|
|
5
|
+
export declare const MAILBOX_SHUTDOWN_GRACE_MS = 500;
|
|
6
|
+
export interface MailboxEventBatchSource {
|
|
7
|
+
prepare(): PreparedAgentMailboxBatch;
|
|
8
|
+
renew(deliveryToken: string): boolean;
|
|
9
|
+
ack(deliveryToken: string, acceptanceLevel?: MailboxAcceptanceLevel): boolean;
|
|
10
|
+
release(deliveryToken: string): boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface MailboxEventBatchEnvelope {
|
|
13
|
+
/** Stable for this durable preparation and required on the application ACK. */
|
|
14
|
+
deliveryId: string;
|
|
15
|
+
batch: AgentMailboxBatch;
|
|
16
|
+
}
|
|
17
|
+
export interface MailboxEventBatchAcceptance {
|
|
18
|
+
acceptedAt: string;
|
|
19
|
+
receiptId?: string;
|
|
20
|
+
/** Absent on older peers: conservatively means transport output only. Never model processing. */
|
|
21
|
+
acceptanceLevel?: MailboxAcceptanceLevel;
|
|
22
|
+
}
|
|
23
|
+
/** Confirms the handoff level actually supported by the transport, without waiting for the model. */
|
|
24
|
+
export interface MailboxEventBatchSink {
|
|
25
|
+
deliver(envelope: MailboxEventBatchEnvelope, signal: AbortSignal): Promise<MailboxEventBatchAcceptance>;
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
export interface MailboxEventBatchPumpOptions {
|
|
29
|
+
source: MailboxEventBatchSource;
|
|
30
|
+
sink: MailboxEventBatchSink;
|
|
31
|
+
adapter?: MailboxAdapterDescriptor;
|
|
32
|
+
now?: () => number;
|
|
33
|
+
diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Coordinates the durable Mailbox detail lane with the Host sink selected for
|
|
37
|
+
* this Owner. Desktop IPC and Channels are sibling adapters over this boundary;
|
|
38
|
+
* the pump knows neither their wire formats nor Monitor presentation.
|
|
39
|
+
*/
|
|
40
|
+
export declare class MailboxEventBatchPump {
|
|
41
|
+
readonly adapter?: MailboxAdapterDescriptor;
|
|
42
|
+
private readonly source;
|
|
43
|
+
private readonly sink;
|
|
44
|
+
private readonly now;
|
|
45
|
+
private readonly diagnostic?;
|
|
46
|
+
private stopped;
|
|
47
|
+
private pending;
|
|
48
|
+
private generation;
|
|
49
|
+
private retryAttempt;
|
|
50
|
+
private timer;
|
|
51
|
+
private timerAtMs;
|
|
52
|
+
private pumpRequested;
|
|
53
|
+
private pumpPromise;
|
|
54
|
+
private activeAbort;
|
|
55
|
+
private preparedDelivery;
|
|
56
|
+
constructor(options: MailboxEventBatchPumpOptions);
|
|
57
|
+
/** Called by Mailbox.afterReady after the Events' epoch is visible to output readers. */
|
|
58
|
+
observeEvents(events: readonly CanonicalEvent[]): void;
|
|
59
|
+
/** Shortens a persisted retry after the Host transport reconnects. */
|
|
60
|
+
retryNow(): void;
|
|
61
|
+
/** Kicks delivery without making Runtime lifecycle flush wait for Host ACK. */
|
|
62
|
+
flush(): Promise<void>;
|
|
63
|
+
/** A bounded final opportunity to finish the current transport handoff, never an Agent turn. */
|
|
64
|
+
drain(timeoutMs?: number): Promise<void>;
|
|
65
|
+
stop(): Promise<void>;
|
|
66
|
+
private requestPump;
|
|
67
|
+
private pump;
|
|
68
|
+
/** Ignore late completion after shutdown, even if a third-party sink ignores AbortSignal. */
|
|
69
|
+
private deliverUntilAborted;
|
|
70
|
+
private scheduleAt;
|
|
71
|
+
private clearTimer;
|
|
72
|
+
private releasePreparedDelivery;
|
|
73
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
const DEFAULT_RETRY_BASE_MS = 250;
|
|
2
|
+
const DEFAULT_RETRY_MAX_MS = 5_000;
|
|
3
|
+
export const MAILBOX_SHUTDOWN_GRACE_MS = 500;
|
|
4
|
+
function errorMessage(error) {
|
|
5
|
+
return error instanceof Error ? error.message : String(error);
|
|
6
|
+
}
|
|
7
|
+
function retryDelay(attempt) {
|
|
8
|
+
const exponent = Math.max(0, Math.min(8, attempt - 1));
|
|
9
|
+
return Math.min(DEFAULT_RETRY_MAX_MS, DEFAULT_RETRY_BASE_MS * (2 ** exponent));
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Coordinates the durable Mailbox detail lane with the Host sink selected for
|
|
13
|
+
* this Owner. Desktop IPC and Channels are sibling adapters over this boundary;
|
|
14
|
+
* the pump knows neither their wire formats nor Monitor presentation.
|
|
15
|
+
*/
|
|
16
|
+
export class MailboxEventBatchPump {
|
|
17
|
+
adapter;
|
|
18
|
+
source;
|
|
19
|
+
sink;
|
|
20
|
+
now;
|
|
21
|
+
diagnostic;
|
|
22
|
+
stopped = false;
|
|
23
|
+
pending = false;
|
|
24
|
+
generation = 0;
|
|
25
|
+
retryAttempt = 0;
|
|
26
|
+
timer;
|
|
27
|
+
timerAtMs;
|
|
28
|
+
pumpRequested = false;
|
|
29
|
+
pumpPromise;
|
|
30
|
+
activeAbort;
|
|
31
|
+
preparedDelivery;
|
|
32
|
+
constructor(options) {
|
|
33
|
+
this.adapter = options.adapter;
|
|
34
|
+
this.source = options.source;
|
|
35
|
+
this.sink = options.sink;
|
|
36
|
+
this.now = options.now ?? Date.now;
|
|
37
|
+
this.diagnostic = options.diagnostic;
|
|
38
|
+
}
|
|
39
|
+
/** Called by Mailbox.afterReady after the Events' epoch is visible to output readers. */
|
|
40
|
+
observeEvents(events) {
|
|
41
|
+
if (this.stopped)
|
|
42
|
+
return;
|
|
43
|
+
const visible = events.filter((event) => event.deliveryClass !== 'internal_only');
|
|
44
|
+
if (visible.length === 0)
|
|
45
|
+
return;
|
|
46
|
+
this.pending = true;
|
|
47
|
+
this.generation += 1;
|
|
48
|
+
this.clearTimer();
|
|
49
|
+
this.requestPump();
|
|
50
|
+
}
|
|
51
|
+
/** Shortens a persisted retry after the Host transport reconnects. */
|
|
52
|
+
retryNow() {
|
|
53
|
+
if (this.stopped || !this.pending || this.retryAttempt === 0)
|
|
54
|
+
return;
|
|
55
|
+
this.clearTimer();
|
|
56
|
+
this.scheduleAt(this.now());
|
|
57
|
+
}
|
|
58
|
+
/** Kicks delivery without making Runtime lifecycle flush wait for Host ACK. */
|
|
59
|
+
async flush() {
|
|
60
|
+
if (this.stopped) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
this.pending = true;
|
|
64
|
+
this.generation += 1;
|
|
65
|
+
this.clearTimer();
|
|
66
|
+
this.requestPump();
|
|
67
|
+
}
|
|
68
|
+
/** A bounded final opportunity to finish the current transport handoff, never an Agent turn. */
|
|
69
|
+
async drain(timeoutMs = MAILBOX_SHUTDOWN_GRACE_MS) {
|
|
70
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
|
|
71
|
+
throw new Error('Invalid Mailbox drain timeout.');
|
|
72
|
+
let timer;
|
|
73
|
+
try {
|
|
74
|
+
const completed = await Promise.race([
|
|
75
|
+
(async () => {
|
|
76
|
+
await this.flush();
|
|
77
|
+
while (this.pumpPromise)
|
|
78
|
+
await this.pumpPromise;
|
|
79
|
+
return true;
|
|
80
|
+
})(),
|
|
81
|
+
new Promise(resolve => { timer = setTimeout(() => resolve(false), timeoutMs); }),
|
|
82
|
+
]);
|
|
83
|
+
if (!completed)
|
|
84
|
+
this.diagnostic?.('runtime.mailbox.shutdown_unconfirmed', {
|
|
85
|
+
timeout_ms: timeoutMs, delivery_id: this.preparedDelivery?.deliveryToken,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
if (timer)
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async stop() {
|
|
94
|
+
if (this.stopped) {
|
|
95
|
+
await this.pumpPromise;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
this.stopped = true;
|
|
99
|
+
this.pending = false;
|
|
100
|
+
this.pumpRequested = false;
|
|
101
|
+
this.clearTimer();
|
|
102
|
+
this.activeAbort?.abort(new Error('mailbox_event_batch_pump_stopped'));
|
|
103
|
+
await this.pumpPromise;
|
|
104
|
+
this.releasePreparedDelivery();
|
|
105
|
+
await this.sink.close();
|
|
106
|
+
}
|
|
107
|
+
requestPump() {
|
|
108
|
+
if (this.stopped)
|
|
109
|
+
return;
|
|
110
|
+
this.pumpRequested = true;
|
|
111
|
+
if (this.pumpPromise)
|
|
112
|
+
return;
|
|
113
|
+
this.pumpPromise = this.pump()
|
|
114
|
+
.catch((error) => {
|
|
115
|
+
this.diagnostic?.('runtime.mailbox.event_batch_pump_failed', {
|
|
116
|
+
error: errorMessage(error),
|
|
117
|
+
});
|
|
118
|
+
})
|
|
119
|
+
.finally(() => {
|
|
120
|
+
this.pumpPromise = undefined;
|
|
121
|
+
if (this.pumpRequested && !this.stopped)
|
|
122
|
+
this.requestPump();
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
async pump() {
|
|
126
|
+
this.pumpRequested = false;
|
|
127
|
+
if (!this.pending || this.stopped)
|
|
128
|
+
return;
|
|
129
|
+
try {
|
|
130
|
+
let prepared = this.preparedDelivery;
|
|
131
|
+
if (prepared) {
|
|
132
|
+
if (!this.source.renew(prepared.deliveryToken)) {
|
|
133
|
+
this.releasePreparedDelivery();
|
|
134
|
+
throw new Error('mailbox_event_batch_lease_lost');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
const selected = this.source.prepare();
|
|
139
|
+
const deliveryToken = selected.deliveryToken;
|
|
140
|
+
if (!deliveryToken || selected.batch.events.length === 0) {
|
|
141
|
+
if (deliveryToken)
|
|
142
|
+
this.source.release(deliveryToken);
|
|
143
|
+
if (selected.nextAttemptAtMs !== undefined) {
|
|
144
|
+
this.scheduleAt(selected.nextAttemptAtMs);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (!this.pumpRequested) {
|
|
148
|
+
this.pending = false;
|
|
149
|
+
this.retryAttempt = 0;
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
this.scheduleAt(this.now());
|
|
153
|
+
}
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
prepared = {
|
|
157
|
+
deliveryToken,
|
|
158
|
+
batch: selected.batch,
|
|
159
|
+
readyEpochSeq: selected.readyEpochSeq,
|
|
160
|
+
generation: this.generation,
|
|
161
|
+
};
|
|
162
|
+
this.preparedDelivery = prepared;
|
|
163
|
+
}
|
|
164
|
+
if (!prepared.acceptance) {
|
|
165
|
+
const controller = new AbortController();
|
|
166
|
+
this.activeAbort = controller;
|
|
167
|
+
prepared.acceptance = await this.deliverUntilAborted({
|
|
168
|
+
deliveryId: prepared.deliveryToken,
|
|
169
|
+
batch: prepared.batch,
|
|
170
|
+
}, controller.signal);
|
|
171
|
+
this.activeAbort = undefined;
|
|
172
|
+
}
|
|
173
|
+
const acceptanceLevel = prepared.acceptance.acceptanceLevel ?? 'sink_emitted';
|
|
174
|
+
if (!this.source.ack(prepared.deliveryToken, acceptanceLevel)) {
|
|
175
|
+
throw new Error('mailbox_event_batch_ack_lost');
|
|
176
|
+
}
|
|
177
|
+
this.preparedDelivery = undefined;
|
|
178
|
+
this.diagnostic?.('runtime.mailbox.event_batch_accepted', {
|
|
179
|
+
delivery_id: prepared.deliveryToken,
|
|
180
|
+
event_count: prepared.batch.events.length,
|
|
181
|
+
ready_epoch_seq: prepared.readyEpochSeq,
|
|
182
|
+
accepted_at: prepared.acceptance.acceptedAt,
|
|
183
|
+
acceptance_level: acceptanceLevel,
|
|
184
|
+
...(prepared.acceptance.receiptId ? { receipt_id: prepared.acceptance.receiptId } : {}),
|
|
185
|
+
});
|
|
186
|
+
this.retryAttempt = 0;
|
|
187
|
+
if (this.generation === prepared.generation) {
|
|
188
|
+
this.pending = false;
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
this.scheduleAt(this.now());
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
this.activeAbort = undefined;
|
|
196
|
+
if (this.stopped) {
|
|
197
|
+
this.releasePreparedDelivery();
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
this.pending = true;
|
|
201
|
+
this.retryAttempt += 1;
|
|
202
|
+
const delayMs = retryDelay(this.retryAttempt);
|
|
203
|
+
this.diagnostic?.('runtime.mailbox.event_batch_retry', {
|
|
204
|
+
attempt: this.retryAttempt,
|
|
205
|
+
retry_in_ms: delayMs,
|
|
206
|
+
error: errorMessage(error),
|
|
207
|
+
});
|
|
208
|
+
this.scheduleAt(this.now() + delayMs);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** Ignore late completion after shutdown, even if a third-party sink ignores AbortSignal. */
|
|
212
|
+
deliverUntilAborted(envelope, signal) {
|
|
213
|
+
let onAbort;
|
|
214
|
+
return new Promise((resolve, reject) => {
|
|
215
|
+
onAbort = () => reject(signal.reason);
|
|
216
|
+
if (signal.aborted) {
|
|
217
|
+
onAbort();
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
221
|
+
Promise.resolve().then(() => this.sink.deliver(envelope, signal)).then(resolve, reject);
|
|
222
|
+
}).finally(() => signal.removeEventListener('abort', onAbort));
|
|
223
|
+
}
|
|
224
|
+
scheduleAt(atMs) {
|
|
225
|
+
if (this.stopped)
|
|
226
|
+
return;
|
|
227
|
+
if (this.timer && this.timerAtMs !== undefined && this.timerAtMs <= atMs)
|
|
228
|
+
return;
|
|
229
|
+
this.clearTimer();
|
|
230
|
+
this.timerAtMs = atMs;
|
|
231
|
+
const timer = setTimeout(() => {
|
|
232
|
+
this.timer = undefined;
|
|
233
|
+
this.timerAtMs = undefined;
|
|
234
|
+
this.requestPump();
|
|
235
|
+
}, Math.max(0, atMs - this.now()));
|
|
236
|
+
timer.unref?.();
|
|
237
|
+
this.timer = timer;
|
|
238
|
+
}
|
|
239
|
+
clearTimer() {
|
|
240
|
+
if (this.timer)
|
|
241
|
+
clearTimeout(this.timer);
|
|
242
|
+
this.timer = undefined;
|
|
243
|
+
this.timerAtMs = undefined;
|
|
244
|
+
}
|
|
245
|
+
releasePreparedDelivery() {
|
|
246
|
+
const prepared = this.preparedDelivery;
|
|
247
|
+
this.preparedDelivery = undefined;
|
|
248
|
+
if (prepared)
|
|
249
|
+
this.source.release(prepared.deliveryToken);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type EventRepository } from '../framework/events/index.js';
|
|
2
|
+
import type { MailboxDeliveryMode, MailboxRepository } from '../framework/mailbox/index.js';
|
|
3
|
+
import type { OwnerControlRequest, OwnerControlResponse } from '../owner/control-channel.js';
|
|
4
|
+
import type { HostMonitorWriteGate } from './host-monitor-rate-gate.js';
|
|
5
|
+
export declare const MAILBOX_RELAY_REQUEST_TYPES: readonly ["mailbox_claim", "mailbox_ack", "mailbox_nack"];
|
|
6
|
+
export type MailboxRelayRequestType = typeof MAILBOX_RELAY_REQUEST_TYPES[number];
|
|
7
|
+
export declare const DEFAULT_RELAY_POLL_MS = 220;
|
|
8
|
+
/**
|
|
9
|
+
* Authenticated Owner-side Mailbox endpoint.
|
|
10
|
+
*
|
|
11
|
+
* The surrounding owner-control server has already authenticated a local
|
|
12
|
+
* master token before this broker is called. Strategy and Perception do not
|
|
13
|
+
* receive owner-control credentials: Owner-thread instances are called
|
|
14
|
+
* directly, and parallel Worker Threads do not use these request families.
|
|
15
|
+
*/
|
|
16
|
+
export declare class MailboxRelayBroker<TPayload extends Record<string, unknown> = Record<string, unknown>> {
|
|
17
|
+
private readonly repository;
|
|
18
|
+
readonly mode: MailboxDeliveryMode;
|
|
19
|
+
private readonly consumerId;
|
|
20
|
+
private readonly maxItems;
|
|
21
|
+
private readonly onDelivered?;
|
|
22
|
+
private lastContactAtMs;
|
|
23
|
+
constructor(repository: EventRepository & MailboxRepository, mode: MailboxDeliveryMode, consumerId?: string, maxItems?: number, onDelivered?: ((eventIds: readonly string[]) => void) | undefined);
|
|
24
|
+
handle(request: OwnerControlRequest): OwnerControlResponse | undefined;
|
|
25
|
+
hasRecentRelay(withinMs?: number, nowMs?: number): boolean;
|
|
26
|
+
hasPendingCurrent(): boolean;
|
|
27
|
+
}
|
|
28
|
+
export interface StdoutMailboxRelayOptions {
|
|
29
|
+
request: (type: MailboxRelayRequestType, payload: Record<string, unknown>, timeoutMs?: number) => Promise<OwnerControlResponse | null>;
|
|
30
|
+
emit: (payload: Record<string, unknown>) => Promise<void>;
|
|
31
|
+
/** Compose one Host wake-up from all items in a coalesced Mailbox claim. */
|
|
32
|
+
compose?: (payloads: readonly Record<string, unknown>[]) => Record<string, unknown>;
|
|
33
|
+
/**
|
|
34
|
+
* Mirror of the Host Monitor rate limiter. When this gate denies a write,
|
|
35
|
+
* the claimed batch is nack'ed (released back to pending) instead of emitted,
|
|
36
|
+
* so events are never dropped — they either reach the agent via a later
|
|
37
|
+
* stdout write, or are pulled by an explicit event query.
|
|
38
|
+
*/
|
|
39
|
+
rateGate?: HostMonitorWriteGate;
|
|
40
|
+
isOwnerAlive: () => boolean;
|
|
41
|
+
mode: MailboxDeliveryMode;
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
relayId?: string;
|
|
44
|
+
pollMs?: number;
|
|
45
|
+
requestTimeoutMs?: number;
|
|
46
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Disposable Host-side loop. It has no Owner shutdown authority and never sends
|
|
50
|
+
* stop/quit when its stdout consumer goes away.
|
|
51
|
+
*/
|
|
52
|
+
export declare function runStdoutMailboxRelay(options: StdoutMailboxRelayOptions): Promise<void>;
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { DEFAULT_EVENT_CONSUMER_ID, } from '../framework/events/index.js';
|
|
3
|
+
export const MAILBOX_RELAY_REQUEST_TYPES = [
|
|
4
|
+
'mailbox_claim',
|
|
5
|
+
'mailbox_ack',
|
|
6
|
+
'mailbox_nack',
|
|
7
|
+
];
|
|
8
|
+
const RELAY_ID_MAX_CHARS = 200;
|
|
9
|
+
const CLAIM_TOKEN_MAX_CHARS = 200;
|
|
10
|
+
const DEFAULT_RELAY_LEASE_TTL_MS = 10_000;
|
|
11
|
+
const MAX_RELAY_LEASE_TTL_MS = 30_000;
|
|
12
|
+
export const DEFAULT_RELAY_POLL_MS = 220;
|
|
13
|
+
const DEFAULT_RELAY_BATCH_SIZE = 100;
|
|
14
|
+
function boundedString(value, maxChars) {
|
|
15
|
+
if (typeof value !== 'string')
|
|
16
|
+
return undefined;
|
|
17
|
+
const trimmed = value.trim();
|
|
18
|
+
if (!trimmed || trimmed.length > maxChars)
|
|
19
|
+
return undefined;
|
|
20
|
+
return trimmed;
|
|
21
|
+
}
|
|
22
|
+
function boundedLeaseTtl(value) {
|
|
23
|
+
const numeric = Number(value);
|
|
24
|
+
if (!Number.isFinite(numeric))
|
|
25
|
+
return DEFAULT_RELAY_LEASE_TTL_MS;
|
|
26
|
+
return Math.max(1_000, Math.min(MAX_RELAY_LEASE_TTL_MS, Math.trunc(numeric)));
|
|
27
|
+
}
|
|
28
|
+
function isRelayRequestType(value) {
|
|
29
|
+
return MAILBOX_RELAY_REQUEST_TYPES.includes(value);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Authenticated Owner-side Mailbox endpoint.
|
|
33
|
+
*
|
|
34
|
+
* The surrounding owner-control server has already authenticated a local
|
|
35
|
+
* master token before this broker is called. Strategy and Perception do not
|
|
36
|
+
* receive owner-control credentials: Owner-thread instances are called
|
|
37
|
+
* directly, and parallel Worker Threads do not use these request families.
|
|
38
|
+
*/
|
|
39
|
+
export class MailboxRelayBroker {
|
|
40
|
+
repository;
|
|
41
|
+
mode;
|
|
42
|
+
consumerId;
|
|
43
|
+
maxItems;
|
|
44
|
+
onDelivered;
|
|
45
|
+
lastContactAtMs = 0;
|
|
46
|
+
constructor(repository, mode, consumerId = DEFAULT_EVENT_CONSUMER_ID, maxItems = DEFAULT_RELAY_BATCH_SIZE, onDelivered) {
|
|
47
|
+
this.repository = repository;
|
|
48
|
+
this.mode = mode;
|
|
49
|
+
this.consumerId = consumerId;
|
|
50
|
+
this.maxItems = maxItems;
|
|
51
|
+
this.onDelivered = onDelivered;
|
|
52
|
+
}
|
|
53
|
+
handle(request) {
|
|
54
|
+
if (!isRelayRequestType(request.type))
|
|
55
|
+
return undefined;
|
|
56
|
+
const relayId = boundedString(request.relay_id, RELAY_ID_MAX_CHARS);
|
|
57
|
+
if (!relayId)
|
|
58
|
+
return { ok: false, error: 'invalid_mailbox_relay_id' };
|
|
59
|
+
if (request.mode !== this.mode) {
|
|
60
|
+
return {
|
|
61
|
+
ok: false,
|
|
62
|
+
error: 'mailbox_mode_mismatch',
|
|
63
|
+
expected_mode: this.mode,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
this.lastContactAtMs = Date.now();
|
|
67
|
+
if (request.type === 'mailbox_claim') {
|
|
68
|
+
const scope = this.repository.currentScope();
|
|
69
|
+
if (!scope) {
|
|
70
|
+
return { ok: true, type: 'mailbox_claim', claim: null, wait_ms: DEFAULT_RELAY_POLL_MS };
|
|
71
|
+
}
|
|
72
|
+
const next = this.repository.peekMailbox({
|
|
73
|
+
consumerId: this.consumerId,
|
|
74
|
+
sessionId: scope.session.sessionId,
|
|
75
|
+
modes: [this.mode],
|
|
76
|
+
states: ['pending', 'claimed'],
|
|
77
|
+
order: 'asc',
|
|
78
|
+
limit: 1,
|
|
79
|
+
})[0];
|
|
80
|
+
const segmentId = next?.segmentId ?? scope.segment.segmentId;
|
|
81
|
+
const claim = this.repository.claimMailbox({
|
|
82
|
+
consumerId: this.consumerId,
|
|
83
|
+
sessionId: scope.session.sessionId,
|
|
84
|
+
segmentId,
|
|
85
|
+
mode: this.mode,
|
|
86
|
+
ownerId: relayId,
|
|
87
|
+
leaseTtlMs: boundedLeaseTtl(request.lease_ttl_ms),
|
|
88
|
+
maxItems: this.maxItems,
|
|
89
|
+
});
|
|
90
|
+
return {
|
|
91
|
+
ok: true,
|
|
92
|
+
type: 'mailbox_claim',
|
|
93
|
+
scope: {
|
|
94
|
+
session_id: scope.session.sessionId,
|
|
95
|
+
segment_id: claim?.items[0]?.segmentId ?? segmentId,
|
|
96
|
+
},
|
|
97
|
+
claim: claim ? {
|
|
98
|
+
claim_token: claim.claimToken,
|
|
99
|
+
expires_at_ms: claim.claimExpiresAtMs,
|
|
100
|
+
items: claim.items.map((item) => ({
|
|
101
|
+
item_id: item.itemId,
|
|
102
|
+
event_id: item.eventId,
|
|
103
|
+
payload: item.payload,
|
|
104
|
+
})),
|
|
105
|
+
} : null,
|
|
106
|
+
wait_ms: DEFAULT_RELAY_POLL_MS,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const claimToken = boundedString(request.claim_token, CLAIM_TOKEN_MAX_CHARS);
|
|
110
|
+
if (!claimToken)
|
|
111
|
+
return { ok: false, error: 'invalid_mailbox_claim_token' };
|
|
112
|
+
if (request.type === 'mailbox_ack') {
|
|
113
|
+
const result = this.repository.ackMailboxClaim({
|
|
114
|
+
ownerId: relayId,
|
|
115
|
+
claimToken,
|
|
116
|
+
acceptedAt: typeof request.accepted_at === 'string'
|
|
117
|
+
? request.accepted_at
|
|
118
|
+
: undefined,
|
|
119
|
+
acceptanceLevel: 'sink_emitted',
|
|
120
|
+
});
|
|
121
|
+
if (result.status !== 'claim_lost') {
|
|
122
|
+
try {
|
|
123
|
+
this.onDelivered?.(result.eventIds);
|
|
124
|
+
}
|
|
125
|
+
catch { /* Best-effort display only. */ }
|
|
126
|
+
}
|
|
127
|
+
return { ok: true, type: 'mailbox_ack', result };
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
ok: true,
|
|
131
|
+
type: 'mailbox_nack',
|
|
132
|
+
result: this.repository.nackMailboxClaim({
|
|
133
|
+
ownerId: relayId,
|
|
134
|
+
claimToken,
|
|
135
|
+
retryAtMs: Number.isFinite(Number(request.retry_at_ms))
|
|
136
|
+
? Math.max(Date.now(), Math.trunc(Number(request.retry_at_ms)))
|
|
137
|
+
: Date.now() + DEFAULT_RELAY_POLL_MS,
|
|
138
|
+
errorCode: boundedString(request.error_code, 100) ?? 'host_relay_write_failed',
|
|
139
|
+
}),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
hasRecentRelay(withinMs = 2_000, nowMs = Date.now()) {
|
|
143
|
+
return this.lastContactAtMs > 0 && nowMs - this.lastContactAtMs <= withinMs;
|
|
144
|
+
}
|
|
145
|
+
hasPendingCurrent() {
|
|
146
|
+
const scope = this.repository.currentScope();
|
|
147
|
+
if (!scope)
|
|
148
|
+
return false;
|
|
149
|
+
return this.repository.peekMailbox({
|
|
150
|
+
consumerId: this.consumerId,
|
|
151
|
+
sessionId: scope.session.sessionId,
|
|
152
|
+
modes: [this.mode],
|
|
153
|
+
states: ['pending', 'claimed'],
|
|
154
|
+
order: 'asc',
|
|
155
|
+
limit: 1,
|
|
156
|
+
}).length > 0;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function defaultSleep(ms, signal) {
|
|
160
|
+
if (signal?.aborted)
|
|
161
|
+
return Promise.resolve();
|
|
162
|
+
return new Promise((resolve) => {
|
|
163
|
+
const timer = setTimeout(finish, ms);
|
|
164
|
+
const onAbort = () => finish();
|
|
165
|
+
function finish() {
|
|
166
|
+
clearTimeout(timer);
|
|
167
|
+
signal?.removeEventListener('abort', onAbort);
|
|
168
|
+
resolve();
|
|
169
|
+
}
|
|
170
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
function relayClaim(value) {
|
|
174
|
+
if (!value || typeof value !== 'object')
|
|
175
|
+
return null;
|
|
176
|
+
const claim = value;
|
|
177
|
+
const claimToken = boundedString(claim.claim_token, CLAIM_TOKEN_MAX_CHARS);
|
|
178
|
+
if (!claimToken || !Array.isArray(claim.items) || claim.items.length === 0)
|
|
179
|
+
return null;
|
|
180
|
+
const items = claim.items.map((value) => {
|
|
181
|
+
if (!value || typeof value !== 'object')
|
|
182
|
+
return null;
|
|
183
|
+
const payload = value.payload;
|
|
184
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload))
|
|
185
|
+
return null;
|
|
186
|
+
return { payload: payload };
|
|
187
|
+
});
|
|
188
|
+
if (items.some((item) => item === null))
|
|
189
|
+
return null;
|
|
190
|
+
return { claimToken, items: items };
|
|
191
|
+
}
|
|
192
|
+
async function acknowledgeWithRetry(options, relayId, claimToken) {
|
|
193
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
194
|
+
try {
|
|
195
|
+
const response = await options.request('mailbox_ack', {
|
|
196
|
+
relay_id: relayId,
|
|
197
|
+
mode: options.mode,
|
|
198
|
+
claim_token: claimToken,
|
|
199
|
+
accepted_at: new Date().toISOString(),
|
|
200
|
+
}, options.requestTimeoutMs);
|
|
201
|
+
const status = response?.result?.status;
|
|
202
|
+
if (response?.ok && (status === 'accepted' || status === 'already_accepted'))
|
|
203
|
+
return true;
|
|
204
|
+
if (status === 'claim_lost')
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
catch { }
|
|
208
|
+
if (!options.isOwnerAlive() || options.signal?.aborted)
|
|
209
|
+
return false;
|
|
210
|
+
await (options.sleep ?? defaultSleep)(50 * (attempt + 1), options.signal);
|
|
211
|
+
}
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Disposable Host-side loop. It has no Owner shutdown authority and never sends
|
|
216
|
+
* stop/quit when its stdout consumer goes away.
|
|
217
|
+
*/
|
|
218
|
+
export async function runStdoutMailboxRelay(options) {
|
|
219
|
+
const relayId = options.relayId ?? `stdout:${process.pid}:${randomUUID()}`;
|
|
220
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
221
|
+
const pollMs = Math.max(25, Math.trunc(options.pollMs ?? DEFAULT_RELAY_POLL_MS));
|
|
222
|
+
while (!options.signal?.aborted) {
|
|
223
|
+
if (!options.isOwnerAlive())
|
|
224
|
+
return;
|
|
225
|
+
let response = null;
|
|
226
|
+
try {
|
|
227
|
+
response = await options.request('mailbox_claim', {
|
|
228
|
+
relay_id: relayId,
|
|
229
|
+
mode: options.mode,
|
|
230
|
+
lease_ttl_ms: DEFAULT_RELAY_LEASE_TTL_MS,
|
|
231
|
+
}, options.requestTimeoutMs);
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
if (!options.isOwnerAlive())
|
|
235
|
+
return;
|
|
236
|
+
await sleep(pollMs, options.signal);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (!response) {
|
|
240
|
+
if (!options.isOwnerAlive())
|
|
241
|
+
return;
|
|
242
|
+
await sleep(pollMs, options.signal);
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (!response.ok) {
|
|
246
|
+
throw new Error(response.error ?? 'mailbox_relay_rejected');
|
|
247
|
+
}
|
|
248
|
+
if (!response.claim) {
|
|
249
|
+
if (!options.isOwnerAlive())
|
|
250
|
+
return;
|
|
251
|
+
await sleep(Math.max(25, Number(response.wait_ms) || pollMs), options.signal);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const claim = relayClaim(response.claim);
|
|
255
|
+
if (!claim)
|
|
256
|
+
throw new Error('invalid_mailbox_claim');
|
|
257
|
+
// Mirror the Host Monitor token bucket: if the Host would suppress this
|
|
258
|
+
// write (bucket empty), do NOT emit. Nack the claim so the batch returns to
|
|
259
|
+
// pending — events stay durable and reach the agent on a later poll or via
|
|
260
|
+
// an explicit event query. Emitting anyway would be silently dropped by the Host.
|
|
261
|
+
if (options.rateGate && !options.rateGate.allow()) {
|
|
262
|
+
try {
|
|
263
|
+
await options.request('mailbox_nack', {
|
|
264
|
+
relay_id: relayId,
|
|
265
|
+
mode: options.mode,
|
|
266
|
+
claim_token: claim.claimToken,
|
|
267
|
+
retry_at_ms: Date.now() + pollMs,
|
|
268
|
+
error_code: 'host_rate_limited',
|
|
269
|
+
}, options.requestTimeoutMs);
|
|
270
|
+
}
|
|
271
|
+
catch { }
|
|
272
|
+
await sleep(Math.max(25, Number(response.wait_ms) || pollMs), options.signal);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
if (options.compose) {
|
|
277
|
+
await options.emit(options.compose(claim.items.map((item) => item.payload)));
|
|
278
|
+
}
|
|
279
|
+
else {
|
|
280
|
+
for (const item of claim.items)
|
|
281
|
+
await options.emit(item.payload);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
try {
|
|
286
|
+
await options.request('mailbox_nack', {
|
|
287
|
+
relay_id: relayId,
|
|
288
|
+
mode: options.mode,
|
|
289
|
+
claim_token: claim.claimToken,
|
|
290
|
+
retry_at_ms: Date.now() + pollMs,
|
|
291
|
+
error_code: 'stdout_write_failed',
|
|
292
|
+
}, options.requestTimeoutMs);
|
|
293
|
+
}
|
|
294
|
+
catch { }
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
await acknowledgeWithRetry(options, relayId, claim.claimToken);
|
|
298
|
+
}
|
|
299
|
+
}
|