File size: 14,354 Bytes
4440aec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | // Enqueues follow-up reply runs and schedules queue drains.
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import { normalizeChatType } from "../../../channels/chat-type.js";
import { racePromiseWithAbortSignal } from "../../../infra/abort-signal.js";
import { logMessageQueuedWithBacklogPolicy } from "../../../logging/diagnostic-runtime.js";
import { channelRouteDedupeKey } from "../../../plugin-sdk/channel-route.js";
import { defaultRuntime } from "../../../runtime.js";
import { extractTextFromChatContent } from "../../../shared/chat-content.js";
import { createDeferredCore } from "../../../shared/deferred.js";
import {
applyQueueDropPolicy,
countPendingQueueItems,
shouldSkipQueueItem,
} from "../../../utils/queue-helpers.js";
import {
clearFollowupDrainCallback,
createOverflowSummaryRetrySource,
dropAbortedFollowups,
kickFollowupDrainIfIdle,
rememberFollowupDrainCallback,
resolveFollowupDeliveryContextKey,
} from "./drain.js";
import {
peekRecentQueueMessageId,
recordRecentQueueMessageId,
resetRecentQueuedMessageIdDedupe,
} from "./recent-message-ids.js";
import {
FOLLOWUP_QUEUES,
getExistingFollowupQueue,
getFollowupQueue,
trimSummaryElisionsToCap,
} from "./state.js";
import {
completeFollowupRunLifecycle,
isFollowupRunAborted,
markFollowupRunEnqueued,
resolveFollowupAbortSignal,
type EnqueueFollowupRunOptions,
type FollowupRun,
type QueueDedupeMode,
type QueueSettings,
} from "./types.js";
function followupMessageRouteIdentityKey(run: FollowupRun): string {
return JSON.stringify([
channelRouteDedupeKey({
channel: run.originatingChannel,
to: run.originatingTo,
accountId: run.originatingAccountId,
threadId: run.originatingThreadId,
}),
normalizeChatType(run.originatingChatType) ?? "",
]);
}
function buildRecentMessageIdKey(run: FollowupRun, queueKey: string): string | undefined {
const messageId = normalizeOptionalString(run.messageId);
if (!messageId) {
return undefined;
}
// Use JSON tuple serialization to avoid delimiter-collision edge cases when
// channel/to/account values contain "|" characters.
return JSON.stringify(["queue", queueKey, followupMessageRouteIdentityKey(run), messageId]);
}
function isRunAlreadyQueued(run: FollowupRun, items: FollowupRun[]): boolean {
const messageId = normalizeOptionalString(run.messageId);
if (messageId) {
const messageRouteKey = followupMessageRouteIdentityKey(run);
return items.some(
(item) =>
normalizeOptionalString(item.messageId) === messageId &&
followupMessageRouteIdentityKey(item) === messageRouteKey,
);
}
return false;
}
function appendQueueItem(params: {
key: string;
queue: ReturnType<typeof getFollowupQueue>;
run: FollowupRun;
recentMessageIdKey?: string;
runFollowup?: (run: FollowupRun) => Promise<void>;
restartIfIdle: boolean;
front: boolean;
}): void {
params.queue.lastEnqueuedAt = Date.now();
params.queue.lastRun = params.run.run;
params.run.queueAbortSignal = params.queue.abortController.signal;
params.queue.items[params.front ? "unshift" : "push"](params.run);
if (params.recentMessageIdKey) {
recordRecentQueueMessageId(params.run, params.recentMessageIdKey);
}
const runFollowup = params.runFollowup;
if (runFollowup) {
rememberFollowupDrainCallback(params.key, runFollowup);
}
const signal = params.run.abortSignal;
const lifecycle = params.run.turnAdoptionLifecycle;
if (signal && lifecycle && runFollowup) {
const onAbort = () => {
const queue = getExistingFollowupQueue(params.key);
if (queue) {
// Cancellation must release pending ownership even while normal draining is dormant.
void dropAbortedFollowups(queue, runFollowup).catch((error: unknown) => {
defaultRuntime.error?.(`followup queue cancellation failed: ${String(error)}`);
});
}
};
const onSettled = lifecycle.onSettled;
lifecycle.onSettled = () => {
signal.removeEventListener("abort", onAbort);
onSettled?.();
};
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) {
onAbort();
}
}
if (params.restartIfIdle && !params.queue.draining) {
kickFollowupDrainIfIdle(params.key);
}
}
export function enqueueFollowupRun(
key: string,
run: FollowupRun,
settings: QueueSettings,
dedupeMode: QueueDedupeMode = "message-id",
runFollowup?: (run: FollowupRun) => Promise<void>,
restartIfIdle = true,
options: EnqueueFollowupRunOptions = {},
): boolean {
if (isFollowupRunAborted(run)) {
return false;
}
if (options.position === "front") {
run.protectFromQueueOverflow = true;
}
if (options.steerCandidate) {
run.steerAnchor = true;
}
// Peek before getFollowupQueue: rejecting a redelivery after the original
// queue drained and self-deleted must not recreate an empty registry entry,
// which nothing would ever delete again.
const recentMessageIdKey = dedupeMode !== "none" ? buildRecentMessageIdKey(run, key) : undefined;
if (recentMessageIdKey && peekRecentQueueMessageId(recentMessageIdKey)) {
return false;
}
const queue = getFollowupQueue(key, settings);
const dedupe = dedupeMode === "none" ? undefined : isRunAlreadyQueued;
// Deduplicate: skip if the same message is already queued.
if (shouldSkipQueueItem({ item: run, items: queue.items, dedupe })) {
return false;
}
if (options.steerCandidate) {
if (!markFollowupRunEnqueued(run)) {
return false;
}
const { promise: acceptance, resolve: settle } = createDeferredCore<boolean>();
run.steerPending = { phase: "waiting", predecessor: queue.steerAcceptanceTail, settle };
queue.steerAcceptanceTail = acceptance;
appendQueueItem({
key,
queue,
run,
recentMessageIdKey,
runFollowup,
restartIfIdle,
front: options.position === "front",
});
return true;
}
// A later normal/interrupt prompt cannot be dropped while an older steer is
// deciding between same-turn delivery and fallback. Append it behind the
// anchor; ordinary overflow policy resumes as soon as the gate resolves.
if (queue.items.some((item) => item.steerPending)) {
if (!markFollowupRunEnqueued(run)) {
return false;
}
appendQueueItem({
key,
queue,
run,
recentMessageIdKey,
runFollowup,
restartIfIdle,
front: false,
});
return true;
}
// drop:new rejects this source without mutating the existing queue. Do not
// publish an external queued identity for work that will never be admitted.
const pendingCount = countPendingQueueItems(queue.items, queue.inFlight);
if (
!options.steerCandidate &&
queue.dropPolicy === "new" &&
queue.cap > 0 &&
pendingCount >= queue.cap
) {
run.onQueueDisposition?.("queue-cap-new");
completeFollowupRunLifecycle(run);
return false;
}
if (!markFollowupRunEnqueued(run)) {
return false;
}
const elidedSummaryLines: string[] = [];
const shouldEnqueue = applyQueueDropPolicy({
queue,
inFlight: queue.inFlight,
summarize: (item) => {
const approved = item.userTurnTranscriptRecorder?.getPendingInputMessage?.();
// Capture the approved body before overflow stores its bounded preview.
return approved
? (extractTextFromChatContent(approved.content, {
normalizeText: (text) => text,
joinWith: "\n",
}) ?? "")
: normalizeOptionalString(item.summaryLine) || item.prompt.trim();
},
onSummaryElide: (lines) => elidedSummaryLines.push(...lines),
onDrop: (dropped) => {
if (queue.dropPolicy === "summarize") {
queue.summarySources.push(...dropped);
return;
}
for (const item of dropped) {
item.onQueueDisposition?.("queue-cap-old");
completeFollowupRunLifecycle(item);
}
},
isProtected: (item) => item.protectFromQueueOverflow === true || item.steerAnchor === true,
});
if (queue.dropPolicy === "summarize") {
const overflow = queue.summarySources.length - queue.summaryLines.length;
if (overflow > 0) {
const removed = queue.summarySources.splice(0, overflow);
for (const [index, item] of removed.entries()) {
const summaryLine = elidedSummaryLines[index];
if (summaryLine === undefined) {
throw new Error("followup queue summary source lost its elided line");
}
const contextKey = resolveFollowupDeliveryContextKey(item);
const lastElision = queue.summaryElisions.at(-1);
if (lastElision?.contextKey === contextKey) {
const compactSource = createOverflowSummaryRetrySource(item);
lastElision.count += 1;
lastElision.sources.push(compactSource);
lastElision.summaryLines.push(summaryLine);
lastElision.sourceRefs.set(item, compactSource);
if (queue.activeSummarySources.has(item)) {
queue.activeSummarySources.add(compactSource);
}
} else {
const compactSource = createOverflowSummaryRetrySource(item);
queue.summaryElisions.push({
contextKey,
count: 1,
sources: [compactSource],
summaryLines: [summaryLine],
sourceRefs: new WeakMap([[item, compactSource]]),
});
if (queue.activeSummarySources.has(item)) {
queue.activeSummarySources.add(compactSource);
}
}
trimSummaryElisionsToCap(queue);
}
}
}
if (!shouldEnqueue) {
run.onQueueDisposition?.("queue-cap");
completeFollowupRunLifecycle(run);
return false;
}
appendQueueItem({
key,
queue,
run,
recentMessageIdKey,
runFollowup,
restartIfIdle,
front: options.position === "front",
});
return true;
}
export function getFollowupQueueDepth(key: string): number {
const queue = getExistingFollowupQueue(key);
if (!queue) {
return 0;
}
return countPendingQueueItems(queue.items, queue.inFlight);
}
function settleParkedSteerAcceptance(key: string, run: FollowupRun, accepted: boolean): boolean {
const queue = getExistingFollowupQueue(key);
const pending = run.steerPending;
if (!queue?.items.includes(run) || !pending) {
return false;
}
pending.settle(accepted);
if (!accepted) {
delete run.steerPending;
reapplyDeferredOverflow(key);
kickFollowupDrainIfIdle(key);
}
return true;
}
function isParkedFollowupRunOwned(key: string, run: FollowupRun): boolean {
return getExistingFollowupQueue(key)?.items.includes(run) === true;
}
function reapplyDeferredOverflow(key: string): void {
const queue = getExistingFollowupQueue(key);
if (!queue || queue.items.some((item) => item.steerPending)) {
return;
}
const lastAnchor = queue.items.findLastIndex((item) => item.steerAnchor === true);
const suffix = queue.items.splice(lastAnchor + 1);
if (suffix.length === 0) {
return;
}
const originalCap = queue.cap;
const settings: QueueSettings = {
mode: queue.mode,
debounceMs: queue.debounceMs,
cap: originalCap + lastAnchor + 1,
dropPolicy: queue.dropPolicy,
};
for (const item of suffix) {
if (!enqueueFollowupRun(key, item, settings, "none", undefined, false)) {
completeFollowupRunLifecycle(item);
}
}
queue.cap = originalCap;
}
/** Remove an exactly committed steer while preserving every sibling's FIFO position. */
function consumeParkedFollowupRun(
key: string,
run: FollowupRun,
disposition?: "consumed",
): boolean {
const queue = getExistingFollowupQueue(key);
const index = queue?.items.indexOf(run) ?? -1;
if (!queue || index < 0) {
return false;
}
queue.items.splice(index, 1);
run.steerPending?.settle(true);
delete run.steerPending;
delete run.protectFromQueueOverflow;
delete run.steerAnchor;
reapplyDeferredOverflow(key);
completeFollowupRunLifecycle(run, disposition);
if (
!queue.draining &&
queue.items.length === 0 &&
queue.inFlight.size === 0 &&
queue.droppedCount === 0 &&
FOLLOWUP_QUEUES.get(key) === queue
) {
FOLLOWUP_QUEUES.delete(key);
clearFollowupDrainCallback(key);
} else {
kickFollowupDrainIfIdle(key);
}
return true;
}
type ParkedSteerReservation = {
admit: () => Promise<"steer" | "fallback" | "cancelled">;
accepted: (accepted: boolean) => void;
fallback: () => void;
consume: (disposition?: "consumed") => void;
};
export function parkSteerCandidate(
key: string,
run: FollowupRun,
settings: QueueSettings,
runFollowup: (run: FollowupRun) => Promise<void>,
): ParkedSteerReservation | undefined {
if (
!enqueueFollowupRun(key, run, settings, "message-id", runFollowup, false, {
steerCandidate: true,
})
) {
return undefined;
}
logMessageQueuedWithBacklogPolicy(
{
sessionId: run.run.sessionId,
sessionKey: key,
channel: run.originatingChannel ?? run.run.messageProvider,
source: "followup-queue-steer",
},
false,
);
return {
async admit() {
const pending = run.steerPending;
const predecessorAccepted = await racePromiseWithAbortSignal(
pending?.predecessor ?? Promise.resolve(true),
resolveFollowupAbortSignal(run),
).catch((error: unknown) => {
if (isFollowupRunAborted(run)) {
return false;
}
throw error;
});
if (isFollowupRunAborted(run) || !isParkedFollowupRunOwned(key, run)) {
return "cancelled";
}
if (!predecessorAccepted || !pending || run.steerPending !== pending) {
return "fallback";
}
// The injection owner now decides whether this input can safely be replayed.
pending.phase = "injecting";
return "steer";
},
accepted: (accepted) => settleParkedSteerAcceptance(key, run, accepted),
fallback: () => settleParkedSteerAcceptance(key, run, false),
consume: (disposition) => consumeParkedFollowupRun(key, run, disposition),
};
}
if (process.env.VITEST === "true" || process.env.NODE_ENV === "test") {
(globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw.queueEnqueueTestApi")] = {
resetRecentQueuedMessageIdDedupe,
};
}
|