@ynhcj/xiaoyi-channel 0.0.217-beta → 0.0.217-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 +3 -3
- package/dist/index.js +81 -3
- package/dist/src/bot.js +56 -8
- package/dist/src/compaction-provider.d.ts +50 -0
- package/dist/src/compaction-provider.js +202 -0
- package/dist/src/cron-query-handler.d.ts +20 -0
- package/dist/src/cron-query-handler.js +481 -91
- package/dist/src/cron-recovery.d.ts +25 -0
- package/dist/src/cron-recovery.js +587 -0
- package/dist/src/cspl/call_api.d.ts +1 -1
- package/dist/src/cspl/call_api.js +17 -12
- package/dist/src/cspl/config.d.ts +1 -0
- package/dist/src/cspl/config.js +59 -65
- package/dist/src/cspl/constants.d.ts +1 -36
- package/dist/src/cspl/constants.js +0 -9
- package/dist/src/cspl/sentinel_hook.js +30 -35
- package/dist/src/cspl/upload_file.js +12 -6
- package/dist/src/cspl/utils.d.ts +9 -20
- package/dist/src/cspl/utils.js +75 -119
- package/dist/src/monitor.js +49 -8
- package/dist/src/provider.js +89 -2
- package/dist/src/skill-retriever/hooks.js +10 -1
- package/dist/src/skill-retriever/tool-search.js +13 -11
- package/dist/src/steer-queue.d.ts +1 -0
- package/dist/src/steer-queue.js +9 -0
- package/dist/src/tools/call-phone-tool.d.ts +0 -1
- package/dist/src/tools/call-phone-tool.js +5 -8
- package/package.json +3 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
declare const
|
|
3
|
-
export default
|
|
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",
|
|
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
|
|
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
|
|
334
|
+
export default plugin;
|
package/dist/src/bot.js
CHANGED
|
@@ -15,6 +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 { resolveActiveEmbeddedRunSessionId, queueAgentHarnessMessage, } from "openclaw/plugin-sdk/agent-harness-runtime";
|
|
18
19
|
import { registerTaskId, decrementTaskIdRef, hasActiveTask, } from "./task-manager.js";
|
|
19
20
|
import { logger } from "./utils/logger.js";
|
|
20
21
|
/**
|
|
@@ -299,6 +300,30 @@ export async function handleXYMessage(params) {
|
|
|
299
300
|
textForAgent = `${textForAgent}${fileHint}`;
|
|
300
301
|
log.log(`[BOT] Steer: appended file paths to text`);
|
|
301
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
|
+
}
|
|
302
327
|
// Resolve envelope format options (following feishu pattern)
|
|
303
328
|
const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
|
|
304
329
|
// Build message body with speaker prefix (following feishu pattern)
|
|
@@ -314,12 +339,20 @@ export async function handleXYMessage(params) {
|
|
|
314
339
|
envelope: envelopeOptions,
|
|
315
340
|
body: messageBody,
|
|
316
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
|
+
}
|
|
317
349
|
// ✅ Finalize inbound context (following feishu pattern)
|
|
318
350
|
// Use route.accountId and route.sessionKey instead of parsed fields
|
|
319
351
|
const ctxPayload = core.channel.reply.finalizeInboundContext({
|
|
320
352
|
Body: body,
|
|
321
|
-
RawBody:
|
|
322
|
-
CommandBody:
|
|
353
|
+
RawBody: steerCommandBody,
|
|
354
|
+
CommandBody: steerCommandBody,
|
|
355
|
+
...(isUpdate ? { CommandSource: "native" } : {}),
|
|
323
356
|
From: parsed.sessionId,
|
|
324
357
|
To: parsed.sessionId, // ✅ Simplified: use sessionId as target (context is managed by SessionKey)
|
|
325
358
|
SessionKey: route.sessionKey, // ✅ Use route.sessionKey
|
|
@@ -343,15 +376,23 @@ export async function handleXYMessage(params) {
|
|
|
343
376
|
// response and cleanup — the first message's dispatcher handles those.
|
|
344
377
|
const steerState = { steered: isUpdate };
|
|
345
378
|
// 🔑 创建dispatcher
|
|
346
|
-
log.log(`[BOT-DISPATCHER] Creating reply dispatcher`);
|
|
379
|
+
log.log(`[BOT-DISPATCHER] Creating reply dispatcher, isSteer=${isUpdate}, sessionKey=${route.sessionKey}`);
|
|
347
380
|
// Cleanup: 必须在 onIdle 内部执行(参见 reply-dispatcher.ts 中 onIdleComplete 的注释)
|
|
381
|
+
// Steer dispatches must NOT decrement refCount because the steer injection
|
|
382
|
+
// uses skipRegistration (no increment). Only the original message's
|
|
383
|
+
// dispatcher owns the refCount lifecycle.
|
|
348
384
|
let cleaned = false;
|
|
349
385
|
const cleanup = () => {
|
|
350
386
|
if (cleaned)
|
|
351
387
|
return;
|
|
352
388
|
cleaned = true;
|
|
353
|
-
log.log(`[BOT] Cleanup started`);
|
|
354
|
-
|
|
389
|
+
log.log(`[BOT] Cleanup started, steered=${steerState.steered}`);
|
|
390
|
+
if (!steerState.steered) {
|
|
391
|
+
decrementTaskIdRef(parsed.sessionId);
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
log.log(`[BOT] Steered cleanup, skipping decrementTaskIdRef`);
|
|
395
|
+
}
|
|
355
396
|
log.log(`[BOT] Cleanup completed`);
|
|
356
397
|
};
|
|
357
398
|
const { dispatcher, replyOptions, markDispatchIdle, startStatusInterval, updateFallbackTaskId } = createXYReplyDispatcher({
|
|
@@ -406,8 +447,9 @@ export async function handleXYMessage(params) {
|
|
|
406
447
|
// signal init complete to release the global dispatch gate
|
|
407
448
|
// for the next session.
|
|
408
449
|
const dispatchPromise = runWithSessionContext(sessionContext, async () => {
|
|
409
|
-
|
|
410
|
-
log.log(`[
|
|
450
|
+
const isSteerDispatch = isUpdate && !skipReg;
|
|
451
|
+
log.log(`[ALS-PROOF] bot entered dispatch scope sessionId=${sessionContext.sessionId} taskId=${sessionContext.taskId} isSteer=${isSteerDispatch}`);
|
|
452
|
+
log.log(`[BOT-DISPATCH] dispatchReplyFromConfig starting, body.length=${ctxPayload.Body?.length ?? 0}, isSteer=${isSteerDispatch}`);
|
|
411
453
|
try {
|
|
412
454
|
const result = await core.channel.reply.dispatchReplyFromConfig({
|
|
413
455
|
ctx: ctxPayload,
|
|
@@ -415,7 +457,13 @@ export async function handleXYMessage(params) {
|
|
|
415
457
|
dispatcher,
|
|
416
458
|
replyOptions,
|
|
417
459
|
});
|
|
418
|
-
|
|
460
|
+
// 区分 steer 成功(undefined)和 steer 失败/正常 run(有结果)
|
|
461
|
+
if (result === undefined) {
|
|
462
|
+
log.log(`[BOT-STEER] dispatchReplyFromConfig returned undefined — steer injected via fast path OK, sessionKey=${route.sessionKey}`);
|
|
463
|
+
}
|
|
464
|
+
else {
|
|
465
|
+
log.log(`[BOT-DISPATCH] dispatchReplyFromConfig returned, resultType=${typeof result}, isSteer=${isSteerDispatch}, steered=${steerState.steered}`);
|
|
466
|
+
}
|
|
419
467
|
return result;
|
|
420
468
|
}
|
|
421
469
|
catch (dispatchErr) {
|
|
@@ -0,0 +1,50 @@
|
|
|
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
|
+
/** Auth headers from options.headers in the last normal request. */
|
|
22
|
+
requestHeaders?: Record<string, string>;
|
|
23
|
+
/** API key from the last normal request (for Bearer token auth). */
|
|
24
|
+
apiKey?: string;
|
|
25
|
+
/** Model-level headers from resolveDynamicModel (streamSimple adds these). */
|
|
26
|
+
modelHeaders?: Record<string, string>;
|
|
27
|
+
}
|
|
28
|
+
/** Store config captured from prepareExtraParams so summarize() can read it. */
|
|
29
|
+
export declare function setCompactionConfig(config: CompactionConfig | null): void;
|
|
30
|
+
/**
|
|
31
|
+
* Store a snapshot of the resolved session headers captured from the
|
|
32
|
+
* most recent wrapStreamFn call. This lets the CompactionProvider reuse
|
|
33
|
+
* the A2A traceId/sessionId during compaction summarization.
|
|
34
|
+
*/
|
|
35
|
+
export declare function setCompactionSessionSnapshot(snapshot: CompactionSessionSnapshot | null): void;
|
|
36
|
+
export declare const xiaoyiCompactionProvider: {
|
|
37
|
+
id: string;
|
|
38
|
+
label: string;
|
|
39
|
+
summarize(params: {
|
|
40
|
+
messages: unknown[];
|
|
41
|
+
signal?: AbortSignal;
|
|
42
|
+
customInstructions?: string;
|
|
43
|
+
summarizationInstructions?: {
|
|
44
|
+
identifierPolicy?: string;
|
|
45
|
+
identifierInstructions?: string;
|
|
46
|
+
};
|
|
47
|
+
previousSummary?: string;
|
|
48
|
+
}): Promise<string>;
|
|
49
|
+
};
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,202 @@
|
|
|
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
|
+
// Reconstruct the exact same headers that the normal request uses.
|
|
127
|
+
// streamSimple adds model.headers to the HTTP request directly, so
|
|
128
|
+
// we capture them separately from options.headers.
|
|
129
|
+
const reqHdrs = session?.requestHeaders;
|
|
130
|
+
const modelHdrs = session?.modelHeaders;
|
|
131
|
+
const reqKeys = reqHdrs ? Object.keys(reqHdrs) : [];
|
|
132
|
+
const modelKeys = modelHdrs ? Object.keys(modelHdrs) : [];
|
|
133
|
+
logger.log(`[compaction-provider] snapshot auth: hasApiKey=${!!session?.apiKey} ` +
|
|
134
|
+
`requestHeaders=[${reqKeys.join(",")}] modelHeaders=[${modelKeys.join(",")}]`);
|
|
135
|
+
const headers = {
|
|
136
|
+
"Content-Type": "application/json",
|
|
137
|
+
...modelHdrs,
|
|
138
|
+
...reqHdrs,
|
|
139
|
+
...(session?.apiKey ? { Authorization: `Bearer ${session.apiKey}` } : {}),
|
|
140
|
+
[HEADER_TRACE_ID]: traceId,
|
|
141
|
+
[HEADER_SESSION_ID]: sessionId,
|
|
142
|
+
[HEADER_INTERACTION_ID]: interactionId,
|
|
143
|
+
};
|
|
144
|
+
if (session?.deviceType) {
|
|
145
|
+
headers["x-device-type"] = session.deviceType;
|
|
146
|
+
}
|
|
147
|
+
if (session?.appVer) {
|
|
148
|
+
headers["x-app-ver"] = session.appVer;
|
|
149
|
+
}
|
|
150
|
+
if (session?.sdkApiVersion) {
|
|
151
|
+
headers["x-sdk-api-version"] = session.sdkApiVersion;
|
|
152
|
+
}
|
|
153
|
+
const body = {
|
|
154
|
+
model: cfg.modelName,
|
|
155
|
+
messages: [
|
|
156
|
+
{ role: "system", content: SUMMARIZATION_SYSTEM_PROMPT },
|
|
157
|
+
{ role: "user", content: promptText },
|
|
158
|
+
],
|
|
159
|
+
max_tokens: 4096,
|
|
160
|
+
temperature: 0.3,
|
|
161
|
+
};
|
|
162
|
+
const url = `${cfg.baseUrl.replace(/\/+$/, "")}/chat/completions`;
|
|
163
|
+
// Log headers for diagnostics (redact sensitive values)
|
|
164
|
+
const safeHeaders = {};
|
|
165
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
166
|
+
if (key.toLowerCase().includes("auth") || key.toLowerCase().includes("api-key")) {
|
|
167
|
+
safeHeaders[key] = value ? `${value.slice(0, 4)}***` : "(empty)";
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
safeHeaders[key] = value;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
logger.log(`[compaction-provider] POST ${url} headers=${JSON.stringify(safeHeaders)}`);
|
|
174
|
+
// ── Call ──────────────────────────────────────────────────────
|
|
175
|
+
let response;
|
|
176
|
+
try {
|
|
177
|
+
response = await fetch(url, {
|
|
178
|
+
method: "POST",
|
|
179
|
+
headers,
|
|
180
|
+
body: JSON.stringify(body),
|
|
181
|
+
signal: params.signal,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
catch (err) {
|
|
185
|
+
logger.error(`[compaction-provider] fetch failed: ${String(err)}`);
|
|
186
|
+
throw err;
|
|
187
|
+
}
|
|
188
|
+
if (!response.ok) {
|
|
189
|
+
const errorText = await response.text().catch(() => "");
|
|
190
|
+
logger.error(`[compaction-provider] API error status=${response.status} body=${errorText.slice(0, 500)}`);
|
|
191
|
+
throw new Error(`Compaction API returned ${response.status}`);
|
|
192
|
+
}
|
|
193
|
+
const data = (await response.json());
|
|
194
|
+
const summary = data.choices?.[0]?.message?.content;
|
|
195
|
+
if (!summary?.trim()) {
|
|
196
|
+
logger.warn("[compaction-provider] empty summary returned");
|
|
197
|
+
throw new Error("Empty summary from compaction API");
|
|
198
|
+
}
|
|
199
|
+
logger.log(`[compaction-provider] done summaryLen=${summary.length}`);
|
|
200
|
+
return summary;
|
|
201
|
+
},
|
|
202
|
+
};
|
|
@@ -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
|
*
|