openclaw-openagent 1.0.1 → 1.0.3

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 (188) hide show
  1. package/dist/index.d.ts +25 -0
  2. package/dist/index.js +105 -0
  3. package/dist/src/app/channel-tools.d.ts +28 -0
  4. package/dist/src/app/channel-tools.js +251 -0
  5. package/dist/src/app/discovery-tools.d.ts +35 -0
  6. package/dist/src/app/discovery-tools.js +243 -0
  7. package/dist/src/app/download-file-tool.d.ts +10 -0
  8. package/dist/src/app/download-file-tool.js +104 -0
  9. package/dist/src/app/hooks.d.ts +14 -0
  10. package/dist/src/app/hooks.js +118 -0
  11. package/dist/src/app/index.d.ts +13 -0
  12. package/dist/src/app/index.js +44 -0
  13. package/dist/src/app/messaging-tools.d.ts +11 -0
  14. package/dist/src/app/messaging-tools.js +79 -0
  15. package/dist/src/app/ops-tools.d.ts +21 -0
  16. package/dist/src/app/ops-tools.js +158 -0
  17. package/dist/src/app/remote-agent-tool.d.ts +27 -0
  18. package/dist/src/app/remote-agent-tool.js +461 -0
  19. package/dist/src/app/types.d.ts +61 -0
  20. package/dist/src/app/types.js +11 -0
  21. package/dist/src/app/upload-file-tool.d.ts +16 -0
  22. package/dist/src/app/upload-file-tool.js +353 -0
  23. package/dist/src/app/verbose-preflight.d.ts +2 -0
  24. package/dist/src/app/verbose-preflight.js +145 -0
  25. package/dist/src/auth/config.d.ts +79 -0
  26. package/dist/src/auth/config.js +133 -0
  27. package/dist/src/auth/credential-manager.d.ts +65 -0
  28. package/dist/src/auth/credential-manager.js +122 -0
  29. package/dist/src/auth/index.d.ts +6 -0
  30. package/dist/src/auth/index.js +6 -0
  31. package/dist/src/auth/verify.d.ts +42 -0
  32. package/dist/src/auth/verify.js +60 -0
  33. package/dist/src/channel.d.ts +269 -0
  34. package/dist/src/channel.js +488 -0
  35. package/dist/src/compat.d.ts +37 -0
  36. package/dist/src/compat.js +70 -0
  37. package/dist/src/config/config-schema.d.ts +56 -0
  38. package/dist/src/config/config-schema.js +34 -0
  39. package/dist/src/messaging/aggregator.d.ts +25 -0
  40. package/dist/src/messaging/aggregator.js +90 -0
  41. package/dist/src/messaging/collector.d.ts +27 -0
  42. package/dist/src/messaging/collector.js +76 -0
  43. package/dist/src/messaging/executor.d.ts +14 -0
  44. package/dist/src/messaging/executor.js +59 -0
  45. package/dist/src/messaging/inbound.d.ts +97 -0
  46. package/dist/src/messaging/inbound.js +63 -0
  47. package/dist/src/messaging/index.d.ts +10 -0
  48. package/dist/src/messaging/index.js +9 -0
  49. package/dist/src/messaging/mention-protocol.d.ts +42 -0
  50. package/dist/src/messaging/mention-protocol.js +74 -0
  51. package/dist/src/messaging/process-c2c-request.d.ts +55 -0
  52. package/dist/src/messaging/process-c2c-request.js +445 -0
  53. package/dist/src/messaging/process-message.d.ts +62 -0
  54. package/dist/src/messaging/process-message.js +282 -0
  55. package/dist/src/messaging/scheduler.d.ts +17 -0
  56. package/dist/src/messaging/scheduler.js +47 -0
  57. package/dist/src/messaging/types.d.ts +34 -0
  58. package/dist/src/messaging/types.js +4 -0
  59. package/dist/src/plugin-ui/assets/openagent-override.js +9278 -0
  60. package/dist/src/plugin-ui/index.d.ts +13 -0
  61. package/dist/src/plugin-ui/index.js +16 -0
  62. package/dist/src/plugin-ui/ui-extension-loader/backup.d.ts +23 -0
  63. package/dist/src/plugin-ui/ui-extension-loader/backup.js +82 -0
  64. package/dist/src/plugin-ui/ui-extension-loader/index.d.ts +28 -0
  65. package/dist/src/plugin-ui/ui-extension-loader/index.js +240 -0
  66. package/dist/src/plugin-ui/ui-extension-loader/locator.d.ts +35 -0
  67. package/dist/src/plugin-ui/ui-extension-loader/locator.js +129 -0
  68. package/dist/src/plugin-ui/ui-extension-loader/manifest.d.ts +26 -0
  69. package/dist/src/plugin-ui/ui-extension-loader/manifest.js +45 -0
  70. package/dist/src/plugin-ui/ui-extension-loader/registry-regex.d.ts +9 -0
  71. package/dist/src/plugin-ui/ui-extension-loader/registry-regex.js +724 -0
  72. package/dist/src/plugin-ui/ui-extension-loader/removed-extensions.d.ts +8 -0
  73. package/dist/src/plugin-ui/ui-extension-loader/removed-extensions.js +58 -0
  74. package/dist/src/plugin-ui/ui-extension-loader/types.d.ts +55 -0
  75. package/dist/src/plugin-ui/ui-extension-loader/types.js +23 -0
  76. package/dist/src/proxy/auth-proxy.d.ts +20 -0
  77. package/dist/src/proxy/auth-proxy.js +337 -0
  78. package/dist/src/runtime/account.d.ts +156 -0
  79. package/dist/src/runtime/account.js +491 -0
  80. package/dist/src/runtime/index.d.ts +5 -0
  81. package/dist/src/runtime/index.js +6 -0
  82. package/dist/src/runtime/plugin-runtime.d.ts +40 -0
  83. package/dist/src/runtime/plugin-runtime.js +72 -0
  84. package/dist/src/runtime/registry.d.ts +41 -0
  85. package/dist/src/runtime/registry.js +60 -0
  86. package/dist/src/sdk/CLASS_MAP.md +143 -0
  87. package/dist/src/sdk/index.d.ts +126 -0
  88. package/dist/src/sdk/index.js +23990 -0
  89. package/dist/src/sdk/modules/cloud-search-module.js +1117 -0
  90. package/dist/src/sdk/modules/follow-module.js +1069 -0
  91. package/dist/src/sdk/modules/group-module.js +7397 -0
  92. package/dist/src/sdk/modules/relationship-module.js +2269 -0
  93. package/dist/src/sdk/modules/signaling-module.js +1468 -0
  94. package/dist/src/sdk/modules/tim-upload-plugin.js +730 -0
  95. package/dist/src/sdk/node-env/http-request.js +90 -0
  96. package/dist/src/sdk/node-env/index.js +57 -0
  97. package/dist/src/sdk/node-env/storage.js +114 -0
  98. package/dist/src/sdk/package.json +10 -0
  99. package/dist/src/sdk/sdk/CLASS_MAP.md +143 -0
  100. package/dist/src/sdk/sdk/index.d.ts +126 -0
  101. package/dist/src/sdk/sdk/index.js +23990 -0
  102. package/dist/src/sdk/sdk/modules/cloud-search-module.js +1117 -0
  103. package/dist/src/sdk/sdk/modules/follow-module.js +1069 -0
  104. package/dist/src/sdk/sdk/modules/group-module.js +7397 -0
  105. package/dist/src/sdk/sdk/modules/relationship-module.js +2269 -0
  106. package/dist/src/sdk/sdk/modules/signaling-module.js +1468 -0
  107. package/dist/src/sdk/sdk/modules/tim-upload-plugin.js +730 -0
  108. package/dist/src/sdk/sdk/node-env/http-request.js +90 -0
  109. package/dist/src/sdk/sdk/node-env/index.js +57 -0
  110. package/dist/src/sdk/sdk/node-env/storage.js +114 -0
  111. package/dist/src/sdk/sdk/package.json +10 -0
  112. package/dist/src/sdk/sdk/tsconfig.json +16 -0
  113. package/dist/src/sdk/tsconfig.json +16 -0
  114. package/dist/src/state/pending-invocation-store.d.ts +26 -0
  115. package/dist/src/state/pending-invocation-store.js +39 -0
  116. package/dist/src/state/store.d.ts +165 -0
  117. package/dist/src/state/store.js +535 -0
  118. package/dist/src/tim/c2c.d.ts +83 -0
  119. package/dist/src/tim/c2c.js +318 -0
  120. package/dist/src/tim/channels.d.ts +95 -0
  121. package/dist/src/tim/channels.js +279 -0
  122. package/dist/src/tim/client.d.ts +54 -0
  123. package/dist/src/tim/client.js +268 -0
  124. package/dist/src/tim/index.d.ts +6 -0
  125. package/dist/src/tim/index.js +6 -0
  126. package/dist/src/tim/messages.d.ts +50 -0
  127. package/dist/src/tim/messages.js +104 -0
  128. package/dist/src/tim/sdk-logger-init.d.ts +13 -0
  129. package/dist/src/tim/sdk-logger-init.js +46 -0
  130. package/dist/src/tools.d.ts +9 -0
  131. package/dist/src/tools.js +8 -0
  132. package/dist/src/transport/factory.d.ts +63 -0
  133. package/dist/src/transport/factory.js +54 -0
  134. package/dist/src/transport/oasn/index.d.ts +12 -0
  135. package/dist/src/transport/oasn/index.js +9 -0
  136. package/dist/src/transport/oasn/oasn-agent-card.d.ts +38 -0
  137. package/dist/src/transport/oasn/oasn-agent-card.js +102 -0
  138. package/dist/src/transport/oasn/oasn-discovery.d.ts +33 -0
  139. package/dist/src/transport/oasn/oasn-discovery.js +97 -0
  140. package/dist/src/transport/oasn/oasn-files.d.ts +64 -0
  141. package/dist/src/transport/oasn/oasn-files.js +174 -0
  142. package/dist/src/transport/oasn/oasn-http.d.ts +98 -0
  143. package/dist/src/transport/oasn/oasn-http.js +362 -0
  144. package/dist/src/transport/oasn/oasn-invocation.d.ts +154 -0
  145. package/dist/src/transport/oasn/oasn-invocation.js +432 -0
  146. package/dist/src/transport/oasn/oasn-normalize.d.ts +6 -0
  147. package/dist/src/transport/oasn/oasn-normalize.js +112 -0
  148. package/dist/src/transport/oasn/oasn-register.d.ts +19 -0
  149. package/dist/src/transport/oasn/oasn-register.js +24 -0
  150. package/dist/src/transport/oasn/oasn-transport.d.ts +114 -0
  151. package/dist/src/transport/oasn/oasn-transport.js +230 -0
  152. package/dist/src/transport/oasn/oasn-types.d.ts +331 -0
  153. package/dist/src/transport/oasn/oasn-types.js +44 -0
  154. package/dist/src/transport/tim/index.d.ts +7 -0
  155. package/dist/src/transport/tim/index.js +6 -0
  156. package/dist/src/transport/tim/tim-transport.d.ts +122 -0
  157. package/dist/src/transport/tim/tim-transport.js +402 -0
  158. package/dist/src/transport/types.d.ts +450 -0
  159. package/dist/src/transport/types.js +38 -0
  160. package/dist/src/util/http.d.ts +21 -0
  161. package/dist/src/util/http.js +93 -0
  162. package/dist/src/util/logger.d.ts +20 -0
  163. package/dist/src/util/logger.js +100 -0
  164. package/dist/src/util/url-resolver.d.ts +7 -0
  165. package/dist/src/util/url-resolver.js +20 -0
  166. package/index.ts +11 -0
  167. package/openclaw.plugin.json +9 -0
  168. package/package.json +7 -4
  169. package/src/app/download-file-tool.ts +133 -0
  170. package/src/app/hooks.ts +89 -5
  171. package/src/app/index.ts +6 -0
  172. package/src/app/remote-agent-tool.ts +46 -0
  173. package/src/app/types.ts +1 -0
  174. package/src/app/upload-file-tool.ts +411 -0
  175. package/src/plugin-ui/assets/openagent-override.js +15 -66
  176. package/src/plugin-ui/modules/agent-book/panel/agent-book.js +0 -61
  177. package/src/plugin-ui/modules/agent-book/panel/agent-data.js +0 -1
  178. package/src/plugin-ui/modules/agent-book/panel/inject-ui.js +14 -3
  179. package/src/plugin-ui/ui-extension-loader/registry-regex.ts +102 -63
  180. package/src/runtime/account.ts +0 -23
  181. package/src/transport/oasn/oasn-files.ts +5 -5
  182. package/src/transport/oasn/oasn-invocation.ts +44 -2
  183. package/src/transport/oasn/oasn-normalize.ts +0 -26
  184. package/src/transport/oasn/oasn-register.ts +8 -81
  185. package/src/transport/oasn/oasn-transport.ts +9 -32
  186. package/src/transport/oasn/oasn-types.ts +53 -6
  187. package/src/transport/types.ts +33 -36
  188. package/src/util/url-resolver.ts +17 -0
@@ -0,0 +1,445 @@
1
+ /**
2
+ * Process C2C Request — Remote agent task request handler (T3)
3
+ *
4
+ * ⚠️ TIM-only 路径(v3.9+ 双轨抽象)
5
+ * ---------------------------------------------------------
6
+ * 本文件只在 transport='tim' 下被 AccountRuntime._connectTIM() 通过
7
+ * `this.client.on('c2c_request', ...)` 注册。OASN 路径下 AccountRuntime
8
+ * 不会监听 c2c_request 事件 —— OASN ClientAgent 是消费侧,不接收外来 Invocation,
9
+ * 远程 Agent 调用统一由发起方走 transport.sendTask / waitForTaskResult 完成。
10
+ *
11
+ * Handles incoming `c2c_request` events from c2c.ts (T1).
12
+ * Mirrors the process-message.ts pattern but for C2C task requests:
13
+ *
14
+ * 1. Parse request parameters (from, requestId, task, sessionMode)
15
+ * 2. Compute sessionKey (aligned with OpenClaw buildAgentPeerSessionKey)
16
+ * 3. Register onAgentEvent listener ({openagent_progress} prefix filter)
17
+ * 4. Build MsgContext (adapted for C2C, not group)
18
+ * 5. channelRuntime pipeline: resolveAgentRoute → finalize → record → dispatch
19
+ * 6. deliver callback routes kind="block" → progress, kind="final" → result
20
+ * 7. Unsubscribe onAgentEvent listener
21
+ *
22
+ * @see docs/specs/2026-06-16-oasn-transport-abstraction-design.md §4.2
23
+ * @see docs/products/orchestrator/specs/T3-remote-handler.md
24
+ * @see docs/products/orchestrator/specs/T1-c2c-infra.md §6.2 (c2c_request emit)
25
+ */
26
+ import { randomUUID } from 'node:crypto';
27
+ import fs from 'node:fs';
28
+ import nodePath from 'node:path';
29
+ import { ZipFile } from 'yazl';
30
+ import { sendC2CCustomMessage } from '../tim/c2c.js';
31
+ import { getOpenagentPluginRuntime } from '../runtime/plugin-runtime.js';
32
+ import { registry } from '../runtime/registry.js';
33
+ import { logger } from '../util/logger.js';
34
+ // ── Progress prefix constant ──
35
+ /**
36
+ * Marker prefix for tool progress messages.
37
+ * Remote developers add this prefix to onUpdate() calls to opt-in
38
+ * to progress forwarding via OpenAgent C2C.
39
+ *
40
+ * @see T3-remote-handler.md §9.1.2
41
+ */
42
+ const PROGRESS_PREFIX = '{openagent_progress}';
43
+ // ── Directory → ZIP helper ──
44
+ /**
45
+ * Recursively zip a directory into a .zip file.
46
+ * Returns the path to the created zip file in /tmp/openclaw/openagent-media/.
47
+ *
48
+ * Uses yazl (pure JS, ~75KB) for cross-platform zip creation.
49
+ * The zip preserves directory structure with relative paths.
50
+ */
51
+ function zipDirectory(dirPath) {
52
+ return new Promise((resolve, reject) => {
53
+ const dirName = nodePath.basename(dirPath);
54
+ const tmpDir = '/tmp/openclaw/openagent-media';
55
+ fs.mkdirSync(tmpDir, { recursive: true });
56
+ const zipPath = nodePath.join(tmpDir, `${Date.now()}-${dirName}.zip`);
57
+ const zipfile = new ZipFile();
58
+ // Recursively add all files
59
+ const addDir = (currentPath, prefix) => {
60
+ const entries = fs.readdirSync(currentPath, { withFileTypes: true });
61
+ for (const entry of entries) {
62
+ const fullPath = nodePath.join(currentPath, entry.name);
63
+ const arcPath = prefix ? `${prefix}/${entry.name}` : entry.name;
64
+ if (entry.isDirectory()) {
65
+ addDir(fullPath, arcPath);
66
+ }
67
+ else if (entry.isFile()) {
68
+ zipfile.addFile(fullPath, arcPath);
69
+ }
70
+ }
71
+ };
72
+ addDir(dirPath, dirName);
73
+ zipfile.end();
74
+ const output = fs.createWriteStream(zipPath);
75
+ zipfile.outputStream.pipe(output);
76
+ output.on('close', () => {
77
+ logger.info(`[c2c-request] T4: zipped directory ${dirName}/ → ${zipPath} (${fs.statSync(zipPath).size} bytes)`);
78
+ resolve(zipPath);
79
+ });
80
+ output.on('error', reject);
81
+ zipfile.outputStream.on('error', reject);
82
+ });
83
+ }
84
+ // ── Core processing ──
85
+ /**
86
+ * Process a single incoming C2C task request through the standard
87
+ * OpenClaw channelRuntime pipeline.
88
+ *
89
+ * This is the T3 equivalent of processOneMessage (process-message.ts).
90
+ * Fire-and-forget safe — errors are caught and result in an error C2C reply.
91
+ */
92
+ export async function processC2CRequest(request, deps) {
93
+ const { from: fromUserId, payload, time } = request;
94
+ const { request_id: requestId, task, session_mode: sessionMode } = payload;
95
+ logger.info(`[c2c-request] Incoming task: from=${fromUserId} requestId=${requestId} mode=${sessionMode} taskLen=${task.length}`);
96
+ // ① Validate
97
+ if (!fromUserId || !requestId || !task) {
98
+ logger.error(`[c2c-request] Invalid request: missing required fields`);
99
+ await sendErrorResult(fromUserId, requestId, 'Invalid request: missing required fields');
100
+ return;
101
+ }
102
+ // ② Compute sessionKey — aligned with OpenClaw buildAgentPeerSessionKey
103
+ // Format: agent:{agentId}:{channel}:{peerKind}:{peerId}
104
+ // @see T1-c2c-infra.md §3.1 sessionKey naming convention
105
+ const agentId = 'main'; // Default agent ID; multi-agent is P1 (T3 §9.2)
106
+ // buildAgentPeerSessionKey (session-key-DAhnzjyr.js L211) lowercases peerId.
107
+ // Must match exactly for onAgentEvent sessionKey filtering to work.
108
+ const normalizedFrom = fromUserId.toLowerCase();
109
+ const sessionKey = sessionMode === 'run'
110
+ ? `agent:${agentId}:openagent:remote:${normalizedFrom}:run:${requestId}`
111
+ : `agent:${agentId}:openagent:remote:${normalizedFrom}`;
112
+ logger.debug(`[c2c-request] sessionKey=${sessionKey}`);
113
+ // ③ Register onAgentEvent listener for {openagent_progress} prefix
114
+ // Must be BEFORE dispatchReplyFromConfig — otherwise tool events are missed.
115
+ //
116
+ // Filter by runId (NOT sessionKey). OpenClaw sets isControlUiVisible=false
117
+ // for external channels like OpenAgent, which causes emitAgentEvent to strip
118
+ // sessionKey to undefined. runId is always preserved.
119
+ // @see audit/021-progress-pipeline-v1.md §4 (root cause)
120
+ const runId = randomUUID();
121
+ logger.debug(`[c2c-request] generated runId=${runId} for requestId=${requestId}`);
122
+ let unsubscribe = null;
123
+ try {
124
+ const runtime = getOpenagentPluginRuntime();
125
+ unsubscribe = runtime.events.onAgentEvent((evt) => {
126
+ if (evt.runId !== runId)
127
+ return;
128
+ if (evt.stream !== 'tool' || evt.data.phase !== 'update')
129
+ return;
130
+ // partialResult is AgentToolResult object: { content: [{ type: "text", text: "..." }] }
131
+ // Source: sanitizeToolResult (L173042-173071) returns same structure.
132
+ // OpenAgent toolResult() (types.ts L51-53): { content: [{ type: 'text', text }] }
133
+ const pr = evt.data.partialResult;
134
+ let raw;
135
+ if (pr && typeof pr === 'object' && Array.isArray(pr.content)) {
136
+ raw = pr.content.find((c) => c?.type === 'text')?.text ?? '';
137
+ }
138
+ else {
139
+ raw = String(pr ?? '');
140
+ }
141
+ if (!raw.startsWith(PROGRESS_PREFIX))
142
+ return; // No prefix → discard
143
+ const content = raw.slice(PROGRESS_PREFIX.length).trim();
144
+ if (!content)
145
+ return;
146
+ logger.info(`[c2c-request] Tool progress: requestId=${requestId} runId=${runId} content=${content.slice(0, 80)}`);
147
+ // Send via same TIM C2C path as deliver callback
148
+ void sendC2CCustomMessage(fromUserId, {
149
+ type: 'openagent_task_progress',
150
+ request_id: requestId,
151
+ content,
152
+ }).catch((err) => {
153
+ logger.error(`[c2c-request] Failed to send tool progress: ${err.message}`);
154
+ });
155
+ });
156
+ }
157
+ catch (err) {
158
+ // If PluginRuntime isn't available, continue without progress monitoring
159
+ logger.warn(`[c2c-request] Could not register onAgentEvent: ${err.message}`);
160
+ }
161
+ try {
162
+ const { channelRuntime, config, accountId } = deps;
163
+ // ④ Build MsgContext for C2C request
164
+ // NOT using timMessageToMsgContext — that's for group messages (ChatType='group').
165
+ // C2C requests are a different chat type.
166
+ const msgContext = {
167
+ // Message body
168
+ Body: task,
169
+ BodyForAgent: task,
170
+ RawBody: task,
171
+ CommandBody: task,
172
+ // Routing
173
+ From: fromUserId,
174
+ To: fromUserId, // C2C: destination is the sender (reply goes back to them)
175
+ AccountId: accountId,
176
+ // Sender info
177
+ SenderId: fromUserId,
178
+ SenderName: fromUserId,
179
+ // Conversation label
180
+ ConversationLabel: `openagent:remote:${fromUserId}`,
181
+ GroupSubject: '',
182
+ // Channel metadata
183
+ OriginatingChannel: 'openagent',
184
+ OriginatingTo: fromUserId,
185
+ MessageSid: `c2c:${requestId}`,
186
+ Timestamp: time * 1000, // TIM time is seconds, OpenClaw expects ms
187
+ Provider: 'openagent',
188
+ Surface: 'openagent',
189
+ ChatType: 'direct', // NOT 'group' — this is a C2C request
190
+ // Session
191
+ SessionKey: sessionKey,
192
+ // No mention, no history for C2C requests
193
+ WasMentioned: true, // Always process (no mention gating for C2C)
194
+ };
195
+ // ⑤ Agent routing
196
+ const route = channelRuntime.routing.resolveAgentRoute({
197
+ cfg: config,
198
+ channel: 'openagent',
199
+ accountId,
200
+ peer: { kind: 'remote', id: fromUserId },
201
+ });
202
+ logger.debug(`[c2c-request] route: agentId=${route.agentId ?? '(none)'} sessionKey=${route.sessionKey ?? '(none)'}`);
203
+ // Use our computed sessionKey, not the route's
204
+ // (route may return a different key for group-based routing)
205
+ msgContext.SessionKey = sessionKey;
206
+ // ⑤ Finalize inbound context
207
+ const finalized = channelRuntime.reply.finalizeInboundContext(msgContext);
208
+ // ⑤ Record inbound session
209
+ const storePath = channelRuntime.session.resolveStorePath(config.session?.store, { agentId: route.agentId || agentId });
210
+ await channelRuntime.session.recordInboundSession({
211
+ storePath,
212
+ sessionKey,
213
+ ctx: finalized,
214
+ updateLastRoute: {
215
+ sessionKey: route.mainSessionKey || sessionKey,
216
+ channel: 'openagent',
217
+ to: fromUserId,
218
+ accountId,
219
+ },
220
+ onRecordError: (err) => logger.error(`[c2c-request] recordInboundSession error: ${String(err)}`),
221
+ });
222
+ // ⑥ Create reply dispatcher + dispatch AI reply
223
+ const { dispatcher, replyOptions, markDispatchIdle } = channelRuntime.reply.createReplyDispatcherWithTyping({
224
+ deliver: async (deliverPayload, deliverMeta) => {
225
+ const text = deliverPayload.text ?? '';
226
+ const kind = deliverMeta?.kind;
227
+ if (kind === 'block') {
228
+ // LLM streaming text → C2C progress (unchanged)
229
+ if (!text)
230
+ return;
231
+ logger.debug(`[c2c-request] deliver block: requestId=${requestId} textLen=${text.length}`);
232
+ await sendC2CCustomMessage(fromUserId, {
233
+ type: 'openagent_task_progress',
234
+ request_id: requestId,
235
+ content: text,
236
+ });
237
+ }
238
+ // kind="tool" → skip. Remote LLM will summarize tool data into natural language.
239
+ if (kind === 'final') {
240
+ // ── T4: File detection + upload ──
241
+ // Collect file paths from two sources:
242
+ // Path A: deliverPayload.mediaUrls (tool results, e.g. image_generate)
243
+ // Path B: {openagent_file} text markers (skill scripts)
244
+ const filePaths = [];
245
+ // Path A: structured mediaUrls from OpenClaw delivery pipeline
246
+ if (deliverPayload.mediaUrls) {
247
+ for (const u of deliverPayload.mediaUrls) {
248
+ if (u)
249
+ filePaths.push(u);
250
+ }
251
+ }
252
+ if (deliverPayload.mediaUrl) {
253
+ filePaths.push(deliverPayload.mediaUrl);
254
+ }
255
+ // Path B: {openagent_file} text markers
256
+ let cleanText = text;
257
+ const fileMarkerRegex = /\{openagent_file:([^}]+)\}/g;
258
+ let match;
259
+ while ((match = fileMarkerRegex.exec(text)) !== null) {
260
+ const markerPath = match[1];
261
+ filePaths.push(markerPath);
262
+ cleanText = cleanText.replace(match[0], '').trim();
263
+ }
264
+ const tripDataPath = findTripCardDataFile(text);
265
+ if (tripDataPath && !filePaths.includes(tripDataPath)) {
266
+ filePaths.push(tripDataPath);
267
+ logger.info(`[c2c-request] T4: attaching trip card data ${tripDataPath}`);
268
+ }
269
+ // Upload files via TIM C2C (TIMFileElem) — before sending text result
270
+ let fileCount = 0;
271
+ if (filePaths.length > 0) {
272
+ logger.info(`[c2c-request] T4: ${filePaths.length} file(s) detected for requestId=${requestId}`);
273
+ const rt = registry.getDefault();
274
+ const chat = rt?.client?._chat;
275
+ const types = rt?.client?._types;
276
+ if (chat && types && rt?.client?.isReady) {
277
+ const fs = await import('node:fs');
278
+ const nodePath = await import('node:path');
279
+ for (let filePath of filePaths) {
280
+ try {
281
+ if (!fs.existsSync(filePath)) {
282
+ logger.warn(`[c2c-request] T4: file not found, skip: ${filePath}`);
283
+ continue;
284
+ }
285
+ // T4: If path is a directory, zip it first
286
+ if (fs.statSync(filePath).isDirectory()) {
287
+ logger.info(`[c2c-request] T4: path is directory, zipping: ${filePath}`);
288
+ filePath = await zipDirectory(filePath);
289
+ }
290
+ const buffer = fs.readFileSync(filePath);
291
+ const fileName = nodePath.basename(filePath);
292
+ const file = new File([buffer], fileName);
293
+ // TIM SDK expects payload.file to behave like an HTMLInputElement
294
+ // with a .files property (FileList). Node.js File doesn't have this.
295
+ // Wrap in a shim: { files: [File] } to satisfy SDK's internal check
296
+ // at createFileMessage → _isEmptyFileList(s.file.files).
297
+ const fileShim = { files: [file] };
298
+ logger.info(`[c2c-request] T4: uploading ${fileName} (${buffer.byteLength} bytes) to ${fromUserId}`);
299
+ const fileMsg = chat.createFileMessage({
300
+ to: fromUserId,
301
+ conversationType: types.CONV_C2C,
302
+ payload: { file: fileShim },
303
+ });
304
+ await chat.sendMessage(fileMsg);
305
+ fileCount++;
306
+ logger.info(`[c2c-request] T4: file sent OK: ${fileName}`);
307
+ }
308
+ catch (fileErr) {
309
+ logger.error(`[c2c-request] T4: file upload failed: ${fileErr.message} path=${filePath}`);
310
+ }
311
+ }
312
+ }
313
+ else {
314
+ logger.warn(`[c2c-request] T4: TIM SDK not ready, skipping file upload`);
315
+ }
316
+ }
317
+ // Send text result (with file_count for receiver coordination)
318
+ const finalText = filePaths.length > 0 ? cleanText : text;
319
+ if (finalText || fileCount > 0) {
320
+ logger.info(`[c2c-request] deliver final: requestId=${requestId} textLen=${finalText.length} files=${fileCount}`);
321
+ await sendC2CCustomMessage(fromUserId, {
322
+ type: 'openagent_task_result',
323
+ request_id: requestId,
324
+ status: 'complete',
325
+ content: finalText || '(file transfer)',
326
+ file_count: fileCount,
327
+ });
328
+ }
329
+ }
330
+ },
331
+ onError: (err, info) => {
332
+ logger.error(`[c2c-request] reply ${info.kind} error: ${String(err)}`);
333
+ },
334
+ });
335
+ logger.debug(`[c2c-request] dispatching AI turn for requestId=${requestId}`);
336
+ try {
337
+ await channelRuntime.reply.withReplyDispatcher({
338
+ dispatcher,
339
+ run: () => channelRuntime.reply.dispatchReplyFromConfig({
340
+ ctx: finalized,
341
+ cfg: config,
342
+ dispatcher,
343
+ replyOptions: { ...replyOptions, runId },
344
+ }),
345
+ });
346
+ logger.info(`[c2c-request] AI turn completed for requestId=${requestId}`);
347
+ }
348
+ catch (err) {
349
+ logger.error(`[c2c-request] dispatchReplyFromConfig error: ${err.message}`);
350
+ await sendErrorResult(fromUserId, requestId, err.message);
351
+ }
352
+ finally {
353
+ markDispatchIdle();
354
+ }
355
+ }
356
+ catch (err) {
357
+ // Top-level error → send error result to requester
358
+ logger.error(`[c2c-request] Fatal error processing request: ${err.message}`);
359
+ await sendErrorResult(fromUserId, requestId, err.message);
360
+ }
361
+ finally {
362
+ // ⑦ Always unsubscribe onAgentEvent listener
363
+ if (unsubscribe) {
364
+ unsubscribe();
365
+ logger.debug(`[c2c-request] onAgentEvent listener unsubscribed for requestId=${requestId}`);
366
+ }
367
+ }
368
+ }
369
+ // ── Helpers ──
370
+ /**
371
+ * Send an error result back to the requesting agent.
372
+ * Best-effort — if this fails, we just log.
373
+ */
374
+ async function sendErrorResult(toUserId, requestId, errorMessage) {
375
+ try {
376
+ await sendC2CCustomMessage(toUserId, {
377
+ type: 'openagent_task_result',
378
+ request_id: requestId,
379
+ status: 'error',
380
+ content: errorMessage,
381
+ });
382
+ }
383
+ catch (err) {
384
+ logger.error(`[c2c-request] Failed to send error result: ${err.message}`);
385
+ }
386
+ }
387
+ function findTripCardDataFile(text) {
388
+ if (!text || !hasTripCardTags(text))
389
+ return null;
390
+ const candidates = getControlUiCandidates().flatMap((dir) => [
391
+ nodePath.join(dir, 'trip-card-data.json'),
392
+ nodePath.join(dir, 'ctrip-card-data.json'),
393
+ ]);
394
+ const cardIds = extractTripCardIds(text);
395
+ for (const candidate of candidates) {
396
+ if (!fs.existsSync(candidate))
397
+ continue;
398
+ if (cardIds.length === 0 || tripDataMatches(candidate, cardIds)) {
399
+ return candidate;
400
+ }
401
+ }
402
+ logger.warn(`[c2c-request] Trip card tags found but no matching trip-card-data.json was available`);
403
+ return null;
404
+ }
405
+ function hasTripCardTags(text) {
406
+ return /<(?:sh_card|tr_card|i_card|la_card|bg_card|fr_card|time_data_card)>/i.test(text)
407
+ || /\[TRIP_CARDS_READY\]|\[CTRIP_CARDS_READY\]/.test(text);
408
+ }
409
+ function extractTripCardIds(text) {
410
+ const ids = new Set();
411
+ const re = /<(?:tr_card|i_card|la_card)>([\s\S]*?)<\/(?:tr_card|i_card|la_card)>/gi;
412
+ let match;
413
+ while ((match = re.exec(text)) !== null) {
414
+ const id = match[1]?.trim();
415
+ if (id)
416
+ ids.add(id);
417
+ }
418
+ return Array.from(ids);
419
+ }
420
+ function tripDataMatches(filePath, ids) {
421
+ try {
422
+ const raw = fs.readFileSync(filePath, 'utf8');
423
+ return ids.some((id) => raw.includes(id));
424
+ }
425
+ catch {
426
+ return false;
427
+ }
428
+ }
429
+ function getControlUiCandidates() {
430
+ const dirs = new Set();
431
+ const argvEntry = process.argv[1] || '';
432
+ if (argvEntry) {
433
+ dirs.add(nodePath.join(nodePath.dirname(argvEntry), 'control-ui'));
434
+ }
435
+ dirs.add(nodePath.join(process.cwd(), 'dist', 'control-ui'));
436
+ dirs.add('/app/dist/control-ui');
437
+ return Array.from(dirs).filter((dir) => {
438
+ try {
439
+ return fs.existsSync(dir) && fs.statSync(dir).isDirectory();
440
+ }
441
+ catch {
442
+ return false;
443
+ }
444
+ });
445
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Process Message — Core inbound dispatch pipeline
3
+ *
4
+ * ⚠️ TIM-only 路径(v3.9+ 双轨抽象)
5
+ * ---------------------------------------------------------
6
+ * 仅在 transport='tim' 下被 AccountRuntime._connectTIM() 通过
7
+ * `this.client.on('message', ...)` 注册。OASN 路径下没有 WebSocket 群聊消息,
8
+ * 该 pipeline 整体不参与运行。
9
+ *
10
+ * Replaces the old 4-module pipeline (Collector→Aggregator→Scheduler→Executor)
11
+ * with OpenClaw's standard channelRuntime dispatch:
12
+ *
13
+ * 1. Self-message filter
14
+ * 2. channelRuntime safety check
15
+ * 3. Append to channel history ring buffer
16
+ * 4. Fetch group context (name, skill)
17
+ * 5. TIM → MsgContext conversion (inbound.ts) with enriched context
18
+ * 6. Agent routing (channelRuntime.routing.resolveAgentRoute)
19
+ * 7. Finalize context (channelRuntime.reply.finalizeInboundContext)
20
+ * 8. Record session (channelRuntime.session.recordInboundSession)
21
+ * 9. Create reply dispatcher (channelRuntime.reply.createReplyDispatcherWithTyping)
22
+ * 10. Dispatch AI reply (channelRuntime.reply.dispatchReplyFromConfig)
23
+ *
24
+ * v3.4.0: Added InboundHistory ring buffer and GroupSystemPrompt/GroupSubject
25
+ * injection to fix LLM NO_REPLY conversation breaks.
26
+ * See: docs/audit/008-inbound-context-gap.md
27
+ *
28
+ * Reference: docs/reference/plugins/openclaw-weixin/src/messaging/process-message.ts
29
+ */
30
+ import type { PluginRuntime } from 'openclaw/plugin-sdk/core';
31
+ import type { RawPushMessage } from '../tim/client.js';
32
+ import type { MentionMember } from './mention-protocol.js';
33
+ /** Dependencies injected by the caller (AccountRuntime). */
34
+ export interface ProcessMessageDeps {
35
+ accountId: string;
36
+ selfUserId: string;
37
+ config: Record<string, unknown>;
38
+ channelRuntime: PluginRuntime['channel'];
39
+ sendMessage: (channelId: string, text: string, atUserList?: string[]) => Promise<void>;
40
+ /** Fetch channel skill/rules (stored in TIM group notification). */
41
+ getChannelSkill?: (channelId: string) => Promise<string | null>;
42
+ /** Fetch channel display name. */
43
+ getGroupName?: (channelId: string) => Promise<string | null>;
44
+ /** Fetch a group-level custom field (AppDefinedData). */
45
+ getGroupCustomField?: (channelId: string, key: string) => Promise<string | null>;
46
+ /** Fetch group member list for mention protocol injection. */
47
+ getGroupMembers?: (channelId: string) => Promise<MentionMember[]>;
48
+ log: {
49
+ info: (msg: string) => void;
50
+ warn: (msg: string) => void;
51
+ error: (msg: string) => void;
52
+ debug: (msg: string) => void;
53
+ };
54
+ }
55
+ /**
56
+ * Process a single inbound TIM push message through the standard
57
+ * OpenClaw channelRuntime pipeline.
58
+ *
59
+ * This function is fire-and-forget safe — errors are caught and logged,
60
+ * never propagated to crash the TIM event listener.
61
+ */
62
+ export declare function processOneMessage(raw: RawPushMessage, deps: ProcessMessageDeps): Promise<void>;