@myclaw163/clawclaw-cli 0.7.5 → 0.7.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/desktop-event-push.md +154 -0
- package/docs/runtime/README.md +1 -0
- package/docs/runtime/official-perception-modules.md +346 -0
- package/package.json +2 -1
- package/src/commands/game/index.test.ts +167 -1
- package/src/commands/game/index.ts +125 -36
- package/src/lib/game-client.test.ts +15 -0
- package/src/lib/game-client.ts +4 -0
- package/src/lib/participation-status.ts +113 -0
- package/src/lib/service-status.test.ts +56 -0
- package/src/lib/service-status.ts +111 -0
- package/src/pipeline/event-format.test.ts +30 -0
- package/src/pipeline/event-format.ts +26 -1
- package/src/pipeline/event-hints.test.ts +18 -3
- package/src/pipeline/event-hints.ts +11 -0
- package/src/pipeline/game-sync-event-normalization.test.ts +58 -1
- package/src/pipeline/game-sync-event-normalization.ts +51 -0
- package/src/runtime/clawclaw/agent-event-policy.test.ts +4 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
- package/src/runtime/clawclaw/owner.ts +62 -3
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +189 -0
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +532 -0
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +363 -0
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +236 -0
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +411 -0
- package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +166 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +194 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +262 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +28 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +49 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +77 -259
- package/src/runtime/clawclaw/plugins/perception/contracts.ts +4 -0
- package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +6 -0
- package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +6 -0
- package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +6 -0
- package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +6 -0
- package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +6 -0
- package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +6 -0
- package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +6 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +11 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +8 -0
- package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +12 -0
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +37 -1
- package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +5 -0
- package/src/runtime/clawclaw/plugins/source/room-transport.ts +2 -1
- package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +201 -1
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +113 -24
- package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
- package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +6 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +4 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +4 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +36 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +13 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +22 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +46 -16
- package/src/runtime/clawclaw-event-catalog.test.ts +2 -0
- package/src/runtime/clawclaw-event-catalog.ts +1 -0
- package/src/sdk/perception-plugin/index.ts +14 -0
- package/src/sdk/resource-metadata.test.ts +40 -0
- package/src/sdk/resource-metadata.ts +63 -0
- package/src/sdk/strategy-plugin/index.ts +14 -0
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_EVENT_CONSUMER_ID,
|
|
4
|
+
type CanonicalEvent,
|
|
5
|
+
type ConsumerLease,
|
|
6
|
+
type EventRepository,
|
|
7
|
+
} from '../../../framework/events/index.js';
|
|
8
|
+
import type { RuntimeReadyView } from '../../../framework/runtime.js';
|
|
9
|
+
|
|
10
|
+
export const AGENT_MAILBOX_COALESCE_MS = 220;
|
|
11
|
+
const AGENT_MAILBOX_LEASE_TTL_MS = 5 * 60_000;
|
|
12
|
+
const AGENT_MAILBOX_PREPARE_WAIT_MS = 5_000;
|
|
13
|
+
const READY_VIEW_RETRY_MS = 25;
|
|
14
|
+
|
|
15
|
+
export type AgentMailboxDeliveryVia =
|
|
16
|
+
| 'mailbox_full'
|
|
17
|
+
| 'ccl_events'
|
|
18
|
+
| 'ccl_events_backlog';
|
|
19
|
+
|
|
20
|
+
export interface AgentMailboxBatch {
|
|
21
|
+
state: Record<string, unknown> | null;
|
|
22
|
+
events: Array<Record<string, unknown> | string>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface PreparedAgentMailboxBatch {
|
|
26
|
+
batch: AgentMailboxBatch;
|
|
27
|
+
deliveryToken?: string;
|
|
28
|
+
readyEpochSeq: number;
|
|
29
|
+
/** Earliest useful retry when the coalescing or Ready View boundary is pending. */
|
|
30
|
+
nextAttemptAtMs?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PrepareAgentMailboxBatchOptions {
|
|
34
|
+
readyView?: RuntimeReadyView;
|
|
35
|
+
/** Pull adapters use an explicit query boundary and do not need push coalescing. */
|
|
36
|
+
bypassDelay?: boolean;
|
|
37
|
+
deliveryVia?: AgentMailboxDeliveryVia;
|
|
38
|
+
ownerIdPrefix?: string;
|
|
39
|
+
/** Adapter-specific lease lifetime; omitted adapters use the Mailbox default. */
|
|
40
|
+
leaseTtlMs?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface AgentMailboxCoordinatorOptions {
|
|
44
|
+
repository: EventRepository;
|
|
45
|
+
readyView: () => RuntimeReadyView;
|
|
46
|
+
presentEvent: (
|
|
47
|
+
event: CanonicalEvent,
|
|
48
|
+
state: Record<string, any> | null | undefined,
|
|
49
|
+
) => Record<string, unknown> | string;
|
|
50
|
+
compactState: (
|
|
51
|
+
state: Record<string, any> | null | undefined,
|
|
52
|
+
events?: Array<Record<string, any>>,
|
|
53
|
+
) => Record<string, any> | null;
|
|
54
|
+
consumerId?: string;
|
|
55
|
+
coalesceMs?: number;
|
|
56
|
+
leaseTtlMs?: number;
|
|
57
|
+
now?: () => number;
|
|
58
|
+
diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface PreparedDelivery {
|
|
62
|
+
lease: ConsumerLease;
|
|
63
|
+
leaseTtlMs: number;
|
|
64
|
+
eventIds: string[];
|
|
65
|
+
readyEpochSeq: number;
|
|
66
|
+
sessionId: string;
|
|
67
|
+
segmentIds: string[];
|
|
68
|
+
deliveryVia: AgentMailboxDeliveryVia;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface AgentDelayWindow {
|
|
72
|
+
sessionId: string;
|
|
73
|
+
firstCommitSeq: number;
|
|
74
|
+
deadlineMs: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function nonEmptyString(value: unknown): string | undefined {
|
|
78
|
+
return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function compactStrategyState(
|
|
82
|
+
value: unknown,
|
|
83
|
+
runtime: string | undefined,
|
|
84
|
+
lastError: string | undefined,
|
|
85
|
+
phase: string | undefined,
|
|
86
|
+
alive: boolean | undefined,
|
|
87
|
+
): Record<string, unknown> | null {
|
|
88
|
+
const status = value && typeof value === 'object' && !Array.isArray(value)
|
|
89
|
+
? value as Record<string, unknown>
|
|
90
|
+
: {};
|
|
91
|
+
const id = runtime === 'not_selected' ? undefined : nonEmptyString(status.strategy);
|
|
92
|
+
const stageDoing = alive === false
|
|
93
|
+
? '角色已死亡,自动策略已停止。'
|
|
94
|
+
: phase === 'meeting'
|
|
95
|
+
? '会议阶段,自动策略已暂停。'
|
|
96
|
+
: phase === 'game_over'
|
|
97
|
+
? '本局结束,自动策略已停止。'
|
|
98
|
+
: phase === 'preparing'
|
|
99
|
+
? '等待进入游走阶段。'
|
|
100
|
+
: undefined;
|
|
101
|
+
const runtimeDoing = runtime === 'error'
|
|
102
|
+
? '策略执行出错,等待恢复。'
|
|
103
|
+
: runtime === 'not_selected'
|
|
104
|
+
? '尚未选择自动策略。'
|
|
105
|
+
: undefined;
|
|
106
|
+
const doing = stageDoing
|
|
107
|
+
?? runtimeDoing
|
|
108
|
+
?? nonEmptyString(status.summary)
|
|
109
|
+
?? (runtime === 'waiting_for_state' ? '等待最新游戏状态后继续。' : undefined);
|
|
110
|
+
const parameters = runtime !== 'not_selected' && status.parameters
|
|
111
|
+
&& typeof status.parameters === 'object'
|
|
112
|
+
&& !Array.isArray(status.parameters)
|
|
113
|
+
&& Object.keys(status.parameters).length > 0
|
|
114
|
+
? structuredClone(status.parameters)
|
|
115
|
+
: undefined;
|
|
116
|
+
const availability = status.dataAvailability
|
|
117
|
+
&& typeof status.dataAvailability === 'object'
|
|
118
|
+
&& !Array.isArray(status.dataAvailability)
|
|
119
|
+
? status.dataAvailability as Record<string, unknown>
|
|
120
|
+
: {};
|
|
121
|
+
const issue = runtime === 'error'
|
|
122
|
+
? lastError ?? 'strategy_error'
|
|
123
|
+
: runtime === 'not_selected'
|
|
124
|
+
? 'not_selected'
|
|
125
|
+
: availability.tasks === 'unavailable'
|
|
126
|
+
? 'tasks_unavailable'
|
|
127
|
+
: runtime && runtime !== 'active'
|
|
128
|
+
? runtime
|
|
129
|
+
: undefined;
|
|
130
|
+
const result = {
|
|
131
|
+
...(id ? { id } : {}),
|
|
132
|
+
...(doing ? { doing } : {}),
|
|
133
|
+
...(parameters ? { params: parameters } : {}),
|
|
134
|
+
...(issue ? { issue } : {}),
|
|
135
|
+
};
|
|
136
|
+
return Object.keys(result).length > 0 ? result : null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function emptyBatch(state: Record<string, unknown> | null = null): AgentMailboxBatch {
|
|
140
|
+
return { state, events: [] };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Durable Agent communication core owned by the Mailbox Plugin.
|
|
145
|
+
*
|
|
146
|
+
* It owns Ready View selection, full Agent presentation, coalescing and the
|
|
147
|
+
* details lease. Desktop IPC, Claude Channels and legacy pull commands are
|
|
148
|
+
* sibling adapters and may not advance delivery state outside this class.
|
|
149
|
+
*/
|
|
150
|
+
export class AgentMailboxCoordinator {
|
|
151
|
+
private readonly repository: EventRepository;
|
|
152
|
+
private readonly readyView: () => RuntimeReadyView;
|
|
153
|
+
private readonly presentEvent: AgentMailboxCoordinatorOptions['presentEvent'];
|
|
154
|
+
private readonly compactState: AgentMailboxCoordinatorOptions['compactState'];
|
|
155
|
+
private readonly consumerId: string;
|
|
156
|
+
private readonly coalesceMs: number;
|
|
157
|
+
private readonly leaseTtlMs: number;
|
|
158
|
+
private readonly now: () => number;
|
|
159
|
+
private readonly diagnostic?: AgentMailboxCoordinatorOptions['diagnostic'];
|
|
160
|
+
private readonly prepared = new Map<string, PreparedDelivery>();
|
|
161
|
+
private readonly preparedSlotWaiters = new Set<() => void>();
|
|
162
|
+
private prepareTail: Promise<void> = Promise.resolve();
|
|
163
|
+
private delayWindow?: AgentDelayWindow;
|
|
164
|
+
private lastObservedReadyEpochSeq = 0;
|
|
165
|
+
private stopped = false;
|
|
166
|
+
|
|
167
|
+
constructor(options: AgentMailboxCoordinatorOptions) {
|
|
168
|
+
this.repository = options.repository;
|
|
169
|
+
this.readyView = options.readyView;
|
|
170
|
+
this.presentEvent = options.presentEvent;
|
|
171
|
+
this.compactState = options.compactState;
|
|
172
|
+
this.consumerId = options.consumerId ?? DEFAULT_EVENT_CONSUMER_ID;
|
|
173
|
+
this.coalesceMs = options.coalesceMs ?? AGENT_MAILBOX_COALESCE_MS;
|
|
174
|
+
this.leaseTtlMs = options.leaseTtlMs ?? AGENT_MAILBOX_LEASE_TTL_MS;
|
|
175
|
+
this.now = options.now ?? Date.now;
|
|
176
|
+
this.diagnostic = options.diagnostic;
|
|
177
|
+
if (!Number.isFinite(this.coalesceMs) || this.coalesceMs < 0) {
|
|
178
|
+
throw new Error('Agent Mailbox coalesceMs must be non-negative.');
|
|
179
|
+
}
|
|
180
|
+
if (!Number.isFinite(this.leaseTtlMs) || this.leaseTtlMs <= 0) {
|
|
181
|
+
throw new Error('Agent Mailbox leaseTtlMs must be positive.');
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
prepare(options: PrepareAgentMailboxBatchOptions = {}): PreparedAgentMailboxBatch {
|
|
186
|
+
return this.prepareEvents(options);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Selects and projects one durable Agent-facing Event batch. */
|
|
190
|
+
prepareEvents(options: PrepareAgentMailboxBatchOptions = {}): PreparedAgentMailboxBatch {
|
|
191
|
+
this.assertRunning();
|
|
192
|
+
this.releaseExpiredPrepared();
|
|
193
|
+
if (this.prepared.size > 0) throw new Error('agent_mailbox_delivery_busy');
|
|
194
|
+
|
|
195
|
+
const ready = this.captureReadyView(options.readyView);
|
|
196
|
+
if (ready.epochSeq <= 0) {
|
|
197
|
+
return {
|
|
198
|
+
batch: emptyBatch(),
|
|
199
|
+
readyEpochSeq: 0,
|
|
200
|
+
...(this.delayWindow ? { nextAttemptAtMs: this.now() + READY_VIEW_RETRY_MS } : {}),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const state = this.compactReadyState(ready);
|
|
205
|
+
this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId);
|
|
206
|
+
const pending = this.repository.listEvents({
|
|
207
|
+
sessionId: ready.scope.sessionId,
|
|
208
|
+
detailStates: ['pending', 'deferred'],
|
|
209
|
+
maxCommitSeq: ready.eventWatermark,
|
|
210
|
+
maxEpochSeq: ready.epochSeq,
|
|
211
|
+
order: 'asc',
|
|
212
|
+
}, this.consumerId);
|
|
213
|
+
if (pending.length === 0) {
|
|
214
|
+
const eventIsBeyondReadyBoundary = this.delayWindow?.sessionId === ready.scope.sessionId
|
|
215
|
+
&& this.delayWindow.firstCommitSeq > ready.eventWatermark;
|
|
216
|
+
if (eventIsBeyondReadyBoundary) {
|
|
217
|
+
return {
|
|
218
|
+
batch: emptyBatch(state),
|
|
219
|
+
readyEpochSeq: ready.epochSeq,
|
|
220
|
+
nextAttemptAtMs: this.now() + READY_VIEW_RETRY_MS,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
this.delayWindow = undefined;
|
|
224
|
+
return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (this.delayWindow?.sessionId !== ready.scope.sessionId) {
|
|
228
|
+
this.delayWindow = {
|
|
229
|
+
sessionId: ready.scope.sessionId,
|
|
230
|
+
firstCommitSeq: pending[0]!.event.commitSeq,
|
|
231
|
+
deadlineMs: this.now() + this.coalesceMs,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
if (!options.bypassDelay && this.now() < this.delayWindow.deadlineMs) {
|
|
235
|
+
return {
|
|
236
|
+
batch: emptyBatch(state),
|
|
237
|
+
readyEpochSeq: ready.epochSeq,
|
|
238
|
+
nextAttemptAtMs: this.delayWindow.deadlineMs,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const deliveryVia = options.deliveryVia ?? 'mailbox_full';
|
|
243
|
+
const leaseTtlMs = options.leaseTtlMs ?? this.leaseTtlMs;
|
|
244
|
+
if (!Number.isFinite(leaseTtlMs) || leaseTtlMs <= 0) {
|
|
245
|
+
throw new Error('Agent Mailbox leaseTtlMs must be positive.');
|
|
246
|
+
}
|
|
247
|
+
const lease = this.repository.acquireLease({
|
|
248
|
+
consumerId: this.consumerId,
|
|
249
|
+
channel: 'details',
|
|
250
|
+
ownerId: `${options.ownerIdPrefix ?? 'agent_mailbox'}:${randomUUID()}`,
|
|
251
|
+
ttlMs: leaseTtlMs,
|
|
252
|
+
nowMs: this.now(),
|
|
253
|
+
});
|
|
254
|
+
if (!lease) throw new Error('agent_mailbox_delivery_busy');
|
|
255
|
+
|
|
256
|
+
try {
|
|
257
|
+
const candidates = this.repository.listEvents({
|
|
258
|
+
sessionId: ready.scope.sessionId,
|
|
259
|
+
detailStates: ['pending', 'deferred'],
|
|
260
|
+
maxCommitSeq: ready.eventWatermark,
|
|
261
|
+
maxEpochSeq: ready.epochSeq,
|
|
262
|
+
order: 'desc',
|
|
263
|
+
}, this.consumerId);
|
|
264
|
+
if (candidates.length === 0) {
|
|
265
|
+
this.delayWindow = undefined;
|
|
266
|
+
this.repository.releaseLease(lease);
|
|
267
|
+
return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const deliveryToken = randomUUID();
|
|
271
|
+
const segmentIds = [...new Set(candidates.map((row) => row.event.segmentId))];
|
|
272
|
+
this.prepared.set(deliveryToken, {
|
|
273
|
+
lease,
|
|
274
|
+
leaseTtlMs,
|
|
275
|
+
eventIds: candidates.map((row) => row.event.eventId),
|
|
276
|
+
readyEpochSeq: ready.epochSeq,
|
|
277
|
+
sessionId: ready.scope.sessionId,
|
|
278
|
+
segmentIds,
|
|
279
|
+
deliveryVia,
|
|
280
|
+
});
|
|
281
|
+
this.delayWindow = undefined;
|
|
282
|
+
this.diagnostic?.('runtime.agent_mailbox.delivery_prepared', {
|
|
283
|
+
consumer: this.consumerId,
|
|
284
|
+
delivery_token: deliveryToken,
|
|
285
|
+
delivery_via: deliveryVia,
|
|
286
|
+
session_id: ready.scope.sessionId,
|
|
287
|
+
segment_ids: segmentIds,
|
|
288
|
+
ready_epoch_seq: ready.epochSeq,
|
|
289
|
+
event_count: candidates.length,
|
|
290
|
+
});
|
|
291
|
+
return {
|
|
292
|
+
batch: {
|
|
293
|
+
state,
|
|
294
|
+
events: candidates.map((row) => this.presentEvent(row.event, ready.state.state)),
|
|
295
|
+
},
|
|
296
|
+
deliveryToken,
|
|
297
|
+
readyEpochSeq: ready.epochSeq,
|
|
298
|
+
};
|
|
299
|
+
} catch (error) {
|
|
300
|
+
this.repository.releaseLease(lease);
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
prepareWhenAvailable(
|
|
306
|
+
options: PrepareAgentMailboxBatchOptions = {},
|
|
307
|
+
timeoutMs = AGENT_MAILBOX_PREPARE_WAIT_MS,
|
|
308
|
+
): Promise<PreparedAgentMailboxBatch> {
|
|
309
|
+
return this.prepareEventsWhenAvailable(options, timeoutMs);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
prepareEventsWhenAvailable(
|
|
313
|
+
options: PrepareAgentMailboxBatchOptions = {},
|
|
314
|
+
timeoutMs = AGENT_MAILBOX_PREPARE_WAIT_MS,
|
|
315
|
+
): Promise<PreparedAgentMailboxBatch> {
|
|
316
|
+
const operation = this.prepareTail.then(async () => {
|
|
317
|
+
await this.waitForPreparedSlot(timeoutMs);
|
|
318
|
+
return this.prepareEvents(options);
|
|
319
|
+
});
|
|
320
|
+
this.prepareTail = operation.then(() => undefined, () => undefined);
|
|
321
|
+
return operation;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
stateForReadyView(readyView?: RuntimeReadyView): Record<string, any> | null {
|
|
325
|
+
this.assertRunning();
|
|
326
|
+
return this.compactReadyState(this.captureReadyView(readyView));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
ack(deliveryToken: string): boolean {
|
|
330
|
+
const prepared = this.prepared.get(deliveryToken);
|
|
331
|
+
if (!prepared || !this.renewPreparedLease(prepared)) return false;
|
|
332
|
+
const nowMs = this.now();
|
|
333
|
+
const transition = {
|
|
334
|
+
eventIds: prepared.eventIds,
|
|
335
|
+
consumerId: this.consumerId,
|
|
336
|
+
from: ['pending', 'deferred'],
|
|
337
|
+
to: 'delivered',
|
|
338
|
+
deliveredAt: new Date(nowMs).toISOString(),
|
|
339
|
+
deliveryVia: prepared.deliveryVia,
|
|
340
|
+
lease: prepared.lease,
|
|
341
|
+
nowMs,
|
|
342
|
+
} as Parameters<EventRepository['transitionDetails']>[0];
|
|
343
|
+
const changed = this.repository.transitionDetails(transition);
|
|
344
|
+
if (changed !== prepared.eventIds.length) return false;
|
|
345
|
+
this.prepared.delete(deliveryToken);
|
|
346
|
+
this.repository.releaseLease(prepared.lease);
|
|
347
|
+
this.notifyPreparedSlotAvailable();
|
|
348
|
+
this.diagnostic?.('runtime.agent_mailbox.delivery_acked', {
|
|
349
|
+
consumer: this.consumerId,
|
|
350
|
+
delivery_token: deliveryToken,
|
|
351
|
+
delivery_via: prepared.deliveryVia,
|
|
352
|
+
session_id: prepared.sessionId,
|
|
353
|
+
segment_ids: prepared.segmentIds,
|
|
354
|
+
ready_epoch_seq: prepared.readyEpochSeq,
|
|
355
|
+
event_count: prepared.eventIds.length,
|
|
356
|
+
});
|
|
357
|
+
return true;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
renew(deliveryToken: string): boolean {
|
|
361
|
+
const prepared = this.prepared.get(deliveryToken);
|
|
362
|
+
return prepared ? this.renewPreparedLease(prepared) : false;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
release(deliveryToken: string): boolean {
|
|
366
|
+
const prepared = this.prepared.get(deliveryToken);
|
|
367
|
+
if (!prepared) return false;
|
|
368
|
+
this.prepared.delete(deliveryToken);
|
|
369
|
+
const released = this.repository.releaseLease(prepared.lease);
|
|
370
|
+
this.delayWindow = {
|
|
371
|
+
sessionId: prepared.sessionId,
|
|
372
|
+
firstCommitSeq: 0,
|
|
373
|
+
deadlineMs: this.now(),
|
|
374
|
+
};
|
|
375
|
+
this.notifyPreparedSlotAvailable();
|
|
376
|
+
this.diagnostic?.('runtime.agent_mailbox.delivery_released', {
|
|
377
|
+
consumer: this.consumerId,
|
|
378
|
+
delivery_token: deliveryToken,
|
|
379
|
+
delivery_via: prepared.deliveryVia,
|
|
380
|
+
session_id: prepared.sessionId,
|
|
381
|
+
segment_ids: prepared.segmentIds,
|
|
382
|
+
ready_epoch_seq: prepared.readyEpochSeq,
|
|
383
|
+
event_count: prepared.eventIds.length,
|
|
384
|
+
released,
|
|
385
|
+
});
|
|
386
|
+
return released;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
observeEvents(events: readonly CanonicalEvent[]): void {
|
|
390
|
+
const first = events
|
|
391
|
+
.filter((event) => event.deliveryClass !== 'internal_only')
|
|
392
|
+
.sort((left, right) => left.commitSeq - right.commitSeq)[0];
|
|
393
|
+
if (!first || this.delayWindow?.sessionId === first.sessionId) return;
|
|
394
|
+
this.delayWindow = {
|
|
395
|
+
sessionId: first.sessionId,
|
|
396
|
+
firstCommitSeq: first.commitSeq,
|
|
397
|
+
deadlineMs: this.now() + this.coalesceMs,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async flush(): Promise<void> {
|
|
402
|
+
if (this.delayWindow) this.delayWindow.deadlineMs = this.now();
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async waitForDrain(shouldAbort: () => boolean = () => false): Promise<boolean> {
|
|
406
|
+
while (!shouldAbort()) {
|
|
407
|
+
const ready = this.captureReadyView();
|
|
408
|
+
if (ready.epochSeq <= 0) return this.prepared.size === 0;
|
|
409
|
+
this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId);
|
|
410
|
+
const pending = this.repository.listEvents({
|
|
411
|
+
sessionId: ready.scope.sessionId,
|
|
412
|
+
detailStates: ['pending', 'deferred'],
|
|
413
|
+
maxCommitSeq: ready.eventWatermark,
|
|
414
|
+
maxEpochSeq: ready.epochSeq,
|
|
415
|
+
order: 'asc',
|
|
416
|
+
}, this.consumerId);
|
|
417
|
+
if (pending.length === 0 && this.prepared.size === 0) return true;
|
|
418
|
+
await new Promise<void>((resolve) => {
|
|
419
|
+
const timer = setTimeout(resolve, READY_VIEW_RETRY_MS);
|
|
420
|
+
timer.unref?.();
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
return false;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async stop(): Promise<void> {
|
|
427
|
+
if (this.stopped) return;
|
|
428
|
+
this.stopped = true;
|
|
429
|
+
for (const token of [...this.prepared.keys()]) this.release(token);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
private captureReadyView(readyView?: RuntimeReadyView): RuntimeReadyView {
|
|
433
|
+
const ready = structuredClone(readyView ?? this.readyView());
|
|
434
|
+
if (ready.epochSeq > this.lastObservedReadyEpochSeq) {
|
|
435
|
+
this.diagnostic?.('runtime.agent_mailbox.ready_advanced', {
|
|
436
|
+
previous_ready_epoch_seq: this.lastObservedReadyEpochSeq,
|
|
437
|
+
ready_epoch_seq: ready.epochSeq,
|
|
438
|
+
event_commit_seq: ready.eventWatermark,
|
|
439
|
+
frame_seq: ready.frameSeq,
|
|
440
|
+
});
|
|
441
|
+
this.lastObservedReadyEpochSeq = ready.epochSeq;
|
|
442
|
+
}
|
|
443
|
+
return ready;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
private compactReadyState(ready: RuntimeReadyView): Record<string, any> | null {
|
|
447
|
+
if (!ready.state.state) return null;
|
|
448
|
+
const state = this.compactState(ready.state.state);
|
|
449
|
+
if (!state) return null;
|
|
450
|
+
const strategyState = ready.pluginStates['strategy.status'];
|
|
451
|
+
const strategyOutcome = ready.pluginOutcomes['clawclaw.strategy'];
|
|
452
|
+
if (!strategyState && !strategyOutcome) return state;
|
|
453
|
+
const runtime = strategyOutcome?.outcome === 'failed'
|
|
454
|
+
? 'error'
|
|
455
|
+
: strategyOutcome?.reason === 'strategy_inactive_stage'
|
|
456
|
+
? 'inactive_stage'
|
|
457
|
+
: strategyOutcome?.reason === 'strategy_waiting_for_current_state'
|
|
458
|
+
? 'waiting_for_state'
|
|
459
|
+
: strategyOutcome?.reason === 'strategy_not_selected'
|
|
460
|
+
? 'not_selected'
|
|
461
|
+
: strategyOutcome
|
|
462
|
+
? 'active'
|
|
463
|
+
: undefined;
|
|
464
|
+
const lastError = strategyOutcome?.outcome === 'failed'
|
|
465
|
+
? strategyOutcome.reason
|
|
466
|
+
: undefined;
|
|
467
|
+
const strategy = compactStrategyState(
|
|
468
|
+
strategyState?.value,
|
|
469
|
+
runtime,
|
|
470
|
+
lastError,
|
|
471
|
+
nonEmptyString(state.phase),
|
|
472
|
+
typeof state.you?.alive === 'boolean' ? state.you.alive : undefined,
|
|
473
|
+
);
|
|
474
|
+
return strategy ? { ...state, strategy } : state;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
private releaseExpiredPrepared(): void {
|
|
478
|
+
const nowMs = this.now();
|
|
479
|
+
for (const [token, prepared] of this.prepared) {
|
|
480
|
+
if (prepared.lease.expiresAt > nowMs) continue;
|
|
481
|
+
this.prepared.delete(token);
|
|
482
|
+
this.repository.releaseLease(prepared.lease);
|
|
483
|
+
}
|
|
484
|
+
this.notifyPreparedSlotAvailable();
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
private renewPreparedLease(prepared: PreparedDelivery): boolean {
|
|
488
|
+
const renewed = this.repository.acquireLease({
|
|
489
|
+
consumerId: prepared.lease.consumerId,
|
|
490
|
+
channel: prepared.lease.channel,
|
|
491
|
+
ownerId: prepared.lease.ownerId,
|
|
492
|
+
ttlMs: prepared.leaseTtlMs,
|
|
493
|
+
nowMs: this.now(),
|
|
494
|
+
});
|
|
495
|
+
if (!renewed) return false;
|
|
496
|
+
prepared.lease = renewed;
|
|
497
|
+
return true;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private waitForPreparedSlot(timeoutMs: number): Promise<void> {
|
|
501
|
+
this.assertRunning();
|
|
502
|
+
this.releaseExpiredPrepared();
|
|
503
|
+
if (this.prepared.size === 0) return Promise.resolve();
|
|
504
|
+
const boundedTimeoutMs = Math.max(1, Math.trunc(timeoutMs));
|
|
505
|
+
return new Promise((resolve, reject) => {
|
|
506
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
507
|
+
const cleanup = (): void => {
|
|
508
|
+
if (timer) clearTimeout(timer);
|
|
509
|
+
this.preparedSlotWaiters.delete(available);
|
|
510
|
+
};
|
|
511
|
+
const available = (): void => {
|
|
512
|
+
cleanup();
|
|
513
|
+
resolve();
|
|
514
|
+
};
|
|
515
|
+
this.preparedSlotWaiters.add(available);
|
|
516
|
+
timer = setTimeout(() => {
|
|
517
|
+
cleanup();
|
|
518
|
+
reject(new Error('agent_mailbox_delivery_busy'));
|
|
519
|
+
}, boundedTimeoutMs);
|
|
520
|
+
timer.unref?.();
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
private notifyPreparedSlotAvailable(): void {
|
|
525
|
+
if (this.prepared.size > 0) return;
|
|
526
|
+
for (const waiter of [...this.preparedSlotWaiters]) waiter();
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
private assertRunning(): void {
|
|
530
|
+
if (this.stopped) throw new Error('agent_mailbox_stopped');
|
|
531
|
+
}
|
|
532
|
+
}
|