@ynhcj/xiaoyi-channel 0.0.208-beta → 0.0.210-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.
Files changed (39) hide show
  1. package/dist/index.d.ts +3 -8
  2. package/dist/index.js +5 -1
  3. package/dist/src/bot.js +16 -77
  4. package/dist/src/cspl/call_api.d.ts +1 -1
  5. package/dist/src/cspl/call_api.js +6 -12
  6. package/dist/src/cspl/config.d.ts +0 -1
  7. package/dist/src/cspl/config.js +65 -59
  8. package/dist/src/cspl/constants.d.ts +36 -1
  9. package/dist/src/cspl/constants.js +9 -0
  10. package/dist/src/cspl/sentinel_hook.js +26 -22
  11. package/dist/src/cspl/upload_file.js +5 -6
  12. package/dist/src/cspl/utils.d.ts +20 -9
  13. package/dist/src/cspl/utils.js +119 -75
  14. package/dist/src/log-reporter/index.d.ts +1 -1
  15. package/dist/src/log-reporter/index.js +159 -35
  16. package/dist/src/log-reporter/openclaw-parser.d.ts +18 -0
  17. package/dist/src/log-reporter/openclaw-parser.js +94 -0
  18. package/dist/src/log-reporter/path-resolver.d.ts +5 -0
  19. package/dist/src/log-reporter/path-resolver.js +50 -0
  20. package/dist/src/log-reporter/reporter.d.ts +4 -4
  21. package/dist/src/log-reporter/reporter.js +52 -13
  22. package/dist/src/log-reporter/scanner.d.ts +7 -3
  23. package/dist/src/log-reporter/scanner.js +3 -7
  24. package/dist/src/log-reporter/types.d.ts +26 -27
  25. package/dist/src/log-reporter/uploader.d.ts +4 -3
  26. package/dist/src/log-reporter/uploader.js +32 -9
  27. package/dist/src/monitor.js +0 -1
  28. package/dist/src/skill-retriever/config.js +2 -0
  29. package/dist/src/skill-retriever/hooks.js +1 -0
  30. package/dist/src/skill-retriever/tool-search.d.ts +3 -0
  31. package/dist/src/skill-retriever/tool-search.js +27 -11
  32. package/dist/src/skill-retriever/types.d.ts +1 -0
  33. package/dist/src/tools/device-tool-map.js +0 -6
  34. package/dist/src/tools/hmos-cli.d.ts +103 -0
  35. package/dist/src/tools/hmos-cli.js +561 -0
  36. package/dist/src/tools/invoke.d.ts +48 -0
  37. package/dist/src/tools/invoke.js +1201 -0
  38. package/dist/src/websocket.js +10 -0
  39. package/package.json +1 -1
@@ -0,0 +1,50 @@
1
+ // Path resolver: resolves file path templates with date wildcards to actual files on disk
2
+ import { readdirSync } from "fs";
3
+ import { dirname, basename, join } from "path";
4
+ // Replace longer tokens first to avoid partial matches
5
+ const WILDCARD_TOKENS = [
6
+ ["{year-month-day}", "\\d{4}-\\d{2}-\\d{2}"],
7
+ ["{year}{month}{day}", "\\d{8}"],
8
+ ["{hour}{minute}{second}", "\\d{6}"],
9
+ ["{year}", "\\d{4}"],
10
+ ["{month}", "\\d{2}"],
11
+ ["{day}", "\\d{2}"],
12
+ ["{hour}", "\\d{2}"],
13
+ ["{minute}", "\\d{2}"],
14
+ ["{second}", "\\d{2}"],
15
+ ];
16
+ function escapeRegex(s) {
17
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18
+ }
19
+ /**
20
+ * Convert a path with date wildcards into a RegExp that matches the filename part only.
21
+ * Returns { dir, regex } where dir is the directory portion and regex matches filenames.
22
+ */
23
+ function pathToPattern(templatePath) {
24
+ const dir = dirname(templatePath);
25
+ let pattern = basename(templatePath);
26
+ // Escape regex special chars in the literal parts, then replace tokens
27
+ pattern = escapeRegex(pattern);
28
+ for (const [token, replacement] of WILDCARD_TOKENS) {
29
+ pattern = pattern.replaceAll(escapeRegex(token), replacement);
30
+ }
31
+ return { dir, regex: new RegExp(`^${pattern}$`) };
32
+ }
33
+ /**
34
+ * Resolve a path template with date wildcards to actual file paths on disk.
35
+ * Scans the directory and returns all files matching the pattern.
36
+ */
37
+ export function resolveLogFiles(templatePath) {
38
+ const { dir, regex } = pathToPattern(templatePath);
39
+ let entries;
40
+ try {
41
+ entries = readdirSync(dir);
42
+ }
43
+ catch {
44
+ return [];
45
+ }
46
+ return entries
47
+ .filter((f) => regex.test(f))
48
+ .map((f) => join(dir, f))
49
+ .sort(); // chronological order for date-named logs
50
+ }
@@ -1,6 +1,6 @@
1
- import type { ScanResult } from "./types.js";
1
+ import type { ReportPayload, LogReporterEnv } from "./types.js";
2
2
  /**
3
- * Send a log report to the server with the uploaded file URL.
4
- * MOCK implementation — real request logic will be added later.
3
+ * Send a log report to the sync API with retry on failure.
4
+ * Retries up to 3 times with delays of 10s, 20s, 30s.
5
5
  */
6
- export declare function sendReport(reportUrl: string, fileUrl: string, result: ScanResult): Promise<void>;
6
+ export declare function sendReport(payload: ReportPayload, env: LogReporterEnv): Promise<void>;
@@ -1,17 +1,56 @@
1
+ // Reporter: sends log report to the sync API
2
+ import fetch from "node-fetch";
3
+ import { calculateSHA256String } from "../utils/crypto.js";
4
+ import { logger } from "../utils/logger.js";
5
+ /** Retry delays in milliseconds: 10s, 20s, 30s */
6
+ const RETRY_DELAYS_MS = [10000, 20000, 30000];
7
+ const MAX_RETRIES = RETRY_DELAYS_MS.length;
8
+ /** Sleep for a given duration in milliseconds */
9
+ function sleep(ms) {
10
+ return new Promise((resolve) => setTimeout(resolve, ms));
11
+ }
1
12
  /**
2
- * Send a log report to the server with the uploaded file URL.
3
- * MOCK implementation — real request logic will be added later.
13
+ * Send a log report to the sync API with retry on failure.
14
+ * Retries up to 3 times with delays of 10s, 20s, 30s.
4
15
  */
5
- export async function sendReport(reportUrl, fileUrl, result) {
6
- // TODO: Replace with actual HTTP request
7
- const payload = {
8
- logName: result.name,
9
- filePath: result.filePath,
10
- lineStart: result.lineStart,
11
- lineEnd: result.lineEnd,
12
- newLineCount: result.newLineCount,
13
- fileUrl,
14
- timestamp: new Date().toISOString(),
16
+ export async function sendReport(payload, env) {
17
+ if (payload.logFiles.length === 0) {
18
+ return; // nothing to report
19
+ }
20
+ const url = `${env.serviceUrl}/fulfillment/v1/claw/log-file/sync`;
21
+ const traceId = `${calculateSHA256String(env.uid).substring(0, 32)}_${Date.now()}`;
22
+ const headers = {
23
+ "Content-Type": "application/json",
24
+ "x-api-key": env.apiKey,
25
+ "x-uid": env.uid,
26
+ "x-hag-trace-id": traceId,
27
+ "x-request-from": "openclaw",
15
28
  };
16
- console.log(`[log-reporter] Mock report to ${reportUrl}:`, JSON.stringify(payload, null, 2));
29
+ logger.log(`[log-reporter] Sending report to ${url}, ${payload.logFiles.length} log file(s)`);
30
+ let lastError;
31
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
32
+ try {
33
+ const resp = await fetch(url, {
34
+ method: "POST",
35
+ headers,
36
+ body: JSON.stringify(payload),
37
+ });
38
+ if (!resp.ok) {
39
+ const body = await resp.text().catch(() => "");
40
+ throw new Error(`Report API returned HTTP ${resp.status}: ${body}`);
41
+ }
42
+ logger.log(`[log-reporter] Report sent successfully, status: ${resp.status}`);
43
+ return; // success, exit
44
+ }
45
+ catch (err) {
46
+ lastError = err instanceof Error ? err : new Error(String(err));
47
+ if (attempt < MAX_RETRIES) {
48
+ const delay = RETRY_DELAYS_MS[attempt];
49
+ logger.warn(`[log-reporter] Report failed (attempt ${attempt + 1}/${MAX_RETRIES + 1}): ${lastError.message}. Retrying in ${delay / 1000}s...`);
50
+ await sleep(delay);
51
+ }
52
+ }
53
+ }
54
+ // All retries exhausted
55
+ throw lastError;
17
56
  }
@@ -1,6 +1,10 @@
1
- import type { ScanResult, CursorStore } from "./types.js";
1
+ import type { FileCursor, CursorStore } from "./types.js";
2
2
  /**
3
3
  * Scan a single log file for new content.
4
- * Returns a ScanResult if there are new lines, or null if no changes.
4
+ * Returns { filePath, content, newCursor } if there are new lines, or null if no changes.
5
5
  */
6
- export declare function scanFile(filePath: string, name: string, cursorStore: CursorStore): Promise<ScanResult | null>;
6
+ export declare function scanFile(filePath: string, cursorStore: CursorStore): Promise<{
7
+ filePath: string;
8
+ content: string;
9
+ newCursor: FileCursor;
10
+ } | null>;
@@ -1,4 +1,4 @@
1
- // Core scanner: resolves wildcard paths, reads incremental log content using byte-offset cursors
1
+ // Core scanner: reads incremental log content using byte-offset cursors
2
2
  import { statSync, createReadStream } from "fs";
3
3
  import { getCursor } from "./cursor-store.js";
4
4
  /**
@@ -39,9 +39,9 @@ function resolveStartByte(currentSize, currentMtimeMs, cursor) {
39
39
  }
40
40
  /**
41
41
  * Scan a single log file for new content.
42
- * Returns a ScanResult if there are new lines, or null if no changes.
42
+ * Returns { filePath, content, newCursor } if there are new lines, or null if no changes.
43
43
  */
44
- export async function scanFile(filePath, name, cursorStore) {
44
+ export async function scanFile(filePath, cursorStore) {
45
45
  let stats;
46
46
  try {
47
47
  stats = statSync(filePath);
@@ -72,11 +72,7 @@ export async function scanFile(filePath, name, cursorStore) {
72
72
  };
73
73
  return {
74
74
  filePath,
75
- name,
76
75
  content,
77
- lineStart: prevLine + 1,
78
- lineEnd: prevLine + newLineCount,
79
- newLineCount,
80
76
  newCursor,
81
77
  };
82
78
  }
@@ -1,20 +1,11 @@
1
- /** Configuration for a single log file to monitor */
2
- export interface LogFileConfig {
3
- /** File path with optional date wildcards: {year}, {month}, {day}, {year-month-day}, {year}{month}{day} */
1
+ /** Configuration for a single log monitor (hardcoded) */
2
+ export interface LogMonitorConfig {
3
+ /** File path with date wildcards: {year}, {month}, {day}, {year-month-day}, {year}{month}{day}, {hour}, {minute}, {second} */
4
4
  path: string;
5
- /** Logical name used in .bak filename and reporting */
6
- name: string;
7
- }
8
- /** Top-level log reporter configuration (loaded from JSON file) */
9
- export interface LogReporterConfig {
10
- /** Scan interval in milliseconds (default: 600000 = 10 min) */
11
- scanIntervalMs: number;
12
- /** Directory for .bak files and cursor state */
13
- bakDir: string;
14
- /** Report server URL (mock for now) */
15
- reportUrl: string;
16
- /** Log files to monitor */
17
- logFiles: LogFileConfig[];
5
+ /** Business type for reporting */
6
+ businessType: string;
7
+ /** Whether to parse JSON log lines (openclaw gateway format) */
8
+ jsonParse: boolean;
18
9
  }
19
10
  /** Cursor state for a single log file */
20
11
  export interface FileCursor {
@@ -33,23 +24,15 @@ export interface CursorStore {
33
24
  export interface ScanResult {
34
25
  /** Resolved absolute file path */
35
26
  filePath: string;
36
- /** Logical name from config */
37
- name: string;
38
- /** The new log lines (incremental content) */
27
+ /** Business type from monitor config */
28
+ businessType: string;
29
+ /** The new log lines (incremental content, may be parsed/formatted) */
39
30
  content: string;
40
- /** Start line number (1-based, inclusive) */
41
- lineStart: number;
42
- /** End line number (1-based, inclusive) */
43
- lineEnd: number;
44
- /** Number of new lines */
45
- newLineCount: number;
46
31
  /** Updated cursor to persist after successful upload */
47
32
  newCursor: FileCursor;
48
33
  }
49
34
  /** Options passed to startLogReporter */
50
35
  export interface LogReporterOptions {
51
- /** Absolute path to the JSON config file */
52
- configPath: string;
53
36
  /** File upload service instance (from xy_channel) */
54
37
  uploadService: UploadService;
55
38
  }
@@ -57,3 +40,19 @@ export interface LogReporterOptions {
57
40
  export interface UploadService {
58
41
  uploadFileAndGetUrl(filePath: string, objectType?: string): Promise<string>;
59
42
  }
43
+ /** A single log file entry in the report payload */
44
+ export interface ReportLogFileEntry {
45
+ businessType: string;
46
+ fileUrl: string;
47
+ }
48
+ /** Report payload sent to the sync API */
49
+ export interface ReportPayload {
50
+ instanceId: string;
51
+ logFiles: ReportLogFileEntry[];
52
+ }
53
+ /** Environment config read from .xiaoyienv */
54
+ export interface LogReporterEnv {
55
+ serviceUrl: string;
56
+ apiKey: string;
57
+ uid: string;
58
+ }
@@ -1,6 +1,7 @@
1
- import type { UploadService, ScanResult } from "./types.js";
1
+ import type { UploadService } from "./types.js";
2
2
  /**
3
- * Write incremental content to .bak file, upload, and return the URL.
3
+ * Write content to a .bak file, upload, and return the URL.
4
+ * Retries upload up to 3 times with delays of 10s, 20s, 30s.
4
5
  * Cleans up .bak file regardless of success/failure.
5
6
  */
6
- export declare function uploadIncrementalContent(result: ScanResult, bakDir: string, uploadService: UploadService): Promise<string>;
7
+ export declare function uploadContent(content: string, name: string, bakDir: string, uploadService: UploadService): Promise<string>;
@@ -1,26 +1,49 @@
1
- // Uploader: creates .bak file, uploads via XYFileUploadService, cleans up
1
+ // Uploader: creates .bak file, uploads via UploadService, cleans up
2
2
  import { writeFileSync, unlinkSync } from "fs";
3
3
  import { join } from "path";
4
4
  import { mkdirSync } from "fs";
5
+ import { logger } from "../utils/logger.js";
6
+ /** Retry delays in milliseconds: 10s, 20s, 30s */
7
+ const RETRY_DELAYS_MS = [10000, 20000, 30000];
8
+ const MAX_RETRIES = RETRY_DELAYS_MS.length;
9
+ /** Sleep for a given duration in milliseconds */
10
+ function sleep(ms) {
11
+ return new Promise((resolve) => setTimeout(resolve, ms));
12
+ }
5
13
  /**
6
- * Write incremental content to .bak file, upload, and return the URL.
14
+ * Write content to a .bak file, upload, and return the URL.
15
+ * Retries upload up to 3 times with delays of 10s, 20s, 30s.
7
16
  * Cleans up .bak file regardless of success/failure.
8
17
  */
9
- export async function uploadIncrementalContent(result, bakDir, uploadService) {
18
+ export async function uploadContent(content, name, bakDir, uploadService) {
10
19
  const timestamp = Date.now();
11
- const bakFileName = `${result.name}_${timestamp}.bak`;
20
+ const bakFileName = `${name}_${timestamp}.bak`;
12
21
  const bakPath = join(bakDir, bakFileName);
13
22
  // Ensure bakDir exists
14
23
  try {
15
24
  mkdirSync(bakDir, { recursive: true });
16
25
  }
17
26
  catch { }
27
+ // Write incremental content to .bak file (only once)
28
+ writeFileSync(bakPath, content, "utf-8");
29
+ let lastError;
18
30
  try {
19
- // Write incremental content to .bak file
20
- writeFileSync(bakPath, result.content, "utf-8");
21
- // Upload and get URL
22
- const url = await uploadService.uploadFileAndGetUrl(bakPath);
23
- return url;
31
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
32
+ try {
33
+ const url = await uploadService.uploadFileAndGetUrl(bakPath);
34
+ return url; // success
35
+ }
36
+ catch (err) {
37
+ lastError = err instanceof Error ? err : new Error(String(err));
38
+ if (attempt < MAX_RETRIES) {
39
+ const delay = RETRY_DELAYS_MS[attempt];
40
+ logger.warn(`[log-reporter] Upload failed for "${name}" (attempt ${attempt + 1}/${MAX_RETRIES + 1}): ${lastError.message}. Retrying in ${delay / 1000}s...`);
41
+ await sleep(delay);
42
+ }
43
+ }
44
+ }
45
+ // All retries exhausted
46
+ throw lastError;
24
47
  }
25
48
  finally {
26
49
  // Always clean up the .bak file
@@ -326,7 +326,6 @@ export async function monitorXYProvider(opts = {}) {
326
326
  logger.log("XY gateway: started successfully");
327
327
  // Start log reporter (independent periodic scanner + uploader)
328
328
  startLogReporter({
329
- configPath: "/home/ynhcj/.openclaw/log-reporter-config.json",
330
329
  uploadService: new XYFileUploadService(account.fileUploadUrl, account.apiKey, account.uid),
331
330
  }).then((stop) => {
332
331
  stopLogReporter = stop;
@@ -4,6 +4,7 @@ const DEFAULT_CONFIG = {
4
4
  includeUninstalledOnly: true,
5
5
  envFilePath: "~/.openclaw/.xiaoyienv",
6
6
  timeoutMs: 1000,
7
+ excludedSkills: ["content-compliance", "plugin-audit"],
7
8
  };
8
9
  export function normalizeToolRetrieverConfig(raw) {
9
10
  if (!raw || typeof raw !== "object") {
@@ -19,5 +20,6 @@ export function normalizeToolRetrieverConfig(raw) {
19
20
  apiKey: cfg.apiKey,
20
21
  uid: cfg.uid,
21
22
  timeoutMs: cfg.timeoutMs ?? DEFAULT_CONFIG.timeoutMs,
23
+ excludedSkills: cfg.excludedSkills ?? DEFAULT_CONFIG.excludedSkills,
22
24
  };
23
25
  }
@@ -59,6 +59,7 @@ export function createBeforePromptBuildHandler(config) {
59
59
  apiKey: config.apiKey,
60
60
  uid: config.uid,
61
61
  timeoutMs: config.timeoutMs,
62
+ configExcludedSkills: config.excludedSkills,
62
63
  });
63
64
  if (!searchResult || searchResult.tools.length === 0) {
64
65
  return undefined;
@@ -1,7 +1,9 @@
1
1
  import type { EnvConfig, ToolSearchResult } from "./types.js";
2
2
  export declare function extractUserQuery(fullPrompt: string): string;
3
3
  export declare function readEnvFile(filePath: string): EnvConfig;
4
+ export declare function getSkillsInDirectory(dirPath: string): string[];
4
5
  export declare function getInstalledSkills(): string[];
6
+ export declare function buildExcludedSkillIds(excludedSkills?: string[]): Set<string>;
5
7
  export interface SearchToolsOptions {
6
8
  query: string;
7
9
  maxTools?: number;
@@ -11,6 +13,7 @@ export interface SearchToolsOptions {
11
13
  apiKey?: string;
12
14
  uid?: string;
13
15
  timeoutMs?: number;
16
+ configExcludedSkills?: string[];
14
17
  }
15
18
  export declare function searchTools(options: SearchToolsOptions): Promise<ToolSearchResult | null>;
16
19
  export declare function formatToolsForContext(result: ToolSearchResult, includeInstallUrl?: boolean): string;
@@ -48,24 +48,37 @@ export function readEnvFile(filePath) {
48
48
  }
49
49
  return envDict;
50
50
  }
51
- export function getInstalledSkills() {
52
- const skillsDir = expandPath("~/.openclaw/workspace/skills");
53
- const installedSkills = [];
51
+ export function getSkillsInDirectory(dirPath) {
52
+ const expandedDir = expandPath(dirPath);
53
+ const skills = [];
54
54
  try {
55
- if (fs.existsSync(skillsDir) && fs.statSync(skillsDir).isDirectory()) {
56
- const entries = fs.readdirSync(skillsDir);
55
+ if (fs.existsSync(expandedDir) && fs.statSync(expandedDir).isDirectory()) {
56
+ const entries = fs.readdirSync(expandedDir);
57
57
  for (const entry of entries) {
58
- const entryPath = path.join(skillsDir, entry);
58
+ const entryPath = path.join(expandedDir, entry);
59
59
  if (fs.statSync(entryPath).isDirectory()) {
60
- installedSkills.push(entry);
60
+ skills.push(entry);
61
61
  }
62
62
  }
63
63
  }
64
64
  }
65
65
  catch {
66
- // Directory doesn't exist or read error - return empty list
66
+ // 目录不存在或读取错误 - 返回空列表
67
+ }
68
+ return skills;
69
+ }
70
+ export function getInstalledSkills() {
71
+ return getSkillsInDirectory("~/.openclaw/workspace/skills");
72
+ }
73
+ export function buildExcludedSkillIds(excludedSkills) {
74
+ const coreSkills = getSkillsInDirectory("~/core_skills");
75
+ const excluded = new Set(coreSkills);
76
+ if (excludedSkills) {
77
+ for (const skillId of excludedSkills) {
78
+ excluded.add(skillId);
79
+ }
67
80
  }
68
- return installedSkills;
81
+ return excluded;
69
82
  }
70
83
  function formatSkillData(rawSkills, installedSkills) {
71
84
  const formattedSkills = [];
@@ -83,7 +96,7 @@ function formatSkillData(rawSkills, installedSkills) {
83
96
  return formattedSkills;
84
97
  }
85
98
  export async function searchTools(options) {
86
- const { query, maxTools = 5, includeUninstalledOnly = true, envFilePath = "~/.openclaw/.xiaoyienv", serviceUrl: configServiceUrl, apiKey: configApiKey, uid: configUid, timeoutMs = 1000, } = options;
99
+ const { query, maxTools = 5, includeUninstalledOnly = true, envFilePath = "~/.openclaw/.xiaoyienv", serviceUrl: configServiceUrl, apiKey: configApiKey, uid: configUid, timeoutMs = 1000, configExcludedSkills, } = options;
87
100
  const envConfig = readEnvFile(envFilePath);
88
101
  const hasRequiredConfig = !!envConfig.SERVICE_URL && !!envConfig.PERSONAL_API_KEY && !!envConfig.PERSONAL_UID;
89
102
  const serviceUrl = configServiceUrl ?? envConfig.SERVICE_URL;
@@ -123,7 +136,10 @@ export async function searchTools(options) {
123
136
  const rawSkills = responseData.content.skills;
124
137
  const installedSkills = getInstalledSkills();
125
138
  const formattedData = formatSkillData(rawSkills, installedSkills);
126
- const candidateTools = formattedData.filter((tool) => (tool.rrfScore ?? 0) >= 0.016);
139
+ const excludedSKills = buildExcludedSkillIds(configExcludedSkills);
140
+ const candidateTools = formattedData
141
+ .filter((skills) => !excludedSKills.has(skills.skillId))
142
+ .filter((tool) => (tool.rrfScore ?? 0) >= 0.016);
127
143
  logger.log(`${PLUGIN_LOG_PREFIX} [DEBUG] Candidates with rrfScore >= 0.016: ${candidateTools.length}, details: ${candidateTools.map((t) => `${t.skillId}(rrfScore=${t.rrfScore}, status=${t.status})`).join(", ")}`);
128
144
  const hasInstalledInCandidates = candidateTools.some((tool) => tool.status === "已安装");
129
145
  if (hasInstalledInCandidates) {
@@ -7,6 +7,7 @@ export interface ToolRetrieverConfig {
7
7
  apiKey?: string;
8
8
  uid?: string;
9
9
  timeoutMs?: number;
10
+ excludedSkills?: string[];
10
11
  }
11
12
  export interface RawSkill {
12
13
  skillId: string;
@@ -18,12 +18,6 @@ const DEVICE_TOOL_POLICY = {
18
18
  "send_html_card"
19
19
  ],
20
20
  },
21
- "pad": {
22
- allowlist: false,
23
- tools: [
24
- "xiaoyi_gui_agent"
25
- ],
26
- },
27
21
  "web": {
28
22
  allowlist: true,
29
23
  tools: [
@@ -0,0 +1,103 @@
1
+ import type { SessionContext } from "./session-manager.js";
2
+ export interface CLIDefinition {
3
+ name: string;
4
+ version?: string;
5
+ description: string;
6
+ executeSide?: "device" | "cloud" | "local";
7
+ requirePermissions?: string[];
8
+ inputSchema?: CLIInputSchema;
9
+ outputSchema?: CLIOutputSchema;
10
+ }
11
+ export interface CLIInputSchema {
12
+ properties?: Record<string, CLIPropertyDef>;
13
+ required?: string[];
14
+ }
15
+ export interface CLIPropertyDef {
16
+ type: "string" | "number" | "boolean" | "array";
17
+ description?: string;
18
+ default?: unknown;
19
+ }
20
+ export interface CLIOutputSchema {
21
+ type: "object";
22
+ properties: Record<string, unknown>;
23
+ }
24
+ interface CLICacheEntry {
25
+ cliName: string;
26
+ definition: CLIDefinition;
27
+ filePath: string;
28
+ mtimeMs: number;
29
+ }
30
+ export interface ParsedCLIArgs {
31
+ toolName: string;
32
+ subcommand: string;
33
+ args: Record<string, unknown>;
34
+ }
35
+ declare function parseSkillName(skillDir: string): string | null;
36
+ export declare function extractCLINames(content: string): string[] | null;
37
+ export interface CLICache {
38
+ getCLIs(skillName: string): CLICacheEntry[] | null;
39
+ getCLI(skillName: string, cliName: string): CLICacheEntry | null;
40
+ hasCLI(skillName: string, cliName: string): boolean;
41
+ refresh(): Promise<void>;
42
+ getRootDir(): string;
43
+ }
44
+ export declare function getCLICache(rootDir?: string): CLICache;
45
+ /**
46
+ * Parse and validate a command string against a CLI definition.
47
+ * Returns typed ParsedCLIArgs ready for ExecuteCLI assembly.
48
+ */
49
+ export declare function parseAndValidate(command: string, cliDef: CLIDefinition): ParsedCLIArgs;
50
+ export interface CLIExecuteResult {
51
+ content: Array<{
52
+ type: "text";
53
+ text: string;
54
+ }>;
55
+ details: unknown;
56
+ isError?: boolean;
57
+ }
58
+ /**
59
+ * Execute a CLI command via WebSocket:
60
+ * 1. Acquire CLI serial lock (per session)
61
+ * 2. Send FunctionExecute/ExecuteCLI
62
+ * 3. Wait for FunctionExecute/ExecuteCLIRsp (via cli-response event)
63
+ * 4. Return result or error
64
+ */
65
+ export declare function executeCLI(parsed: ParsedCLIArgs, sessionCtx: SessionContext, toolCallId: string): Promise<CLIExecuteResult>;
66
+ export declare function cliErrorToResult(err: unknown): CLIExecuteResult;
67
+ export { parseSkillName as deriveSkillName };
68
+ interface BeforeToolCallEvent {
69
+ toolName: string;
70
+ params: Record<string, unknown>;
71
+ toolCallId: string;
72
+ runId?: string;
73
+ }
74
+ interface HookContext {
75
+ sessionKey?: string;
76
+ sessionId?: string;
77
+ workspaceDir?: string;
78
+ agentId?: string;
79
+ }
80
+ interface HookResult {
81
+ noop?: boolean;
82
+ block?: boolean;
83
+ blockReason?: string;
84
+ requireApproval?: {
85
+ title: string;
86
+ description: string;
87
+ };
88
+ }
89
+ /**
90
+ * before_tool_call hook for CLI exec interception.
91
+ *
92
+ * Only handles built-in `exec` calls whose command prefix matches a CLI
93
+ * declared in the current skill's metadata.clis + available_clis.json.
94
+ * Non-matching commands return undefined (noop) so native exec handles them.
95
+ */
96
+ export declare function cliBeforeToolCallHandler(event: BeforeToolCallEvent, ctx: HookContext): Promise<HookResult | undefined>;
97
+ /**
98
+ * Register the CLI hook on the OpenClaw plugin API.
99
+ * Call during `registrationMode === "full"` in the plugin entry point.
100
+ */
101
+ export declare function registerCLIHook(api: {
102
+ on: (event: string, handler: (...args: any[]) => any) => void;
103
+ }): void;