@qwen-code/channel-base 0.28.1-preview.0 → 0.28.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AcpBridge.d.ts +22 -1
- package/dist/AcpBridge.d.ts.map +1 -1
- package/dist/AcpBridge.js +107 -2
- package/dist/AcpBridge.js.map +1 -1
- package/dist/ChannelAgentBridge.d.ts +48 -0
- package/dist/ChannelAgentBridge.d.ts.map +1 -1
- package/dist/ChannelAgentBridge.js +14 -0
- package/dist/ChannelAgentBridge.js.map +1 -1
- package/dist/ChannelBase.d.ts +80 -0
- package/dist/ChannelBase.d.ts.map +1 -1
- package/dist/ChannelBase.js +409 -4
- package/dist/ChannelBase.js.map +1 -1
- package/dist/group-history-store.d.ts +12 -0
- package/dist/group-history-store.d.ts.map +1 -1
- package/dist/group-history-store.js +41 -0
- package/dist/group-history-store.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/managed-channel.d.ts +54 -2
- package/dist/managed-channel.d.ts.map +1 -1
- package/dist/managed-channel.js +59 -0
- package/dist/managed-channel.js.map +1 -1
- package/dist/types.d.ts +8 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/dist/ChannelBase.js
CHANGED
|
@@ -13,7 +13,7 @@ import { matchMessageRoute } from './message-routes.js';
|
|
|
13
13
|
import { NamedSessionManager, NamedSessionTaskError, } from './named-session-manager.js';
|
|
14
14
|
import { getGlobalQwenDir } from './paths.js';
|
|
15
15
|
import { sanitizeSenderName, sanitizeQuotedText, sanitizePromptText, sanitizePromptPath, sanitizeLogText, sanitizeDisplayText, truncateCodePoints, PROMPT_UNSAFE_INVISIBLES, } from './sanitize.js';
|
|
16
|
-
import { BACKGROUND_WORKFLOW_APPROVAL_META_KEY, CHANNEL_WORKFLOW_ORIGIN_META_KEY, ChannelPromptCancelledError, parseChannelWorkflowOrigin, } from './ChannelAgentBridge.js';
|
|
16
|
+
import { BACKGROUND_WORKFLOW_APPROVAL_META_KEY, CHANNEL_WORKFLOW_ORIGIN_META_KEY, ChannelPromptCancelledError, MID_TURN_QUEUE_MAX_CHARS, MID_TURN_QUEUE_MAX_MESSAGES, parseChannelWorkflowOrigin, } from './ChannelAgentBridge.js';
|
|
17
17
|
import { ChannelLoopSkippedError } from './ChannelLoopScheduler.js';
|
|
18
18
|
import { buildChannelWebhookPrompt, resolveChannelWebhookTarget, } from './ChannelWebhookTask.js';
|
|
19
19
|
import { parseChannelMemoryIntent, } from './channel-memory-intent.js';
|
|
@@ -199,8 +199,39 @@ export class ChannelBase {
|
|
|
199
199
|
/** Per-session active prompt tracking for dispatch modes. */
|
|
200
200
|
activePrompts = new Map();
|
|
201
201
|
activeBtw = new Map();
|
|
202
|
+
/**
|
|
203
|
+
* Arrival ordinal stamped on every message admitted to the collect buffer or
|
|
204
|
+
* the mid-turn queue. Both structures hold messages of the same turn and are
|
|
205
|
+
* merged at its boundary, so only a shared counter can restore their
|
|
206
|
+
* interleaved arrival order.
|
|
207
|
+
*/
|
|
208
|
+
inboundOrdinal = 0;
|
|
202
209
|
/** Per-session message buffer for collect mode. */
|
|
203
210
|
collectBuffers = new Map();
|
|
211
|
+
/**
|
|
212
|
+
* Accepted mid-turn injections of the session's RUNNING turn, in arrival
|
|
213
|
+
* order. At the turn boundary the channel takes back whatever the bridge
|
|
214
|
+
* never drained and replays it as a new turn instead of letting it leak into
|
|
215
|
+
* the next one.
|
|
216
|
+
*/
|
|
217
|
+
midTurnInjections = new Map();
|
|
218
|
+
/**
|
|
219
|
+
* Sessions whose current turn already routed a message to the bounded
|
|
220
|
+
* inject→collect fallback: subsequent messages must follow it there, or a
|
|
221
|
+
* later injected instruction could overtake an earlier parked one. This gate
|
|
222
|
+
* also carries the fallback's capacity accounting.
|
|
223
|
+
*/
|
|
224
|
+
injectDegradedSessions = new Set();
|
|
225
|
+
/**
|
|
226
|
+
* Sessions whose current turn already parked a message in the collect buffer
|
|
227
|
+
* for any reason (media, a slash command, a foreign chat/thread, an
|
|
228
|
+
* unauthorized member, a rejected injection): later messages must park too
|
|
229
|
+
* to keep arrival order, but as plain `collect` entries, outside the bounded
|
|
230
|
+
* fallback's accounting.
|
|
231
|
+
*/
|
|
232
|
+
injectOrderLockedSessions = new Set();
|
|
233
|
+
/** Sessions already told (once) that their bridge cannot inject at all. */
|
|
234
|
+
injectUnsupportedNotified = new Set();
|
|
204
235
|
preflightedEnvelopes = new WeakSet();
|
|
205
236
|
bridgeToolCallListener = (event) => {
|
|
206
237
|
this.dispatchToolCall(event);
|
|
@@ -1020,6 +1051,7 @@ export class ChannelBase {
|
|
|
1020
1051
|
}
|
|
1021
1052
|
this.cancelBtw(sessionId);
|
|
1022
1053
|
this.dropCollectBuffer(sessionId);
|
|
1054
|
+
this.dropMidTurnInjections(sessionId);
|
|
1023
1055
|
this.instructedSessions.delete(sessionId);
|
|
1024
1056
|
this.unattendedMemorySessions.delete(sessionId);
|
|
1025
1057
|
this.removePendingPermissionsForSession(sessionId);
|
|
@@ -1444,12 +1476,129 @@ export class ChannelBase {
|
|
|
1444
1476
|
// Telemetry must never affect channel delivery.
|
|
1445
1477
|
}
|
|
1446
1478
|
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Settle the turn's accepted mid-turn injections at its boundary: whatever
|
|
1481
|
+
* the bridge never drained (a tool-free turn drains nothing, and a turn that
|
|
1482
|
+
* ends before the child's next drain would otherwise leak the text into the
|
|
1483
|
+
* NEXT turn) is taken back and queued for replay as its own turn. Runs after
|
|
1484
|
+
* the prompt settled and only while this turn still owns the session.
|
|
1485
|
+
*/
|
|
1486
|
+
settleUndrainedMidTurnInjections(sessionId) {
|
|
1487
|
+
this.injectDegradedSessions.delete(sessionId);
|
|
1488
|
+
this.injectOrderLockedSessions.delete(sessionId);
|
|
1489
|
+
const pending = this.midTurnInjections.get(sessionId);
|
|
1490
|
+
if (!pending || pending.length === 0)
|
|
1491
|
+
return;
|
|
1492
|
+
this.midTurnInjections.delete(sessionId);
|
|
1493
|
+
const undrained = this.bridge.takeUndrainedMidTurnMessages?.(sessionId);
|
|
1494
|
+
if (!undrained || undrained.length === 0)
|
|
1495
|
+
return;
|
|
1496
|
+
// A drain always consumes from the head of the queue, so the leftovers are
|
|
1497
|
+
// exactly the tail of this turn's accepted injections.
|
|
1498
|
+
const replay = pending.slice(Math.max(0, pending.length - undrained.length));
|
|
1499
|
+
if (replay.length === 0)
|
|
1500
|
+
return;
|
|
1501
|
+
// Each replayed message was accepted mid-turn and consumed its backfill at
|
|
1502
|
+
// acceptance. Hand the consumed entries back before the replay turn runs,
|
|
1503
|
+
// so it composes the same wrapper instead of answering a reference it can
|
|
1504
|
+
// no longer resolve. Restore newest-last: a later injection consumed newer
|
|
1505
|
+
// entries, and each restore prepends, so iterating backwards keeps the
|
|
1506
|
+
// store's arrival order.
|
|
1507
|
+
for (let i = replay.length - 1; i >= 0; i--) {
|
|
1508
|
+
this.restoreInjectedGroupHistory(replay[i]);
|
|
1509
|
+
}
|
|
1510
|
+
let buffer = this.collectBuffers.get(sessionId);
|
|
1511
|
+
if (!buffer) {
|
|
1512
|
+
buffer = [];
|
|
1513
|
+
this.collectBuffers.set(sessionId, buffer);
|
|
1514
|
+
}
|
|
1515
|
+
// A message the bounded fallback parked after these injections were
|
|
1516
|
+
// accepted must not be replayed ahead of them, so merge by arrival ordinal
|
|
1517
|
+
// rather than appending the recovered tail.
|
|
1518
|
+
for (const entry of replay) {
|
|
1519
|
+
buffer.push({
|
|
1520
|
+
text: entry.text,
|
|
1521
|
+
envelope: entry.envelope,
|
|
1522
|
+
sequence: entry.sequence,
|
|
1523
|
+
});
|
|
1524
|
+
}
|
|
1525
|
+
buffer.sort((a, b) => a.sequence - b.sequence);
|
|
1526
|
+
process.stderr.write(`[${this.name}] inject: ${replay.length} mid-turn message(s) were not drained before the turn ended; replaying as a new turn for session ${sessionId}\n`);
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* Drop the session's queued (not yet drained) mid-turn injections, e.g. when
|
|
1530
|
+
* the running turn is cancelled: they are already invalid for the cancelled
|
|
1531
|
+
* turn and must not surface in the next one out of context. Surfaces the drop
|
|
1532
|
+
* through the same buffer-drop notification the collect path uses, but only
|
|
1533
|
+
* for the not-yet-drained tail: injections the child already drained reached
|
|
1534
|
+
* the running turn, so reporting them as dropped would contradict the
|
|
1535
|
+
* transport state adapters acknowledge from that notification.
|
|
1536
|
+
*/
|
|
1537
|
+
dropMidTurnInjections(sessionId) {
|
|
1538
|
+
this.injectDegradedSessions.delete(sessionId);
|
|
1539
|
+
this.injectOrderLockedSessions.delete(sessionId);
|
|
1540
|
+
this.injectUnsupportedNotified.delete(sessionId);
|
|
1541
|
+
const pending = this.midTurnInjections.get(sessionId);
|
|
1542
|
+
this.midTurnInjections.delete(sessionId);
|
|
1543
|
+
// Take the bridge's leftovers before clearing them: their count is the
|
|
1544
|
+
// authoritative number of accepted injections the child never received.
|
|
1545
|
+
const undrainedCount = this.bridge.takeUndrainedMidTurnMessages?.(sessionId).length;
|
|
1546
|
+
this.bridge.dropMidTurnMessages?.(sessionId);
|
|
1547
|
+
if (!pending || pending.length === 0)
|
|
1548
|
+
return;
|
|
1549
|
+
// A drain always consumes from the head of the admission ledger, so the
|
|
1550
|
+
// undrained messages are exactly its tail. Bridges without the accessor
|
|
1551
|
+
// cannot tell, and keep the older whole-ledger behaviour.
|
|
1552
|
+
const dropped = undrainedCount === undefined
|
|
1553
|
+
? pending
|
|
1554
|
+
: pending.slice(Math.max(0, pending.length - Math.min(undrainedCount, pending.length)));
|
|
1555
|
+
if (dropped.length === 0)
|
|
1556
|
+
return;
|
|
1557
|
+
const chatId = dropped[0].envelope.chatId;
|
|
1558
|
+
const messageIds = dropped
|
|
1559
|
+
.map((entry) => entry.envelope.messageId)
|
|
1560
|
+
.filter((id) => id !== undefined);
|
|
1561
|
+
try {
|
|
1562
|
+
this.onPromptBufferDropped(chatId, sessionId, messageIds);
|
|
1563
|
+
}
|
|
1564
|
+
catch (err) {
|
|
1565
|
+
process.stderr.write(`[${this.name}] onPromptBufferDropped threw for injected messages in session ${sessionId}: ${err instanceof Error ? err.message : err}\n`);
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1447
1568
|
drainCollectBufferForCurrentPrompt(sessionId, stillCurrent, taskLabel) {
|
|
1569
|
+
if (!stillCurrent)
|
|
1570
|
+
return;
|
|
1571
|
+
this.settleUndrainedMidTurnInjections(sessionId);
|
|
1448
1572
|
const buffer = this.collectBuffers.get(sessionId);
|
|
1449
|
-
if (!
|
|
1573
|
+
if (!buffer || buffer.length === 0) {
|
|
1450
1574
|
return;
|
|
1451
1575
|
}
|
|
1452
1576
|
this.collectBuffers.delete(sessionId);
|
|
1577
|
+
// A session-scoped session can hold buffered messages from more than one
|
|
1578
|
+
// route: a message whose chat/thread does not own the running turn parks
|
|
1579
|
+
// here. The replay is attributed to the LAST entry's route, so coalescing
|
|
1580
|
+
// two routes into one turn would answer one of them in the wrong chat —
|
|
1581
|
+
// the exact harm `runningTurnOwnsEnvelope` prevents for mid-turn
|
|
1582
|
+
// injections. Replay each contiguous run of one route as its own turn in
|
|
1583
|
+
// arrival order: grouping every entry of a route instead would let a later
|
|
1584
|
+
// message overtake an earlier one from another route, and these replays
|
|
1585
|
+
// share one session's arrival order.
|
|
1586
|
+
const ordered = [...buffer].sort((a, b) => a.sequence - b.sequence);
|
|
1587
|
+
let run = [];
|
|
1588
|
+
for (const entry of ordered) {
|
|
1589
|
+
if (run.length > 0 &&
|
|
1590
|
+
this.routeKey(run[0].envelope) !== this.routeKey(entry.envelope)) {
|
|
1591
|
+
this.replayCollectedEntries(sessionId, run, taskLabel);
|
|
1592
|
+
run = [];
|
|
1593
|
+
}
|
|
1594
|
+
run.push(entry);
|
|
1595
|
+
}
|
|
1596
|
+
if (run.length > 0) {
|
|
1597
|
+
this.replayCollectedEntries(sessionId, run, taskLabel);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
/** Replay one route's buffered messages as a single turn. */
|
|
1601
|
+
replayCollectedEntries(sessionId, buffer, taskLabel) {
|
|
1453
1602
|
const lost = buffer.length;
|
|
1454
1603
|
const coalesced = buffer.map((b) => b.text).join('\n\n');
|
|
1455
1604
|
const lastEnvelope = buffer[buffer.length - 1].envelope;
|
|
@@ -1458,6 +1607,8 @@ export class ChannelBase {
|
|
|
1458
1607
|
...lastEnvelope,
|
|
1459
1608
|
text: coalesced,
|
|
1460
1609
|
alreadyPrefixed: true,
|
|
1610
|
+
// The replay must become its own turn; `inject` skips it by this marker.
|
|
1611
|
+
collectReplay: true,
|
|
1461
1612
|
referencedText: undefined,
|
|
1462
1613
|
mentionedMemberIds: undefined,
|
|
1463
1614
|
attachments: undefined,
|
|
@@ -2050,6 +2201,10 @@ export class ChannelBase {
|
|
|
2050
2201
|
}
|
|
2051
2202
|
active.cancelled = true;
|
|
2052
2203
|
this.dropCollectBuffer(sessionId);
|
|
2204
|
+
// The cancelled turn can still drain its mid-turn queue as it winds
|
|
2205
|
+
// down, so its queued injections are dropped with the collect buffer —
|
|
2206
|
+
// otherwise they would surface in the user's NEXT turn out of context.
|
|
2207
|
+
this.dropMidTurnInjections(sessionId);
|
|
2053
2208
|
this.removePendingPermissionsForSession(sessionId, 'run_cancelled', {
|
|
2054
2209
|
preserveBackgroundWorkflows: reason !== 'clear',
|
|
2055
2210
|
});
|
|
@@ -2094,6 +2249,71 @@ export class ChannelBase {
|
|
|
2094
2249
|
.map((entry) => entry.envelope.messageId)
|
|
2095
2250
|
.filter((id) => typeof id === 'string' && id.length > 0);
|
|
2096
2251
|
}
|
|
2252
|
+
/** Route identity of a chat/thread pair; comparisons stay in one place. */
|
|
2253
|
+
routeKey(target) {
|
|
2254
|
+
return `${target.chatId}\u0000${target.threadId ?? ''}`;
|
|
2255
|
+
}
|
|
2256
|
+
/** The running turn's output route is bound to its originating chat/thread. */
|
|
2257
|
+
runningTurnOwnsEnvelope(active, envelope) {
|
|
2258
|
+
return this.routeKey(active) === this.routeKey(envelope);
|
|
2259
|
+
}
|
|
2260
|
+
nextInboundOrdinal() {
|
|
2261
|
+
return ++this.inboundOrdinal;
|
|
2262
|
+
}
|
|
2263
|
+
recordInjectedMessage(sessionId, text, envelope, groupHistory) {
|
|
2264
|
+
let pending = this.midTurnInjections.get(sessionId);
|
|
2265
|
+
if (!pending) {
|
|
2266
|
+
pending = [];
|
|
2267
|
+
this.midTurnInjections.set(sessionId, pending);
|
|
2268
|
+
}
|
|
2269
|
+
pending.push({
|
|
2270
|
+
text,
|
|
2271
|
+
envelope,
|
|
2272
|
+
sequence: this.nextInboundOrdinal(),
|
|
2273
|
+
groupHistory,
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
/**
|
|
2277
|
+
* Return the pending group history a replayed injected message consumed when
|
|
2278
|
+
* it was accepted to the store, so the message's own turn composes the same
|
|
2279
|
+
* backfill the running turn saw. Entries are restored ahead of anything
|
|
2280
|
+
* recorded since the acceptance, which is newer by construction.
|
|
2281
|
+
*/
|
|
2282
|
+
restoreInjectedGroupHistory(entry) {
|
|
2283
|
+
if (entry.groupHistory.length === 0)
|
|
2284
|
+
return;
|
|
2285
|
+
const limit = this.groupHistoryLimit(entry.envelope);
|
|
2286
|
+
if (limit <= 0)
|
|
2287
|
+
return;
|
|
2288
|
+
try {
|
|
2289
|
+
this.groupHistory.recordFront(this.groupHistoryKey(entry.envelope), entry.groupHistory, limit);
|
|
2290
|
+
}
|
|
2291
|
+
catch (err) {
|
|
2292
|
+
process.stderr.write(`[${this.name}] failed to restore group history for a replayed injected message: ${err instanceof Error ? err.message : err}\n`);
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
notifyPromptInjected(chatId, sessionId, messageId) {
|
|
2296
|
+
try {
|
|
2297
|
+
this.onPromptInjected(chatId, sessionId, messageId);
|
|
2298
|
+
}
|
|
2299
|
+
catch (err) {
|
|
2300
|
+
process.stderr.write(`[${this.name}] onPromptInjected threw for session ${sessionId}: ${err instanceof Error ? err.message : err}\n`);
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
logInjectUnsupported(sessionId) {
|
|
2304
|
+
if (this.injectUnsupportedNotified.has(sessionId))
|
|
2305
|
+
return;
|
|
2306
|
+
this.injectUnsupportedNotified.add(sessionId);
|
|
2307
|
+
process.stderr.write(`[${this.name}] inject: bridge for session ${sanitizeLogText(sessionId, 64)} cannot queue mid-turn messages; buffering as collect (inject requires an ACP-bridge-backed channel)\n`);
|
|
2308
|
+
}
|
|
2309
|
+
async notifyInjectRefused(envelope, text) {
|
|
2310
|
+
try {
|
|
2311
|
+
await this.sendThreadMessage(envelope.chatId, envelope.threadId, text);
|
|
2312
|
+
}
|
|
2313
|
+
catch (err) {
|
|
2314
|
+
process.stderr.write(`[${this.name}] inject: failed to tell ${envelope.senderId} their message was refused: ${err instanceof Error ? err.message : err}\n`);
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2097
2317
|
logCancelSessionFailure(sessionId, err) {
|
|
2098
2318
|
process.stderr.write(`[${sanitizeLogText(this.name, 64)}] cancelSession failed for session=${sanitizeLogText(sessionId, 64)}: ${this.lifecycleError(err)}\n`);
|
|
2099
2319
|
}
|
|
@@ -2124,6 +2344,10 @@ export class ChannelBase {
|
|
|
2124
2344
|
this.router.handleSessionDied(sessionId);
|
|
2125
2345
|
this.instructedSessions.delete(sessionId);
|
|
2126
2346
|
this.unattendedMemorySessions.delete(sessionId);
|
|
2347
|
+
this.midTurnInjections.delete(sessionId);
|
|
2348
|
+
this.injectDegradedSessions.delete(sessionId);
|
|
2349
|
+
this.injectOrderLockedSessions.delete(sessionId);
|
|
2350
|
+
this.injectUnsupportedNotified.delete(sessionId);
|
|
2127
2351
|
this.removePendingPermissionsForSession(sessionId);
|
|
2128
2352
|
}
|
|
2129
2353
|
/**
|
|
@@ -2161,6 +2385,18 @@ export class ChannelBase {
|
|
|
2161
2385
|
return true;
|
|
2162
2386
|
}
|
|
2163
2387
|
onPromptBuffered(_chatId, _sessionId, _messageId) { }
|
|
2388
|
+
/**
|
|
2389
|
+
* Called when the running turn ACCEPTED this message into its mid-turn queue.
|
|
2390
|
+
* Unlike `onPromptBuffered` the message starts no turn of its own, so an
|
|
2391
|
+
* adapter that tracks per-message state can keep it until the running turn's
|
|
2392
|
+
* `onPromptEnd` fires — that is the turn which reads the injected text.
|
|
2393
|
+
* Injected messages are text-only: media parks for a replay turn and inline
|
|
2394
|
+
* images are refused, so no media resource is retained for injection. If the
|
|
2395
|
+
* turn ends before the bridge drains the message, it is replayed as its own
|
|
2396
|
+
* turn: that replay fires the ordinary `onPromptStart`/`onPromptEnd` hooks
|
|
2397
|
+
* and carries the replay envelope's IDs, not the injected message's.
|
|
2398
|
+
*/
|
|
2399
|
+
onPromptInjected(_chatId, _sessionId, _messageId) { }
|
|
2164
2400
|
onPromptBufferDrained(_chatId, _sessionId, _messageIds) { }
|
|
2165
2401
|
onPromptBufferDropped(_chatId, _sessionId, _messageIds) { }
|
|
2166
2402
|
/**
|
|
@@ -3030,6 +3266,7 @@ export class ChannelBase {
|
|
|
3030
3266
|
// or resurrect via collect-drain — the just-cleared session.
|
|
3031
3267
|
const active = this.activePrompts.get(id);
|
|
3032
3268
|
this.dropCollectBuffer(id);
|
|
3269
|
+
this.dropMidTurnInjections(id);
|
|
3033
3270
|
if (active) {
|
|
3034
3271
|
// Bounded cancel + wind-down wait; purge regardless of the result.
|
|
3035
3272
|
const settled = await this.cancelAndAwaitActive(active, id);
|
|
@@ -4429,6 +4666,26 @@ export class ChannelBase {
|
|
|
4429
4666
|
return [];
|
|
4430
4667
|
}
|
|
4431
4668
|
}
|
|
4669
|
+
peekPendingGroupHistory(envelope) {
|
|
4670
|
+
const limit = this.groupHistoryLimit(envelope);
|
|
4671
|
+
if (limit <= 0) {
|
|
4672
|
+
return [];
|
|
4673
|
+
}
|
|
4674
|
+
try {
|
|
4675
|
+
const entries = this.groupHistory.peek(this.groupHistoryKey(envelope), limit);
|
|
4676
|
+
if (this.config.groupPolicy === 'pairing' &&
|
|
4677
|
+
!this.groupGate.isGroupApproved(envelope.chatId)) {
|
|
4678
|
+
return [];
|
|
4679
|
+
}
|
|
4680
|
+
return envelope.messageId === undefined
|
|
4681
|
+
? entries
|
|
4682
|
+
: entries.filter((entry) => entry.messageId !== envelope.messageId);
|
|
4683
|
+
}
|
|
4684
|
+
catch (err) {
|
|
4685
|
+
process.stderr.write(`[${this.name}] failed to peek group history for chat ${sanitizeLogText(envelope.chatId, 64)}: ${err instanceof Error ? err.message : err}\n`);
|
|
4686
|
+
return [];
|
|
4687
|
+
}
|
|
4688
|
+
}
|
|
4432
4689
|
forgetPendingGroupHistory(envelope) {
|
|
4433
4690
|
if (envelope.messageId === undefined)
|
|
4434
4691
|
return;
|
|
@@ -5193,14 +5450,162 @@ export class ChannelBase {
|
|
|
5193
5450
|
if (active) {
|
|
5194
5451
|
// A prompt is already running for this session
|
|
5195
5452
|
switch (mode) {
|
|
5196
|
-
case 'collect':
|
|
5453
|
+
case 'collect':
|
|
5454
|
+
case 'inject': {
|
|
5455
|
+
// `inject` hands the text to the bridge's mid-turn queue so the
|
|
5456
|
+
// agent reads it inside the RUNNING turn, at its next drain
|
|
5457
|
+
// boundary. The queue carries plain text only and the RUNNING
|
|
5458
|
+
// turn's route decides where the answer goes, so a message whose
|
|
5459
|
+
// route/content it cannot carry (a recognized slash command, a
|
|
5460
|
+
// chat/thread its turn does not own, an unauthorized member's
|
|
5461
|
+
// text, a collect replay) parks in `collectBuffers` exactly as
|
|
5462
|
+
// `collect` would instead of being injected. A bridge without the
|
|
5463
|
+
// capability, or one rejecting injections, also falls back. Media
|
|
5464
|
+
// carrying inline image bytes is refused visibly before any parking
|
|
5465
|
+
// path: the replay envelope strips attachments and imageBase64, so
|
|
5466
|
+
// parking it would silently destroy the picture with no notice to
|
|
5467
|
+
// the sender. Media saved to a local path is different — its
|
|
5468
|
+
// `saved to:` line is plain text that survives the replay — so it
|
|
5469
|
+
// still parks. Every fallback below lands in `collectBuffers` and
|
|
5470
|
+
// is replayed as its own turn once this one ends, so nothing
|
|
5471
|
+
// parked here is reported as delivered.
|
|
5472
|
+
let injectFallback = false;
|
|
5473
|
+
let injectRejectReason;
|
|
5474
|
+
if (mode === 'inject' && !envelope.collectReplay) {
|
|
5475
|
+
if (images.length > 0) {
|
|
5476
|
+
// Inline image bytes cannot survive a collect replay (the
|
|
5477
|
+
// replay envelope strips attachments/imageBase64), so parking
|
|
5478
|
+
// this message would silently drop the picture. Refuse before
|
|
5479
|
+
// the capability arm and every other parking gate: the sender
|
|
5480
|
+
// has no reason to resend otherwise.
|
|
5481
|
+
process.stderr.write(`[${this.name}] inject: refusing message with image(s) from ${envelope.senderId} for session ${sessionId} (mid-turn injection is text-only)\n`);
|
|
5482
|
+
await this.notifyInjectRefused(envelope, 'Mid-turn injection supports text-only messages. Send this again after the current task finishes, or use a different dispatch mode.');
|
|
5483
|
+
return;
|
|
5484
|
+
}
|
|
5485
|
+
if (!this.bridge.queueMidTurnMessage) {
|
|
5486
|
+
// Daemon-managed bridges have no mid-turn surface. Say so once
|
|
5487
|
+
// per session so a configured `inject` is not silently `collect`
|
|
5488
|
+
// with no operator-visible reason.
|
|
5489
|
+
this.logInjectUnsupported(sessionId);
|
|
5490
|
+
}
|
|
5491
|
+
else if (envelope.attachments?.length) {
|
|
5492
|
+
// The attachment lines (a `saved to:` path) are plain text, so
|
|
5493
|
+
// buffer the message: the adapter keeps the file for the
|
|
5494
|
+
// buffered message and the replay turn reads it from the path.
|
|
5495
|
+
}
|
|
5496
|
+
else if (recognizedSlashCommand) {
|
|
5497
|
+
// A command only executes on the prompt path; injected it
|
|
5498
|
+
// reaches the model as prose with a prefix that defeats slash
|
|
5499
|
+
// parsing. Let it become its own turn.
|
|
5500
|
+
}
|
|
5501
|
+
else if (!this.isAuthorizedForSharedSession(envelope)) {
|
|
5502
|
+
process.stderr.write(`[${this.name}] inject denied for ${envelope.senderId} in shared session (chat=${sanitizeLogText(envelope.chatId, 64)}); buffering instead\n`);
|
|
5503
|
+
}
|
|
5504
|
+
else if (!this.runningTurnOwnsEnvelope(active, envelope)) {
|
|
5505
|
+
// The running turn's output route is bound to its originating
|
|
5506
|
+
// chat; injecting another chat's (session-scope-collapsed)
|
|
5507
|
+
// message would answer it in the wrong chat.
|
|
5508
|
+
process.stderr.write(`[${this.name}] inject skipped for ${envelope.senderId}: chat ${sanitizeLogText(envelope.chatId, 64)}/thread ${sanitizeLogText(envelope.threadId ?? '', 64)} is not the running turn's target; buffering instead\n`);
|
|
5509
|
+
}
|
|
5510
|
+
else if (this.injectDegradedSessions.has(sessionId)) {
|
|
5511
|
+
// An earlier message of this turn is already parked in the
|
|
5512
|
+
// bounded fallback; keep arrival order instead of letting this
|
|
5513
|
+
// one overtake it into the running turn.
|
|
5514
|
+
injectFallback = true;
|
|
5515
|
+
injectRejectReason = 'ordered after a parked message';
|
|
5516
|
+
}
|
|
5517
|
+
else if (this.injectOrderLockedSessions.has(sessionId)) {
|
|
5518
|
+
// An earlier message of this turn is parked in the collect
|
|
5519
|
+
// buffer for another reason; keep arrival order without
|
|
5520
|
+
// charging the bounded fallback's accounting.
|
|
5521
|
+
process.stderr.write(`[${this.name}] inject: NOT delivered mid-turn (an earlier message of this turn is parked); buffered for the next turn from ${envelope.senderId} into session ${sessionId}\n`);
|
|
5522
|
+
}
|
|
5523
|
+
else {
|
|
5524
|
+
// The injected text must carry the same group-history backfill
|
|
5525
|
+
// a queued turn would get, or the agent answers a reference
|
|
5526
|
+
// ("the third one") it cannot resolve. The pending history is
|
|
5527
|
+
// only PEEKED here: a rejected injection parks the unwrapped
|
|
5528
|
+
// text so the replay composes a single fresh wrapper, and an
|
|
5529
|
+
// accepted one drains it right after the queue accepts it.
|
|
5530
|
+
const pendingHistory = this.peekPendingGroupHistory(envelope);
|
|
5531
|
+
const injectText = this.prependGroupHistoryContext(envelope, promptText, pendingHistory);
|
|
5532
|
+
const receipt = this.bridge.queueMidTurnMessage(sessionId, injectText);
|
|
5533
|
+
if (receipt.accepted) {
|
|
5534
|
+
// Consume the history this injection carried. No await
|
|
5535
|
+
// between the accepted queue call and this drain, so no other
|
|
5536
|
+
// turn can deliver the same backfill. The consumed entries
|
|
5537
|
+
// ride on the ledger entry: acceptance is not delivery, and a
|
|
5538
|
+
// turn that ends without a drain point replays this message
|
|
5539
|
+
// as its own turn, which must still compose that backfill.
|
|
5540
|
+
this.drainPendingGroupHistory(envelope);
|
|
5541
|
+
// Record the RAW text, not `injectText`: the wrapper above is
|
|
5542
|
+
// for the running turn only. If the running turn ends before
|
|
5543
|
+
// draining this message, the ledger entry is replayed as its
|
|
5544
|
+
// own turn, and that replay composes a fresh wrapper of its
|
|
5545
|
+
// own — storing the wrapped text would nest a stale wrapper
|
|
5546
|
+
// and present the previous backfill as the message to answer.
|
|
5547
|
+
this.recordInjectedMessage(sessionId, promptText, envelope, pendingHistory);
|
|
5548
|
+
process.stderr.write(`[${this.name}] inject: delivered mid-turn message from ${envelope.senderId} into session ${sessionId}\n`);
|
|
5549
|
+
this.notifyPromptInjected(envelope.chatId, sessionId, envelope.messageId);
|
|
5550
|
+
return;
|
|
5551
|
+
}
|
|
5552
|
+
// A rejected injection opens the fallback for the rest of this
|
|
5553
|
+
// turn: messages must stay in arrival order.
|
|
5554
|
+
this.injectDegradedSessions.add(sessionId);
|
|
5555
|
+
injectFallback = true;
|
|
5556
|
+
injectRejectReason = receipt.reason;
|
|
5557
|
+
}
|
|
5558
|
+
}
|
|
5559
|
+
if (injectFallback) {
|
|
5560
|
+
// Bounded fallback: retained only until this turn ends, then
|
|
5561
|
+
// replayed in arrival order. It bounds the injections the bridge
|
|
5562
|
+
// REJECTED from its mid-turn queue together with the later
|
|
5563
|
+
// same-turn messages parked behind them to keep that order
|
|
5564
|
+
// (bounds shared from ChannelAgentBridge); plain collect-mode
|
|
5565
|
+
// buffering is unbounded and unchanged. A single rejected message
|
|
5566
|
+
// whose own text exceeds the character bound is kept in that
|
|
5567
|
+
// ordinary collect buffer instead of being refused.
|
|
5568
|
+
const fallbackEntries = (this.collectBuffers.get(sessionId) ?? []).filter((entry) => entry.injectFallback);
|
|
5569
|
+
const fallbackChars = fallbackEntries.reduce((total, entry) => total + entry.text.length, 0);
|
|
5570
|
+
const overBound = fallbackEntries.length >= MID_TURN_QUEUE_MAX_MESSAGES ||
|
|
5571
|
+
(fallbackEntries.length > 0 &&
|
|
5572
|
+
fallbackChars + promptText.length > MID_TURN_QUEUE_MAX_CHARS);
|
|
5573
|
+
if (overBound) {
|
|
5574
|
+
// Metadata only: the refused text is the user's private
|
|
5575
|
+
// message and the sanitizer does not redact it.
|
|
5576
|
+
process.stderr.write(`[${this.name}] inject: could not queue mid-turn message (capacity) and the fallback buffer is full; refusing message from ${envelope.senderId} for session ${sessionId} (${promptText.length} chars)\n`);
|
|
5577
|
+
await this.notifyInjectRefused(envelope, 'This message was not delivered: the current task is still running and too many follow-up messages are already waiting. Please resend it once the current task finishes.');
|
|
5578
|
+
return;
|
|
5579
|
+
}
|
|
5580
|
+
if (fallbackEntries.length === 0 &&
|
|
5581
|
+
promptText.length > MID_TURN_QUEUE_MAX_CHARS) {
|
|
5582
|
+
// A single message larger than the fallback's whole budget
|
|
5583
|
+
// cannot be held there without defeating the bound's purpose;
|
|
5584
|
+
// plain collect retains it unbounded, like every other mode.
|
|
5585
|
+
process.stderr.write(`[${this.name}] inject: message from ${envelope.senderId} for session ${sessionId} exceeds the fallback bound; buffering as plain collect\n`);
|
|
5586
|
+
injectFallback = false;
|
|
5587
|
+
}
|
|
5588
|
+
else {
|
|
5589
|
+
process.stderr.write(`[${this.name}] inject: NOT delivered mid-turn (${injectRejectReason}); buffered for the next turn from ${envelope.senderId} into session ${sessionId}\n`);
|
|
5590
|
+
}
|
|
5591
|
+
}
|
|
5197
5592
|
// Buffer the message; it will be coalesced when the active prompt finishes
|
|
5198
5593
|
let buffer = this.collectBuffers.get(sessionId);
|
|
5199
5594
|
if (!buffer) {
|
|
5200
5595
|
buffer = [];
|
|
5201
5596
|
this.collectBuffers.set(sessionId, buffer);
|
|
5202
5597
|
}
|
|
5203
|
-
|
|
5598
|
+
const entry = {
|
|
5599
|
+
text: promptText,
|
|
5600
|
+
envelope,
|
|
5601
|
+
sequence: this.nextInboundOrdinal(),
|
|
5602
|
+
};
|
|
5603
|
+
if (injectFallback)
|
|
5604
|
+
entry.injectFallback = true;
|
|
5605
|
+
buffer.push(entry);
|
|
5606
|
+
// A parked message gates the rest of the turn: a later injection
|
|
5607
|
+
// would overtake it, so every follower parks here too.
|
|
5608
|
+
this.injectOrderLockedSessions.add(sessionId);
|
|
5204
5609
|
try {
|
|
5205
5610
|
this.onPromptBuffered(envelope.chatId, sessionId, envelope.messageId);
|
|
5206
5611
|
}
|