@ynhcj/xiaoyi-channel 0.0.214-beta → 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,7 +12,9 @@ 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";
17
+ import { logger } from "./src/utils/logger.js";
15
18
  /**
16
19
  * Parse a file path string to detect if it refers to a SKILL.md file within
17
20
  * a skills directory. Returns the skill name (parent directory) if so.
@@ -205,6 +208,72 @@ function readJobIdFromResult(result) {
205
208
  }
206
209
  return undefined;
207
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
+ }
208
277
  function registerFullHooks(api) {
209
278
  // SKILL RETRIEVER HOOK: before_prompt_build hook
210
279
  const pluginConfig = api.pluginConfig || {};
@@ -216,10 +285,13 @@ function registerFullHooks(api) {
216
285
  timeoutMs: pluginConfig.skillRetrieverTimeoutMs ?? 1000,
217
286
  });
218
287
  const beforePromptBuildHandler = createBeforePromptBuildHandler(skillRetrieverConfig);
219
- api.on("before_prompt_build", beforePromptBuildHandler);
288
+ api.on("before_prompt_build", async (event, ctx) => {
289
+ logger.log(`[BEFORE_PROMPT_BUILD] hook fired, sessionKey=${ctx.sessionKey || "undefined"}, sessionId=${ctx.sessionId || "undefined"}`);
290
+ return beforePromptBuildHandler(event, ctx);
291
+ });
220
292
  registerSelfEvolutionToolResultNudge(api);
221
293
  }
222
- const pluginEntry = definePluginEntry({
294
+ const plugin = definePluginEntry({
223
295
  id: "xiaoyi-channel",
224
296
  name: "Xiaoyi Channel",
225
297
  description: "Xiaoyi channel plugin - Xiaoyi A2A protocol integration",
@@ -227,6 +299,10 @@ const pluginEntry = definePluginEntry({
227
299
  // Always register the provider so wrapStreamFn/prepareExtraParams work
228
300
  // in ALL registration modes (not just "full").
229
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);
230
306
  if (api.registrationMode === "cli-metadata") {
231
307
  return;
232
308
  }
@@ -248,9 +324,11 @@ const pluginEntry = definePluginEntry({
248
324
  registerCronDetectionHook(api);
249
325
  // CLI exec hook: intercepts built-in exec for HarmonyOS CLI skill tools
250
326
  registerCLIHook(api);
327
+ // Cron recovery hook: prunes stale cron-push-map and pushData on gateway startup
328
+ registerCronRecoveryHook(api);
251
329
  // Skills diagnostic hook: log skill usage (detected via SKILL.md reads)
252
330
  registerSkillsDiagnosticHook(api);
253
331
  }
254
332
  },
255
333
  });
256
- export default pluginEntry;
334
+ export default plugin;
package/dist/src/bot.js CHANGED
@@ -7,7 +7,6 @@ import { downloadFilesFromParts } from "./file-download.js";
7
7
  import { resolveXYConfig } from "./config.js";
8
8
  import { sendStatusUpdate, sendClearContextResponse, sendTasksCancelResponse, sendA2AResponse } from "./formatter.js";
9
9
  import { appendSelfEvolutionKeywordNudge, shouldNudgeForSelfEvolutionKeyword, } from "./self-evolution-keyword.js";
10
- import { queueAgentHarnessMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
11
10
  import { runWithSessionContext } from "./tools/session-manager.js";
12
11
  import { configManager } from "./utils/config-manager.js";
13
12
  import { addPushId } from "./utils/pushid-manager.js";
@@ -16,6 +15,7 @@ import { selfEvolutionManager } from "./utils/self-evolution-manager.js";
16
15
  import { saveRuntimeInfo } from "./utils/runtime-manager.js";
17
16
  import { toolCallNudgeManager } from "./utils/tool-call-nudge-manager.js";
18
17
  import { setCsplSteerContext } from "./cspl/steer-context.js";
18
+ import { 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
  /**
@@ -242,18 +242,20 @@ export async function handleXYMessage(params) {
242
242
  log.error(`[BOT] Failed to patch session model override:`, patchErr);
243
243
  }
244
244
  }
245
- // 🔑 发送初始状态更新
246
- 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
- });
245
+ // 🔑 发送初始状态更新(仅首条消息,steer 不重复发送)
246
+ if (!isUpdate) {
247
+ log.log(`[BOT] Sending initial status update`);
248
+ void sendStatusUpdate({
249
+ config,
250
+ sessionId: parsed.sessionId,
251
+ taskId: parsed.taskId,
252
+ messageId: parsed.messageId,
253
+ text: "任务正在处理中,请稍候~",
254
+ state: "working",
255
+ }).catch((err) => {
256
+ log.error(`Failed to send initial status update:`, err);
257
+ });
258
+ }
257
259
  }
258
260
  // Extract text and files from parts
259
261
  const text = extractTextFromParts(parsed.parts);
@@ -278,46 +280,50 @@ export async function handleXYMessage(params) {
278
280
  log.error(`[SELF_EVOLUTION] Failed to append inline keyword nudge: ${String(selfEvolutionError)}`);
279
281
  }
280
282
  }
281
- // 🔑 Steer消息: 跳过旧路径直接进入 streaming-signal 队列
282
- // /steer 前缀由 dispatchSteerWhenReady 内部添加
283
- if (isUpdate) {
284
- // 立即释放 init gate——steer 不走 withReplyDispatcher run()
285
- // 回调,onInitComplete 永远不会被触发。如果不释放,后续消息
286
- // 会被 globalDispatchInitGate 永久阻塞。
287
- params.onInitComplete?.();
288
- // Steer 也支持文件 —— 提取并下载,附带到 mediaPayload
289
- const steerFileParts = extractFileParts(parsed.parts);
290
- const steerDownloadedFiles = await downloadFilesFromParts(steerFileParts);
291
- const steerMediaPayload = buildXYMediaPayload(steerDownloadedFiles);
292
- if (steerFileParts.length > 0) {
293
- log.log(`[BOT] Steer message with ${steerFileParts.length} file(s), enqueuing to streaming-signal queue`);
294
- }
295
- else {
296
- log.log(`[BOT] Steer message — enqueuing to streaming-signal queue`);
297
- }
298
- await enqueueSteer({
299
- sessionId: parsed.sessionId,
300
- sessionKey: route.sessionKey,
301
- steerText: textForAgent, // 原始文本,不带 /steer 前缀
302
- mediaPayload: steerMediaPayload,
303
- cfg,
304
- runtime,
305
- parsed,
306
- route,
307
- deviceType,
308
- });
309
- log.log(`[BOT] Steer queue completed`);
310
- return;
311
- }
312
- // ── First message (non-steer) path below ──────────────────────
313
- // File download — only for real user messages, steer injections have no files
283
+ // ── Build message and dispatch via auto-reply pipeline ──────────
284
+ // OpenClaw's auto-reply pipeline (src/auto-reply/reply/agent-runner.ts)
285
+ // detects active runs and handles steer injection natively — the channel
286
+ // does not need its own steer detection or polling logic.
287
+ // File download
314
288
  let mediaPayload = {};
315
- if (!skipReg) {
289
+ if (!skipReg || isUpdate) {
316
290
  const fileParts = extractFileParts(parsed.parts);
317
291
  const downloadedFiles = await downloadFilesFromParts(fileParts);
318
292
  log.log(`[BOT] Downloaded ${downloadedFiles.length} file(s)`);
319
293
  mediaPayload = buildXYMediaPayload(downloadedFiles);
320
294
  }
295
+ // 🔑 对于 steer 消息,将文件路径附加到消息文本中。
296
+ // auto-reply 管道的 steer 注入只携带 prompt 文本(followupRun.prompt),
297
+ // 不携带 mediaPayload,所以模型需要以文本形式看到附件路径。
298
+ if (isUpdate && mediaPayload.MediaPaths?.length) {
299
+ const fileHint = `\n【用户上传附件】:${JSON.stringify(mediaPayload.MediaPaths)}`;
300
+ textForAgent = `${textForAgent}${fileHint}`;
301
+ log.log(`[BOT] Steer: appended file paths to text`);
302
+ }
303
+ // 🔑 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`);
325
+ }
326
+ }
321
327
  // Resolve envelope format options (following feishu pattern)
322
328
  const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
323
329
  // Build message body with speaker prefix (following feishu pattern)
@@ -333,12 +339,20 @@ export async function handleXYMessage(params) {
333
339
  envelope: envelopeOptions,
334
340
  body: messageBody,
335
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
+ }
336
349
  // ✅ Finalize inbound context (following feishu pattern)
337
350
  // Use route.accountId and route.sessionKey instead of parsed fields
338
351
  const ctxPayload = core.channel.reply.finalizeInboundContext({
339
352
  Body: body,
340
- RawBody: textForAgent,
341
- CommandBody: textForAgent,
353
+ RawBody: steerCommandBody,
354
+ CommandBody: steerCommandBody,
355
+ ...(isUpdate ? { CommandSource: "native" } : {}),
342
356
  From: parsed.sessionId,
343
357
  To: parsed.sessionId, // ✅ Simplified: use sessionId as target (context is managed by SessionKey)
344
358
  SessionKey: route.sessionKey, // ✅ Use route.sessionKey
@@ -358,10 +372,11 @@ export async function handleXYMessage(params) {
358
372
  ReplyToBody: undefined, // A2A protocol doesn't support reply/quote
359
373
  ...mediaPayload,
360
374
  });
361
- // 🔑 Streaming 信号已在上方创建(在文件下载之前)
362
- const steerState = { steered: false };
375
+ // 🔑 For steer messages, pre-set steered=true so the dispatcher skips final
376
+ // response and cleanup the first message's dispatcher handles those.
377
+ const steerState = { steered: isUpdate };
363
378
  // 🔑 创建dispatcher
364
- log.log(`[BOT-DISPATCHER] Creating reply dispatcher`);
379
+ log.log(`[BOT-DISPATCHER] Creating reply dispatcher, isSteer=${isUpdate}, sessionKey=${route.sessionKey}`);
365
380
  // Cleanup: 必须在 onIdle 内部执行(参见 reply-dispatcher.ts 中 onIdleComplete 的注释)
366
381
  let cleaned = false;
367
382
  const cleanup = () => {
@@ -384,8 +399,9 @@ export async function handleXYMessage(params) {
384
399
  });
385
400
  // 🔑 注册 dispatcher 的 fallback taskId 更新函数,供 steer 路径调用
386
401
  dispatcherUpdaters.set(parsed.sessionId, updateFallbackTaskId);
387
- // Steer injections don't need status intervals
388
- if (!skipReg) {
402
+ // Steer messages don't need a status interval — the first message's
403
+ // dispatcher already has one running.
404
+ if (!isUpdate) {
389
405
  startStatusInterval();
390
406
  }
391
407
  // Build session context for AsyncLocalStorage
@@ -423,8 +439,9 @@ export async function handleXYMessage(params) {
423
439
  // signal init complete to release the global dispatch gate
424
440
  // for the next session.
425
441
  const dispatchPromise = runWithSessionContext(sessionContext, async () => {
426
- log.log(`[ALS-PROOF] bot entered dispatch scope sessionId=${sessionContext.sessionId} taskId=${sessionContext.taskId} isSteer=false`);
427
- log.log(`[BOT-DISPATCH] dispatchReplyFromConfig starting, body.length=${ctxPayload.Body?.length ?? 0}`);
442
+ const isSteerDispatch = isUpdate && !skipReg;
443
+ log.log(`[ALS-PROOF] bot entered dispatch scope sessionId=${sessionContext.sessionId} taskId=${sessionContext.taskId} isSteer=${isSteerDispatch}`);
444
+ log.log(`[BOT-DISPATCH] dispatchReplyFromConfig starting, body.length=${ctxPayload.Body?.length ?? 0}, isSteer=${isSteerDispatch}`);
428
445
  try {
429
446
  const result = await core.channel.reply.dispatchReplyFromConfig({
430
447
  ctx: ctxPayload,
@@ -432,7 +449,13 @@ export async function handleXYMessage(params) {
432
449
  dispatcher,
433
450
  replyOptions,
434
451
  });
435
- log.log(`[BOT-DISPATCH] dispatchReplyFromConfig returned, result=${JSON.stringify(result)}`);
452
+ // 区分 steer 成功(undefined)和 steer 失败/正常 run(有结果)
453
+ if (result === undefined) {
454
+ log.log(`[BOT-STEER] dispatchReplyFromConfig returned undefined — steer injected via fast path OK, sessionKey=${route.sessionKey}`);
455
+ }
456
+ else {
457
+ log.log(`[BOT-DISPATCH] dispatchReplyFromConfig returned, resultType=${typeof result}, isSteer=${isSteerDispatch}, steered=${steerState.steered}`);
458
+ }
436
459
  return result;
437
460
  }
438
461
  catch (dispatchErr) {
@@ -492,85 +515,11 @@ function buildXYMediaPayload(mediaList) {
492
515
  };
493
516
  }
494
517
  // ─────────────────────────────────────────────────────────────
495
- // Steer 串行队列
518
+ // Dispatcher updaters (cross-chain taskId bridging)
496
519
  // ─────────────────────────────────────────────────────────────
497
520
  // Use globalThis to survive module deduplication — provider.ts may load a
498
521
  // different copy of bot.ts, so a plain module-level Map would be two objects.
499
522
  const _g = globalThis;
500
- if (!_g.__xySteerQueues)
501
- _g.__xySteerQueues = new Map();
502
523
  if (!_g.__xyDispatcherUpdaters)
503
524
  _g.__xyDispatcherUpdaters = new Map();
504
- const steerQueues = _g.__xySteerQueues;
505
525
  const dispatcherUpdaters = _g.__xyDispatcherUpdaters;
506
- /**
507
- * 将 steer 消息放入 per-session 串行队列。
508
- * 通过指数退避轮询注入(queueAgentHarnessMessage),直到 Pi agent 接受消息或 run 结束。
509
- * 多个 steer 按到达顺序串行处理。
510
- */
511
- function enqueueSteer(params) {
512
- const { sessionId } = params;
513
- const log = logger.withContext(sessionId, params.parsed.taskId);
514
- // 取出当前队列尾部(或 undefined),然后链上新的 Promise
515
- const prev = steerQueues.get(sessionId);
516
- const next = (prev ?? Promise.resolve()).then(() => dispatchSteerWhenReady(params));
517
- steerQueues.set(sessionId, next);
518
- // 链条结束后清理
519
- next.catch((err) => {
520
- log.error(`[STEER-QUEUE] Steer chain failed: ${String(err)}`);
521
- }).finally(() => {
522
- if (steerQueues.get(sessionId) === next) {
523
- steerQueues.delete(sessionId);
524
- }
525
- });
526
- return next;
527
- }
528
- /**
529
- * Poll the active embedded run with exponential backoff until the steer message
530
- * is accepted or the run completes.
531
- *
532
- * Replaces the previous signal-based approach (notifyModelStreaming) which fired
533
- * from wrapStreamFn too early — before the Pi agent had set state.isStreaming=true.
534
- * queueAgentHarnessMessage internally checks isStreaming(), so we retry until the
535
- * Pi agent is ready to accept messages.
536
- */
537
- async function dispatchSteerWhenReady(params) {
538
- const { sessionId, steerText } = params;
539
- const log = logger.withContext(sessionId, params.parsed.taskId);
540
- const mediaPaths = params.mediaPayload?.MediaPaths;
541
- const fileHint = mediaPaths && mediaPaths.length > 0
542
- ? `\n【用户上传附件】:${JSON.stringify(mediaPaths)}`
543
- : "";
544
- const steerMessage = `${steerText}${fileHint}`;
545
- log.log(`[STEER-QUEUE] Injecting steer message directly into active run`);
546
- // Exponential backoff polling until:
547
- // 1. Injection succeeds (queueAgentHarnessMessage returns true)
548
- // 2. The original run has completed (hasActiveTask returns false)
549
- // 3. Maximum total wait time exceeded
550
- const MAX_WAIT_MS = 30_000;
551
- const MAX_BACKOFF_MS = 4_000;
552
- const BASE_DELAY_MS = 500;
553
- const startedAt = Date.now();
554
- let attempt = 0;
555
- while (Date.now() - startedAt < MAX_WAIT_MS) {
556
- // Termination: first message's run has already finished
557
- if (!hasActiveTask(sessionId)) {
558
- log.log(`[STEER-QUEUE] First message completed, skip steer`);
559
- return;
560
- }
561
- const injected = queueAgentHarnessMessage(sessionId, steerMessage, {
562
- steeringMode: "all",
563
- });
564
- if (injected) {
565
- log.log(`[STEER-QUEUE] Steer injected successfully on attempt ${attempt}`);
566
- return;
567
- }
568
- // Exponential backoff: min(BASE_DELAY_MS * 2^attempt, MAX_BACKOFF_MS)
569
- const delay = Math.min(BASE_DELAY_MS * Math.pow(2, attempt), MAX_BACKOFF_MS);
570
- log.log(`[STEER-QUEUE] Attempt ${attempt}: run not accepting, retrying in ${delay}ms`);
571
- await new Promise(r => setTimeout(r, delay));
572
- attempt++;
573
- }
574
- // Max wait exceeded — model may still be in provider retry loop or unresponsive
575
- log.log(`[STEER-QUEUE] Steer injection failed after ${MAX_WAIT_MS}ms timeout`);
576
- }
@@ -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
+ };