@ynhcj/xiaoyi-channel 0.0.210-beta → 0.0.210-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 +44 -1
- package/dist/src/bot.d.ts +0 -5
- package/dist/src/bot.js +54 -166
- package/dist/src/channel.js +2 -0
- package/dist/src/cspl/call_api.js +4 -0
- package/dist/src/log-reporter/index.js +5 -0
- package/dist/src/monitor.js +7 -8
- package/dist/src/provider.js +2 -7
- 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/dist/src/tools/hmos-cli.d.ts +7 -1
- package/dist/src/tools/hmos-cli.js +28 -31
- package/dist/src/tools/invoke.d.ts +49 -9
- package/dist/src/tools/invoke.js +139 -131
- package/dist/src/utils/skills-logger.d.ts +5 -0
- package/dist/src/utils/skills-logger.js +76 -0
- package/dist/src/websocket.js +1 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -11,6 +11,44 @@ import { registerSelfEvolutionToolResultNudge } from "./src/self-evolution-tool-
|
|
|
11
11
|
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
|
+
import { writeSkillUsage } from "./src/utils/skills-logger.js";
|
|
15
|
+
import { logger } from "./src/utils/logger.js";
|
|
16
|
+
/**
|
|
17
|
+
* Parse a file path string to detect if it refers to a SKILL.md file within
|
|
18
|
+
* a skills directory. Returns the skill name (parent directory) if so.
|
|
19
|
+
*
|
|
20
|
+
* Matches paths like:
|
|
21
|
+
* ~/.openclaw/workspace/skills/my-skill/SKILL.md
|
|
22
|
+
* /home/user/core_skills/my-skill/SKILL.md
|
|
23
|
+
* skills/my-skill/SKILL.md
|
|
24
|
+
*/
|
|
25
|
+
function extractSkillNameFromPath(filePath) {
|
|
26
|
+
if (typeof filePath !== "string" || !filePath)
|
|
27
|
+
return null;
|
|
28
|
+
// Normalize common path prefixes
|
|
29
|
+
const normalized = filePath.replace(/^~\//, "/home/").replace(/\\/g, "/");
|
|
30
|
+
// Match: .../skills/<skillName>/SKILL.md or .../skills/<skillName>/...
|
|
31
|
+
// Also match: .../core_skills/<skillName>/SKILL.md
|
|
32
|
+
const match = normalized.match(/\/(?:core_)?skills\/([^/]+)\/SKILL\.md$/i);
|
|
33
|
+
return match ? match[1] : null;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Register the skills diagnostic event listener via after_tool_call hook.
|
|
37
|
+
*
|
|
38
|
+
* When openclaw fires a `skill.used` diagnostic event, the skill's SKILL.md
|
|
39
|
+
* is typically read by the model first. We detect SKILL.md reads through
|
|
40
|
+
* the `after_tool_call` hook and write the skill name to the skills log.
|
|
41
|
+
*/
|
|
42
|
+
function registerSkillsDiagnosticHook(api) {
|
|
43
|
+
api.on("after_tool_call", async (event, _ctx) => {
|
|
44
|
+
if (event.toolName !== "read")
|
|
45
|
+
return;
|
|
46
|
+
const skillName = extractSkillNameFromPath(event.params?.path);
|
|
47
|
+
if (skillName) {
|
|
48
|
+
writeSkillUsage(skillName);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
14
52
|
/**
|
|
15
53
|
* Register the cron detection hook.
|
|
16
54
|
*
|
|
@@ -179,7 +217,10 @@ function registerFullHooks(api) {
|
|
|
179
217
|
timeoutMs: pluginConfig.skillRetrieverTimeoutMs ?? 1000,
|
|
180
218
|
});
|
|
181
219
|
const beforePromptBuildHandler = createBeforePromptBuildHandler(skillRetrieverConfig);
|
|
182
|
-
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
|
+
});
|
|
183
224
|
registerSelfEvolutionToolResultNudge(api);
|
|
184
225
|
}
|
|
185
226
|
const pluginEntry = definePluginEntry({
|
|
@@ -211,6 +252,8 @@ const pluginEntry = definePluginEntry({
|
|
|
211
252
|
registerCronDetectionHook(api);
|
|
212
253
|
// CLI exec hook: intercepts built-in exec for HarmonyOS CLI skill tools
|
|
213
254
|
registerCLIHook(api);
|
|
255
|
+
// Skills diagnostic hook: log skill usage (detected via SKILL.md reads)
|
|
256
|
+
registerSkillsDiagnosticHook(api);
|
|
214
257
|
}
|
|
215
258
|
},
|
|
216
259
|
});
|
package/dist/src/bot.d.ts
CHANGED
|
@@ -24,8 +24,3 @@ export interface HandleXYMessageParams {
|
|
|
24
24
|
* Runtime is expected to be validated before calling this function.
|
|
25
25
|
*/
|
|
26
26
|
export declare function handleXYMessage(params: HandleXYMessageParams): Promise<void>;
|
|
27
|
-
/**
|
|
28
|
-
* 由 provider.ts 在 wrapStreamFn 调用时触发。
|
|
29
|
-
* 这是模型 API 被调用的精确时刻,此时 isStreaming 一定为 true。
|
|
30
|
-
*/
|
|
31
|
-
export declare function notifyModelStreaming(sessionId: string): void;
|
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";
|
|
@@ -242,18 +241,20 @@ export async function handleXYMessage(params) {
|
|
|
242
241
|
log.error(`[BOT] Failed to patch session model override:`, patchErr);
|
|
243
242
|
}
|
|
244
243
|
}
|
|
245
|
-
// 🔑
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
244
|
+
// 🔑 发送初始状态更新(仅首条消息,steer 不重复发送)
|
|
245
|
+
if (!isUpdate) {
|
|
246
|
+
log.log(`[BOT] Sending initial status update`);
|
|
247
|
+
void sendStatusUpdate({
|
|
248
|
+
config,
|
|
249
|
+
sessionId: parsed.sessionId,
|
|
250
|
+
taskId: parsed.taskId,
|
|
251
|
+
messageId: parsed.messageId,
|
|
252
|
+
text: "任务正在处理中,请稍候~",
|
|
253
|
+
state: "working",
|
|
254
|
+
}).catch((err) => {
|
|
255
|
+
log.error(`Failed to send initial status update:`, err);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
257
258
|
}
|
|
258
259
|
// Extract text and files from parts
|
|
259
260
|
const text = extractTextFromParts(parsed.parts);
|
|
@@ -278,49 +279,26 @@ export async function handleXYMessage(params) {
|
|
|
278
279
|
log.error(`[SELF_EVOLUTION] Failed to append inline keyword nudge: ${String(selfEvolutionError)}`);
|
|
279
280
|
}
|
|
280
281
|
}
|
|
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
|
-
// 🔑 立即创建 streaming 信号——必须在文件下载等耗时操作之前,
|
|
314
|
-
// 否则 steer 消息的 dispatchSteerWhenReady 会找不到信号而跳过等待。
|
|
315
|
-
createStreamingSignal(parsed.sessionId);
|
|
316
|
-
// File download — only for real user messages, steer injections have no files
|
|
282
|
+
// ── Build message and dispatch via auto-reply pipeline ──────────
|
|
283
|
+
// OpenClaw's auto-reply pipeline (src/auto-reply/reply/agent-runner.ts)
|
|
284
|
+
// detects active runs and handles steer injection natively — the channel
|
|
285
|
+
// does not need its own steer detection or polling logic.
|
|
286
|
+
// File download
|
|
317
287
|
let mediaPayload = {};
|
|
318
|
-
if (!skipReg) {
|
|
288
|
+
if (!skipReg || isUpdate) {
|
|
319
289
|
const fileParts = extractFileParts(parsed.parts);
|
|
320
290
|
const downloadedFiles = await downloadFilesFromParts(fileParts);
|
|
321
291
|
log.log(`[BOT] Downloaded ${downloadedFiles.length} file(s)`);
|
|
322
292
|
mediaPayload = buildXYMediaPayload(downloadedFiles);
|
|
323
293
|
}
|
|
294
|
+
// 🔑 对于 steer 消息,将文件路径附加到消息文本中。
|
|
295
|
+
// auto-reply 管道的 steer 注入只携带 prompt 文本(followupRun.prompt),
|
|
296
|
+
// 不携带 mediaPayload,所以模型需要以文本形式看到附件路径。
|
|
297
|
+
if (isUpdate && mediaPayload.MediaPaths?.length) {
|
|
298
|
+
const fileHint = `\n【用户上传附件】:${JSON.stringify(mediaPayload.MediaPaths)}`;
|
|
299
|
+
textForAgent = `${textForAgent}${fileHint}`;
|
|
300
|
+
log.log(`[BOT] Steer: appended file paths to text`);
|
|
301
|
+
}
|
|
324
302
|
// Resolve envelope format options (following feishu pattern)
|
|
325
303
|
const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
|
|
326
304
|
// Build message body with speaker prefix (following feishu pattern)
|
|
@@ -336,12 +314,17 @@ export async function handleXYMessage(params) {
|
|
|
336
314
|
envelope: envelopeOptions,
|
|
337
315
|
body: messageBody,
|
|
338
316
|
});
|
|
317
|
+
// 🔑 Steer messages use /steer prefix to trigger the native slash command
|
|
318
|
+
// fast path in get-reply, which calls handleSteerCommand → queueEmbedded-
|
|
319
|
+
// AgentMessageWithOutcomeAsync without going through admitReplyTurn or
|
|
320
|
+
// the isStreaming guard in runReplyAgent.
|
|
321
|
+
const steerCommandBody = isUpdate ? `/steer ${textForAgent}` : textForAgent;
|
|
339
322
|
// ✅ Finalize inbound context (following feishu pattern)
|
|
340
323
|
// Use route.accountId and route.sessionKey instead of parsed fields
|
|
341
324
|
const ctxPayload = core.channel.reply.finalizeInboundContext({
|
|
342
325
|
Body: body,
|
|
343
|
-
RawBody:
|
|
344
|
-
CommandBody:
|
|
326
|
+
RawBody: steerCommandBody,
|
|
327
|
+
CommandBody: steerCommandBody,
|
|
345
328
|
From: parsed.sessionId,
|
|
346
329
|
To: parsed.sessionId, // ✅ Simplified: use sessionId as target (context is managed by SessionKey)
|
|
347
330
|
SessionKey: route.sessionKey, // ✅ Use route.sessionKey
|
|
@@ -361,8 +344,9 @@ export async function handleXYMessage(params) {
|
|
|
361
344
|
ReplyToBody: undefined, // A2A protocol doesn't support reply/quote
|
|
362
345
|
...mediaPayload,
|
|
363
346
|
});
|
|
364
|
-
// 🔑
|
|
365
|
-
|
|
347
|
+
// 🔑 For steer messages, pre-set steered=true so the dispatcher skips final
|
|
348
|
+
// response and cleanup — the first message's dispatcher handles those.
|
|
349
|
+
const steerState = { steered: isUpdate };
|
|
366
350
|
// 🔑 创建dispatcher
|
|
367
351
|
log.log(`[BOT-DISPATCHER] Creating reply dispatcher`);
|
|
368
352
|
// Cleanup: 必须在 onIdle 内部执行(参见 reply-dispatcher.ts 中 onIdleComplete 的注释)
|
|
@@ -372,7 +356,6 @@ export async function handleXYMessage(params) {
|
|
|
372
356
|
return;
|
|
373
357
|
cleaned = true;
|
|
374
358
|
log.log(`[BOT] Cleanup started`);
|
|
375
|
-
streamingSignals.delete(parsed.sessionId);
|
|
376
359
|
decrementTaskIdRef(parsed.sessionId);
|
|
377
360
|
log.log(`[BOT] Cleanup completed`);
|
|
378
361
|
};
|
|
@@ -388,8 +371,9 @@ export async function handleXYMessage(params) {
|
|
|
388
371
|
});
|
|
389
372
|
// 🔑 注册 dispatcher 的 fallback taskId 更新函数,供 steer 路径调用
|
|
390
373
|
dispatcherUpdaters.set(parsed.sessionId, updateFallbackTaskId);
|
|
391
|
-
// Steer
|
|
392
|
-
|
|
374
|
+
// Steer messages don't need a status interval — the first message's
|
|
375
|
+
// dispatcher already has one running.
|
|
376
|
+
if (!isUpdate) {
|
|
393
377
|
startStatusInterval();
|
|
394
378
|
}
|
|
395
379
|
// Build session context for AsyncLocalStorage
|
|
@@ -427,8 +411,9 @@ export async function handleXYMessage(params) {
|
|
|
427
411
|
// signal init complete to release the global dispatch gate
|
|
428
412
|
// for the next session.
|
|
429
413
|
const dispatchPromise = runWithSessionContext(sessionContext, async () => {
|
|
430
|
-
|
|
431
|
-
log.log(`[
|
|
414
|
+
const isSteerDispatch = isUpdate && !skipReg;
|
|
415
|
+
log.log(`[ALS-PROOF] bot entered dispatch scope sessionId=${sessionContext.sessionId} taskId=${sessionContext.taskId} isSteer=${isSteerDispatch}`);
|
|
416
|
+
log.log(`[BOT-DISPATCH] dispatchReplyFromConfig starting, body.length=${ctxPayload.Body?.length ?? 0}, isSteer=${isSteerDispatch}`);
|
|
432
417
|
try {
|
|
433
418
|
const result = await core.channel.reply.dispatchReplyFromConfig({
|
|
434
419
|
ctx: ctxPayload,
|
|
@@ -436,7 +421,13 @@ export async function handleXYMessage(params) {
|
|
|
436
421
|
dispatcher,
|
|
437
422
|
replyOptions,
|
|
438
423
|
});
|
|
439
|
-
|
|
424
|
+
// 区分 steer 成功(undefined)和 steer 失败/正常 run(有结果)
|
|
425
|
+
if (result === undefined) {
|
|
426
|
+
log.log(`[BOT-DISPATCH] dispatchReplyFromConfig returned undefined — steer injected successfully`);
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
log.log(`[BOT-DISPATCH] dispatchReplyFromConfig returned, resultType=${typeof result}, isSteer=${isSteerDispatch}, steered=${steerState.steered}`);
|
|
430
|
+
}
|
|
440
431
|
return result;
|
|
441
432
|
}
|
|
442
433
|
catch (dispatchErr) {
|
|
@@ -495,115 +486,12 @@ function buildXYMediaPayload(mediaList) {
|
|
|
495
486
|
MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
|
|
496
487
|
};
|
|
497
488
|
}
|
|
489
|
+
// ─────────────────────────────────────────────────────────────
|
|
490
|
+
// Dispatcher updaters (cross-chain taskId bridging)
|
|
491
|
+
// ─────────────────────────────────────────────────────────────
|
|
498
492
|
// Use globalThis to survive module deduplication — provider.ts may load a
|
|
499
493
|
// different copy of bot.ts, so a plain module-level Map would be two objects.
|
|
500
494
|
const _g = globalThis;
|
|
501
|
-
if (!_g.__xyStreamingSignals)
|
|
502
|
-
_g.__xyStreamingSignals = new Map();
|
|
503
|
-
if (!_g.__xySteerQueues)
|
|
504
|
-
_g.__xySteerQueues = new Map();
|
|
505
495
|
if (!_g.__xyDispatcherUpdaters)
|
|
506
496
|
_g.__xyDispatcherUpdaters = new Map();
|
|
507
|
-
const streamingSignals = _g.__xyStreamingSignals;
|
|
508
|
-
const steerQueues = _g.__xySteerQueues;
|
|
509
497
|
const dispatcherUpdaters = _g.__xyDispatcherUpdaters;
|
|
510
|
-
/**
|
|
511
|
-
* 由 provider.ts 在 wrapStreamFn 调用时触发。
|
|
512
|
-
* 这是模型 API 被调用的精确时刻,此时 isStreaming 一定为 true。
|
|
513
|
-
*/
|
|
514
|
-
export function notifyModelStreaming(sessionId) {
|
|
515
|
-
const log = logger.withContext(sessionId, "");
|
|
516
|
-
const signal = streamingSignals.get(sessionId);
|
|
517
|
-
if (signal) {
|
|
518
|
-
// 不删除 signal——后续 steer 需要靠它判断模型已在 streaming。
|
|
519
|
-
// 清理由第一条消息的 onSettled 兜底。
|
|
520
|
-
signal.notify();
|
|
521
|
-
log.log(`[STEER-QUEUE] Model streaming signal fired`);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
function createStreamingSignal(sessionId) {
|
|
525
|
-
const log = logger.withContext(sessionId, "");
|
|
526
|
-
let resolve;
|
|
527
|
-
const promise = new Promise(r => { resolve = r; });
|
|
528
|
-
const signal = { promise, notify: resolve };
|
|
529
|
-
streamingSignals.set(sessionId, signal);
|
|
530
|
-
log.log(`[STEER-QUEUE] Streaming signal created`);
|
|
531
|
-
return signal;
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* 将 steer 消息放入 per-session 串行队列。
|
|
535
|
-
* 等待第一条消息的 streaming 信号(deliver 首次触发),然后 dispatch。
|
|
536
|
-
* 多个 steer 按到达顺序串行处理,无需重试。
|
|
537
|
-
*/
|
|
538
|
-
function enqueueSteer(params) {
|
|
539
|
-
const { sessionId } = params;
|
|
540
|
-
const log = logger.withContext(sessionId, params.parsed.taskId);
|
|
541
|
-
// 取出当前队列尾部(或 undefined),然后链上新的 Promise
|
|
542
|
-
const prev = steerQueues.get(sessionId);
|
|
543
|
-
const next = (prev ?? Promise.resolve()).then(() => dispatchSteerWhenReady(params));
|
|
544
|
-
steerQueues.set(sessionId, next);
|
|
545
|
-
// 链条结束后清理
|
|
546
|
-
next.catch((err) => {
|
|
547
|
-
log.error(`[STEER-QUEUE] Steer chain failed: ${String(err)}`);
|
|
548
|
-
}).finally(() => {
|
|
549
|
-
if (steerQueues.get(sessionId) === next) {
|
|
550
|
-
steerQueues.delete(sessionId);
|
|
551
|
-
}
|
|
552
|
-
});
|
|
553
|
-
return next;
|
|
554
|
-
}
|
|
555
|
-
async function dispatchSteerWhenReady(params) {
|
|
556
|
-
const { sessionId, steerText } = params;
|
|
557
|
-
const log = logger.withContext(sessionId, params.parsed.taskId);
|
|
558
|
-
// 1. 等待第一条消息开始 streaming
|
|
559
|
-
// signal 可能尚未创建(第一条消息还在文件下载等耗时操作中),
|
|
560
|
-
// 轮询等待直到 signal 出现,最長等待 ~5 秒。
|
|
561
|
-
let signal = streamingSignals.get(sessionId);
|
|
562
|
-
if (!signal) {
|
|
563
|
-
log.log(`[STEER-QUEUE] Signal not yet created, polling`);
|
|
564
|
-
for (let i = 0; i < 50; i++) {
|
|
565
|
-
await new Promise(r => setTimeout(r, 100));
|
|
566
|
-
signal = streamingSignals.get(sessionId);
|
|
567
|
-
if (signal)
|
|
568
|
-
break;
|
|
569
|
-
if (!hasActiveTask(sessionId)) {
|
|
570
|
-
log.log(`[STEER-QUEUE] First message completed while waiting, skip steer`);
|
|
571
|
-
return;
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
if (signal) {
|
|
576
|
-
log.log(`[STEER-QUEUE] Waiting for streaming signal`);
|
|
577
|
-
await signal.promise;
|
|
578
|
-
log.log(`[STEER-QUEUE] Streaming signal received`);
|
|
579
|
-
}
|
|
580
|
-
else {
|
|
581
|
-
// 轮询超时且 hasActiveTask 仍为 true——说明第一条消息可能卡在异常路径,
|
|
582
|
-
// 没有创建 signal。此时放弃,避免并发碰撞。
|
|
583
|
-
log.log(`[STEER-QUEUE] Signal never appeared after polling, skip steer to avoid collision`);
|
|
584
|
-
return;
|
|
585
|
-
}
|
|
586
|
-
// 2. 第一条消息已结束 → 放弃
|
|
587
|
-
if (!hasActiveTask(sessionId)) {
|
|
588
|
-
log.log(`[STEER-QUEUE] First message completed, skip steer`);
|
|
589
|
-
return;
|
|
590
|
-
}
|
|
591
|
-
// 3. 直接注入到活跃的 Pi run 中,不创建独立 dispatcher。
|
|
592
|
-
// 模型回复通过第一条消息的 dispatcher 的 onPartialReply 流式发出,
|
|
593
|
-
// 使用 registerTaskId + updateFallbackTaskId 已同步的最新 taskId。
|
|
594
|
-
const mediaPaths = params.mediaPayload?.MediaPaths;
|
|
595
|
-
const fileHint = mediaPaths && mediaPaths.length > 0
|
|
596
|
-
? `\n【用户上传附件】:${JSON.stringify(mediaPaths)}`
|
|
597
|
-
: "";
|
|
598
|
-
const steerMessage = `${steerText}${fileHint}`;
|
|
599
|
-
log.log(`[STEER-QUEUE] Injecting steer message directly into active run`);
|
|
600
|
-
const injected = queueAgentHarnessMessage(sessionId, steerMessage, {
|
|
601
|
-
steeringMode: "all",
|
|
602
|
-
});
|
|
603
|
-
if (injected) {
|
|
604
|
-
log.log(`[STEER-QUEUE] Steer message injected successfully`);
|
|
605
|
-
}
|
|
606
|
-
else {
|
|
607
|
-
log.log(`[STEER-QUEUE] Steer injection failed — run may not be accepting messages`);
|
|
608
|
-
}
|
|
609
|
-
}
|
package/dist/src/channel.js
CHANGED
|
@@ -27,6 +27,7 @@ import { discoverCrossDevicesTool } from "./tools/discover-cross-devices-tool.js
|
|
|
27
27
|
import { sendCrossDeviceTaskTool } from "./tools/send-cross-device-task-tool.js";
|
|
28
28
|
import { displayA2UICardByPathTool } from "./tools/display-a2ui-card-bypath-tool.js";
|
|
29
29
|
import { checkPluginPrivilegeTool } from "./tools/check-plugin-privilege-tool.js";
|
|
30
|
+
import { invokeTool } from "./tools/invoke.js";
|
|
30
31
|
const ALL_TOOLS = [
|
|
31
32
|
locationTool,
|
|
32
33
|
discoverCrossDevicesTool,
|
|
@@ -50,6 +51,7 @@ const ALL_TOOLS = [
|
|
|
50
51
|
loginTokenTool,
|
|
51
52
|
agentAsSkillTool,
|
|
52
53
|
checkPluginPrivilegeTool,
|
|
54
|
+
invokeTool,
|
|
53
55
|
];
|
|
54
56
|
/**
|
|
55
57
|
* Xiaoyi Channel Plugin for OpenClaw.
|
|
@@ -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) => {
|
|
@@ -32,6 +32,11 @@ const MONITORS = [
|
|
|
32
32
|
businessType: "openclaw-init",
|
|
33
33
|
jsonParse: false,
|
|
34
34
|
},
|
|
35
|
+
{
|
|
36
|
+
path: "/tmp/openclaw/skills-{year}{month}{day}.log",
|
|
37
|
+
businessType: "openclaw-skill",
|
|
38
|
+
jsonParse: false,
|
|
39
|
+
},
|
|
35
40
|
];
|
|
36
41
|
// ── State ────────────────────────────────────────────────────────────────────
|
|
37
42
|
let intervalId = null;
|
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-HANDLER] STEER MODE: Concurrent execution for ${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,7 +11,6 @@ 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 { notifyModelStreaming } from "./bot.js";
|
|
15
14
|
// ── Retry config ──────────────────────────────────────────────
|
|
16
15
|
const RETRY_DELAYS_MS = [10_000, 20_000, 40_000, 60_000, 60_000];
|
|
17
16
|
const MAX_RETRY_ATTEMPTS = 5;
|
|
@@ -588,17 +587,13 @@ export const xiaoyiProvider = {
|
|
|
588
587
|
}
|
|
589
588
|
// 记录输入
|
|
590
589
|
logger.log(`[xiaoyiprovider] input messages count: ${context.messages?.length ?? 0}`);
|
|
591
|
-
// 🔑 通知 steer 队列:模型 API 已被调用,此时 isStreaming 一定为 true
|
|
592
|
-
const sessionCtx = getCurrentSessionContext();
|
|
593
|
-
if (sessionCtx?.sessionId) {
|
|
594
|
-
notifyModelStreaming(sessionCtx.sessionId);
|
|
595
|
-
}
|
|
596
590
|
if (context.systemPrompt) {
|
|
597
591
|
logger.log(`[xiaoyiprovider] system prompt length: ${context.systemPrompt.length}`);
|
|
598
592
|
}
|
|
599
593
|
// deviceType: prefer text-extracted value, ALS as fallback.
|
|
594
|
+
const sessionCtx = getCurrentSessionContext();
|
|
600
595
|
const deviceType = extractedDeviceType
|
|
601
|
-
??
|
|
596
|
+
?? sessionCtx?.deviceType;
|
|
602
597
|
// app_ver and sdk_api_version from session context (ALS)
|
|
603
598
|
const appVer = sessionCtx?.appVer;
|
|
604
599
|
const sdkApiVersion = sessionCtx?.sdkApiVersion;
|
|
@@ -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, index.ts agent_turn_prepare hook reads.
|
|
2
|
+
// Uses globalThis to survive module deduplication (same pattern as dispatcherUpdaters).
|
|
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。
|
|
@@ -38,6 +38,11 @@ export interface CLICache {
|
|
|
38
38
|
getCLIs(skillName: string): CLICacheEntry[] | null;
|
|
39
39
|
getCLI(skillName: string, cliName: string): CLICacheEntry | null;
|
|
40
40
|
hasCLI(skillName: string, cliName: string): boolean;
|
|
41
|
+
/** Search all cached skills for a CLI whose name matches the command prefix. */
|
|
42
|
+
findCLIByCommand(command: string): {
|
|
43
|
+
entry: CLICacheEntry;
|
|
44
|
+
skillName: string;
|
|
45
|
+
} | null;
|
|
41
46
|
refresh(): Promise<void>;
|
|
42
47
|
getRootDir(): string;
|
|
43
48
|
}
|
|
@@ -90,7 +95,8 @@ interface HookResult {
|
|
|
90
95
|
* before_tool_call hook for CLI exec interception.
|
|
91
96
|
*
|
|
92
97
|
* Only handles built-in `exec` calls whose command prefix matches a CLI
|
|
93
|
-
*
|
|
98
|
+
* from any skill's metadata.clis + available_clis.json (searched across
|
|
99
|
+
* all cached skills, not just the current session's skill).
|
|
94
100
|
* Non-matching commands return undefined (noop) so native exec handles them.
|
|
95
101
|
*/
|
|
96
102
|
export declare function cliBeforeToolCallHandler(event: BeforeToolCallEvent, ctx: HookContext): Promise<HookResult | undefined>;
|
|
@@ -15,6 +15,7 @@ import path from "path";
|
|
|
15
15
|
import os from "os";
|
|
16
16
|
import { logger } from "../utils/logger.js";
|
|
17
17
|
import { InvokeError, invokeErrorToResult } from "./invoke.js";
|
|
18
|
+
import { getCurrentSessionContext } from "./session-manager.js";
|
|
18
19
|
import { getXYWebSocketManager } from "../client.js";
|
|
19
20
|
import { sendCommand } from "../formatter.js";
|
|
20
21
|
import { getCurrentTaskId } from "../task-manager.js";
|
|
@@ -215,6 +216,23 @@ function wrapState(state) {
|
|
|
215
216
|
return entries.find(e => e.cliName === cliName) ?? null;
|
|
216
217
|
},
|
|
217
218
|
hasCLI(skillName, cliName) { return this.getCLI(skillName, cliName) !== null; },
|
|
219
|
+
findCLIByCommand(command) {
|
|
220
|
+
maybeRefresh(state);
|
|
221
|
+
const all = [];
|
|
222
|
+
for (const [skillName, entries] of state.skillClis) {
|
|
223
|
+
for (const entry of entries) {
|
|
224
|
+
all.push({ entry, skillName });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
// Longest CLI name first so "foo bar" matches before "foo"
|
|
228
|
+
all.sort((a, b) => b.entry.cliName.length - a.entry.cliName.length);
|
|
229
|
+
for (const item of all) {
|
|
230
|
+
if (command === item.entry.cliName || command.startsWith(item.entry.cliName + " ")) {
|
|
231
|
+
return item;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return null;
|
|
235
|
+
},
|
|
218
236
|
async refresh() {
|
|
219
237
|
state.skillClis = scanCLIDirectories(state.rootDir);
|
|
220
238
|
state.lastScanMs = Date.now();
|
|
@@ -469,7 +487,8 @@ export { parseSkillName as deriveSkillName };
|
|
|
469
487
|
* before_tool_call hook for CLI exec interception.
|
|
470
488
|
*
|
|
471
489
|
* Only handles built-in `exec` calls whose command prefix matches a CLI
|
|
472
|
-
*
|
|
490
|
+
* from any skill's metadata.clis + available_clis.json (searched across
|
|
491
|
+
* all cached skills, not just the current session's skill).
|
|
473
492
|
* Non-matching commands return undefined (noop) so native exec handles them.
|
|
474
493
|
*/
|
|
475
494
|
export async function cliBeforeToolCallHandler(event, ctx) {
|
|
@@ -480,37 +499,15 @@ export async function cliBeforeToolCallHandler(event, ctx) {
|
|
|
480
499
|
return undefined;
|
|
481
500
|
const t0 = performance.now();
|
|
482
501
|
const command = rawCommand.trim();
|
|
483
|
-
//
|
|
484
|
-
const workspaceDir = ctx.workspaceDir;
|
|
485
|
-
if (!workspaceDir) {
|
|
486
|
-
logger.log(`[CLI-HOOK] no workspaceDir, noop (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
487
|
-
return undefined;
|
|
488
|
-
}
|
|
489
|
-
const skillName = parseSkillName(workspaceDir);
|
|
490
|
-
if (!skillName) {
|
|
491
|
-
logger.log(`[CLI-HOOK] no skill name in ${workspaceDir}, noop (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
492
|
-
return undefined;
|
|
493
|
-
}
|
|
502
|
+
// Search all cached skills for a CLI matching the command prefix
|
|
494
503
|
const cache = getCLICache();
|
|
495
|
-
const
|
|
496
|
-
if (!
|
|
497
|
-
logger.log(`[CLI-HOOK]
|
|
498
|
-
return undefined;
|
|
499
|
-
}
|
|
500
|
-
// Match longest CLI name first
|
|
501
|
-
const sorted = [...skillCLIs].sort((a, b) => b.cliName.length - a.cliName.length);
|
|
502
|
-
let matchedCLI = null;
|
|
503
|
-
for (const entry of sorted) {
|
|
504
|
-
if (command === entry.cliName || command.startsWith(entry.cliName + " ")) {
|
|
505
|
-
matchedCLI = entry;
|
|
506
|
-
break;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
if (!matchedCLI) {
|
|
510
|
-
logger.log(`[CLI-HOOK] No CLI match for command prefix, noop (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
504
|
+
const match = cache.findCLIByCommand(command);
|
|
505
|
+
if (!match) {
|
|
506
|
+
logger.log(`[CLI-HOOK] No CLI match for '${command}', noop (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
511
507
|
return undefined;
|
|
512
508
|
}
|
|
513
|
-
|
|
509
|
+
const { entry: matchedCLI, skillName } = match;
|
|
510
|
+
logger.log(`[CLI-HOOK] Matched CLI '${matchedCLI.cliName}' in skill '${skillName}' (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
514
511
|
// Parse and validate
|
|
515
512
|
let parsed;
|
|
516
513
|
try {
|
|
@@ -534,8 +531,8 @@ export async function cliBeforeToolCallHandler(event, ctx) {
|
|
|
534
531
|
},
|
|
535
532
|
};
|
|
536
533
|
}
|
|
537
|
-
// Get session context
|
|
538
|
-
const sessionCtx =
|
|
534
|
+
// Get session context via ALS (propagated through the async call chain)
|
|
535
|
+
const sessionCtx = getCurrentSessionContext();
|
|
539
536
|
if (!sessionCtx) {
|
|
540
537
|
logger.warn(`[CLI-HOOK] No session context, blocking (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
541
538
|
return { block: true, blockReason: JSON.stringify({ code: "CONFIG_MISSING", message: "No active session context for CLI execution", retryable: false }) };
|
|
@@ -18,8 +18,6 @@
|
|
|
18
18
|
* 7. Device executor
|
|
19
19
|
* 8. Invoke tool factory (public API)
|
|
20
20
|
*/
|
|
21
|
-
import type { ChannelAgentTool } from "openclaw/plugin-sdk";
|
|
22
|
-
import type { SessionContext } from "./session-manager.js";
|
|
23
21
|
export type InvokeErrorCode = "INVALID_PARAM" | "INVALID_TOOL_DEFINITION" | "CONFIG_MISSING" | "AUTH_FAIL" | "PERMISSION_DENIED" | "CLI_COMMAND_BLOCKED" | "RATE_LIMIT" | "TIMEOUT" | "TOOL_NOT_FOUND" | "TOOL_CONFLICT" | "UNSUPPORTED_PLUGIN_TYPE" | "UNSUPPORTED_PROTOCOL" | "DEVICE_TOOL_BLOCKED" | "UPSTREAM_ERROR" | "NETWORK_ERROR" | "UNKNOWN";
|
|
24
22
|
interface ExecuteResult {
|
|
25
23
|
content: Array<{
|
|
@@ -38,11 +36,53 @@ export declare class InvokeError extends Error {
|
|
|
38
36
|
get status(): number;
|
|
39
37
|
}
|
|
40
38
|
export declare function invokeErrorToResult(error: InvokeError): ExecuteResult;
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
39
|
+
export declare const invokeTool: {
|
|
40
|
+
name: string;
|
|
41
|
+
label: string;
|
|
42
|
+
description: string;
|
|
43
|
+
parameters: {
|
|
44
|
+
type: string;
|
|
45
|
+
properties: {
|
|
46
|
+
functionName: {
|
|
47
|
+
type: string;
|
|
48
|
+
minLength: number;
|
|
49
|
+
description: string;
|
|
50
|
+
};
|
|
51
|
+
funcName: {
|
|
52
|
+
type: string;
|
|
53
|
+
minLength: number;
|
|
54
|
+
description: string;
|
|
55
|
+
};
|
|
56
|
+
arguments: {
|
|
57
|
+
type: string;
|
|
58
|
+
description: string;
|
|
59
|
+
properties: {
|
|
60
|
+
bundleName: {
|
|
61
|
+
type: string;
|
|
62
|
+
minLength: number;
|
|
63
|
+
description: string;
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
required: string[];
|
|
67
|
+
additionalProperties: boolean;
|
|
68
|
+
};
|
|
69
|
+
params: {
|
|
70
|
+
type: string;
|
|
71
|
+
description: string;
|
|
72
|
+
properties: {
|
|
73
|
+
bundleName: {
|
|
74
|
+
type: string;
|
|
75
|
+
minLength: number;
|
|
76
|
+
description: string;
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
required: string[];
|
|
80
|
+
additionalProperties: boolean;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
required: any[];
|
|
84
|
+
additionalProperties: boolean;
|
|
85
|
+
};
|
|
86
|
+
execute(toolCallId: string, rawParams: unknown, _signal?: AbortSignal, _onUpdate?: (partialResult: any) => void): Promise<ExecuteResult>;
|
|
87
|
+
};
|
|
48
88
|
export {};
|
package/dist/src/tools/invoke.js
CHANGED
|
@@ -27,6 +27,7 @@ import { logger } from "../utils/logger.js";
|
|
|
27
27
|
import { getXYWebSocketManager } from "../client.js";
|
|
28
28
|
import { sendCommand } from "../formatter.js";
|
|
29
29
|
import { getCurrentTaskId } from "../task-manager.js";
|
|
30
|
+
import { getCurrentSessionContext } from "./session-manager.js";
|
|
30
31
|
const RETRYABLE_CODES = new Set([
|
|
31
32
|
"RATE_LIMIT",
|
|
32
33
|
"TIMEOUT",
|
|
@@ -46,6 +47,13 @@ const CLIENT_ERROR_CODES = new Set([
|
|
|
46
47
|
"DEVICE_TOOL_BLOCKED",
|
|
47
48
|
"UNKNOWN",
|
|
48
49
|
]);
|
|
50
|
+
/** Parse the &-separated taskId into sessionId (part 0) and interactionId (part 1). */
|
|
51
|
+
function parseTaskId(taskId) {
|
|
52
|
+
const parts = taskId.split("&");
|
|
53
|
+
const taskSessionId = parts[0] ?? taskId;
|
|
54
|
+
const interactionId = parseInt(parts[1] ?? "1", 10) || 1;
|
|
55
|
+
return { taskSessionId, interactionId };
|
|
56
|
+
}
|
|
49
57
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
50
58
|
// 2. Errors
|
|
51
59
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
@@ -126,7 +134,7 @@ const REFRESH_INTERVAL_MS = 30_000;
|
|
|
126
134
|
const REQUIRED_FIELDS = ["schemaVersion", "bundleName", "toolName", "pluginType", "description", "arguments"];
|
|
127
135
|
const CORE_FIELDS = ["bundleName", "toolName", "toolType", "pluginType", "protocol", "description", "arguments", "deviceCommand"];
|
|
128
136
|
const VALID_PLUGIN_TYPES = new Set(["Cloud", "Device", "MCP"]);
|
|
129
|
-
const VALID_PROTOCOLS = new Set(["REST", "SSE", "Websocket"]);
|
|
137
|
+
const VALID_PROTOCOLS = new Set(["REST", "SSE", "Websocket", "WebSocket"]);
|
|
130
138
|
const FILENAME_PATTERN = /^(.+)__(.+)\.json$/;
|
|
131
139
|
const _g = globalThis;
|
|
132
140
|
const CACHE_SLOT = "__xyInvokeToolCache";
|
|
@@ -525,13 +533,14 @@ function loadCloudConfig() {
|
|
|
525
533
|
return { serviceUrl: env["SERVICE_URL"], apiKey: env["PERSONAL-API-KEY"], uid: env["PERSONAL-UID"] };
|
|
526
534
|
}
|
|
527
535
|
function buildCloudRequest(p) {
|
|
536
|
+
const { taskSessionId, interactionId } = parseTaskId(p.taskId);
|
|
528
537
|
return {
|
|
529
538
|
version: "1.0",
|
|
530
539
|
session: {
|
|
531
540
|
isNew: "true",
|
|
532
|
-
sessionId:
|
|
533
|
-
interactionId
|
|
534
|
-
conversationId:
|
|
541
|
+
sessionId: taskSessionId,
|
|
542
|
+
interactionId,
|
|
543
|
+
conversationId: p.sessionId, // ctx.sessionId
|
|
535
544
|
agentLoginSessionId1: p.agentId,
|
|
536
545
|
},
|
|
537
546
|
endpoint: {
|
|
@@ -563,11 +572,11 @@ function buildCloudRequest(p) {
|
|
|
563
572
|
},
|
|
564
573
|
};
|
|
565
574
|
}
|
|
566
|
-
function buildHeaders(config, skillName, protocol) {
|
|
575
|
+
function buildHeaders(config, skillName, protocol, taskId) {
|
|
567
576
|
return {
|
|
568
577
|
"content-type": "application/json",
|
|
569
578
|
accept: protocol === "REST" ? "application/json" : "text/event-stream",
|
|
570
|
-
"x-hag-trace-id":
|
|
579
|
+
"x-hag-trace-id": taskId,
|
|
571
580
|
"x-uid": config.uid,
|
|
572
581
|
"x-api-key": config.apiKey,
|
|
573
582
|
"x-request-from": "openclaw",
|
|
@@ -581,10 +590,10 @@ function buildHeaders(config, skillName, protocol) {
|
|
|
581
590
|
// - REST: single JSON frame
|
|
582
591
|
// - SSE/Websocket: multiple SSE frames; only the final frame is used (§4.7)
|
|
583
592
|
async function executePluginExecutor(config, requestBody, headers, toolName, bundleName, protocol) {
|
|
584
|
-
//
|
|
585
|
-
const wsBaseUrl = config.serviceUrl.replace(/^
|
|
593
|
+
// Map http→ws, https→wss
|
|
594
|
+
const wsBaseUrl = config.serviceUrl.replace(/^http(s)?:\/\//i, "ws$1://");
|
|
586
595
|
const url = `${wsBaseUrl}${UNIFIED_API_SUFFIX}`;
|
|
587
|
-
const isStreaming = protocol === "SSE" || protocol === "Websocket";
|
|
596
|
+
const isStreaming = protocol === "SSE" || protocol === "Websocket" || protocol === "WebSocket";
|
|
588
597
|
logger.log(`[INVOKE-CLOUD] calling PluginExecutor via WebSocket`, { url, toolName, bundleName, protocol });
|
|
589
598
|
const urlObj = new URL(url);
|
|
590
599
|
const isWssWithIP = urlObj.protocol === "wss:" && /^(\d{1,3}\.){3}\d{1,3}$/.test(urlObj.hostname);
|
|
@@ -856,14 +865,14 @@ async function executeCloudTool(params) {
|
|
|
856
865
|
toolName, bundleName, skillName, protocol,
|
|
857
866
|
businessKeysCount: Object.keys(businessParams).length,
|
|
858
867
|
});
|
|
859
|
-
if (protocol !== "REST" && protocol !== "SSE" && protocol !== "Websocket") {
|
|
868
|
+
if (protocol !== "REST" && protocol !== "SSE" && protocol !== "Websocket" && protocol !== "WebSocket") {
|
|
860
869
|
logger.warn("[INVOKE-CLOUD] unknown protocol", { toolName, bundleName, protocol });
|
|
861
870
|
throw new InvokeError("UNSUPPORTED_PROTOCOL", `Unknown protocol: ${protocol}`);
|
|
862
871
|
}
|
|
863
872
|
// Per invoke.md §4.3: REST, SSE, and Websocket all use the same endpoint.
|
|
864
873
|
// Only the accept header and response handling differ.
|
|
865
874
|
const config = loadCloudConfig();
|
|
866
|
-
return executePluginExecutor(config, buildCloudRequest(params), buildHeaders(config, skillName, protocol), toolName, bundleName, protocol);
|
|
875
|
+
return executePluginExecutor(config, buildCloudRequest(params), buildHeaders(config, skillName, protocol, params.taskId), toolName, bundleName, protocol);
|
|
867
876
|
}
|
|
868
877
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
869
878
|
// 7. Device executor
|
|
@@ -1066,136 +1075,135 @@ function validateBusinessParams(businessParams, definition) {
|
|
|
1066
1075
|
}
|
|
1067
1076
|
return null;
|
|
1068
1077
|
}
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
bundleName: {
|
|
1098
|
-
type: "string",
|
|
1099
|
-
minLength: 1,
|
|
1100
|
-
description: "HarmonyOS 应用唯一标识,如 com.example.weather。",
|
|
1101
|
-
},
|
|
1078
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1079
|
+
// 8. Invoke tool (static — matches ALL_TOOLS pattern)
|
|
1080
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1081
|
+
export const invokeTool = {
|
|
1082
|
+
name: "invoke",
|
|
1083
|
+
label: "Invoke",
|
|
1084
|
+
description: "调用已安装 skill 中声明的工具。必须传 functionName(或funcName) 与 arguments(或params);functionName 的值等于工具定义中的 toolName;arguments 是包含 bundleName 和业务参数字段的对象;完整业务参数定义见 references/tools/<bundleName>__<toolName>.json。",
|
|
1085
|
+
parameters: {
|
|
1086
|
+
type: "object",
|
|
1087
|
+
properties: {
|
|
1088
|
+
functionName: {
|
|
1089
|
+
type: "string",
|
|
1090
|
+
minLength: 1,
|
|
1091
|
+
description: "工具名称,值等于对应 references/tools JSON 中的 toolName,如 weather_query(优先使用;funcName 已废弃但仍兼容)。",
|
|
1092
|
+
},
|
|
1093
|
+
funcName: {
|
|
1094
|
+
type: "string",
|
|
1095
|
+
minLength: 1,
|
|
1096
|
+
description: "[废弃] 请使用 functionName 替代。工具名称,值等于对应 references/tools JSON 中的 toolName。",
|
|
1097
|
+
},
|
|
1098
|
+
arguments: {
|
|
1099
|
+
type: "object",
|
|
1100
|
+
description: "包含定位字段 bundleName 与业务参数字段;除 bundleName 外的字段遵循对应 references/tools JSON 中的 arguments schema(优先使用;params 已废弃但仍兼容)。",
|
|
1101
|
+
properties: {
|
|
1102
|
+
bundleName: {
|
|
1103
|
+
type: "string",
|
|
1104
|
+
minLength: 1,
|
|
1105
|
+
description: "HarmonyOS 应用唯一标识,如 com.example.weather。",
|
|
1102
1106
|
},
|
|
1103
|
-
required: ["bundleName"],
|
|
1104
|
-
additionalProperties: true,
|
|
1105
1107
|
},
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1108
|
+
required: ["bundleName"],
|
|
1109
|
+
additionalProperties: true,
|
|
1110
|
+
},
|
|
1111
|
+
params: {
|
|
1112
|
+
type: "object",
|
|
1113
|
+
description: "[废弃] 请使用 arguments 替代。包含定位字段 bundleName 与业务参数字段。",
|
|
1114
|
+
properties: {
|
|
1115
|
+
bundleName: {
|
|
1116
|
+
type: "string",
|
|
1117
|
+
minLength: 1,
|
|
1118
|
+
description: "HarmonyOS 应用唯一标识,如 com.example.weather。",
|
|
1115
1119
|
},
|
|
1116
|
-
required: ["bundleName"],
|
|
1117
|
-
additionalProperties: true,
|
|
1118
1120
|
},
|
|
1121
|
+
required: ["bundleName"],
|
|
1122
|
+
additionalProperties: true,
|
|
1119
1123
|
},
|
|
1120
|
-
required: [],
|
|
1121
|
-
additionalProperties: false,
|
|
1122
1124
|
},
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1125
|
+
required: [],
|
|
1126
|
+
additionalProperties: false,
|
|
1127
|
+
},
|
|
1128
|
+
async execute(toolCallId, rawParams, _signal, _onUpdate) {
|
|
1129
|
+
const ctx = getCurrentSessionContext();
|
|
1130
|
+
// Layer 1: input validation
|
|
1131
|
+
const validated = validateAndExtract(rawParams);
|
|
1132
|
+
if ("content" in validated) {
|
|
1133
|
+
logger.warn("[INVOKE] input validation failed", { toolCallId });
|
|
1134
|
+
return validated;
|
|
1135
|
+
}
|
|
1136
|
+
const { toolName, bundleName, businessParams } = validated;
|
|
1137
|
+
const businessKeys = Object.keys(businessParams);
|
|
1138
|
+
logger.log("[INVOKE] tool called", {
|
|
1139
|
+
toolCallId, toolName, bundleName,
|
|
1140
|
+
businessKeys: businessKeys.join(","),
|
|
1141
|
+
businessKeysCount: businessKeys.length,
|
|
1142
|
+
});
|
|
1143
|
+
// Layer 2: cache lookup
|
|
1144
|
+
const cache = getToolCache();
|
|
1145
|
+
const entry = cache.get(bundleName, toolName);
|
|
1146
|
+
if (!entry) {
|
|
1147
|
+
const conflict = cache.getConflict(bundleName, toolName);
|
|
1148
|
+
if (conflict) {
|
|
1149
|
+
const files = conflict.entries.map((e) => e.filePath).join(", ");
|
|
1150
|
+
logger.warn("[INVOKE] tool conflict", { toolCallId, toolName, bundleName, conflictCount: conflict.entries.length });
|
|
1151
|
+
return invokeErrorToResult(new InvokeError("TOOL_CONFLICT", `Multiple conflicting definitions for '${toolName}' in bundle '${bundleName}': ${files}`));
|
|
1149
1152
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1153
|
+
logger.warn("[INVOKE] tool not found", { toolCallId, toolName, bundleName });
|
|
1154
|
+
return invokeErrorToResult(new InvokeError("TOOL_NOT_FOUND", `Tool '${toolName}' not found in bundle '${bundleName}'.`));
|
|
1155
|
+
}
|
|
1156
|
+
const { definition, skillName } = entry;
|
|
1157
|
+
logger.log("[INVOKE] cache hit", {
|
|
1158
|
+
toolCallId, toolName, bundleName, skillName,
|
|
1159
|
+
pluginType: definition.pluginType,
|
|
1160
|
+
protocol: definition.protocol ?? "N/A",
|
|
1161
|
+
});
|
|
1162
|
+
// Layer 2b: business param validation
|
|
1163
|
+
const paramError = validateBusinessParams(businessParams, definition);
|
|
1164
|
+
if (paramError) {
|
|
1165
|
+
logger.warn("[INVOKE] business param validation failed", { toolCallId, toolName, bundleName });
|
|
1166
|
+
return paramError;
|
|
1167
|
+
}
|
|
1168
|
+
// Layer 3: execute
|
|
1169
|
+
const pluginType = definition.pluginType;
|
|
1170
|
+
logger.log(`[INVOKE] dispatching to ${pluginType} executor`, { toolCallId, toolName, bundleName, pluginType });
|
|
1171
|
+
try {
|
|
1172
|
+
if (pluginType === "Cloud" || pluginType === "MCP") {
|
|
1173
|
+
const result = await executeCloudTool({ definition, businessParams, skillName, sessionId: ctx?.sessionId ?? "", agentId: ctx?.agentId ?? "", taskId: ctx?.taskId ?? toolCallId });
|
|
1174
|
+
logger.log("[INVOKE] cloud execution succeeded", {
|
|
1175
|
+
toolCallId, toolName, bundleName, pluginType,
|
|
1176
|
+
resultLength: result.content[0]?.text?.length ?? 0,
|
|
1177
|
+
});
|
|
1178
|
+
return result;
|
|
1161
1179
|
}
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
try {
|
|
1166
|
-
if (pluginType === "Cloud" || pluginType === "MCP") {
|
|
1167
|
-
const result = await executeCloudTool({ definition, businessParams, skillName, sessionId: ctx.sessionId, agentId: ctx.agentId });
|
|
1168
|
-
logger.log("[INVOKE] cloud execution succeeded", {
|
|
1169
|
-
toolCallId, toolName, bundleName, pluginType,
|
|
1170
|
-
resultLength: result.content[0]?.text?.length ?? 0,
|
|
1171
|
-
});
|
|
1172
|
-
return result;
|
|
1180
|
+
if (pluginType === "Device") {
|
|
1181
|
+
if (!ctx) {
|
|
1182
|
+
return invokeErrorToResult(new InvokeError("DEVICE_TOOL_BLOCKED", "Device tools require an active session context."));
|
|
1173
1183
|
}
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
return result;
|
|
1181
|
-
}
|
|
1182
|
-
logger.warn("[INVOKE] unsupported pluginType", { toolCallId, toolName, bundleName, pluginType });
|
|
1183
|
-
return invokeErrorToResult(new InvokeError("UNSUPPORTED_PLUGIN_TYPE", `Unsupported pluginType '${pluginType}'. Must be Cloud, Device, or MCP.`));
|
|
1184
|
+
const result = await executeDeviceTool({ definition, businessParams, toolCallId }, ctx);
|
|
1185
|
+
logger.log("[INVOKE] device execution succeeded", {
|
|
1186
|
+
toolCallId, toolName, bundleName,
|
|
1187
|
+
resultLength: result.content[0]?.text?.length ?? 0,
|
|
1188
|
+
});
|
|
1189
|
+
return result;
|
|
1184
1190
|
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
return invokeErrorToResult(err);
|
|
1192
|
-
}
|
|
1193
|
-
logger.error("[INVOKE] unexpected execution error", {
|
|
1191
|
+
logger.warn("[INVOKE] unsupported pluginType", { toolCallId, toolName, bundleName, pluginType });
|
|
1192
|
+
return invokeErrorToResult(new InvokeError("UNSUPPORTED_PLUGIN_TYPE", `Unsupported pluginType '${pluginType}'. Must be Cloud, Device, or MCP.`));
|
|
1193
|
+
}
|
|
1194
|
+
catch (err) {
|
|
1195
|
+
if (err instanceof InvokeError) {
|
|
1196
|
+
logger.warn("[INVOKE] invocation error", {
|
|
1194
1197
|
toolCallId, toolName, bundleName, pluginType,
|
|
1195
|
-
|
|
1198
|
+
errorCode: err.code, errorMessage: err.message, retryable: err.retryable,
|
|
1196
1199
|
});
|
|
1197
|
-
return
|
|
1200
|
+
return invokeErrorToResult(err);
|
|
1198
1201
|
}
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
}
|
|
1202
|
+
logger.error("[INVOKE] unexpected execution error", {
|
|
1203
|
+
toolCallId, toolName, bundleName, pluginType,
|
|
1204
|
+
error: err instanceof Error ? `${err.name}: ${err.message}` : String(err),
|
|
1205
|
+
});
|
|
1206
|
+
return unknownErrorToResult(err);
|
|
1207
|
+
}
|
|
1208
|
+
},
|
|
1209
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Skills usage logger
|
|
2
|
+
// Format: |timestamp|skillName|
|
|
3
|
+
import { mkdirSync, readdirSync, unlinkSync, statSync } from "fs";
|
|
4
|
+
import { join } from "path";
|
|
5
|
+
import pino from "pino";
|
|
6
|
+
// ── Configuration ──
|
|
7
|
+
const LOG_DIR = "/tmp/openclaw";
|
|
8
|
+
const LOG_PREFIX = "skills";
|
|
9
|
+
const MAX_AGE_DAYS = 30;
|
|
10
|
+
// ── UTC+8 helpers ──
|
|
11
|
+
function getTodayDateStr() {
|
|
12
|
+
const utc8 = new Date(Date.now() + 8 * 60 * 60 * 1000);
|
|
13
|
+
return `${utc8.getUTCFullYear()}${String(utc8.getUTCMonth() + 1).padStart(2, "0")}${String(utc8.getUTCDate()).padStart(2, "0")}`;
|
|
14
|
+
}
|
|
15
|
+
function formatTimestampUTC8() {
|
|
16
|
+
const utc8 = new Date(Date.now() + 8 * 60 * 60 * 1000);
|
|
17
|
+
const y = utc8.getUTCFullYear();
|
|
18
|
+
const M = String(utc8.getUTCMonth() + 1).padStart(2, "0");
|
|
19
|
+
const D = String(utc8.getUTCDate()).padStart(2, "0");
|
|
20
|
+
const h = String(utc8.getUTCHours()).padStart(2, "0");
|
|
21
|
+
const m = String(utc8.getUTCMinutes()).padStart(2, "0");
|
|
22
|
+
const s = String(utc8.getUTCSeconds()).padStart(2, "0");
|
|
23
|
+
return `${y}${M}${D}T${h}${m}${s}`;
|
|
24
|
+
}
|
|
25
|
+
function getLogFilePath(dateStr) {
|
|
26
|
+
return join(LOG_DIR, `${LOG_PREFIX}-${dateStr ?? getTodayDateStr()}.log`);
|
|
27
|
+
}
|
|
28
|
+
// ── Ensure log directory ──
|
|
29
|
+
try {
|
|
30
|
+
mkdirSync(LOG_DIR, { recursive: true });
|
|
31
|
+
}
|
|
32
|
+
catch { }
|
|
33
|
+
// ── Cleanup expired logs (older than MAX_AGE_DAYS) ──
|
|
34
|
+
function cleanupOldLogs() {
|
|
35
|
+
try {
|
|
36
|
+
const files = readdirSync(LOG_DIR);
|
|
37
|
+
const cutoff = Date.now() - MAX_AGE_DAYS * 24 * 60 * 60 * 1000;
|
|
38
|
+
for (const f of files) {
|
|
39
|
+
if (!f.startsWith(LOG_PREFIX) || !f.endsWith(".log"))
|
|
40
|
+
continue;
|
|
41
|
+
const fp = join(LOG_DIR, f);
|
|
42
|
+
try {
|
|
43
|
+
if (statSync(fp).mtimeMs < cutoff)
|
|
44
|
+
unlinkSync(fp);
|
|
45
|
+
}
|
|
46
|
+
catch { }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch { }
|
|
50
|
+
}
|
|
51
|
+
// Run cleanup on module load
|
|
52
|
+
cleanupOldLogs();
|
|
53
|
+
// Schedule periodic cleanup every 6 hours
|
|
54
|
+
const cleanupTimer = setInterval(cleanupOldLogs, 6 * 60 * 60 * 1000);
|
|
55
|
+
cleanupTimer.unref?.();
|
|
56
|
+
// ── File destination with daily rotation ──
|
|
57
|
+
let currentDate = getTodayDateStr();
|
|
58
|
+
const dest = pino.destination({ dest: getLogFilePath(currentDate), sync: false, mkdir: true });
|
|
59
|
+
// ── Rotation check ──
|
|
60
|
+
function checkRotation() {
|
|
61
|
+
const today = getTodayDateStr();
|
|
62
|
+
if (today !== currentDate) {
|
|
63
|
+
currentDate = today;
|
|
64
|
+
dest.reopen(getLogFilePath(today));
|
|
65
|
+
cleanupOldLogs();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Write a skill-usage record to the skills log.
|
|
70
|
+
* Format: |YYYYMMDDThhmmss|skillName|
|
|
71
|
+
*/
|
|
72
|
+
export function writeSkillUsage(skillName) {
|
|
73
|
+
checkRotation();
|
|
74
|
+
const timestamp = formatTimestampUTC8();
|
|
75
|
+
dest.write(`|${timestamp}|${skillName}|\n`);
|
|
76
|
+
}
|
package/dist/src/websocket.js
CHANGED
|
@@ -512,6 +512,7 @@ export class XYWebSocketManager extends EventEmitter {
|
|
|
512
512
|
? logger.withContext(sessionId, taskId)
|
|
513
513
|
: { log: (msg, ...args) => logger.log(msg, ...args) };
|
|
514
514
|
log.log(`[WS-RECV] Raw message frame, size: ${messageStr.length} characters`);
|
|
515
|
+
log.log(`[WS-RECV] Full message body: ${messageStr}`);
|
|
515
516
|
// Handle direct cross-task requests (top-level networkId)
|
|
516
517
|
const directRunCrossTaskRequest = this.toRunCrossTaskA2ARequest(parsed);
|
|
517
518
|
if (directRunCrossTaskRequest) {
|