@ynhcj/xiaoyi-channel 0.0.172-beta → 0.0.172-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.
Files changed (47) hide show
  1. package/dist/index.js +141 -1
  2. package/dist/src/acp-session-binding.d.ts +37 -0
  3. package/dist/src/acp-session-binding.js +237 -0
  4. package/dist/src/bot.js +60 -2
  5. package/dist/src/cron-command.d.ts +2 -0
  6. package/dist/src/cron-command.js +14 -8
  7. package/dist/src/cron-query-handler.js +45 -8
  8. package/dist/src/cspl/call_api.js +2 -2
  9. package/dist/src/cspl/upload_file.js +2 -2
  10. package/dist/src/formatter.js +47 -2
  11. package/dist/src/log-reporter/config-loader.d.ts +11 -0
  12. package/dist/src/log-reporter/config-loader.js +68 -0
  13. package/dist/src/log-reporter/cursor-store.d.ts +5 -0
  14. package/dist/src/log-reporter/cursor-store.js +26 -0
  15. package/dist/src/log-reporter/index.d.ts +10 -0
  16. package/dist/src/log-reporter/index.js +77 -0
  17. package/dist/src/log-reporter/reporter.d.ts +6 -0
  18. package/dist/src/log-reporter/reporter.js +17 -0
  19. package/dist/src/log-reporter/scanner.d.ts +6 -0
  20. package/dist/src/log-reporter/scanner.js +82 -0
  21. package/dist/src/log-reporter/types.d.ts +59 -0
  22. package/dist/src/log-reporter/types.js +2 -0
  23. package/dist/src/log-reporter/uploader.d.ts +6 -0
  24. package/dist/src/log-reporter/uploader.js +32 -0
  25. package/dist/src/memory-query-handler.d.ts +1 -0
  26. package/dist/src/memory-query-handler.js +282 -0
  27. package/dist/src/monitor.js +9 -0
  28. package/dist/src/parser.d.ts +12 -0
  29. package/dist/src/parser.js +39 -13
  30. package/dist/src/provider.js +56 -3
  31. package/dist/src/reply-dispatcher.js +29 -46
  32. package/dist/src/tools/agent-as-skill-tool.js +7 -12
  33. package/dist/src/tools/device-tool-map.d.ts +1 -1
  34. package/dist/src/tools/device-tool-map.js +8 -1
  35. package/dist/src/tools/modify-alarm-tool.js +17 -0
  36. package/dist/src/tools/send-cross-device-task-tool.js +84 -15
  37. package/dist/src/tools/send-file-to-user-tool.js +9 -11
  38. package/dist/src/tools/send-html-card-tool.js +4 -4
  39. package/dist/src/tools/session-manager.d.ts +12 -2
  40. package/dist/src/tools/session-manager.js +65 -18
  41. package/dist/src/types.d.ts +6 -6
  42. package/dist/src/utils/config-manager.d.ts +3 -2
  43. package/dist/src/utils/config-manager.js +22 -2
  44. package/dist/src/utils/cron-push-map.d.ts +26 -0
  45. package/dist/src/utils/cron-push-map.js +131 -0
  46. package/dist/src/websocket.js +29 -13
  47. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3,7 +3,10 @@ import { xiaoyiProvider } from "./src/provider.js";
3
3
  import { xyPlugin } from "./src/channel.js";
4
4
  import registerSentinelHook from "./src/cspl/sentinel_hook.js";
5
5
  import { setXYRuntime } from "./src/runtime.js";
6
- import { markCronToolCall, clearCronToolCall } from "./src/tools/session-manager.js";
6
+ import { markCronToolCall, clearCronToolCall, getSessionContext } from "./src/tools/session-manager.js";
7
+ import { configManager } from "./src/utils/config-manager.js";
8
+ import { setJobPushId } from "./src/utils/cron-push-map.js";
9
+ import { getAllPushIds } from "./src/utils/pushid-manager.js";
7
10
  import { registerSelfEvolutionToolResultNudge } from "./src/self-evolution-tool-result-nudge.js";
8
11
  import { createBeforePromptBuildHandler } from "./src/skill-retriever/hooks.js";
9
12
  import { normalizeToolRetrieverConfig } from "./src/skill-retriever/config.js";
@@ -25,8 +28,145 @@ function registerCronDetectionHook(api) {
25
28
  if (event.toolCallId) {
26
29
  clearCronToolCall(event.toolCallId);
27
30
  }
31
+ // 捕获对话创建的 cron job:agent 调 cron(add) 后,从 result 拿 jobId,
32
+ // 配合当前会话的 pushId,写入 jobId↔pushId 映射,供 fire 时反查设备。
33
+ await captureCronAddMapping(event, ctx).catch((err) => {
34
+ // 捕获失败不影响工具结果
35
+ console.error("[xy] captureCronAddMapping failed:", err);
36
+ });
28
37
  });
29
38
  }
39
+ /** 从 cron add 工具结果中提取 jobId 并写入 pushId 映射。 */
40
+ async function captureCronAddMapping(event, ctx) {
41
+ // 两条创建路径都要捕获:
42
+ // 1) cron agent 工具:toolName==="cron", params.action==="add"
43
+ // 2) exec 跑 CLI:toolName==="exec", params.command 含 "cron add"
44
+ // (agent 实际用的是这条:openclaw cron add --name ... --cron ... --message ...)
45
+ const isCronAddTool = event.toolName === "cron" &&
46
+ (event.params?.action === "add" || event.params?.action === "create");
47
+ const isExecCronAdd = event.toolName === "exec" && isExecCronAddCommand(event.params?.command);
48
+ if (!isCronAddTool && !isExecCronAdd)
49
+ return;
50
+ console.log(`[CRONMAP] after_tool_call path=${event.toolName}, resultType=${typeof event.result}`);
51
+ const jobId = readJobIdFromResult(event.result);
52
+ if (!jobId) {
53
+ console.log(`[CRONMAP] skip: could not extract jobId. preview=${preview(event.result)}`);
54
+ return;
55
+ }
56
+ console.log(`[CRONMAP] extracted jobId=${jobId}`);
57
+ const sessionCtx = ctx.sessionKey ? getSessionContext(ctx.sessionKey) : null;
58
+ const sessionId = sessionCtx?.sessionId;
59
+ if (!sessionId) {
60
+ console.log(`[CRONMAP] skip: no sessionId (sessionKey=${ctx.sessionKey}, ctxFound=${!!sessionCtx})`);
61
+ return;
62
+ }
63
+ const pushId = await resolvePushId(sessionId);
64
+ if (!pushId) {
65
+ console.log(`[CRONMAP] skip: no pushId available for sessionId=${sessionId} (no session match, no global, no file)`);
66
+ return;
67
+ }
68
+ console.log(`[CRONMAP] writing map: jobId=${jobId}, sessionId=${sessionId}, pushId=${pushId.substring(0, 16)}...`);
69
+ await setJobPushId(jobId, {
70
+ pushId,
71
+ sessionId,
72
+ deviceType: sessionCtx?.deviceType,
73
+ source: event.toolName === "exec" ? "exec-cli" : "conversation",
74
+ });
75
+ console.log(`[CRONMAP] map written OK`);
76
+ }
77
+ /** 回退链取 pushId:当前会话 → 全局兜底 → 本地文件首个(保底)。 */
78
+ async function resolvePushId(sessionId) {
79
+ // 1. 同会话
80
+ const session = configManager.getPushId(sessionId);
81
+ if (session)
82
+ return session;
83
+ // 2. 全局(任何会话注册过的)
84
+ const global = configManager.getPushId();
85
+ if (global)
86
+ return global;
87
+ // 3. 文件兜底
88
+ try {
89
+ const all = await getAllPushIds();
90
+ if (all.length > 0)
91
+ return all[0];
92
+ }
93
+ catch {
94
+ // ignore
95
+ }
96
+ return null;
97
+ }
98
+ /** 判断 exec 命令是否为 cron add(匹配 "openclaw cron add" 或裸 "cron add",排除 list/remove 等)。 */
99
+ function isExecCronAddCommand(command) {
100
+ if (typeof command !== "string")
101
+ return false;
102
+ return /\bcron\s+add\b/.test(command);
103
+ }
104
+ /** 取结果的短预览,用于诊断。 */
105
+ function preview(value) {
106
+ if (value == null)
107
+ return String(value);
108
+ const s = typeof value === "string" ? value : JSON.stringify(value);
109
+ return s.length > 200 ? s.slice(0, 200) + "…" : s;
110
+ }
111
+ /** 防御性地从 cron add 结果中取 job id。
112
+ * 覆盖:裸 job 对象、JSON 字符串、exec 输出文本、
113
+ * {content:[{text}]} / {stdout} / data/result/job 嵌套。 */
114
+ function readJobIdFromResult(result) {
115
+ if (!result)
116
+ return undefined;
117
+ // {content: [{type:"text", text: "..."}]} — exec 工具的输出信封
118
+ if (result && typeof result === "object") {
119
+ const contentArr = result.content;
120
+ if (Array.isArray(contentArr)) {
121
+ for (const item of contentArr) {
122
+ if (item && typeof item === "object") {
123
+ const text = item.text;
124
+ if (typeof text === "string" && text.trim()) {
125
+ const fromContent = readJobIdFromResult(text);
126
+ if (fromContent)
127
+ return fromContent;
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+ // {stdout} — 备选 exec 输出信封
134
+ if (result && typeof result === "object") {
135
+ const stdout = result.stdout;
136
+ if (typeof stdout === "string" && stdout.trim()) {
137
+ const fromStdout = readJobIdFromResult(stdout);
138
+ if (fromStdout)
139
+ return fromStdout;
140
+ }
141
+ }
142
+ let obj = result;
143
+ if (typeof result === "string") {
144
+ try {
145
+ obj = JSON.parse(result);
146
+ }
147
+ catch {
148
+ // 纯文本:可能含 stderr 前缀行 + JSON。用正则抓 "id":"..."。
149
+ const m = result.match(/"id"\s*:\s*"([^"]+)"/);
150
+ if (m)
151
+ return m[1];
152
+ return undefined;
153
+ }
154
+ }
155
+ if (obj && typeof obj === "object") {
156
+ const id = obj.id;
157
+ if (typeof id === "string" && id.trim())
158
+ return id.trim();
159
+ for (const k of ["data", "result", "job"]) {
160
+ const inner = obj[k];
161
+ if (inner && typeof inner === "object") {
162
+ const innerId = inner.id;
163
+ if (typeof innerId === "string" && innerId.trim())
164
+ return innerId.trim();
165
+ }
166
+ }
167
+ }
168
+ return undefined;
169
+ }
30
170
  function registerFullHooks(api) {
31
171
  // SKILL RETRIEVER HOOK: before_prompt_build hook
32
172
  const pluginConfig = api.pluginConfig || {};
@@ -0,0 +1,37 @@
1
+ import { type BindingTargetKind } from "openclaw/plugin-sdk/conversation-runtime";
2
+ type XyBindingTargetKind = "subagent" | "acp";
3
+ type XyAcpBindingRecord = {
4
+ accountId: string;
5
+ conversationId: string;
6
+ parentConversationId?: string;
7
+ deliveryTo?: string;
8
+ targetKind: XyBindingTargetKind;
9
+ targetSessionKey: string;
10
+ agentId?: string;
11
+ label?: string;
12
+ boundBy?: string;
13
+ boundAt: number;
14
+ lastActivityAt: number;
15
+ };
16
+ type XyAcpBindingManager = {
17
+ accountId: string;
18
+ getByConversationId: (conversationId: string) => XyAcpBindingRecord | undefined;
19
+ listBySessionKey: (targetSessionKey: string) => XyAcpBindingRecord[];
20
+ bindConversation: (params: {
21
+ conversationId: string;
22
+ parentConversationId?: string;
23
+ targetKind: BindingTargetKind;
24
+ targetSessionKey: string;
25
+ metadata?: Record<string, unknown>;
26
+ }) => XyAcpBindingRecord | null;
27
+ touchConversation: (conversationId: string, at?: number) => XyAcpBindingRecord | null;
28
+ unbindConversation: (conversationId: string) => XyAcpBindingRecord | null;
29
+ unbindBySessionKey: (targetSessionKey: string) => XyAcpBindingRecord[];
30
+ stop: () => void;
31
+ };
32
+ export declare function createXyAcpBindingManager(params: {
33
+ accountId?: string;
34
+ cfg: any;
35
+ }): XyAcpBindingManager;
36
+ export declare function getXyAcpBindingManager(accountId?: string): XyAcpBindingManager | null;
37
+ export {};
@@ -0,0 +1,237 @@
1
+ // ACP Session Binding Adapter for xiaoyi-channel.
2
+ // Follows the feishu thread-bindings.ts pattern.
3
+ //
4
+ // Maps A2A sessionId (stable conversation identifier) to ACP/subagent
5
+ // session keys so that openclaw can bind spawned sessions to the
6
+ // current xiaoyi conversation.
7
+ //
8
+ // Key design: xiaoyi-channel only supports `placement: "current"` —
9
+ // it cannot create child threads (unlike Discord). All spawned sessions
10
+ // are bound to the current A2A conversation identified by sessionId.
11
+ // NOTE: Using `any` for cfg type to avoid version mismatch between
12
+ // local and global openclaw installs (auth.profiles.aws-sdk union).
13
+ import { resolveThreadBindingIdleTimeoutMsForChannel, resolveThreadBindingMaxAgeMsForChannel, resolveThreadBindingConversationIdFromBindingId, registerSessionBindingAdapter, unregisterSessionBindingAdapter, } from "openclaw/plugin-sdk/conversation-runtime";
14
+ import { normalizeAccountId, resolveAgentIdFromSessionKey } from "openclaw/plugin-sdk/routing";
15
+ import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
16
+ import { logger } from "./utils/logger.js";
17
+ // ─── Global state (survives module dedup) ─────────────────────
18
+ const XY_ACP_BINDINGS_KEY = Symbol.for("openclaw.xyAcpBindingsState");
19
+ let state;
20
+ function getState() {
21
+ if (!state) {
22
+ const globalStore = globalThis;
23
+ state = globalStore[XY_ACP_BINDINGS_KEY] ?? {
24
+ managersByAccountId: new Map(),
25
+ bindingsByAccountConversation: new Map(),
26
+ };
27
+ globalStore[XY_ACP_BINDINGS_KEY] = state;
28
+ }
29
+ return state;
30
+ }
31
+ function resolveBindingKey(params) {
32
+ return `${params.accountId}:${params.conversationId}`;
33
+ }
34
+ // ─── Kind conversion ──────────────────────────────────────────
35
+ function toSessionBindingTargetKind(raw) {
36
+ return raw === "subagent" ? "subagent" : "session";
37
+ }
38
+ function toXyTargetKind(raw) {
39
+ return raw === "subagent" ? "subagent" : "acp";
40
+ }
41
+ // ─── Record conversion ────────────────────────────────────────
42
+ function toSessionBindingRecord(record, defaults) {
43
+ const idleExpiresAt = defaults.idleTimeoutMs > 0 ? record.lastActivityAt + defaults.idleTimeoutMs : undefined;
44
+ const maxAgeExpiresAt = defaults.maxAgeMs > 0 ? record.boundAt + defaults.maxAgeMs : undefined;
45
+ const expiresAt = idleExpiresAt != null && maxAgeExpiresAt != null
46
+ ? Math.min(idleExpiresAt, maxAgeExpiresAt)
47
+ : (idleExpiresAt ?? maxAgeExpiresAt);
48
+ return {
49
+ bindingId: resolveBindingKey({
50
+ accountId: record.accountId,
51
+ conversationId: record.conversationId,
52
+ }),
53
+ targetSessionKey: record.targetSessionKey,
54
+ targetKind: toSessionBindingTargetKind(record.targetKind),
55
+ conversation: {
56
+ channel: "xiaoyi-channel",
57
+ accountId: record.accountId,
58
+ conversationId: record.conversationId,
59
+ parentConversationId: record.parentConversationId,
60
+ },
61
+ status: "active",
62
+ boundAt: record.boundAt,
63
+ expiresAt,
64
+ metadata: {
65
+ agentId: record.agentId,
66
+ label: record.label,
67
+ boundBy: record.boundBy,
68
+ deliveryTo: record.deliveryTo,
69
+ lastActivityAt: record.lastActivityAt,
70
+ idleTimeoutMs: defaults.idleTimeoutMs,
71
+ maxAgeMs: defaults.maxAgeMs,
72
+ },
73
+ };
74
+ }
75
+ // ─── Manager factory ──────────────────────────────────────────
76
+ export function createXyAcpBindingManager(params) {
77
+ const accountId = normalizeAccountId(params.accountId);
78
+ const existing = getState().managersByAccountId.get(accountId);
79
+ if (existing) {
80
+ return existing;
81
+ }
82
+ const idleTimeoutMs = resolveThreadBindingIdleTimeoutMsForChannel({
83
+ cfg: params.cfg,
84
+ channel: "xiaoyi-channel",
85
+ accountId,
86
+ });
87
+ const maxAgeMs = resolveThreadBindingMaxAgeMsForChannel({
88
+ cfg: params.cfg,
89
+ channel: "xiaoyi-channel",
90
+ accountId,
91
+ });
92
+ const log = logger.withContext("", "");
93
+ const manager = {
94
+ accountId,
95
+ getByConversationId: (conversationId) => getState().bindingsByAccountConversation.get(resolveBindingKey({ accountId, conversationId })),
96
+ listBySessionKey: (targetSessionKey) => [...getState().bindingsByAccountConversation.values()].filter((record) => record.accountId === accountId && record.targetSessionKey === targetSessionKey),
97
+ bindConversation: ({ conversationId, parentConversationId, targetKind, targetSessionKey, metadata, }) => {
98
+ const normalizedConversationId = conversationId.trim();
99
+ const normalizedTargetSessionKey = targetSessionKey.trim();
100
+ if (!normalizedConversationId || !normalizedTargetSessionKey) {
101
+ return null;
102
+ }
103
+ const existingLocal = getState().bindingsByAccountConversation.get(resolveBindingKey({ accountId, conversationId: normalizedConversationId }));
104
+ const now = Date.now();
105
+ const record = {
106
+ accountId,
107
+ conversationId: normalizedConversationId,
108
+ parentConversationId: normalizeOptionalString(parentConversationId) ?? existingLocal?.parentConversationId,
109
+ deliveryTo: typeof metadata?.deliveryTo === "string" && metadata.deliveryTo.trim()
110
+ ? metadata.deliveryTo.trim()
111
+ : existingLocal?.deliveryTo,
112
+ targetKind: toXyTargetKind(targetKind),
113
+ targetSessionKey: normalizedTargetSessionKey,
114
+ agentId: typeof metadata?.agentId === "string" && metadata.agentId.trim()
115
+ ? metadata.agentId.trim()
116
+ : (existingLocal?.agentId ?? resolveAgentIdFromSessionKey(normalizedTargetSessionKey)),
117
+ label: typeof metadata?.label === "string" && metadata.label.trim()
118
+ ? metadata.label.trim()
119
+ : existingLocal?.label,
120
+ boundBy: typeof metadata?.boundBy === "string" && metadata.boundBy.trim()
121
+ ? metadata.boundBy.trim()
122
+ : existingLocal?.boundBy,
123
+ boundAt: now,
124
+ lastActivityAt: now,
125
+ };
126
+ getState().bindingsByAccountConversation.set(resolveBindingKey({ accountId, conversationId: normalizedConversationId }), record);
127
+ log.log(`[XY-ACP-BIND] Bound ${targetKind} session ${normalizedTargetSessionKey.slice(0, 30)} to conversation ${normalizedConversationId.slice(0, 12)}`);
128
+ return record;
129
+ },
130
+ touchConversation: (conversationId, at = Date.now()) => {
131
+ const key = resolveBindingKey({ accountId, conversationId });
132
+ const existingRecord = getState().bindingsByAccountConversation.get(key);
133
+ if (!existingRecord) {
134
+ return null;
135
+ }
136
+ const updated = { ...existingRecord, lastActivityAt: at };
137
+ getState().bindingsByAccountConversation.set(key, updated);
138
+ return updated;
139
+ },
140
+ unbindConversation: (conversationId) => {
141
+ const key = resolveBindingKey({ accountId, conversationId });
142
+ const existingRecord = getState().bindingsByAccountConversation.get(key);
143
+ if (!existingRecord) {
144
+ return null;
145
+ }
146
+ getState().bindingsByAccountConversation.delete(key);
147
+ return existingRecord;
148
+ },
149
+ unbindBySessionKey: (targetSessionKey) => {
150
+ const removed = [];
151
+ for (const record of getState().bindingsByAccountConversation.values()) {
152
+ if (record.accountId !== accountId || record.targetSessionKey !== targetSessionKey) {
153
+ continue;
154
+ }
155
+ getState().bindingsByAccountConversation.delete(resolveBindingKey({ accountId, conversationId: record.conversationId }));
156
+ removed.push(record);
157
+ }
158
+ return removed;
159
+ },
160
+ stop: () => {
161
+ for (const key of getState().bindingsByAccountConversation.keys()) {
162
+ if (key.startsWith(`${accountId}:`)) {
163
+ getState().bindingsByAccountConversation.delete(key);
164
+ }
165
+ }
166
+ getState().managersByAccountId.delete(accountId);
167
+ unregisterSessionBindingAdapter({
168
+ channel: "xiaoyi-channel",
169
+ accountId,
170
+ adapter: sessionBindingAdapter,
171
+ });
172
+ log.log(`[XY-ACP-BIND] Stopped binding manager for account ${accountId}`);
173
+ },
174
+ };
175
+ const sessionBindingAdapter = {
176
+ channel: "xiaoyi-channel",
177
+ accountId,
178
+ capabilities: {
179
+ placements: ["current"],
180
+ },
181
+ bind: async (input) => {
182
+ if (input.conversation.channel !== "xiaoyi-channel" || input.placement === "child") {
183
+ return null;
184
+ }
185
+ const bound = manager.bindConversation({
186
+ conversationId: input.conversation.conversationId,
187
+ parentConversationId: input.conversation.parentConversationId,
188
+ targetKind: input.targetKind,
189
+ targetSessionKey: input.targetSessionKey,
190
+ metadata: input.metadata,
191
+ });
192
+ return bound ? toSessionBindingRecord(bound, { idleTimeoutMs, maxAgeMs }) : null;
193
+ },
194
+ listBySession: (targetSessionKey) => manager
195
+ .listBySessionKey(targetSessionKey)
196
+ .map((entry) => toSessionBindingRecord(entry, { idleTimeoutMs, maxAgeMs })),
197
+ resolveByConversation: (ref) => {
198
+ if (ref.channel !== "xiaoyi-channel") {
199
+ return null;
200
+ }
201
+ const found = manager.getByConversationId(ref.conversationId);
202
+ return found ? toSessionBindingRecord(found, { idleTimeoutMs, maxAgeMs }) : null;
203
+ },
204
+ touch: (bindingId, at) => {
205
+ const conversationId = resolveThreadBindingConversationIdFromBindingId({
206
+ accountId,
207
+ bindingId,
208
+ });
209
+ if (conversationId) {
210
+ manager.touchConversation(conversationId, at);
211
+ }
212
+ },
213
+ unbind: async (input) => {
214
+ if (input.targetSessionKey?.trim()) {
215
+ return manager
216
+ .unbindBySessionKey(input.targetSessionKey.trim())
217
+ .map((entry) => toSessionBindingRecord(entry, { idleTimeoutMs, maxAgeMs }));
218
+ }
219
+ const conversationId = resolveThreadBindingConversationIdFromBindingId({
220
+ accountId,
221
+ bindingId: input.bindingId,
222
+ });
223
+ if (!conversationId) {
224
+ return [];
225
+ }
226
+ const removed = manager.unbindConversation(conversationId);
227
+ return removed ? [toSessionBindingRecord(removed, { idleTimeoutMs, maxAgeMs })] : [];
228
+ },
229
+ };
230
+ registerSessionBindingAdapter(sessionBindingAdapter);
231
+ getState().managersByAccountId.set(accountId, manager);
232
+ log.log(`[XY-ACP-BIND] Created binding manager for account ${accountId} (idleTimeout=${idleTimeoutMs}ms, maxAge=${maxAgeMs}ms)`);
233
+ return manager;
234
+ }
235
+ export function getXyAcpBindingManager(accountId) {
236
+ return getState().managersByAccountId.get(normalizeAccountId(accountId)) ?? null;
237
+ }
package/dist/src/bot.js CHANGED
@@ -1,6 +1,7 @@
1
+ import { updateSessionStoreEntry, updateSessionStore, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
1
2
  import { getXYRuntime } from "./runtime.js";
2
3
  import { createXYReplyDispatcher } from "./reply-dispatcher.js";
3
- import { parseA2AMessage, extractTextFromParts, extractFileParts, extractPushId, extractDeviceType, extractModelName, extractTriggerData, extractRunCrossTaskContext } from "./parser.js";
4
+ import { parseA2AMessage, extractTextFromParts, extractFileParts, extractPushId, extractDeviceType, extractAppVer, extractDisplayVersion, extractModelName, extractTriggerData, extractRunCrossTaskContext } from "./parser.js";
4
5
  import { downloadFilesFromParts } from "./file-download.js";
5
6
  import { resolveXYConfig } from "./config.js";
6
7
  import { sendStatusUpdate, sendClearContextResponse, sendTasksCancelResponse, sendA2AResponse } from "./formatter.js";
@@ -32,7 +33,6 @@ export async function handleXYMessage(params) {
32
33
  try {
33
34
  // Check for special messages BEFORE parsing (these have different param structures)
34
35
  const messageMethod = message.method;
35
- logger.log(`[BOT] Received A2A message: ${JSON.stringify(message)}`);
36
36
  // Handle clearContext messages (sessionId at top level, no params)
37
37
  if (messageMethod === "clearContext" || messageMethod === "clear_context") {
38
38
  const sessionId = message.sessionId ?? message.params?.sessionId;
@@ -139,6 +139,15 @@ export async function handleXYMessage(params) {
139
139
  if (deviceType) {
140
140
  log.log(`[BOT] Extracted deviceType: ${deviceType}`);
141
141
  }
142
+ // Extract app_ver and display_version if present
143
+ const appVer = extractAppVer(parsed.parts);
144
+ if (appVer) {
145
+ log.log(`[BOT] Extracted app_ver: ${appVer}`);
146
+ }
147
+ const displayVersion = extractDisplayVersion(parsed.parts);
148
+ if (displayVersion) {
149
+ log.log(`[BOT] Extracted display_version: ${displayVersion}`);
150
+ }
142
151
  // Extract modelName if present (used by provider.ts to override model.id)
143
152
  const modelName = extractModelName(parsed.parts);
144
153
  if (modelName) {
@@ -170,9 +179,58 @@ export async function handleXYMessage(params) {
170
179
  messageId: parsed.messageId,
171
180
  agentId: route.accountId,
172
181
  deviceType,
182
+ appVer: appVer ?? undefined,
183
+ displayVersion: displayVersion ?? undefined,
173
184
  modelName,
174
185
  runCrossTaskContext: runCrossTaskContext ?? undefined,
175
186
  });
187
+ // 🔑 Sync A2A modelName to OpenClaw session store so that session_status
188
+ // reports the correct model. Without this, session_status returns the
189
+ // configured default model instead of the A2A-specified one.
190
+ if (modelName && modelName.trim() !== "" && modelName.toLowerCase() !== "none") {
191
+ try {
192
+ const storePath = resolveStorePath();
193
+ const result = await updateSessionStoreEntry({
194
+ storePath,
195
+ sessionKey: route.sessionKey,
196
+ update: async () => ({
197
+ providerOverride: "xiaoyiprovider",
198
+ modelOverride: modelName,
199
+ modelOverrideSource: "user",
200
+ model: "",
201
+ modelProvider: "",
202
+ contextTokens: 256_000,
203
+ }),
204
+ });
205
+ if (!result) {
206
+ // Session entry doesn't exist yet (first message, xy_channel
207
+ // bypasses the standard turn kernel). Create a minimal entry
208
+ // with the override via updateSessionStore.
209
+ await updateSessionStore(storePath, (store) => {
210
+ if (!store[route.sessionKey]) {
211
+ store[route.sessionKey] = {
212
+ // sessionId must pass validateSessionId regex /^[a-z0-9][a-z0-9._-]{0,127}$/i
213
+ // route.sessionKey like "agent:main:direct:xxx" contains colons which are invalid.
214
+ // Use parsed.sessionId (raw UUID from A2A) which is always safe.
215
+ sessionId: parsed.sessionId,
216
+ updatedAt: Date.now(),
217
+ providerOverride: "xiaoyiprovider",
218
+ modelOverride: modelName,
219
+ modelOverrideSource: "user",
220
+ contextTokens: 256_000,
221
+ };
222
+ }
223
+ });
224
+ log.log(`[BOT] Created session entry with model override: xiaoyiprovider/${modelName}`);
225
+ }
226
+ else {
227
+ log.log(`[BOT] Patched session store model override: xiaoyiprovider/${modelName}`);
228
+ }
229
+ }
230
+ catch (patchErr) {
231
+ log.error(`[BOT] Failed to patch session model override:`, patchErr);
232
+ }
233
+ }
176
234
  // 🔑 发送初始状态更新
177
235
  log.log(`[BOT] Sending initial status update`);
178
236
  void sendStatusUpdate({
@@ -2,6 +2,8 @@ import type { XYChannelConfig, A2ACommand } from "./types.js";
2
2
  export interface SendCommandViaPushParams {
3
3
  config: XYChannelConfig;
4
4
  command: A2ACommand;
5
+ /** 指定设备的 pushId(多设备路由)。未传时回退到 getAllPushIds()[0]。 */
6
+ pushId?: string;
5
7
  }
6
8
  /**
7
9
  * Send a tool command through the push channel (for cron-triggered tool calls).
@@ -24,16 +24,22 @@ export async function sendCommandViaPush(params) {
24
24
  command.header?.name ??
25
25
  "Command";
26
26
  logger.log(`[CRON-CMD] Sending command via push, intent=${intentName}`);
27
- // 1. Load push IDs, use first one
27
+ // 1. pushId:优先用调用方解析出的设备 pushId(多设备路由正确);
28
+ // 未提供时回退到 getAllPushIds()[0](单设备兼容旧行为)。
28
29
  let pushId = config.pushId;
29
- try {
30
- const pushIdList = await getAllPushIds();
31
- if (pushIdList.length > 0) {
32
- pushId = pushIdList[0];
33
- }
30
+ if (params.pushId) {
31
+ pushId = params.pushId;
34
32
  }
35
- catch (error) {
36
- logger.error("[CRON-CMD] Failed to load pushIds:", error);
33
+ else {
34
+ try {
35
+ const pushIdList = await getAllPushIds();
36
+ if (pushIdList.length > 0) {
37
+ pushId = pushIdList[0];
38
+ }
39
+ }
40
+ catch (error) {
41
+ logger.error("[CRON-CMD] Failed to load pushIds:", error);
42
+ }
37
43
  }
38
44
  // 2. Build and send push notification with command in directives
39
45
  const pushService = new XYPushService(config);
@@ -7,6 +7,8 @@ import { callGatewayTool } from "openclaw/plugin-sdk/agent-harness-runtime";
7
7
  import * as os from "os";
8
8
  import { sendCommand } from "./formatter.js";
9
9
  import { resolveXYConfig } from "./config.js";
10
+ import { configManager } from "./utils/config-manager.js";
11
+ import { setJobPushId } from "./utils/cron-push-map.js";
10
12
  import { logger } from "./utils/logger.js";
11
13
  import { readFileSync, readdirSync } from "fs";
12
14
  import { join } from "path";
@@ -19,7 +21,8 @@ const GATEWAY_TIMEOUT_MS = 60_000;
19
21
  */
20
22
  export async function handleCronQueryEvent(context, cfg) {
21
23
  const { action, jobId, params, sessionId, taskId, messageId } = context;
22
- logger.log(`[CRON-QUERY] Received event: action=${action}, jobId=${jobId ?? "(none)"}`);
24
+ const log = logger.withContext(sessionId ?? "", taskId ?? "");
25
+ log.log(`[CRON-QUERY] Received event: action=${action}, jobId=${jobId ?? "(none)"}`);
23
26
  let result;
24
27
  let error;
25
28
  try {
@@ -38,6 +41,11 @@ export async function handleCronQueryEvent(context, cfg) {
38
41
  break;
39
42
  case "add":
40
43
  result = await callGatewayTool("cron.add", { timeoutMs: GATEWAY_TIMEOUT_MS }, params ?? {});
44
+ // 捕获 jobId↔pushId:cron-query 路径由 channel 自己建 job,
45
+ // 此处 context 握着 sessionId,configManager 有对应设备 pushId。
46
+ await persistCronPushMap(context.sessionId, result).catch((err) => {
47
+ logger.error(`[CRON-QUERY] Failed to persist cron-push-map:`, err);
48
+ });
41
49
  break;
42
50
  case "update":
43
51
  result = await callGatewayTool("cron.update", { timeoutMs: GATEWAY_TIMEOUT_MS }, {
@@ -62,17 +70,17 @@ export async function handleCronQueryEvent(context, cfg) {
62
70
  break;
63
71
  default:
64
72
  error = `Unknown action: ${context.action}`;
65
- logger.error(`[CRON-QUERY] ${error}`);
73
+ log.error(`[CRON-QUERY] ${error}`);
66
74
  result = { error };
67
75
  }
68
76
  }
69
77
  catch (err) {
70
78
  error = err instanceof Error ? err.message : String(err);
71
- logger.error(`[CRON-QUERY] RPC call failed for action=${action}:`, err);
79
+ log.error(`[CRON-QUERY] RPC call failed for action=${action}:`, err);
72
80
  result = { error };
73
81
  }
74
82
  // Log the result
75
- logger.log(`[CRON-QUERY] RPC result for action=${action}: ${JSON.stringify(result, null, 2)}`);
83
+ log.log(`[CRON-QUERY] RPC result for action=${action}: ${JSON.stringify(result, null, 2)}`);
76
84
  // Send result back via sendCommand as System.CronQuery with payload.ans
77
85
  if (cfg && sessionId && taskId && messageId) {
78
86
  try {
@@ -93,17 +101,46 @@ export async function handleCronQueryEvent(context, cfg) {
93
101
  taskId,
94
102
  messageId,
95
103
  command,
96
- final: true,
104
+ final: sessionId.toLowerCase().endsWith("cronquery"),
97
105
  });
98
- logger.log(`[CRON-QUERY] Sent response via sendCommand, action=${action}`);
106
+ log.log(`[CRON-QUERY] Sent response via sendCommand, action=${action}`);
99
107
  }
100
108
  catch (sendErr) {
101
- logger.error(`[CRON-QUERY] Failed to send response via sendCommand:`, sendErr);
109
+ log.error(`[CRON-QUERY] Failed to send response via sendCommand:`, sendErr);
102
110
  }
103
111
  }
104
112
  else {
105
- logger.warn(`[CRON-QUERY] Missing cfg/sessionId/taskId/messageId, skipping sendCommand`);
113
+ log.warn(`[CRON-QUERY] Missing cfg/sessionId/taskId/messageId, skipping sendCommand`);
114
+ }
115
+ }
116
+ /**
117
+ * 从 cron.add 结果中提取 jobId,配合 sessionId 对应的 pushId 写入映射。
118
+ */
119
+ async function persistCronPushMap(sessionId, result) {
120
+ logger.log(`[CRONMAP] cron-query persist: sessionId=${sessionId ?? "(none)"}, resultType=${typeof result}`);
121
+ if (!sessionId) {
122
+ logger.log(`[CRONMAP] cron-query skip: no sessionId in context`);
123
+ return;
124
+ }
125
+ let jobId;
126
+ if (result && typeof result === "object") {
127
+ const id = result.id;
128
+ if (typeof id === "string" && id.trim())
129
+ jobId = id.trim();
130
+ }
131
+ if (!jobId) {
132
+ const preview = typeof result === "string" ? result.slice(0, 200) : JSON.stringify(result)?.slice(0, 200);
133
+ logger.log(`[CRONMAP] cron-query skip: no jobId in result. preview=${preview ?? "(empty)"}`);
134
+ return;
135
+ }
136
+ const pushId = configManager.getPushId(sessionId);
137
+ if (!pushId) {
138
+ logger.log(`[CRONMAP] cron-query skip: configManager has no pushId for sessionId=${sessionId}`);
139
+ return;
106
140
  }
141
+ logger.log(`[CRONMAP] cron-query writing map: jobId=${jobId}, pushId=${pushId.substring(0, 16)}...`);
142
+ await setJobPushId(jobId, { pushId, sessionId, source: "cron-query" });
143
+ logger.log(`[CRONMAP] cron-query map written OK`);
107
144
  }
108
145
  /**
109
146
  * Read local cron folder directly (bypassing openclaw RPC) and return