@ynhcj/xiaoyi-channel 0.0.213-next → 0.0.214-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.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { definePluginEntry } from "openclaw/plugin-sdk/core";
2
- declare const pluginEntry: ReturnType<typeof definePluginEntry>;
3
- export default pluginEntry;
1
+ import { type OpenClawPluginDefinition } from "openclaw/plugin-sdk/core";
2
+ declare const plugin: OpenClawPluginDefinition;
3
+ export default plugin;
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { definePluginEntry } from "openclaw/plugin-sdk/core";
2
2
  import { xiaoyiProvider } from "./src/provider.js";
3
+ import { xiaoyiCompactionProvider } from "./src/compaction-provider.js";
3
4
  import { xyPlugin } from "./src/channel.js";
4
5
  import registerSentinelHook from "./src/cspl/sentinel_hook.js";
5
6
  import { setXYRuntime } from "./src/runtime.js";
@@ -11,6 +12,7 @@ import { registerSelfEvolutionToolResultNudge } from "./src/self-evolution-tool-
11
12
  import { createBeforePromptBuildHandler } from "./src/skill-retriever/hooks.js";
12
13
  import { normalizeToolRetrieverConfig } from "./src/skill-retriever/config.js";
13
14
  import { registerCLIHook } from "./src/tools/hmos-cli.js";
15
+ import { recoverCronState } from "./src/cron-recovery.js";
14
16
  import { writeSkillUsage } from "./src/utils/skills-logger.js";
15
17
  import { logger } from "./src/utils/logger.js";
16
18
  /**
@@ -206,6 +208,72 @@ function readJobIdFromResult(result) {
206
208
  }
207
209
  return undefined;
208
210
  }
211
+ // ── Gateway startup: cron state recovery ────────────────────────────────────
212
+ /**
213
+ * Register the gateway_start hook for cron state recovery.
214
+ *
215
+ * On gateway startup, checks .openclaw/cron/ for legacy JSON/JSONL files
216
+ * and migrates them into the SQLite state database:
217
+ * - Reads legacy jobs.json + jobs-state.json → imports into cron_jobs table
218
+ * - Reads legacy runs/*.jsonl → imports into cron_run_logs table
219
+ * - Archives migrated files with .migrated suffix
220
+ *
221
+ * Pattern follows legacy-store-migration.ts and legacy-run-log-migration.ts:
222
+ * check → load → import into SQLite → archive old files.
223
+ */
224
+ function registerCronRecoveryHook(api) {
225
+ api.on("gateway_start", async (_event, _ctx) => {
226
+ const logTag = "[CRON-RECOVERY-HOOK]";
227
+ const startTime = Date.now();
228
+ logger.log(`${logTag} ═══════════════════════════════════════════`);
229
+ logger.log(`${logTag} gateway_start fired — checking for legacy cron files`);
230
+ logger.log(`${logTag} Timestamp: ${new Date().toISOString()}`);
231
+ logger.log(`${logTag} Plugin registration mode: ${api.registrationMode ?? "unknown"}`);
232
+ let result;
233
+ try {
234
+ result = await recoverCronState();
235
+ }
236
+ catch (err) {
237
+ const errMsg = err instanceof Error ? err.message : String(err);
238
+ const errStack = err instanceof Error ? err.stack : undefined;
239
+ logger.error(`${logTag} cron state recovery threw: ${errMsg}`);
240
+ if (errStack)
241
+ logger.error(`${logTag} Stack: ${errStack}`);
242
+ // Don't let a recovery failure block gateway startup.
243
+ logger.log(`${logTag} Recovery failed after ${Date.now() - startTime}ms — gateway startup continues`);
244
+ return;
245
+ }
246
+ const elapsed = Date.now() - startTime;
247
+ if (result.recovered) {
248
+ logger.log(`${logTag} ✅ Migration performed successfully in ${elapsed}ms:` +
249
+ ` storeMigrated=${result.storeMigrated}, ` +
250
+ ` runLogFilesImported=${result.runLogFilesImported}`);
251
+ }
252
+ else {
253
+ logger.log(`${logTag} ℹ️ No legacy cron files migrated in ${elapsed}ms ` +
254
+ `(nothing to migrate or database unavailable)`);
255
+ }
256
+ // Log diagnostics summary
257
+ const warnings = result.diagnostics.filter((d) => d.includes("skipping") || d.includes("locked") || d.includes("unavailable"));
258
+ const errors = result.diagnostics.filter((d) => d.includes("error") || d.includes("failed") || d.includes("Failed"));
259
+ if (warnings.length > 0) {
260
+ logger.warn(`${logTag} ${warnings.length} warning(s) from migration:`);
261
+ for (const w of warnings) {
262
+ logger.warn(`${logTag} ⚠ ${w}`);
263
+ }
264
+ }
265
+ if (errors.length > 0) {
266
+ logger.error(`${logTag} ${errors.length} error(s) from migration:`);
267
+ for (const e of errors) {
268
+ logger.error(`${logTag} ✗ ${e}`);
269
+ }
270
+ }
271
+ if (warnings.length === 0 && errors.length === 0) {
272
+ logger.log(`${logTag} All diagnostics clean, no warnings or errors`);
273
+ }
274
+ logger.log(`${logTag} ═══════════════════════════════════════════`);
275
+ });
276
+ }
209
277
  function registerFullHooks(api) {
210
278
  // SKILL RETRIEVER HOOK: before_prompt_build hook
211
279
  const pluginConfig = api.pluginConfig || {};
@@ -223,7 +291,7 @@ function registerFullHooks(api) {
223
291
  });
224
292
  registerSelfEvolutionToolResultNudge(api);
225
293
  }
226
- const pluginEntry = definePluginEntry({
294
+ const plugin = definePluginEntry({
227
295
  id: "xiaoyi-channel",
228
296
  name: "Xiaoyi Channel",
229
297
  description: "Xiaoyi channel plugin - Xiaoyi A2A protocol integration",
@@ -231,6 +299,10 @@ const pluginEntry = definePluginEntry({
231
299
  // Always register the provider so wrapStreamFn/prepareExtraParams work
232
300
  // in ALL registration modes (not just "full").
233
301
  api.registerProvider(xiaoyiProvider);
302
+ // Register the compaction provider so openclaw's safeguard hook uses
303
+ // our summarization path (which injects x-hag-trace-id) instead of the
304
+ // built-in LLM path that bypasses wrapStreamFn.
305
+ api.registerCompactionProvider(xiaoyiCompactionProvider);
234
306
  if (api.registrationMode === "cli-metadata") {
235
307
  return;
236
308
  }
@@ -252,9 +324,11 @@ const pluginEntry = definePluginEntry({
252
324
  registerCronDetectionHook(api);
253
325
  // CLI exec hook: intercepts built-in exec for HarmonyOS CLI skill tools
254
326
  registerCLIHook(api);
327
+ // Cron recovery hook: prunes stale cron-push-map and pushData on gateway startup
328
+ registerCronRecoveryHook(api);
255
329
  // Skills diagnostic hook: log skill usage (detected via SKILL.md reads)
256
330
  registerSkillsDiagnosticHook(api);
257
331
  }
258
332
  },
259
333
  });
260
- export default pluginEntry;
334
+ export default plugin;
package/dist/src/bot.js CHANGED
@@ -15,7 +15,7 @@ import { selfEvolutionManager } from "./utils/self-evolution-manager.js";
15
15
  import { saveRuntimeInfo } from "./utils/runtime-manager.js";
16
16
  import { toolCallNudgeManager } from "./utils/tool-call-nudge-manager.js";
17
17
  import { setCsplSteerContext } from "./cspl/steer-context.js";
18
- import { getSteerQueue } from "./steer-queue.js";
18
+ import { resolveActiveEmbeddedRunSessionId, queueAgentHarnessMessage, } from "openclaw/plugin-sdk/agent-harness-runtime";
19
19
  import { registerTaskId, decrementTaskIdRef, hasActiveTask, } from "./task-manager.js";
20
20
  import { logger } from "./utils/logger.js";
21
21
  /**
@@ -300,26 +300,29 @@ export async function handleXYMessage(params) {
300
300
  textForAgent = `${textForAgent}${fileHint}`;
301
301
  log.log(`[BOT] Steer: appended file paths to text`);
302
302
  }
303
- // 🔑 Provider-level steer injection: push steer text to the shared queue.
304
- // provider.ts checks this queue on every model call (including tool-loop
305
- // model calls in agent.continue()) and drains pending steer messages
306
- // directly into context.messages before sending to the model.
307
- // Key: parsed.sessionId (A2A conversationId) matches getCurrentSessionContext().sessionId.
308
- if (isUpdate) {
309
- const steerQueue = getSteerQueue();
310
- const queueKey = parsed.sessionId;
311
- const pending = steerQueue.get(queueKey) ?? [];
312
- pending.push(textForAgent);
313
- steerQueue.set(queueKey, pending);
314
- log.log(`[BOT-STEER] Queued for provider injection, sessionId=${queueKey}, queueDepth=${pending.length}`);
315
- // Bypass dispatchReplyFromConfig entirely — steer injection is handled
316
- // at the provider level (provider.ts drains the queue on every model call).
317
- // No need for /steer command dispatch or dispatcher creation.
318
- if (!skipReg) {
319
- decrementTaskIdRef(parsed.sessionId);
303
+ // 🔑 Direct steer: bypass dispatchReplyFromConfig entirely and inject the
304
+ // message directly into the active embedded agent run. This avoids the
305
+ // per-session ReplyOperation lock in admitReplyTurn which would otherwise
306
+ // block the steer message until the first message completes — making steer
307
+ // indistinguishable from a followup.
308
+ if (isUpdate && !skipReg && route.sessionKey) {
309
+ const activeSessionId = resolveActiveEmbeddedRunSessionId(route.sessionKey);
310
+ if (activeSessionId) {
311
+ log.log(`[BOT-STEER] Direct steer attempt: activeSessionId=${activeSessionId}, textLen=${textForAgent.length}`);
312
+ const queued = queueAgentHarnessMessage(activeSessionId, textForAgent, {
313
+ steeringMode: "all",
314
+ });
315
+ if (queued) {
316
+ log.log(`[BOT-STEER] Direct steer succeeded message injected into active run`);
317
+ // Steer message taskId refCount is no longer needed since we skip the dispatcher.
318
+ decrementTaskIdRef(parsed.sessionId);
319
+ return;
320
+ }
321
+ log.log(`[BOT-STEER] Direct steer failed (queued=false), falling through to dispatchReplyFromConfig`);
322
+ }
323
+ else {
324
+ log.log(`[BOT-STEER] No active embedded run session for key=${route.sessionKey}, falling through to dispatchReplyFromConfig`);
320
325
  }
321
- params.onInitComplete?.();
322
- return;
323
326
  }
324
327
  // Resolve envelope format options (following feishu pattern)
325
328
  const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
@@ -336,12 +339,20 @@ export async function handleXYMessage(params) {
336
339
  envelope: envelopeOptions,
337
340
  body: messageBody,
338
341
  });
342
+ // 🔑 Steer messages use /steer prefix + CommandSource "native" to trigger
343
+ // the native slash command fast path, which calls handleSteerCommand →
344
+ // queueEmbeddedAgentMessageWithOutcomeAsync before admitReplyTurn blocks.
345
+ const steerCommandBody = isUpdate ? `/steer ${textForAgent}` : textForAgent;
346
+ if (isUpdate) {
347
+ log.log(`[BOT-STEER] Dispatching via /steer fast path, sessionKey=${route.sessionKey}, cmdLen=${steerCommandBody.length}`);
348
+ }
339
349
  // ✅ Finalize inbound context (following feishu pattern)
340
350
  // Use route.accountId and route.sessionKey instead of parsed fields
341
351
  const ctxPayload = core.channel.reply.finalizeInboundContext({
342
352
  Body: body,
343
- RawBody: textForAgent,
344
- CommandBody: textForAgent,
353
+ RawBody: steerCommandBody,
354
+ CommandBody: steerCommandBody,
355
+ ...(isUpdate ? { CommandSource: "native" } : {}),
345
356
  From: parsed.sessionId,
346
357
  To: parsed.sessionId, // ✅ Simplified: use sessionId as target (context is managed by SessionKey)
347
358
  SessionKey: route.sessionKey, // ✅ Use route.sessionKey
@@ -0,0 +1,44 @@
1
+ interface CompactionConfig {
2
+ uid: string;
3
+ baseUrl: string;
4
+ modelName: string;
5
+ apiKey?: string;
6
+ }
7
+ /**
8
+ * Snapshot of the resolved session context, captured from the last normal
9
+ * LLM request before compaction is triggered. When available, the
10
+ * CompactionProvider reuses the same A2A traceId/sessionId so the
11
+ * compaction summarization request is linked to the same user session
12
+ * in backend tracing.
13
+ */
14
+ interface CompactionSessionSnapshot {
15
+ traceId: string;
16
+ sessionId: string;
17
+ interactionId: string;
18
+ deviceType?: string;
19
+ appVer?: string;
20
+ sdkApiVersion?: string;
21
+ }
22
+ /** Store config captured from prepareExtraParams so summarize() can read it. */
23
+ export declare function setCompactionConfig(config: CompactionConfig | null): void;
24
+ /**
25
+ * Store a snapshot of the resolved session headers captured from the
26
+ * most recent wrapStreamFn call. This lets the CompactionProvider reuse
27
+ * the A2A traceId/sessionId during compaction summarization.
28
+ */
29
+ export declare function setCompactionSessionSnapshot(snapshot: CompactionSessionSnapshot | null): void;
30
+ export declare const xiaoyiCompactionProvider: {
31
+ id: string;
32
+ label: string;
33
+ summarize(params: {
34
+ messages: unknown[];
35
+ signal?: AbortSignal;
36
+ customInstructions?: string;
37
+ summarizationInstructions?: {
38
+ identifierPolicy?: string;
39
+ identifierInstructions?: string;
40
+ };
41
+ previousSummary?: string;
42
+ }): Promise<string>;
43
+ };
44
+ export {};
@@ -0,0 +1,183 @@
1
+ /**
2
+ * CompactionProvider for xiaoyi-channel.
3
+ *
4
+ * During compaction, the safeguard's built-in summarization path
5
+ * (summarizeInStages -> generateSummary -> completeSimple) bypasses the
6
+ * plugin's wrapStreamFn, so x-hag-trace-id is never injected. Registering
7
+ * a CompactionProvider intercepts the safeguard before it reaches the LLM
8
+ * path and makes the summarization API call ourselves with proper headers.
9
+ */
10
+ import { createHash } from "crypto";
11
+ import { logger } from "./utils/logger.js";
12
+ // ── Header constants (mirrors provider.ts) ────────────────────────
13
+ const HEADER_TRACE_ID = "x-hag-trace-id";
14
+ const HEADER_SESSION_ID = "x-session-id";
15
+ const HEADER_INTERACTION_ID = "x-interaction-id";
16
+ // ── Summarization prompt ──────────────────────────────────────────
17
+ const SUMMARIZATION_SYSTEM_PROMPT = "You are a structured conversation summarization assistant. " +
18
+ "Produce a concise summary that preserves key facts, decisions, " +
19
+ "in-progress tasks, tool results, and the latest user intent.";
20
+ let storedConfig = null;
21
+ let storedSessionSnapshot = null;
22
+ /** Store config captured from prepareExtraParams so summarize() can read it. */
23
+ export function setCompactionConfig(config) {
24
+ storedConfig = config;
25
+ if (config) {
26
+ logger.log(`[compaction-provider] config stored uid=${config.uid.slice(0, 8)}... ` +
27
+ `baseUrl=${config.baseUrl} model=${config.modelName}`);
28
+ }
29
+ else {
30
+ logger.warn("[compaction-provider] config cleared (uid or baseUrl missing)");
31
+ }
32
+ }
33
+ /**
34
+ * Store a snapshot of the resolved session headers captured from the
35
+ * most recent wrapStreamFn call. This lets the CompactionProvider reuse
36
+ * the A2A traceId/sessionId during compaction summarization.
37
+ */
38
+ export function setCompactionSessionSnapshot(snapshot) {
39
+ storedSessionSnapshot = snapshot;
40
+ }
41
+ // ── Helpers ───────────────────────────────────────────────────────
42
+ function encodeUid(uid) {
43
+ return createHash("sha256").update(uid).digest("hex").slice(0, 32);
44
+ }
45
+ function extractMessageText(content) {
46
+ if (typeof content === "string")
47
+ return content;
48
+ if (Array.isArray(content)) {
49
+ return content
50
+ .map((block) => {
51
+ if (block && typeof block === "object" && block.type === "text") {
52
+ return String(block.text ?? "");
53
+ }
54
+ return "";
55
+ })
56
+ .filter(Boolean)
57
+ .join("\n");
58
+ }
59
+ return "";
60
+ }
61
+ function formatMessagesForSummarization(messages) {
62
+ const lines = [];
63
+ for (const msg of messages) {
64
+ if (!msg || typeof msg !== "object")
65
+ continue;
66
+ const m = msg;
67
+ if (m.role === "custom")
68
+ continue; // skip internal runtime messages
69
+ const role = String(m.role ?? "unknown");
70
+ const text = extractMessageText(m.content).trim();
71
+ if (!text)
72
+ continue;
73
+ let label;
74
+ if (role === "assistant") {
75
+ label = "Assistant";
76
+ }
77
+ else if (role === "user") {
78
+ label = "User";
79
+ }
80
+ else if (role === "toolResult") {
81
+ const toolName = typeof m.toolName === "string" && m.toolName ? m.toolName : "tool";
82
+ label = `Tool result (${toolName})`;
83
+ }
84
+ else {
85
+ label = role;
86
+ }
87
+ lines.push(`[${label}]: ${text}`);
88
+ }
89
+ return lines.join("\n\n");
90
+ }
91
+ // ── CompactionProvider ────────────────────────────────────────────
92
+ export const xiaoyiCompactionProvider = {
93
+ id: "xiaoyiprovider",
94
+ label: "Xiaoyi Compaction Provider",
95
+ async summarize(params) {
96
+ const cfg = storedConfig;
97
+ if (!cfg) {
98
+ // No stored config: let the safeguard fall through to the LLM path.
99
+ // Throwing here is intentional — tryProviderSummarize catches and
100
+ // falls through.
101
+ throw new Error("Compaction config not available (uid or baseUrl missing)");
102
+ }
103
+ // Use the A2A session snapshot when available (captured from the last
104
+ // normal wrapStreamFn call before compaction was triggered). Otherwise
105
+ // fall back to the uid_timestamp pattern.
106
+ const session = storedSessionSnapshot;
107
+ const traceId = session?.traceId ?? `${encodeUid(cfg.uid)}_${Date.now()}`;
108
+ const sessionId = session?.sessionId ?? traceId;
109
+ const interactionId = session?.interactionId ?? traceId;
110
+ logger.log(`[compaction-provider] summarize traceId=${traceId} source=${session ? "a2a-snapshot" : "uid-fallback"} msgCount=${params.messages.length}`);
111
+ // ── Build prompt ──────────────────────────────────────────────
112
+ const conversationText = formatMessagesForSummarization(params.messages);
113
+ let promptText = `<conversation>\n${conversationText}\n</conversation>`;
114
+ if (params.previousSummary) {
115
+ promptText += `\n\n<previous-summary>\n${params.previousSummary}\n</previous-summary>`;
116
+ }
117
+ let instructions = "Provide a concise but comprehensive summary of the conversation above. " +
118
+ "Include: key decisions, in-progress tasks, tool results, file operations, " +
119
+ "and the latest user request. Preserve exact file paths, URLs, identifiers, " +
120
+ "and error messages.";
121
+ if (params.customInstructions) {
122
+ instructions += `\n\nAdditional focus: ${params.customInstructions}`;
123
+ }
124
+ promptText += `\n\n${instructions}`;
125
+ // ── Build request ─────────────────────────────────────────────
126
+ const headers = {
127
+ "Content-Type": "application/json",
128
+ [HEADER_TRACE_ID]: traceId,
129
+ [HEADER_SESSION_ID]: sessionId,
130
+ [HEADER_INTERACTION_ID]: interactionId,
131
+ };
132
+ if (session?.deviceType) {
133
+ headers["x-device-type"] = session.deviceType;
134
+ }
135
+ if (session?.appVer) {
136
+ headers["x-app-ver"] = session.appVer;
137
+ }
138
+ if (session?.sdkApiVersion) {
139
+ headers["x-sdk-api-version"] = session.sdkApiVersion;
140
+ }
141
+ if (cfg.apiKey) {
142
+ headers["Authorization"] = `Bearer ${cfg.apiKey}`;
143
+ }
144
+ const body = {
145
+ model: cfg.modelName,
146
+ messages: [
147
+ { role: "system", content: SUMMARIZATION_SYSTEM_PROMPT },
148
+ { role: "user", content: promptText },
149
+ ],
150
+ max_tokens: 4096,
151
+ temperature: 0.3,
152
+ };
153
+ const url = `${cfg.baseUrl.replace(/\/+$/, "")}/chat/completions`;
154
+ logger.log(`[compaction-provider] POST ${url}`);
155
+ // ── Call ──────────────────────────────────────────────────────
156
+ let response;
157
+ try {
158
+ response = await fetch(url, {
159
+ method: "POST",
160
+ headers,
161
+ body: JSON.stringify(body),
162
+ signal: params.signal,
163
+ });
164
+ }
165
+ catch (err) {
166
+ logger.error(`[compaction-provider] fetch failed: ${String(err)}`);
167
+ throw err;
168
+ }
169
+ if (!response.ok) {
170
+ const errorText = await response.text().catch(() => "");
171
+ logger.error(`[compaction-provider] API error status=${response.status} body=${errorText.slice(0, 500)}`);
172
+ throw new Error(`Compaction API returned ${response.status}`);
173
+ }
174
+ const data = (await response.json());
175
+ const summary = data.choices?.[0]?.message?.content;
176
+ if (!summary?.trim()) {
177
+ logger.warn("[compaction-provider] empty summary returned");
178
+ throw new Error("Empty summary from compaction API");
179
+ }
180
+ logger.log(`[compaction-provider] done summaryLen=${summary.length}`);
181
+ return summary;
182
+ },
183
+ };
@@ -1,3 +1,23 @@
1
+ export interface CronRunLogEntry {
2
+ jobId: string;
3
+ ts: number;
4
+ runId?: string;
5
+ status?: string;
6
+ error?: string;
7
+ summary?: string;
8
+ diagnosticsSummary?: string;
9
+ deliveryStatus?: string;
10
+ deliveryError?: string;
11
+ delivered?: boolean;
12
+ sessionId?: string;
13
+ sessionKey?: string;
14
+ runAtMs?: number;
15
+ durationMs?: number;
16
+ nextRunAtMs?: number;
17
+ model?: string;
18
+ provider?: string;
19
+ totalTokens?: number;
20
+ }
1
21
  /**
2
22
  * Handle a cron-query-event.
3
23
  *