@ynhcj/xiaoyi-channel 0.0.211-beta → 0.0.213-beta
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 +39 -0
- package/dist/src/bot.d.ts +0 -5
- package/dist/src/bot.js +43 -76
- package/dist/src/log-reporter/index.js +5 -0
- package/dist/src/provider.js +2 -7
- package/dist/src/tools/hmos-cli.d.ts +7 -1
- package/dist/src/tools/hmos-cli.js +25 -29
- package/dist/src/tools/invoke.js +20 -12
- 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,43 @@ 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
|
+
/**
|
|
16
|
+
* Parse a file path string to detect if it refers to a SKILL.md file within
|
|
17
|
+
* a skills directory. Returns the skill name (parent directory) if so.
|
|
18
|
+
*
|
|
19
|
+
* Matches paths like:
|
|
20
|
+
* ~/.openclaw/workspace/skills/my-skill/SKILL.md
|
|
21
|
+
* /home/user/core_skills/my-skill/SKILL.md
|
|
22
|
+
* skills/my-skill/SKILL.md
|
|
23
|
+
*/
|
|
24
|
+
function extractSkillNameFromPath(filePath) {
|
|
25
|
+
if (typeof filePath !== "string" || !filePath)
|
|
26
|
+
return null;
|
|
27
|
+
// Normalize common path prefixes
|
|
28
|
+
const normalized = filePath.replace(/^~\//, "/home/").replace(/\\/g, "/");
|
|
29
|
+
// Match: .../skills/<skillName>/SKILL.md or .../skills/<skillName>/...
|
|
30
|
+
// Also match: .../core_skills/<skillName>/SKILL.md
|
|
31
|
+
const match = normalized.match(/\/(?:core_)?skills\/([^/]+)\/SKILL\.md$/i);
|
|
32
|
+
return match ? match[1] : null;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Register the skills diagnostic event listener via after_tool_call hook.
|
|
36
|
+
*
|
|
37
|
+
* When openclaw fires a `skill.used` diagnostic event, the skill's SKILL.md
|
|
38
|
+
* is typically read by the model first. We detect SKILL.md reads through
|
|
39
|
+
* the `after_tool_call` hook and write the skill name to the skills log.
|
|
40
|
+
*/
|
|
41
|
+
function registerSkillsDiagnosticHook(api) {
|
|
42
|
+
api.on("after_tool_call", async (event, _ctx) => {
|
|
43
|
+
if (event.toolName !== "read")
|
|
44
|
+
return;
|
|
45
|
+
const skillName = extractSkillNameFromPath(event.params?.path);
|
|
46
|
+
if (skillName) {
|
|
47
|
+
writeSkillUsage(skillName);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
14
51
|
/**
|
|
15
52
|
* Register the cron detection hook.
|
|
16
53
|
*
|
|
@@ -211,6 +248,8 @@ const pluginEntry = definePluginEntry({
|
|
|
211
248
|
registerCronDetectionHook(api);
|
|
212
249
|
// CLI exec hook: intercepts built-in exec for HarmonyOS CLI skill tools
|
|
213
250
|
registerCLIHook(api);
|
|
251
|
+
// Skills diagnostic hook: log skill usage (detected via SKILL.md reads)
|
|
252
|
+
registerSkillsDiagnosticHook(api);
|
|
214
253
|
}
|
|
215
254
|
},
|
|
216
255
|
});
|
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
|
@@ -310,9 +310,6 @@ export async function handleXYMessage(params) {
|
|
|
310
310
|
return;
|
|
311
311
|
}
|
|
312
312
|
// ── First message (non-steer) path below ──────────────────────
|
|
313
|
-
// 🔑 立即创建 streaming 信号——必须在文件下载等耗时操作之前,
|
|
314
|
-
// 否则 steer 消息的 dispatchSteerWhenReady 会找不到信号而跳过等待。
|
|
315
|
-
createStreamingSignal(parsed.sessionId);
|
|
316
313
|
// File download — only for real user messages, steer injections have no files
|
|
317
314
|
let mediaPayload = {};
|
|
318
315
|
if (!skipReg) {
|
|
@@ -372,7 +369,6 @@ export async function handleXYMessage(params) {
|
|
|
372
369
|
return;
|
|
373
370
|
cleaned = true;
|
|
374
371
|
log.log(`[BOT] Cleanup started`);
|
|
375
|
-
streamingSignals.delete(parsed.sessionId);
|
|
376
372
|
decrementTaskIdRef(parsed.sessionId);
|
|
377
373
|
log.log(`[BOT] Cleanup completed`);
|
|
378
374
|
};
|
|
@@ -495,45 +491,22 @@ function buildXYMediaPayload(mediaList) {
|
|
|
495
491
|
MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
|
|
496
492
|
};
|
|
497
493
|
}
|
|
494
|
+
// ─────────────────────────────────────────────────────────────
|
|
495
|
+
// Steer 串行队列
|
|
496
|
+
// ─────────────────────────────────────────────────────────────
|
|
498
497
|
// Use globalThis to survive module deduplication — provider.ts may load a
|
|
499
498
|
// different copy of bot.ts, so a plain module-level Map would be two objects.
|
|
500
499
|
const _g = globalThis;
|
|
501
|
-
if (!_g.__xyStreamingSignals)
|
|
502
|
-
_g.__xyStreamingSignals = new Map();
|
|
503
500
|
if (!_g.__xySteerQueues)
|
|
504
501
|
_g.__xySteerQueues = new Map();
|
|
505
502
|
if (!_g.__xyDispatcherUpdaters)
|
|
506
503
|
_g.__xyDispatcherUpdaters = new Map();
|
|
507
|
-
const streamingSignals = _g.__xyStreamingSignals;
|
|
508
504
|
const steerQueues = _g.__xySteerQueues;
|
|
509
505
|
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
506
|
/**
|
|
534
507
|
* 将 steer 消息放入 per-session 串行队列。
|
|
535
|
-
*
|
|
536
|
-
* 多个 steer
|
|
508
|
+
* 通过指数退避轮询注入(queueAgentHarnessMessage),直到 Pi agent 接受消息或 run 结束。
|
|
509
|
+
* 多个 steer 按到达顺序串行处理。
|
|
537
510
|
*/
|
|
538
511
|
function enqueueSteer(params) {
|
|
539
512
|
const { sessionId } = params;
|
|
@@ -552,58 +525,52 @@ function enqueueSteer(params) {
|
|
|
552
525
|
});
|
|
553
526
|
return next;
|
|
554
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
|
+
*/
|
|
555
537
|
async function dispatchSteerWhenReady(params) {
|
|
556
538
|
const { sessionId, steerText } = params;
|
|
557
539
|
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
540
|
const mediaPaths = params.mediaPayload?.MediaPaths;
|
|
595
541
|
const fileHint = mediaPaths && mediaPaths.length > 0
|
|
596
542
|
? `\n【用户上传附件】:${JSON.stringify(mediaPaths)}`
|
|
597
543
|
: "";
|
|
598
544
|
const steerMessage = `${steerText}${fileHint}`;
|
|
599
545
|
log.log(`[STEER-QUEUE] Injecting steer message directly into active run`);
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
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++;
|
|
608
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`);
|
|
609
576
|
}
|
|
@@ -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/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;
|
|
@@ -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>;
|
|
@@ -216,6 +216,23 @@ function wrapState(state) {
|
|
|
216
216
|
return entries.find(e => e.cliName === cliName) ?? null;
|
|
217
217
|
},
|
|
218
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
|
+
},
|
|
219
236
|
async refresh() {
|
|
220
237
|
state.skillClis = scanCLIDirectories(state.rootDir);
|
|
221
238
|
state.lastScanMs = Date.now();
|
|
@@ -470,7 +487,8 @@ export { parseSkillName as deriveSkillName };
|
|
|
470
487
|
* before_tool_call hook for CLI exec interception.
|
|
471
488
|
*
|
|
472
489
|
* Only handles built-in `exec` calls whose command prefix matches a CLI
|
|
473
|
-
*
|
|
490
|
+
* from any skill's metadata.clis + available_clis.json (searched across
|
|
491
|
+
* all cached skills, not just the current session's skill).
|
|
474
492
|
* Non-matching commands return undefined (noop) so native exec handles them.
|
|
475
493
|
*/
|
|
476
494
|
export async function cliBeforeToolCallHandler(event, ctx) {
|
|
@@ -481,37 +499,15 @@ export async function cliBeforeToolCallHandler(event, ctx) {
|
|
|
481
499
|
return undefined;
|
|
482
500
|
const t0 = performance.now();
|
|
483
501
|
const command = rawCommand.trim();
|
|
484
|
-
//
|
|
485
|
-
const workspaceDir = ctx.workspaceDir;
|
|
486
|
-
if (!workspaceDir) {
|
|
487
|
-
logger.log(`[CLI-HOOK] no workspaceDir, noop (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
488
|
-
return undefined;
|
|
489
|
-
}
|
|
490
|
-
const skillName = parseSkillName(workspaceDir);
|
|
491
|
-
if (!skillName) {
|
|
492
|
-
logger.log(`[CLI-HOOK] no skill name in ${workspaceDir}, noop (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
493
|
-
return undefined;
|
|
494
|
-
}
|
|
502
|
+
// Search all cached skills for a CLI matching the command prefix
|
|
495
503
|
const cache = getCLICache();
|
|
496
|
-
const
|
|
497
|
-
if (!
|
|
498
|
-
logger.log(`[CLI-HOOK]
|
|
499
|
-
return undefined;
|
|
500
|
-
}
|
|
501
|
-
// Match longest CLI name first
|
|
502
|
-
const sorted = [...skillCLIs].sort((a, b) => b.cliName.length - a.cliName.length);
|
|
503
|
-
let matchedCLI = null;
|
|
504
|
-
for (const entry of sorted) {
|
|
505
|
-
if (command === entry.cliName || command.startsWith(entry.cliName + " ")) {
|
|
506
|
-
matchedCLI = entry;
|
|
507
|
-
break;
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
if (!matchedCLI) {
|
|
511
|
-
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)`);
|
|
512
507
|
return undefined;
|
|
513
508
|
}
|
|
514
|
-
|
|
509
|
+
const { entry: matchedCLI, skillName } = match;
|
|
510
|
+
logger.log(`[CLI-HOOK] Matched CLI '${matchedCLI.cliName}' in skill '${skillName}' (${(performance.now() - t0).toFixed(1)}ms)`);
|
|
515
511
|
// Parse and validate
|
|
516
512
|
let parsed;
|
|
517
513
|
try {
|
package/dist/src/tools/invoke.js
CHANGED
|
@@ -47,6 +47,13 @@ const CLIENT_ERROR_CODES = new Set([
|
|
|
47
47
|
"DEVICE_TOOL_BLOCKED",
|
|
48
48
|
"UNKNOWN",
|
|
49
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
|
+
}
|
|
50
57
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
51
58
|
// 2. Errors
|
|
52
59
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
@@ -127,7 +134,7 @@ const REFRESH_INTERVAL_MS = 30_000;
|
|
|
127
134
|
const REQUIRED_FIELDS = ["schemaVersion", "bundleName", "toolName", "pluginType", "description", "arguments"];
|
|
128
135
|
const CORE_FIELDS = ["bundleName", "toolName", "toolType", "pluginType", "protocol", "description", "arguments", "deviceCommand"];
|
|
129
136
|
const VALID_PLUGIN_TYPES = new Set(["Cloud", "Device", "MCP"]);
|
|
130
|
-
const VALID_PROTOCOLS = new Set(["REST", "SSE", "Websocket"]);
|
|
137
|
+
const VALID_PROTOCOLS = new Set(["REST", "SSE", "Websocket", "WebSocket"]);
|
|
131
138
|
const FILENAME_PATTERN = /^(.+)__(.+)\.json$/;
|
|
132
139
|
const _g = globalThis;
|
|
133
140
|
const CACHE_SLOT = "__xyInvokeToolCache";
|
|
@@ -526,13 +533,14 @@ function loadCloudConfig() {
|
|
|
526
533
|
return { serviceUrl: env["SERVICE_URL"], apiKey: env["PERSONAL-API-KEY"], uid: env["PERSONAL-UID"] };
|
|
527
534
|
}
|
|
528
535
|
function buildCloudRequest(p) {
|
|
536
|
+
const { taskSessionId, interactionId } = parseTaskId(p.taskId);
|
|
529
537
|
return {
|
|
530
538
|
version: "1.0",
|
|
531
539
|
session: {
|
|
532
540
|
isNew: "true",
|
|
533
|
-
sessionId:
|
|
534
|
-
interactionId
|
|
535
|
-
conversationId:
|
|
541
|
+
sessionId: taskSessionId,
|
|
542
|
+
interactionId,
|
|
543
|
+
conversationId: p.sessionId, // ctx.sessionId
|
|
536
544
|
agentLoginSessionId1: p.agentId,
|
|
537
545
|
},
|
|
538
546
|
endpoint: {
|
|
@@ -564,11 +572,11 @@ function buildCloudRequest(p) {
|
|
|
564
572
|
},
|
|
565
573
|
};
|
|
566
574
|
}
|
|
567
|
-
function buildHeaders(config, skillName, protocol) {
|
|
575
|
+
function buildHeaders(config, skillName, protocol, taskId) {
|
|
568
576
|
return {
|
|
569
577
|
"content-type": "application/json",
|
|
570
578
|
accept: protocol === "REST" ? "application/json" : "text/event-stream",
|
|
571
|
-
"x-hag-trace-id":
|
|
579
|
+
"x-hag-trace-id": taskId,
|
|
572
580
|
"x-uid": config.uid,
|
|
573
581
|
"x-api-key": config.apiKey,
|
|
574
582
|
"x-request-from": "openclaw",
|
|
@@ -582,10 +590,10 @@ function buildHeaders(config, skillName, protocol) {
|
|
|
582
590
|
// - REST: single JSON frame
|
|
583
591
|
// - SSE/Websocket: multiple SSE frames; only the final frame is used (§4.7)
|
|
584
592
|
async function executePluginExecutor(config, requestBody, headers, toolName, bundleName, protocol) {
|
|
585
|
-
//
|
|
586
|
-
const wsBaseUrl = config.serviceUrl.replace(/^
|
|
593
|
+
// Map http→ws, https→wss
|
|
594
|
+
const wsBaseUrl = config.serviceUrl.replace(/^http(s)?:\/\//i, "ws$1://");
|
|
587
595
|
const url = `${wsBaseUrl}${UNIFIED_API_SUFFIX}`;
|
|
588
|
-
const isStreaming = protocol === "SSE" || protocol === "Websocket";
|
|
596
|
+
const isStreaming = protocol === "SSE" || protocol === "Websocket" || protocol === "WebSocket";
|
|
589
597
|
logger.log(`[INVOKE-CLOUD] calling PluginExecutor via WebSocket`, { url, toolName, bundleName, protocol });
|
|
590
598
|
const urlObj = new URL(url);
|
|
591
599
|
const isWssWithIP = urlObj.protocol === "wss:" && /^(\d{1,3}\.){3}\d{1,3}$/.test(urlObj.hostname);
|
|
@@ -857,14 +865,14 @@ async function executeCloudTool(params) {
|
|
|
857
865
|
toolName, bundleName, skillName, protocol,
|
|
858
866
|
businessKeysCount: Object.keys(businessParams).length,
|
|
859
867
|
});
|
|
860
|
-
if (protocol !== "REST" && protocol !== "SSE" && protocol !== "Websocket") {
|
|
868
|
+
if (protocol !== "REST" && protocol !== "SSE" && protocol !== "Websocket" && protocol !== "WebSocket") {
|
|
861
869
|
logger.warn("[INVOKE-CLOUD] unknown protocol", { toolName, bundleName, protocol });
|
|
862
870
|
throw new InvokeError("UNSUPPORTED_PROTOCOL", `Unknown protocol: ${protocol}`);
|
|
863
871
|
}
|
|
864
872
|
// Per invoke.md §4.3: REST, SSE, and Websocket all use the same endpoint.
|
|
865
873
|
// Only the accept header and response handling differ.
|
|
866
874
|
const config = loadCloudConfig();
|
|
867
|
-
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);
|
|
868
876
|
}
|
|
869
877
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
870
878
|
// 7. Device executor
|
|
@@ -1162,7 +1170,7 @@ export const invokeTool = {
|
|
|
1162
1170
|
logger.log(`[INVOKE] dispatching to ${pluginType} executor`, { toolCallId, toolName, bundleName, pluginType });
|
|
1163
1171
|
try {
|
|
1164
1172
|
if (pluginType === "Cloud" || pluginType === "MCP") {
|
|
1165
|
-
const result = await executeCloudTool({ definition, businessParams, skillName, sessionId: ctx?.sessionId ?? "", agentId: ctx?.agentId ?? "" });
|
|
1173
|
+
const result = await executeCloudTool({ definition, businessParams, skillName, sessionId: ctx?.sessionId ?? "", agentId: ctx?.agentId ?? "", taskId: ctx?.taskId ?? toolCallId });
|
|
1166
1174
|
logger.log("[INVOKE] cloud execution succeeded", {
|
|
1167
1175
|
toolCallId, toolName, bundleName, pluginType,
|
|
1168
1176
|
resultLength: result.content[0]?.text?.length ?? 0,
|
|
@@ -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) {
|