@ynhcj/xiaoyi-channel 0.0.213-beta → 0.0.213-next
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/index.js +5 -1
- package/dist/src/bot.js +68 -130
- package/dist/src/cspl/call_api.js +4 -0
- package/dist/src/monitor.js +7 -8
- package/dist/src/provider.js +21 -0
- package/dist/src/reply-dispatcher.js +1 -0
- package/dist/src/skill-retriever/hooks.js +3 -3
- package/dist/src/steer-queue.d.ts +1 -0
- package/dist/src/steer-queue.js +9 -0
- package/dist/src/task-manager.d.ts +2 -0
- package/dist/src/task-manager.js +15 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -12,6 +12,7 @@ import { createBeforePromptBuildHandler } from "./src/skill-retriever/hooks.js";
|
|
|
12
12
|
import { normalizeToolRetrieverConfig } from "./src/skill-retriever/config.js";
|
|
13
13
|
import { registerCLIHook } from "./src/tools/hmos-cli.js";
|
|
14
14
|
import { writeSkillUsage } from "./src/utils/skills-logger.js";
|
|
15
|
+
import { logger } from "./src/utils/logger.js";
|
|
15
16
|
/**
|
|
16
17
|
* Parse a file path string to detect if it refers to a SKILL.md file within
|
|
17
18
|
* a skills directory. Returns the skill name (parent directory) if so.
|
|
@@ -216,7 +217,10 @@ function registerFullHooks(api) {
|
|
|
216
217
|
timeoutMs: pluginConfig.skillRetrieverTimeoutMs ?? 1000,
|
|
217
218
|
});
|
|
218
219
|
const beforePromptBuildHandler = createBeforePromptBuildHandler(skillRetrieverConfig);
|
|
219
|
-
api.on("before_prompt_build",
|
|
220
|
+
api.on("before_prompt_build", async (event, ctx) => {
|
|
221
|
+
logger.log(`[BEFORE_PROMPT_BUILD] hook fired, sessionKey=${ctx.sessionKey || "undefined"}, sessionId=${ctx.sessionId || "undefined"}`);
|
|
222
|
+
return beforePromptBuildHandler(event, ctx);
|
|
223
|
+
});
|
|
220
224
|
registerSelfEvolutionToolResultNudge(api);
|
|
221
225
|
}
|
|
222
226
|
const pluginEntry = definePluginEntry({
|
package/dist/src/bot.js
CHANGED
|
@@ -7,7 +7,6 @@ import { downloadFilesFromParts } from "./file-download.js";
|
|
|
7
7
|
import { resolveXYConfig } from "./config.js";
|
|
8
8
|
import { sendStatusUpdate, sendClearContextResponse, sendTasksCancelResponse, sendA2AResponse } from "./formatter.js";
|
|
9
9
|
import { appendSelfEvolutionKeywordNudge, shouldNudgeForSelfEvolutionKeyword, } from "./self-evolution-keyword.js";
|
|
10
|
-
import { queueAgentHarnessMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
|
|
11
10
|
import { runWithSessionContext } from "./tools/session-manager.js";
|
|
12
11
|
import { configManager } from "./utils/config-manager.js";
|
|
13
12
|
import { addPushId } from "./utils/pushid-manager.js";
|
|
@@ -16,6 +15,7 @@ import { selfEvolutionManager } from "./utils/self-evolution-manager.js";
|
|
|
16
15
|
import { saveRuntimeInfo } from "./utils/runtime-manager.js";
|
|
17
16
|
import { toolCallNudgeManager } from "./utils/tool-call-nudge-manager.js";
|
|
18
17
|
import { setCsplSteerContext } from "./cspl/steer-context.js";
|
|
18
|
+
import { getSteerQueue } from "./steer-queue.js";
|
|
19
19
|
import { registerTaskId, decrementTaskIdRef, hasActiveTask, } from "./task-manager.js";
|
|
20
20
|
import { logger } from "./utils/logger.js";
|
|
21
21
|
/**
|
|
@@ -242,18 +242,20 @@ export async function handleXYMessage(params) {
|
|
|
242
242
|
log.error(`[BOT] Failed to patch session model override:`, patchErr);
|
|
243
243
|
}
|
|
244
244
|
}
|
|
245
|
-
// 🔑
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
245
|
+
// 🔑 发送初始状态更新(仅首条消息,steer 不重复发送)
|
|
246
|
+
if (!isUpdate) {
|
|
247
|
+
log.log(`[BOT] Sending initial status update`);
|
|
248
|
+
void sendStatusUpdate({
|
|
249
|
+
config,
|
|
250
|
+
sessionId: parsed.sessionId,
|
|
251
|
+
taskId: parsed.taskId,
|
|
252
|
+
messageId: parsed.messageId,
|
|
253
|
+
text: "任务正在处理中,请稍候~",
|
|
254
|
+
state: "working",
|
|
255
|
+
}).catch((err) => {
|
|
256
|
+
log.error(`Failed to send initial status update:`, err);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
257
259
|
}
|
|
258
260
|
// Extract text and files from parts
|
|
259
261
|
const text = extractTextFromParts(parsed.parts);
|
|
@@ -278,46 +280,47 @@ export async function handleXYMessage(params) {
|
|
|
278
280
|
log.error(`[SELF_EVOLUTION] Failed to append inline keyword nudge: ${String(selfEvolutionError)}`);
|
|
279
281
|
}
|
|
280
282
|
}
|
|
281
|
-
//
|
|
282
|
-
//
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
// 会被 globalDispatchInitGate 永久阻塞。
|
|
287
|
-
params.onInitComplete?.();
|
|
288
|
-
// Steer 也支持文件 —— 提取并下载,附带到 mediaPayload
|
|
289
|
-
const steerFileParts = extractFileParts(parsed.parts);
|
|
290
|
-
const steerDownloadedFiles = await downloadFilesFromParts(steerFileParts);
|
|
291
|
-
const steerMediaPayload = buildXYMediaPayload(steerDownloadedFiles);
|
|
292
|
-
if (steerFileParts.length > 0) {
|
|
293
|
-
log.log(`[BOT] Steer message with ${steerFileParts.length} file(s), enqueuing to streaming-signal queue`);
|
|
294
|
-
}
|
|
295
|
-
else {
|
|
296
|
-
log.log(`[BOT] Steer message — enqueuing to streaming-signal queue`);
|
|
297
|
-
}
|
|
298
|
-
await enqueueSteer({
|
|
299
|
-
sessionId: parsed.sessionId,
|
|
300
|
-
sessionKey: route.sessionKey,
|
|
301
|
-
steerText: textForAgent, // 原始文本,不带 /steer 前缀
|
|
302
|
-
mediaPayload: steerMediaPayload,
|
|
303
|
-
cfg,
|
|
304
|
-
runtime,
|
|
305
|
-
parsed,
|
|
306
|
-
route,
|
|
307
|
-
deviceType,
|
|
308
|
-
});
|
|
309
|
-
log.log(`[BOT] Steer queue completed`);
|
|
310
|
-
return;
|
|
311
|
-
}
|
|
312
|
-
// ── First message (non-steer) path below ──────────────────────
|
|
313
|
-
// File download — only for real user messages, steer injections have no files
|
|
283
|
+
// ── Build message and dispatch via auto-reply pipeline ──────────
|
|
284
|
+
// OpenClaw's auto-reply pipeline (src/auto-reply/reply/agent-runner.ts)
|
|
285
|
+
// detects active runs and handles steer injection natively — the channel
|
|
286
|
+
// does not need its own steer detection or polling logic.
|
|
287
|
+
// File download
|
|
314
288
|
let mediaPayload = {};
|
|
315
|
-
if (!skipReg) {
|
|
289
|
+
if (!skipReg || isUpdate) {
|
|
316
290
|
const fileParts = extractFileParts(parsed.parts);
|
|
317
291
|
const downloadedFiles = await downloadFilesFromParts(fileParts);
|
|
318
292
|
log.log(`[BOT] Downloaded ${downloadedFiles.length} file(s)`);
|
|
319
293
|
mediaPayload = buildXYMediaPayload(downloadedFiles);
|
|
320
294
|
}
|
|
295
|
+
// 🔑 对于 steer 消息,将文件路径附加到消息文本中。
|
|
296
|
+
// auto-reply 管道的 steer 注入只携带 prompt 文本(followupRun.prompt),
|
|
297
|
+
// 不携带 mediaPayload,所以模型需要以文本形式看到附件路径。
|
|
298
|
+
if (isUpdate && mediaPayload.MediaPaths?.length) {
|
|
299
|
+
const fileHint = `\n【用户上传附件】:${JSON.stringify(mediaPayload.MediaPaths)}`;
|
|
300
|
+
textForAgent = `${textForAgent}${fileHint}`;
|
|
301
|
+
log.log(`[BOT] Steer: appended file paths to text`);
|
|
302
|
+
}
|
|
303
|
+
// 🔑 Provider-level steer injection: push steer text to the shared queue.
|
|
304
|
+
// provider.ts checks this queue on every model call (including tool-loop
|
|
305
|
+
// model calls in agent.continue()) and drains pending steer messages
|
|
306
|
+
// directly into context.messages before sending to the model.
|
|
307
|
+
// Key: parsed.sessionId (A2A conversationId) matches getCurrentSessionContext().sessionId.
|
|
308
|
+
if (isUpdate) {
|
|
309
|
+
const steerQueue = getSteerQueue();
|
|
310
|
+
const queueKey = parsed.sessionId;
|
|
311
|
+
const pending = steerQueue.get(queueKey) ?? [];
|
|
312
|
+
pending.push(textForAgent);
|
|
313
|
+
steerQueue.set(queueKey, pending);
|
|
314
|
+
log.log(`[BOT-STEER] Queued for provider injection, sessionId=${queueKey}, queueDepth=${pending.length}`);
|
|
315
|
+
// Bypass dispatchReplyFromConfig entirely — steer injection is handled
|
|
316
|
+
// at the provider level (provider.ts drains the queue on every model call).
|
|
317
|
+
// No need for /steer command dispatch or dispatcher creation.
|
|
318
|
+
if (!skipReg) {
|
|
319
|
+
decrementTaskIdRef(parsed.sessionId);
|
|
320
|
+
}
|
|
321
|
+
params.onInitComplete?.();
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
321
324
|
// Resolve envelope format options (following feishu pattern)
|
|
322
325
|
const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
|
|
323
326
|
// Build message body with speaker prefix (following feishu pattern)
|
|
@@ -358,10 +361,11 @@ export async function handleXYMessage(params) {
|
|
|
358
361
|
ReplyToBody: undefined, // A2A protocol doesn't support reply/quote
|
|
359
362
|
...mediaPayload,
|
|
360
363
|
});
|
|
361
|
-
// 🔑
|
|
362
|
-
|
|
364
|
+
// 🔑 For steer messages, pre-set steered=true so the dispatcher skips final
|
|
365
|
+
// response and cleanup — the first message's dispatcher handles those.
|
|
366
|
+
const steerState = { steered: isUpdate };
|
|
363
367
|
// 🔑 创建dispatcher
|
|
364
|
-
log.log(`[BOT-DISPATCHER] Creating reply dispatcher`);
|
|
368
|
+
log.log(`[BOT-DISPATCHER] Creating reply dispatcher, isSteer=${isUpdate}, sessionKey=${route.sessionKey}`);
|
|
365
369
|
// Cleanup: 必须在 onIdle 内部执行(参见 reply-dispatcher.ts 中 onIdleComplete 的注释)
|
|
366
370
|
let cleaned = false;
|
|
367
371
|
const cleanup = () => {
|
|
@@ -384,8 +388,9 @@ export async function handleXYMessage(params) {
|
|
|
384
388
|
});
|
|
385
389
|
// 🔑 注册 dispatcher 的 fallback taskId 更新函数,供 steer 路径调用
|
|
386
390
|
dispatcherUpdaters.set(parsed.sessionId, updateFallbackTaskId);
|
|
387
|
-
// Steer
|
|
388
|
-
|
|
391
|
+
// Steer messages don't need a status interval — the first message's
|
|
392
|
+
// dispatcher already has one running.
|
|
393
|
+
if (!isUpdate) {
|
|
389
394
|
startStatusInterval();
|
|
390
395
|
}
|
|
391
396
|
// Build session context for AsyncLocalStorage
|
|
@@ -423,8 +428,9 @@ export async function handleXYMessage(params) {
|
|
|
423
428
|
// signal init complete to release the global dispatch gate
|
|
424
429
|
// for the next session.
|
|
425
430
|
const dispatchPromise = runWithSessionContext(sessionContext, async () => {
|
|
426
|
-
|
|
427
|
-
log.log(`[
|
|
431
|
+
const isSteerDispatch = isUpdate && !skipReg;
|
|
432
|
+
log.log(`[ALS-PROOF] bot entered dispatch scope sessionId=${sessionContext.sessionId} taskId=${sessionContext.taskId} isSteer=${isSteerDispatch}`);
|
|
433
|
+
log.log(`[BOT-DISPATCH] dispatchReplyFromConfig starting, body.length=${ctxPayload.Body?.length ?? 0}, isSteer=${isSteerDispatch}`);
|
|
428
434
|
try {
|
|
429
435
|
const result = await core.channel.reply.dispatchReplyFromConfig({
|
|
430
436
|
ctx: ctxPayload,
|
|
@@ -432,7 +438,13 @@ export async function handleXYMessage(params) {
|
|
|
432
438
|
dispatcher,
|
|
433
439
|
replyOptions,
|
|
434
440
|
});
|
|
435
|
-
|
|
441
|
+
// 区分 steer 成功(undefined)和 steer 失败/正常 run(有结果)
|
|
442
|
+
if (result === undefined) {
|
|
443
|
+
log.log(`[BOT-STEER] dispatchReplyFromConfig returned undefined — steer injected via fast path OK, sessionKey=${route.sessionKey}`);
|
|
444
|
+
}
|
|
445
|
+
else {
|
|
446
|
+
log.log(`[BOT-DISPATCH] dispatchReplyFromConfig returned, resultType=${typeof result}, isSteer=${isSteerDispatch}, steered=${steerState.steered}`);
|
|
447
|
+
}
|
|
436
448
|
return result;
|
|
437
449
|
}
|
|
438
450
|
catch (dispatchErr) {
|
|
@@ -492,85 +504,11 @@ function buildXYMediaPayload(mediaList) {
|
|
|
492
504
|
};
|
|
493
505
|
}
|
|
494
506
|
// ─────────────────────────────────────────────────────────────
|
|
495
|
-
//
|
|
507
|
+
// Dispatcher updaters (cross-chain taskId bridging)
|
|
496
508
|
// ─────────────────────────────────────────────────────────────
|
|
497
509
|
// Use globalThis to survive module deduplication — provider.ts may load a
|
|
498
510
|
// different copy of bot.ts, so a plain module-level Map would be two objects.
|
|
499
511
|
const _g = globalThis;
|
|
500
|
-
if (!_g.__xySteerQueues)
|
|
501
|
-
_g.__xySteerQueues = new Map();
|
|
502
512
|
if (!_g.__xyDispatcherUpdaters)
|
|
503
513
|
_g.__xyDispatcherUpdaters = new Map();
|
|
504
|
-
const steerQueues = _g.__xySteerQueues;
|
|
505
514
|
const dispatcherUpdaters = _g.__xyDispatcherUpdaters;
|
|
506
|
-
/**
|
|
507
|
-
* 将 steer 消息放入 per-session 串行队列。
|
|
508
|
-
* 通过指数退避轮询注入(queueAgentHarnessMessage),直到 Pi agent 接受消息或 run 结束。
|
|
509
|
-
* 多个 steer 按到达顺序串行处理。
|
|
510
|
-
*/
|
|
511
|
-
function enqueueSteer(params) {
|
|
512
|
-
const { sessionId } = params;
|
|
513
|
-
const log = logger.withContext(sessionId, params.parsed.taskId);
|
|
514
|
-
// 取出当前队列尾部(或 undefined),然后链上新的 Promise
|
|
515
|
-
const prev = steerQueues.get(sessionId);
|
|
516
|
-
const next = (prev ?? Promise.resolve()).then(() => dispatchSteerWhenReady(params));
|
|
517
|
-
steerQueues.set(sessionId, next);
|
|
518
|
-
// 链条结束后清理
|
|
519
|
-
next.catch((err) => {
|
|
520
|
-
log.error(`[STEER-QUEUE] Steer chain failed: ${String(err)}`);
|
|
521
|
-
}).finally(() => {
|
|
522
|
-
if (steerQueues.get(sessionId) === next) {
|
|
523
|
-
steerQueues.delete(sessionId);
|
|
524
|
-
}
|
|
525
|
-
});
|
|
526
|
-
return next;
|
|
527
|
-
}
|
|
528
|
-
/**
|
|
529
|
-
* Poll the active embedded run with exponential backoff until the steer message
|
|
530
|
-
* is accepted or the run completes.
|
|
531
|
-
*
|
|
532
|
-
* Replaces the previous signal-based approach (notifyModelStreaming) which fired
|
|
533
|
-
* from wrapStreamFn too early — before the Pi agent had set state.isStreaming=true.
|
|
534
|
-
* queueAgentHarnessMessage internally checks isStreaming(), so we retry until the
|
|
535
|
-
* Pi agent is ready to accept messages.
|
|
536
|
-
*/
|
|
537
|
-
async function dispatchSteerWhenReady(params) {
|
|
538
|
-
const { sessionId, steerText } = params;
|
|
539
|
-
const log = logger.withContext(sessionId, params.parsed.taskId);
|
|
540
|
-
const mediaPaths = params.mediaPayload?.MediaPaths;
|
|
541
|
-
const fileHint = mediaPaths && mediaPaths.length > 0
|
|
542
|
-
? `\n【用户上传附件】:${JSON.stringify(mediaPaths)}`
|
|
543
|
-
: "";
|
|
544
|
-
const steerMessage = `${steerText}${fileHint}`;
|
|
545
|
-
log.log(`[STEER-QUEUE] Injecting steer message directly into active run`);
|
|
546
|
-
// Exponential backoff polling until:
|
|
547
|
-
// 1. Injection succeeds (queueAgentHarnessMessage returns true)
|
|
548
|
-
// 2. The original run has completed (hasActiveTask returns false)
|
|
549
|
-
// 3. Maximum total wait time exceeded
|
|
550
|
-
const MAX_WAIT_MS = 30_000;
|
|
551
|
-
const MAX_BACKOFF_MS = 4_000;
|
|
552
|
-
const BASE_DELAY_MS = 500;
|
|
553
|
-
const startedAt = Date.now();
|
|
554
|
-
let attempt = 0;
|
|
555
|
-
while (Date.now() - startedAt < MAX_WAIT_MS) {
|
|
556
|
-
// Termination: first message's run has already finished
|
|
557
|
-
if (!hasActiveTask(sessionId)) {
|
|
558
|
-
log.log(`[STEER-QUEUE] First message completed, skip steer`);
|
|
559
|
-
return;
|
|
560
|
-
}
|
|
561
|
-
const injected = queueAgentHarnessMessage(sessionId, steerMessage, {
|
|
562
|
-
steeringMode: "all",
|
|
563
|
-
});
|
|
564
|
-
if (injected) {
|
|
565
|
-
log.log(`[STEER-QUEUE] Steer injected successfully on attempt ${attempt}`);
|
|
566
|
-
return;
|
|
567
|
-
}
|
|
568
|
-
// Exponential backoff: min(BASE_DELAY_MS * 2^attempt, MAX_BACKOFF_MS)
|
|
569
|
-
const delay = Math.min(BASE_DELAY_MS * Math.pow(2, attempt), MAX_BACKOFF_MS);
|
|
570
|
-
log.log(`[STEER-QUEUE] Attempt ${attempt}: run not accepting, retrying in ${delay}ms`);
|
|
571
|
-
await new Promise(r => setTimeout(r, delay));
|
|
572
|
-
attempt++;
|
|
573
|
-
}
|
|
574
|
-
// Max wait exceeded — model may still be in provider retry loop or unresponsive
|
|
575
|
-
log.log(`[STEER-QUEUE] Steer injection failed after ${MAX_WAIT_MS}ms timeout`);
|
|
576
|
-
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import https from 'https';
|
|
5
5
|
import { URL } from 'url';
|
|
6
|
+
import { logger } from '../utils/logger.js';
|
|
6
7
|
import { getConfig } from './config.js';
|
|
7
8
|
import { DEFAULT_HTTPS_PORT, DEFAULT_HTTP_PORT, HTTP_STATUS_BAD_REQUEST, API_URL_SUFFIX } from './constants.js';
|
|
8
9
|
function buildHeadersForCelia(config, sessionId) {
|
|
@@ -69,6 +70,7 @@ function handleResponse(res, resolve, reject) {
|
|
|
69
70
|
data += chunk;
|
|
70
71
|
});
|
|
71
72
|
res.on('end', () => {
|
|
73
|
+
logger.log(`[SENTINEL HOOK] callApi response body: ${data}`);
|
|
72
74
|
try {
|
|
73
75
|
const result = parseResponseData(data);
|
|
74
76
|
resolve(result);
|
|
@@ -85,6 +87,8 @@ export async function callApi(payload, api, sessionId) {
|
|
|
85
87
|
const payloadWithUid = { ...payload, uid: config.uid };
|
|
86
88
|
const httpBody = JSON.stringify(payloadWithUid);
|
|
87
89
|
const apiUrl = `${config.api.url}${API_URL_SUFFIX}`;
|
|
90
|
+
logger.log(`[SENTINEL HOOK] callApi URL: ${apiUrl}`);
|
|
91
|
+
logger.log(`[SENTINEL HOOK] callApi request body: ${httpBody}`);
|
|
88
92
|
return new Promise((resolve, reject) => {
|
|
89
93
|
const options = buildRequestOptions(apiUrl, headersForCelia, config.api.timeout);
|
|
90
94
|
const req = https.request(options, (res) => {
|
package/dist/src/monitor.js
CHANGED
|
@@ -119,8 +119,11 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
119
119
|
activeMessages.delete(messageKey);
|
|
120
120
|
}
|
|
121
121
|
};
|
|
122
|
-
//
|
|
123
|
-
//
|
|
122
|
+
// Steer detection: when queue mode is "steer" and the session has an active
|
|
123
|
+
// run, process the message concurrently (skip the per-session serial queue).
|
|
124
|
+
// This prevents the steer message from waiting behind the first message's
|
|
125
|
+
// completion. The actual steer injection is handled by OpenClaw's auto-reply
|
|
126
|
+
// pipeline (agent-runner.ts), not by the channel itself.
|
|
124
127
|
const messageMethod = message.method;
|
|
125
128
|
if (messageMethod === "clearContext" || messageMethod === "clear_context"
|
|
126
129
|
|| messageMethod === "tasks/cancel" || messageMethod === "tasks_cancel") {
|
|
@@ -135,24 +138,20 @@ export async function monitorXYProvider(opts = {}) {
|
|
|
135
138
|
const steerMode = cfg.messages?.queue?.mode === "steer";
|
|
136
139
|
const hasActiveRun = hasActiveTask(parsed.sessionId);
|
|
137
140
|
if (steerMode && hasActiveRun) {
|
|
138
|
-
|
|
139
|
-
logger.log(`[MONITOR-HANDLER] STEER MODE: Executing concurrently for messageKey=${messageKey}`);
|
|
141
|
+
logger.log(`[MONITOR] STEER MODE: executing concurrently, sessionId=${parsed.sessionId}, messageKey=${messageKey}`);
|
|
140
142
|
void task().catch((err) => {
|
|
141
143
|
logger.error(`XY gateway: concurrent steer task failed for ${messageKey}: ${String(err)}`);
|
|
142
144
|
activeMessages.delete(messageKey);
|
|
143
145
|
});
|
|
144
146
|
}
|
|
145
147
|
else {
|
|
146
|
-
// 正常模式:入队列串行执行
|
|
147
148
|
void enqueue(sessionId, task).catch((err) => {
|
|
148
149
|
logger.error(`XY gateway: queue processing failed: ${String(err)}`);
|
|
149
150
|
activeMessages.delete(messageKey);
|
|
150
151
|
});
|
|
151
152
|
}
|
|
152
153
|
}
|
|
153
|
-
catch
|
|
154
|
-
// 解析失败,回退到正常队列模式
|
|
155
|
-
logger.error(`[MONITOR-HANDLER] Failed to parse message for steer detection: ${String(parseErr)}`);
|
|
154
|
+
catch {
|
|
156
155
|
void enqueue(sessionId, task).catch((err) => {
|
|
157
156
|
logger.error(`XY gateway: queue processing failed: ${String(err)}`);
|
|
158
157
|
activeMessages.delete(messageKey);
|
package/dist/src/provider.js
CHANGED
|
@@ -11,6 +11,7 @@ import { createHash } from "crypto";
|
|
|
11
11
|
import { logger } from "./utils/logger.js";
|
|
12
12
|
import { getCurrentSessionContext, setCurrentCronJobId } from "./tools/session-manager.js";
|
|
13
13
|
import { selfEvolutionManager } from "./utils/self-evolution-manager.js";
|
|
14
|
+
import { getSteerQueue } from "./steer-queue.js";
|
|
14
15
|
// ── Retry config ──────────────────────────────────────────────
|
|
15
16
|
const RETRY_DELAYS_MS = [10_000, 20_000, 40_000, 60_000, 60_000];
|
|
16
17
|
const MAX_RETRY_ATTEMPTS = 5;
|
|
@@ -592,6 +593,26 @@ export const xiaoyiProvider = {
|
|
|
592
593
|
}
|
|
593
594
|
// deviceType: prefer text-extracted value, ALS as fallback.
|
|
594
595
|
const sessionCtx = getCurrentSessionContext();
|
|
596
|
+
// 🔑 Provider-level steer injection: drain pending steer messages from the
|
|
597
|
+
// shared queue and inject them as user messages before each model call.
|
|
598
|
+
// This runs on EVERY model call including tool-loop model calls, so steer
|
|
599
|
+
// messages injected mid-turn take effect immediately (unlike the hook-based
|
|
600
|
+
// approach which only fires at turn boundaries).
|
|
601
|
+
if (sessionCtx?.sessionId && context.messages) {
|
|
602
|
+
const steerQueue = getSteerQueue();
|
|
603
|
+
const pending = steerQueue.get(sessionCtx.sessionId);
|
|
604
|
+
if (pending && pending.length > 0) {
|
|
605
|
+
steerQueue.delete(sessionCtx.sessionId); // drain before injection
|
|
606
|
+
const steerText = pending.splice(0).join("\n\n");
|
|
607
|
+
const steerMessage = {
|
|
608
|
+
role: "user",
|
|
609
|
+
content: [{ type: "text", text: `用户追加诉求:${steerText}` }],
|
|
610
|
+
timestamp: Date.now(),
|
|
611
|
+
};
|
|
612
|
+
context.messages.push(steerMessage);
|
|
613
|
+
logger.log(`[PROVIDER-STEER] Injected steer into context.messages, sessionId=${sessionCtx.sessionId}, textLen=${steerText.length}, msgCount=${context.messages.length}`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
595
616
|
const deviceType = extractedDeviceType
|
|
596
617
|
?? sessionCtx?.deviceType;
|
|
597
618
|
// app_ver and sdk_api_version from session context (ALS)
|
|
@@ -230,6 +230,7 @@ export function createXYReplyDispatcher(params) {
|
|
|
230
230
|
if (steerState.steered && !hasSentResponse) {
|
|
231
231
|
scopedLog().log(`[ON-IDLE] Steered dispatch, no response generated, skipping`);
|
|
232
232
|
stopStatusInterval();
|
|
233
|
+
await onIdleComplete?.();
|
|
233
234
|
return;
|
|
234
235
|
}
|
|
235
236
|
// 🔑 用 try/finally 确保 cleanup 在 onIdle 的 async 工作全部完成后才执行。
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { searchTools, formatToolsForContext, extractUserQuery } from "./tool-search.js";
|
|
2
2
|
import { logger } from "../utils/logger.js";
|
|
3
|
-
const TOOL_RETRIEVER_HEADER =
|
|
4
|
-
|
|
3
|
+
const TOOL_RETRIEVER_HEADER = `<system-reminder>
|
|
5
4
|
`;
|
|
6
5
|
const TOOL_RETRIEVER_FOOTER = `
|
|
7
|
-
|
|
6
|
+
以上是与用户请求相关但尚未安装的skill,请按照TOOLS.md中find-skills中的[隐式推荐触发规则]来判断是否要安装并使用。
|
|
7
|
+
</system-reminder>
|
|
8
8
|
`;
|
|
9
9
|
const PLUGIN_LOG_PREFIX = "[skill-retriever]";
|
|
10
10
|
const SKIP_KEYWORDS = ["安装", "装一下", "下载", "查询", "查找", "install", "卸载", "删除", "重载", "定时任务", "重装", "进化"];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getSteerQueue(): Map<string, string[]>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Shared steer injection queue — bot.ts writes, provider.ts reads.
|
|
2
|
+
// Uses globalThis to survive module deduplication.
|
|
3
|
+
const _g = globalThis;
|
|
4
|
+
if (!_g.__xySteerInjectionQueue) {
|
|
5
|
+
_g.__xySteerInjectionQueue = new Map();
|
|
6
|
+
}
|
|
7
|
+
export function getSteerQueue() {
|
|
8
|
+
return _g.__xySteerInjectionQueue;
|
|
9
|
+
}
|
package/dist/src/task-manager.js
CHANGED
|
@@ -19,10 +19,11 @@ const activeTaskIds = _g.__xyActiveTaskIds;
|
|
|
19
19
|
export function registerTaskId(sessionId, taskId, messageId) {
|
|
20
20
|
const existing = activeTaskIds.get(sessionId);
|
|
21
21
|
if (existing) {
|
|
22
|
-
logger.log(`[TASK_MANAGER] Updating taskId: ${existing.currentTaskId} → ${taskId}`);
|
|
22
|
+
logger.log(`[TASK_MANAGER] Updating taskId: ${existing.currentTaskId} → ${taskId}, refCount: ${existing.refCount} → ${existing.refCount + 1}`);
|
|
23
23
|
existing.currentTaskId = taskId;
|
|
24
24
|
existing.currentMessageId = messageId;
|
|
25
25
|
existing.updatedAt = Date.now();
|
|
26
|
+
existing.refCount++;
|
|
26
27
|
return true; // isUpdate
|
|
27
28
|
}
|
|
28
29
|
else {
|
|
@@ -31,8 +32,9 @@ export function registerTaskId(sessionId, taskId, messageId) {
|
|
|
31
32
|
currentTaskId: taskId,
|
|
32
33
|
currentMessageId: messageId,
|
|
33
34
|
updatedAt: Date.now(),
|
|
35
|
+
refCount: 1,
|
|
34
36
|
});
|
|
35
|
-
logger.log(`[TASK_MANAGER] Registered new taskId: ${taskId}`);
|
|
37
|
+
logger.log(`[TASK_MANAGER] Registered new taskId: ${taskId}, refCount: 1`);
|
|
36
38
|
return false;
|
|
37
39
|
}
|
|
38
40
|
}
|
|
@@ -40,8 +42,17 @@ export function registerTaskId(sessionId, taskId, messageId) {
|
|
|
40
42
|
* 移除session的活跃taskId(消息处理完成时调用)。
|
|
41
43
|
*/
|
|
42
44
|
export function decrementTaskIdRef(sessionId) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
+
const binding = activeTaskIds.get(sessionId);
|
|
46
|
+
if (!binding) {
|
|
47
|
+
logger.log(`[TASK_MANAGER] decrementTaskIdRef: no binding for ${sessionId}`);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
binding.refCount--;
|
|
51
|
+
logger.log(`[TASK_MANAGER] decrementTaskIdRef: taskId=${binding.currentTaskId}, refCount: ${binding.refCount + 1} → ${binding.refCount}`);
|
|
52
|
+
if (binding.refCount <= 0) {
|
|
53
|
+
activeTaskIds.delete(sessionId);
|
|
54
|
+
logger.log(`[TASK_MANAGER] Removed taskId binding (refCount reached 0)`);
|
|
55
|
+
}
|
|
45
56
|
}
|
|
46
57
|
/**
|
|
47
58
|
* 获取session的当前活跃taskId。
|