@agentvault/agentvault 0.15.0 → 0.15.2

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 (65) hide show
  1. package/dist/_cp.d.ts +10 -0
  2. package/dist/_cp.d.ts.map +1 -0
  3. package/dist/cli.js +72036 -253
  4. package/dist/cli.js.map +7 -1
  5. package/dist/index.js +76351 -24
  6. package/dist/index.js.map +7 -1
  7. package/dist/openclaw-entry.js +1449 -1201
  8. package/dist/openclaw-entry.js.map +7 -1
  9. package/package.json +1 -1
  10. package/dist/__tests__/crypto-helpers.test.d.ts +0 -2
  11. package/dist/__tests__/crypto-helpers.test.d.ts.map +0 -1
  12. package/dist/__tests__/functional.test.d.ts +0 -21
  13. package/dist/__tests__/functional.test.d.ts.map +0 -1
  14. package/dist/__tests__/install-plugin.test.d.ts +0 -2
  15. package/dist/__tests__/install-plugin.test.d.ts.map +0 -1
  16. package/dist/__tests__/multi-session.test.d.ts +0 -2
  17. package/dist/__tests__/multi-session.test.d.ts.map +0 -1
  18. package/dist/__tests__/state.test.d.ts +0 -2
  19. package/dist/__tests__/state.test.d.ts.map +0 -1
  20. package/dist/__tests__/transport.test.d.ts +0 -2
  21. package/dist/__tests__/transport.test.d.ts.map +0 -1
  22. package/dist/account-config.js +0 -60
  23. package/dist/account-config.js.map +0 -1
  24. package/dist/channel.js +0 -3411
  25. package/dist/channel.js.map +0 -1
  26. package/dist/create-agent.js +0 -314
  27. package/dist/create-agent.js.map +0 -1
  28. package/dist/crypto-helpers.js +0 -4
  29. package/dist/crypto-helpers.js.map +0 -1
  30. package/dist/doctor.js +0 -415
  31. package/dist/doctor.js.map +0 -1
  32. package/dist/fetch-interceptor.js +0 -213
  33. package/dist/fetch-interceptor.js.map +0 -1
  34. package/dist/gateway-send.js +0 -114
  35. package/dist/gateway-send.js.map +0 -1
  36. package/dist/http-handlers.js +0 -131
  37. package/dist/http-handlers.js.map +0 -1
  38. package/dist/mcp-handlers.js +0 -48
  39. package/dist/mcp-handlers.js.map +0 -1
  40. package/dist/mcp-server.js +0 -192
  41. package/dist/mcp-server.js.map +0 -1
  42. package/dist/openclaw-compat.js +0 -94
  43. package/dist/openclaw-compat.js.map +0 -1
  44. package/dist/openclaw-plugin.js +0 -297
  45. package/dist/openclaw-plugin.js.map +0 -1
  46. package/dist/openclaw-types.js +0 -13
  47. package/dist/openclaw-types.js.map +0 -1
  48. package/dist/setup.js +0 -460
  49. package/dist/setup.js.map +0 -1
  50. package/dist/skill-invoker.js +0 -100
  51. package/dist/skill-invoker.js.map +0 -1
  52. package/dist/skill-manifest.js +0 -249
  53. package/dist/skill-manifest.js.map +0 -1
  54. package/dist/skill-telemetry.js +0 -146
  55. package/dist/skill-telemetry.js.map +0 -1
  56. package/dist/skills-publish.js +0 -133
  57. package/dist/skills-publish.js.map +0 -1
  58. package/dist/state.js +0 -178
  59. package/dist/state.js.map +0 -1
  60. package/dist/transport.js +0 -43
  61. package/dist/transport.js.map +0 -1
  62. package/dist/types.js +0 -2
  63. package/dist/types.js.map +0 -1
  64. package/dist/workspace-handlers.js +0 -177
  65. package/dist/workspace-handlers.js.map +0 -1
@@ -1,1262 +1,1510 @@
1
- /**
2
- * OpenClaw channel plugin entry point.
3
- *
4
- * Intentionally thin no heavy imports (libsodium etc.) at module load time.
5
- * SecureChannel is dynamically imported inside gateway.startAccount (already async)
6
- * so libsodium's top-level await never runs during plugin registration.
7
- *
8
- * Loaded by OpenClaw via the `openclaw.extensions` field in package.json.
9
- */
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // src/openclaw-compat.ts
18
+ var openclaw_compat_exports = {};
19
+ __export(openclaw_compat_exports, {
20
+ onAgentEvent: () => onAgentEvent,
21
+ onSessionTranscriptUpdate: () => onSessionTranscriptUpdate,
22
+ requestHeartbeatNow: () => requestHeartbeatNow
23
+ });
24
+ async function requestHeartbeatNow(opts) {
25
+ if (_heartbeatFn === null) {
26
+ try {
27
+ const mod = await import("openclaw/dist/plugin-sdk/infra/heartbeat-wake.js");
28
+ _heartbeatFn = mod.requestHeartbeatNow ?? mod.default?.requestHeartbeatNow ?? false;
29
+ } catch {
30
+ _heartbeatFn = false;
31
+ }
32
+ }
33
+ if (typeof _heartbeatFn === "function") {
34
+ try {
35
+ await _heartbeatFn(opts);
36
+ return true;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+ return false;
42
+ }
43
+ async function onAgentEvent(callback) {
44
+ if (_agentEventFn === null) {
45
+ try {
46
+ const mod = await import("openclaw/dist/plugin-sdk/infra/agent-events.js");
47
+ _agentEventFn = mod.onAgentEvent ?? mod.default?.onAgentEvent ?? false;
48
+ } catch {
49
+ _agentEventFn = false;
50
+ }
51
+ }
52
+ if (typeof _agentEventFn === "function") {
53
+ try {
54
+ return _agentEventFn(callback);
55
+ } catch {
56
+ return () => {
57
+ };
58
+ }
59
+ }
60
+ return () => {
61
+ };
62
+ }
63
+ async function onSessionTranscriptUpdate(callback) {
64
+ if (_transcriptFn === null) {
65
+ try {
66
+ const mod = await import("openclaw/dist/plugin-sdk/sessions/transcript-events.js");
67
+ _transcriptFn = mod.onSessionTranscriptUpdate ?? mod.default?.onSessionTranscriptUpdate ?? false;
68
+ } catch {
69
+ _transcriptFn = false;
70
+ }
71
+ }
72
+ if (typeof _transcriptFn === "function") {
73
+ try {
74
+ return _transcriptFn(callback);
75
+ } catch {
76
+ return () => {
77
+ };
78
+ }
79
+ }
80
+ return () => {
81
+ };
82
+ }
83
+ var _heartbeatFn, _agentEventFn, _transcriptFn;
84
+ var init_openclaw_compat = __esm({
85
+ "src/openclaw-compat.ts"() {
86
+ "use strict";
87
+ _heartbeatFn = null;
88
+ _agentEventFn = null;
89
+ _transcriptFn = null;
90
+ }
91
+ });
92
+
93
+ // src/openclaw-entry.ts
10
94
  import { resolve } from "node:path";
11
95
  import { randomBytes } from "node:crypto";
12
- import { listAccountIds, resolveAccount } from "./account-config.js";
13
- import { installFetchInterceptor, runWithTraceContext } from "./fetch-interceptor.js";
14
- import { handleSendRequest, handleActionRequest, handleDecisionRequest, handleStatusRequest } from "./http-handlers.js";
15
- import { requestHeartbeatNow } from "./openclaw-compat.js";
16
- // --- Runtime and active channels (set during register) ---
17
- let _ocRuntime = null;
18
- const _channels = new Map();
19
- const _messageQueue = [];
20
- // --- A2A conversation loop prevention ---
21
- // Tracks recent A2A reply timestamps per channel to prevent infinite loops.
22
- // Max replies per channel within the window, then cooldown.
23
- const A2A_MAX_REPLIES_PER_WINDOW = 4;
24
- const A2A_WINDOW_MS = 60_000; // 1-minute sliding window
25
- const A2A_COOLDOWN_MS = 120_000; // 2-minute cooldown after hitting limit
26
- const _a2aReplyTimestamps = new Map();
27
- const _a2aCooldownUntil = new Map();
28
- function _a2aCanReply(channelId) {
29
- const now = Date.now();
30
- // Check cooldown
31
- const cooldownEnd = _a2aCooldownUntil.get(channelId) ?? 0;
32
- if (now < cooldownEnd) {
33
- return false;
96
+
97
+ // src/account-config.ts
98
+ var DEFAULT_API_URL = "https://api.agentvault.chat";
99
+ var DEFAULT_HTTP_PORT = 18790;
100
+ function listAccountIds(cfg) {
101
+ const av = cfg?.channels?.agentvault;
102
+ if (!av) return [];
103
+ if (av.accounts && typeof av.accounts === "object") {
104
+ return Object.keys(av.accounts);
105
+ }
106
+ return av.dataDir ? ["default"] : [];
107
+ }
108
+ function resolveAccount(cfg, accountId) {
109
+ const av = cfg?.channels?.agentvault ?? {};
110
+ const id = accountId ?? "default";
111
+ if (av.accounts && typeof av.accounts === "object") {
112
+ const acct = av.accounts[id];
113
+ if (!acct) {
114
+ return {
115
+ accountId: id,
116
+ dataDir: "",
117
+ apiUrl: av.apiUrl ?? DEFAULT_API_URL,
118
+ agentName: id,
119
+ httpPort: DEFAULT_HTTP_PORT,
120
+ configured: false
121
+ };
122
+ }
123
+ let httpPort = acct.httpPort;
124
+ if (httpPort == null) {
125
+ const keys = Object.keys(av.accounts);
126
+ const index = keys.indexOf(id);
127
+ httpPort = DEFAULT_HTTP_PORT + (index >= 0 ? index : 0);
128
+ }
129
+ return {
130
+ accountId: id,
131
+ dataDir: acct.dataDir ?? "",
132
+ apiUrl: acct.apiUrl ?? av.apiUrl ?? DEFAULT_API_URL,
133
+ agentName: acct.agentName ?? id,
134
+ httpPort,
135
+ configured: Boolean(acct.dataDir)
136
+ };
137
+ }
138
+ return {
139
+ accountId: id,
140
+ dataDir: av.dataDir ?? "~/.openclaw/agentvault",
141
+ apiUrl: av.apiUrl ?? DEFAULT_API_URL,
142
+ agentName: av.agentName ?? "OpenClaw Agent",
143
+ httpPort: av.httpPort ?? DEFAULT_HTTP_PORT,
144
+ configured: Boolean(av.dataDir)
145
+ };
146
+ }
147
+
148
+ // src/fetch-interceptor.ts
149
+ import { AsyncLocalStorage } from "node:async_hooks";
150
+ import diagnosticsChannel from "node:diagnostics_channel";
151
+ var traceStore = new AsyncLocalStorage();
152
+ var DEFAULT_SKIP_PATTERNS = [
153
+ /^https?:\/\/localhost(:\d+)?/,
154
+ /^https?:\/\/127\.0\.0\.1(:\d+)?/,
155
+ /\.agentvault\.chat/,
156
+ /\.agentvault\.dev/,
157
+ /\.clerk\./
158
+ ];
159
+ var installed = false;
160
+ var originalFetch;
161
+ var inflightRequests = /* @__PURE__ */ new WeakMap();
162
+ var unsubCreate;
163
+ var unsubHeaders;
164
+ var unsubError;
165
+ function shouldSkip(url, extraPatterns) {
166
+ const allPatterns = [...DEFAULT_SKIP_PATTERNS, ...extraPatterns];
167
+ return allPatterns.some((p) => p.test(url));
168
+ }
169
+ function extractUrl(origin, path) {
170
+ return `${origin}${path}`;
171
+ }
172
+ function installFetchInterceptor(opts) {
173
+ if (installed) return;
174
+ installed = true;
175
+ const skipPatterns = [
176
+ ...DEFAULT_SKIP_PATTERNS,
177
+ ...opts.skipPatterns ?? []
178
+ ];
179
+ try {
180
+ const createChannel = diagnosticsChannel.channel("undici:request:create");
181
+ const headersChannel = diagnosticsChannel.channel("undici:request:headers");
182
+ const errorChannel = diagnosticsChannel.channel("undici:request:error");
183
+ const onRequestCreate = (message) => {
184
+ try {
185
+ const msg = message;
186
+ const req = msg.request;
187
+ if (!req) return;
188
+ const origin = String(req.origin ?? "");
189
+ const path = String(req.path ?? "/");
190
+ const url = extractUrl(origin, path);
191
+ if (shouldSkip(url, skipPatterns)) return;
192
+ inflightRequests.set(req, {
193
+ url,
194
+ method: String(req.method ?? "GET").toUpperCase(),
195
+ startTime: Date.now()
196
+ });
197
+ } catch {
198
+ }
199
+ };
200
+ const onRequestHeaders = (message) => {
201
+ try {
202
+ const msg = message;
203
+ const tracked = inflightRequests.get(msg.request);
204
+ if (!tracked) return;
205
+ inflightRequests.delete(msg.request);
206
+ const latencyMs = Date.now() - tracked.startTime;
207
+ const ctx = traceStore.getStore();
208
+ opts.onHttpCall({
209
+ method: tracked.method,
210
+ url: tracked.url,
211
+ statusCode: msg.response?.statusCode ?? 0,
212
+ latencyMs,
213
+ traceId: ctx?.traceId,
214
+ parentSpanId: ctx?.parentSpanId
215
+ });
216
+ } catch {
217
+ }
218
+ };
219
+ const onRequestError = (message) => {
220
+ try {
221
+ const msg = message;
222
+ const tracked = inflightRequests.get(msg.request);
223
+ if (!tracked) return;
224
+ inflightRequests.delete(msg.request);
225
+ const latencyMs = Date.now() - tracked.startTime;
226
+ const ctx = traceStore.getStore();
227
+ opts.onHttpCall({
228
+ method: tracked.method,
229
+ url: tracked.url,
230
+ statusCode: 0,
231
+ latencyMs,
232
+ traceId: ctx?.traceId,
233
+ parentSpanId: ctx?.parentSpanId
234
+ });
235
+ } catch {
236
+ }
237
+ };
238
+ createChannel.subscribe(onRequestCreate);
239
+ headersChannel.subscribe(onRequestHeaders);
240
+ errorChannel.subscribe(onRequestError);
241
+ unsubCreate = () => createChannel.unsubscribe(onRequestCreate);
242
+ unsubHeaders = () => headersChannel.unsubscribe(onRequestHeaders);
243
+ unsubError = () => errorChannel.unsubscribe(onRequestError);
244
+ } catch {
245
+ }
246
+ originalFetch = globalThis.fetch;
247
+ const savedOriginal = originalFetch;
248
+ globalThis.fetch = async (input, init) => {
249
+ const url = input instanceof Request ? input.url : input instanceof URL ? input.href : String(input);
250
+ if (shouldSkip(url, skipPatterns)) {
251
+ return savedOriginal(input, init);
34
252
  }
35
- // Get timestamps within window
36
- const timestamps = _a2aReplyTimestamps.get(channelId) ?? [];
37
- const recent = timestamps.filter((t) => now - t < A2A_WINDOW_MS);
38
- if (recent.length >= A2A_MAX_REPLIES_PER_WINDOW) {
39
- // Hit limit enter cooldown
40
- _a2aCooldownUntil.set(channelId, now + A2A_COOLDOWN_MS);
41
- _a2aReplyTimestamps.set(channelId, []);
42
- console.warn(`[AgentVault] A2A rate limit hit for channel ${channelId.slice(0, 8)}... — ` +
43
- `${A2A_MAX_REPLIES_PER_WINDOW} replies in ${A2A_WINDOW_MS / 1000}s, cooling down ${A2A_COOLDOWN_MS / 1000}s`);
44
- return false;
253
+ const method = input instanceof Request ? input.method : init?.method ?? "GET";
254
+ const ctx = traceStore.getStore();
255
+ const start = Date.now();
256
+ try {
257
+ const response = await savedOriginal(input, init);
258
+ const latencyMs = Date.now() - start;
259
+ try {
260
+ opts.onHttpCall({
261
+ method,
262
+ url,
263
+ statusCode: response.status,
264
+ latencyMs,
265
+ traceId: ctx?.traceId,
266
+ parentSpanId: ctx?.parentSpanId
267
+ });
268
+ } catch {
269
+ }
270
+ return response;
271
+ } catch (err) {
272
+ const latencyMs = Date.now() - start;
273
+ try {
274
+ opts.onHttpCall({
275
+ method,
276
+ url,
277
+ statusCode: 0,
278
+ latencyMs,
279
+ traceId: ctx?.traceId,
280
+ parentSpanId: ctx?.parentSpanId
281
+ });
282
+ } catch {
283
+ }
284
+ throw err;
45
285
  }
46
- return true;
286
+ };
287
+ }
288
+ function runWithTraceContext(ctx, fn) {
289
+ return traceStore.run(ctx, fn);
290
+ }
291
+
292
+ // src/http-handlers.ts
293
+ async function handleSendRequest(parsed, channel) {
294
+ const text = parsed.text;
295
+ if (!text || typeof text !== "string") {
296
+ return { status: 400, body: { ok: false, error: "Missing 'text' field" } };
297
+ }
298
+ try {
299
+ let a2aTarget = parsed.hub_address ?? parsed.a2a_address ?? parsed.a2aAddress;
300
+ if (!a2aTarget && parsed.channel_id && typeof parsed.channel_id === "string") {
301
+ const hubAddr = channel.resolveA2AChannelHub(parsed.channel_id);
302
+ if (hubAddr) a2aTarget = hubAddr;
303
+ }
304
+ const roomId = (typeof parsed.room_id === "string" ? parsed.room_id : void 0) ?? channel.lastInboundRoomId;
305
+ if (a2aTarget && typeof a2aTarget === "string") {
306
+ await channel.sendToAgent(a2aTarget, text);
307
+ } else if (roomId) {
308
+ await channel.sendToRoom(roomId, text, {
309
+ messageType: parsed.message_type,
310
+ priority: parsed.priority,
311
+ metadata: parsed.metadata
312
+ });
313
+ } else if (parsed.file_path && typeof parsed.file_path === "string") {
314
+ await channel.sendWithAttachment(text, parsed.file_path, {
315
+ topicId: parsed.topicId
316
+ });
317
+ } else {
318
+ await channel.send(text, {
319
+ topicId: parsed.topicId,
320
+ messageType: parsed.message_type,
321
+ metadata: parsed.metadata
322
+ });
323
+ }
324
+ return { status: 200, body: { ok: true } };
325
+ } catch (err) {
326
+ return { status: 500, body: { ok: false, error: String(err) } };
327
+ }
328
+ }
329
+ async function handleActionRequest(parsed, channel) {
330
+ if (!parsed.action || typeof parsed.action !== "string") {
331
+ return { status: 400, body: { ok: false, error: "Missing 'action' field" } };
332
+ }
333
+ try {
334
+ const confirmation = {
335
+ action: parsed.action,
336
+ status: parsed.status ?? "completed",
337
+ decisionId: parsed.decision_id,
338
+ detail: parsed.detail,
339
+ estimated_cost: parsed.estimated_cost
340
+ };
341
+ if (parsed.room_id && typeof parsed.room_id === "string") {
342
+ await channel.sendActionConfirmationToRoom(parsed.room_id, confirmation);
343
+ } else {
344
+ await channel.sendActionConfirmation(confirmation);
345
+ }
346
+ return { status: 200, body: { ok: true } };
347
+ } catch (err) {
348
+ return { status: 500, body: { ok: false, error: String(err) } };
349
+ }
350
+ }
351
+ async function handleDecisionRequest(parsed, channel) {
352
+ const title = parsed.title;
353
+ if (!title || typeof title !== "string") {
354
+ return { status: 400, body: { ok: false, error: "Missing 'title' field" } };
355
+ }
356
+ const options = parsed.options;
357
+ if (!Array.isArray(options) || options.length < 2) {
358
+ return { status: 400, body: { ok: false, error: "'options' must be an array with at least 2 items" } };
359
+ }
360
+ for (const opt of options) {
361
+ if (!opt || typeof opt !== "object" || !opt.option_id || !opt.label) {
362
+ return { status: 400, body: { ok: false, error: "Each option must have 'option_id' and 'label'" } };
363
+ }
364
+ }
365
+ try {
366
+ const decision_id = await channel.sendDecisionRequest({
367
+ title,
368
+ description: parsed.description,
369
+ options,
370
+ context_refs: parsed.context_refs,
371
+ deadline: parsed.deadline,
372
+ auto_action: parsed.auto_action
373
+ });
374
+ return { status: 200, body: { ok: true, decision_id } };
375
+ } catch (err) {
376
+ return { status: 500, body: { ok: false, error: String(err) } };
377
+ }
378
+ }
379
+ function handleStatusRequest(channel) {
380
+ return {
381
+ status: 200,
382
+ body: {
383
+ ok: true,
384
+ state: channel.state,
385
+ deviceId: channel.deviceId ?? void 0,
386
+ sessions: channel.sessionCount
387
+ }
388
+ };
389
+ }
390
+
391
+ // src/openclaw-entry.ts
392
+ init_openclaw_compat();
393
+ var _ocRuntime = null;
394
+ var _channels = /* @__PURE__ */ new Map();
395
+ var _messageQueue = [];
396
+ var A2A_MAX_REPLIES_PER_WINDOW = 4;
397
+ var A2A_WINDOW_MS = 6e4;
398
+ var A2A_COOLDOWN_MS = 12e4;
399
+ var _a2aReplyTimestamps = /* @__PURE__ */ new Map();
400
+ var _a2aCooldownUntil = /* @__PURE__ */ new Map();
401
+ function _a2aCanReply(channelId) {
402
+ const now = Date.now();
403
+ const cooldownEnd = _a2aCooldownUntil.get(channelId) ?? 0;
404
+ if (now < cooldownEnd) {
405
+ return false;
406
+ }
407
+ const timestamps = _a2aReplyTimestamps.get(channelId) ?? [];
408
+ const recent = timestamps.filter((t) => now - t < A2A_WINDOW_MS);
409
+ if (recent.length >= A2A_MAX_REPLIES_PER_WINDOW) {
410
+ _a2aCooldownUntil.set(channelId, now + A2A_COOLDOWN_MS);
411
+ _a2aReplyTimestamps.set(channelId, []);
412
+ console.warn(
413
+ `[AgentVault] A2A rate limit hit for channel ${channelId.slice(0, 8)}... \u2014 ${A2A_MAX_REPLIES_PER_WINDOW} replies in ${A2A_WINDOW_MS / 1e3}s, cooling down ${A2A_COOLDOWN_MS / 1e3}s`
414
+ );
415
+ return false;
416
+ }
417
+ return true;
47
418
  }
48
419
  function _a2aRecordReply(channelId) {
49
- const now = Date.now();
50
- const timestamps = _a2aReplyTimestamps.get(channelId) ?? [];
51
- timestamps.push(now);
52
- // Keep only timestamps within window
53
- _a2aReplyTimestamps.set(channelId, timestamps.filter((t) => now - t < A2A_WINDOW_MS));
420
+ const now = Date.now();
421
+ const timestamps = _a2aReplyTimestamps.get(channelId) ?? [];
422
+ timestamps.push(now);
423
+ _a2aReplyTimestamps.set(
424
+ channelId,
425
+ timestamps.filter((t) => now - t < A2A_WINDOW_MS)
426
+ );
54
427
  }
55
- /** Whether OpenClaw managed HTTP routes are active (vs self-managed server). */
56
- export let isUsingManagedRoutes = false;
57
- /**
58
- * Shared mutable targets array for OpenClaw outbound routing.
59
- * OpenClaw validates `to` against this list before calling sendText/sendPayload.
60
- * We mutate it at runtime to add A2A channel targets dynamically.
61
- */
62
- const _outboundTargets = [
63
- { id: "owner", label: "AgentVault Owner", accountId: "default" },
64
- { id: "default", label: "AgentVault Owner (default)", accountId: "default" },
428
+ var isUsingManagedRoutes = false;
429
+ var _outboundTargets = [
430
+ { id: "owner", label: "AgentVault Owner", accountId: "default" },
431
+ { id: "default", label: "AgentVault Owner (default)", accountId: "default" }
65
432
  ];
66
- /** Register a room as a valid outbound target (idempotent). */
67
433
  function _registerRoomTarget(roomId, roomName, accountId) {
68
- const targetId = `room:${roomId}`;
69
- if (_outboundTargets.some((t) => t.id === targetId))
70
- return;
71
- _outboundTargets.push({ id: targetId, label: `Room: ${roomName}`, accountId });
72
- console.log(`[AgentVault] Registered room target: ${roomName} (${roomId.slice(0, 8)}...)`);
434
+ const targetId = `room:${roomId}`;
435
+ if (_outboundTargets.some((t) => t.id === targetId)) return;
436
+ _outboundTargets.push({ id: targetId, label: `Room: ${roomName}`, accountId });
437
+ console.log(`[AgentVault] Registered room target: ${roomName} (${roomId.slice(0, 8)}...)`);
73
438
  }
74
- /** Register an A2A peer as a valid outbound target (idempotent). */
75
439
  function _registerA2ATarget(hubAddress, accountId) {
76
- const targetId = `a2a:${hubAddress}`;
77
- if (_outboundTargets.some((t) => t.id === targetId))
78
- return;
79
- _outboundTargets.push({
80
- id: targetId,
81
- label: `A2A: ${hubAddress}`,
82
- accountId,
83
- });
84
- console.log(`[AgentVault] Registered A2A target: ${targetId}`);
440
+ const targetId = `a2a:${hubAddress}`;
441
+ if (_outboundTargets.some((t) => t.id === targetId)) return;
442
+ _outboundTargets.push({
443
+ id: targetId,
444
+ label: `A2A: ${hubAddress}`,
445
+ accountId
446
+ });
447
+ console.log(`[AgentVault] Registered A2A target: ${targetId}`);
85
448
  }
86
449
  function _setRuntime(rt) {
87
- _ocRuntime = rt;
88
- // Flush any messages that arrived before runtime was ready
89
- if (_messageQueue.length > 0) {
90
- const pending = _messageQueue.splice(0);
91
- for (const fn of pending) {
92
- fn().catch(() => { });
93
- }
450
+ _ocRuntime = rt;
451
+ if (_messageQueue.length > 0) {
452
+ const pending = _messageQueue.splice(0);
453
+ for (const fn of pending) {
454
+ fn().catch(() => {
455
+ });
94
456
  }
457
+ }
95
458
  }
96
- // --- @mention filtering for multi-agent rooms ---
97
- /** Extract @mention names from plaintext. Returns lowercased names. */
98
459
  function _parseMentions(text) {
99
- const mentions = [];
100
- // Match @word at word boundary — supports multi-word via sequential matching
101
- const re = /@(\w[\w]*)/gi;
102
- let match;
103
- while ((match = re.exec(text)) !== null) {
104
- mentions.push(match[1].toLowerCase());
105
- }
106
- return mentions;
460
+ const mentions = [];
461
+ const re = /@(\w[\w]*)/gi;
462
+ let match;
463
+ while ((match = re.exec(text)) !== null) {
464
+ mentions.push(match[1].toLowerCase());
465
+ }
466
+ return mentions;
107
467
  }
108
- /** Determine whether this agent should process a room message based on @mentions. */
109
468
  function _shouldProcessRoomMessage(plaintext, agentName, accountId) {
110
- const mentions = _parseMentions(plaintext);
111
- // No mentions broadcast to all agents (current behavior)
112
- if (mentions.length === 0)
113
- return true;
114
- // @all / @everyone → all agents process
115
- if (mentions.includes("all") || mentions.includes("everyone"))
116
- return true;
117
- // Check if this agent is mentioned (by name or accountId)
118
- const nameLower = agentName.toLowerCase();
119
- const idLower = accountId.toLowerCase();
120
- // Match first word of agent name (e.g., "Cortina" from "Cortina (Coder)")
121
- const firstWord = nameLower.split(/[\s(]/)[0];
122
- return mentions.some((m) => m === nameLower || m === firstWord || m === idLower);
469
+ const mentions = _parseMentions(plaintext);
470
+ if (mentions.length === 0) return true;
471
+ if (mentions.includes("all") || mentions.includes("everyone")) return true;
472
+ const nameLower = agentName.toLowerCase();
473
+ const idLower = accountId.toLowerCase();
474
+ const firstWord = nameLower.split(/[\s(]/)[0];
475
+ return mentions.some(
476
+ (m) => m === nameLower || m === firstWord || m === idLower
477
+ );
123
478
  }
124
- /** Strip the matching @mention prefix from plaintext so the agent sees clean text. */
125
479
  function _stripMentions(text, agentName, accountId) {
126
- const nameLower = agentName.toLowerCase();
127
- const firstWord = nameLower.split(/[\s(]/)[0];
128
- const idLower = accountId.toLowerCase();
129
- // Remove all @mentions that match this agent (case-insensitive)
130
- return text
131
- .replace(/@(\w[\w]*)/gi, (full, name) => {
132
- const lower = name.toLowerCase();
133
- if (lower === nameLower || lower === firstWord || lower === idLower) {
134
- return "";
135
- }
136
- // Also strip @all/@everyone since they're routing directives
137
- if (lower === "all" || lower === "everyone")
138
- return "";
139
- return full;
140
- })
141
- .replace(/^\s+/, "") // trim leading whitespace left by stripped mention
142
- .trim();
480
+ const nameLower = agentName.toLowerCase();
481
+ const firstWord = nameLower.split(/[\s(]/)[0];
482
+ const idLower = accountId.toLowerCase();
483
+ return text.replace(/@(\w[\w]*)/gi, (full, name) => {
484
+ const lower = name.toLowerCase();
485
+ if (lower === nameLower || lower === firstWord || lower === idLower) {
486
+ return "";
487
+ }
488
+ if (lower === "all" || lower === "everyone") return "";
489
+ return full;
490
+ }).replace(/^\s+/, "").trim();
143
491
  }
144
- // --- Inbound message dispatch ---
145
492
  async function handleInbound(params) {
146
- const { plaintext: rawPlaintext, metadata, channel, account, cfg } = params;
147
- const isRoomMessage = Boolean(metadata.roomId);
148
- const isA2AMessage = Boolean(metadata.a2aChannelId);
149
- // @mention filtering: only for room messages
150
- if (isRoomMessage) {
151
- if (!_shouldProcessRoomMessage(rawPlaintext, account.agentName ?? "", account.accountId ?? "")) {
152
- return; // This agent is not mentioned — skip silently
153
- }
493
+ const { plaintext: rawPlaintext, metadata, channel, account, cfg } = params;
494
+ const isRoomMessage = Boolean(metadata.roomId);
495
+ const isA2AMessage = Boolean(metadata.a2aChannelId);
496
+ if (isRoomMessage) {
497
+ if (!_shouldProcessRoomMessage(rawPlaintext, account.agentName ?? "", account.accountId ?? "")) {
498
+ return;
154
499
  }
155
- // Strip @mentions from plaintext so the agent sees clean text
156
- const plaintext = isRoomMessage
157
- ? _stripMentions(rawPlaintext, account.agentName ?? "", account.accountId ?? "")
158
- : rawPlaintext;
159
- // Telemetry: hierarchical spans for the full message lifecycle
160
- const startTime = Date.now();
161
- const traceId = randomBytes(16).toString("hex");
162
- const rootSpanId = randomBytes(8).toString("hex");
163
- const inferenceSpanId = randomBytes(8).toString("hex");
164
- // Instrumentation context for agent code to report LLM/tool/error spans
165
- /** Helper: send an activity span over WS for real-time owner display. */
166
- const _sendActivity = (spanData) => {
167
- try {
168
- channel.sendActivitySpan({ ...spanData, trace_id: traceId, parent_span_id: inferenceSpanId });
169
- }
170
- catch { }
171
- };
172
- const _instrument = {
173
- reportLlm: (opts) => {
174
- const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
175
- if (opts.skillName || _instrument.skillName)
176
- enriched.skillName = opts.skillName ?? _instrument.skillName;
177
- try {
178
- channel.telemetry?.reportLlmCall(enriched);
179
- }
180
- catch { }
181
- const activityAttrs = { "ai.agent.llm.model": opts.model ?? "" };
182
- if (enriched.skillName)
183
- activityAttrs["ai.agent.skill.name"] = enriched.skillName;
184
- _sendActivity({
185
- span_id: randomBytes(8).toString("hex"), span_type: "llm", span_name: opts.model ?? "LLM",
186
- status: opts.status === "error" ? "error" : "ok",
187
- start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
188
- end_time: new Date().toISOString(), duration_ms: opts.latencyMs ?? 0,
189
- attributes: activityAttrs,
190
- tokens_input: opts.tokensInput, tokens_output: opts.tokensOutput,
191
- });
192
- },
193
- reportTool: (opts) => {
194
- const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
195
- if (opts.skillName || _instrument.skillName)
196
- enriched.skillName = opts.skillName ?? _instrument.skillName;
197
- try {
198
- channel.telemetry?.reportToolCall(enriched);
199
- }
200
- catch { }
201
- const activityAttrs = { "ai.agent.tool.name": opts.toolName ?? "" };
202
- if (enriched.skillName)
203
- activityAttrs["ai.agent.skill.name"] = enriched.skillName;
204
- _sendActivity({
205
- span_id: randomBytes(8).toString("hex"), span_type: "tool", span_name: opts.toolName ?? "tool",
206
- status: opts.success === false ? "error" : "ok",
207
- start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
208
- end_time: new Date().toISOString(), duration_ms: opts.latencyMs ?? 0,
209
- attributes: activityAttrs,
210
- tool_success: opts.success,
211
- });
212
- },
213
- reportError: (opts) => {
214
- const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
215
- if (opts.skillName || _instrument.skillName)
216
- enriched.skillName = opts.skillName ?? _instrument.skillName;
217
- try {
218
- channel.telemetry?.reportError(enriched);
219
- }
220
- catch { }
221
- const activityAttrs = { "ai.agent.error.type": opts.errorType ?? "" };
222
- if (enriched.skillName)
223
- activityAttrs["ai.agent.skill.name"] = enriched.skillName;
224
- _sendActivity({
225
- span_id: randomBytes(8).toString("hex"), span_type: "error", span_name: opts.errorType ?? "error",
226
- status: "error",
227
- start_time: new Date().toISOString(), end_time: new Date().toISOString(), duration_ms: 0,
228
- attributes: activityAttrs,
229
- error_type: opts.errorType, error_message: opts.errorMessage,
230
- });
231
- },
232
- reportHttp: (opts) => {
233
- const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
234
- if (opts.skillName || _instrument.skillName)
235
- enriched.skillName = opts.skillName ?? _instrument.skillName;
236
- try {
237
- channel.telemetry?.reportHttpCall(enriched);
238
- }
239
- catch { }
240
- const activityAttrs = { "ai.agent.http.method": opts.method ?? "", "ai.agent.http.url": opts.url ?? "" };
241
- if (enriched.skillName)
242
- activityAttrs["ai.agent.skill.name"] = enriched.skillName;
243
- _sendActivity({
244
- span_id: randomBytes(8).toString("hex"), span_type: "http",
245
- span_name: (() => { try {
246
- return new URL(opts.url).hostname;
247
- }
248
- catch {
249
- return opts.url?.slice(0, 40) ?? "http";
250
- } })(),
251
- status: (opts.statusCode ?? 200) >= 400 ? "error" : "ok",
252
- start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
253
- end_time: new Date().toISOString(), duration_ms: opts.latencyMs ?? 0,
254
- attributes: activityAttrs,
255
- http_method: opts.method, http_status_code: opts.statusCode, http_url: opts.url,
256
- });
257
- },
258
- reportAction: (opts) => {
259
- const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
260
- if (opts.skillName || _instrument.skillName)
261
- enriched.skillName = opts.skillName ?? _instrument.skillName;
262
- try {
263
- channel.telemetry?.reportActionCall(enriched);
264
- }
265
- catch { }
266
- const activityAttrs = { "ai.agent.action.type": opts.actionType ?? "", "ai.agent.action.target": opts.target ?? "" };
267
- if (enriched.skillName)
268
- activityAttrs["ai.agent.skill.name"] = enriched.skillName;
269
- _sendActivity({
270
- span_id: randomBytes(8).toString("hex"), span_type: "action",
271
- span_name: `${opts.actionType ?? "action"}: ${opts.target ?? ""}`,
272
- status: opts.success === false ? "error" : "ok",
273
- start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
274
- end_time: new Date().toISOString(), duration_ms: opts.latencyMs ?? 0,
275
- attributes: activityAttrs,
276
- action_type: opts.actionType, action_target: opts.target,
277
- });
278
- },
279
- reportNav: (opts) => {
280
- const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
281
- if (opts.skillName || _instrument.skillName)
282
- enriched.skillName = opts.skillName ?? _instrument.skillName;
283
- try {
284
- channel.telemetry?.reportNavCall(enriched);
285
- }
286
- catch { }
287
- const activityAttrs = { "ai.agent.nav.to_url": opts.toUrl ?? "" };
288
- if (enriched.skillName)
289
- activityAttrs["ai.agent.skill.name"] = enriched.skillName;
290
- _sendActivity({
291
- span_id: randomBytes(8).toString("hex"), span_type: "nav",
292
- span_name: opts.toUrl?.slice(0, 40) ?? "navigate",
293
- status: opts.status === "error" ? "error" : "ok",
294
- start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
295
- end_time: new Date().toISOString(), duration_ms: opts.latencyMs ?? 0,
296
- attributes: activityAttrs,
297
- });
298
- },
299
- skillName: undefined,
300
- traceId,
301
- parentSpanId: inferenceSpanId,
302
- };
303
- let replyCount = 0;
304
- let totalReplyChars = 0;
305
- let firstReplyTime = null;
306
- const replySpans = [];
307
- // Emit "receive" child span immediately — marks inbound arrival
308
- _emitChildSpan(channel, {
309
- traceId,
310
- parentSpanId: rootSpanId,
311
- name: "ai.agent.message.receive",
312
- startTime,
313
- endTime: startTime + 1, // instant
314
- attributes: {
315
- "ai.agent.message.input_chars": plaintext.length,
316
- "ai.agent.message.type": isA2AMessage ? "a2a" : metadata.roomId ? "room" : "direct",
317
- },
318
- status: "ok",
319
- });
320
- // Send typing indicator to owner (non-critical, best-effort)
500
+ }
501
+ const plaintext = isRoomMessage ? _stripMentions(rawPlaintext, account.agentName ?? "", account.accountId ?? "") : rawPlaintext;
502
+ const startTime = Date.now();
503
+ const traceId = randomBytes(16).toString("hex");
504
+ const rootSpanId = randomBytes(8).toString("hex");
505
+ const inferenceSpanId = randomBytes(8).toString("hex");
506
+ const _sendActivity = (spanData) => {
321
507
  try {
322
- channel.sendTyping();
508
+ channel.sendActivitySpan({ ...spanData, trace_id: traceId, parent_span_id: inferenceSpanId });
509
+ } catch {
323
510
  }
324
- catch { /* ignore */ }
325
- const core = _ocRuntime; // Non-null: caller guards with `if (!_ocRuntime)` check
326
- const route = core.channel.routing.resolveAgentRoute({
511
+ };
512
+ const _instrument = {
513
+ reportLlm: (opts) => {
514
+ const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
515
+ if (opts.skillName || _instrument.skillName) enriched.skillName = opts.skillName ?? _instrument.skillName;
516
+ try {
517
+ channel.telemetry?.reportLlmCall(enriched);
518
+ } catch {
519
+ }
520
+ const activityAttrs = { "ai.agent.llm.model": opts.model ?? "" };
521
+ if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
522
+ _sendActivity({
523
+ span_id: randomBytes(8).toString("hex"),
524
+ span_type: "llm",
525
+ span_name: opts.model ?? "LLM",
526
+ status: opts.status === "error" ? "error" : "ok",
527
+ start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
528
+ end_time: (/* @__PURE__ */ new Date()).toISOString(),
529
+ duration_ms: opts.latencyMs ?? 0,
530
+ attributes: activityAttrs,
531
+ tokens_input: opts.tokensInput,
532
+ tokens_output: opts.tokensOutput
533
+ });
534
+ },
535
+ reportTool: (opts) => {
536
+ const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
537
+ if (opts.skillName || _instrument.skillName) enriched.skillName = opts.skillName ?? _instrument.skillName;
538
+ try {
539
+ channel.telemetry?.reportToolCall(enriched);
540
+ } catch {
541
+ }
542
+ const activityAttrs = { "ai.agent.tool.name": opts.toolName ?? "" };
543
+ if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
544
+ _sendActivity({
545
+ span_id: randomBytes(8).toString("hex"),
546
+ span_type: "tool",
547
+ span_name: opts.toolName ?? "tool",
548
+ status: opts.success === false ? "error" : "ok",
549
+ start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
550
+ end_time: (/* @__PURE__ */ new Date()).toISOString(),
551
+ duration_ms: opts.latencyMs ?? 0,
552
+ attributes: activityAttrs,
553
+ tool_success: opts.success
554
+ });
555
+ },
556
+ reportError: (opts) => {
557
+ const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
558
+ if (opts.skillName || _instrument.skillName) enriched.skillName = opts.skillName ?? _instrument.skillName;
559
+ try {
560
+ channel.telemetry?.reportError(enriched);
561
+ } catch {
562
+ }
563
+ const activityAttrs = { "ai.agent.error.type": opts.errorType ?? "" };
564
+ if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
565
+ _sendActivity({
566
+ span_id: randomBytes(8).toString("hex"),
567
+ span_type: "error",
568
+ span_name: opts.errorType ?? "error",
569
+ status: "error",
570
+ start_time: (/* @__PURE__ */ new Date()).toISOString(),
571
+ end_time: (/* @__PURE__ */ new Date()).toISOString(),
572
+ duration_ms: 0,
573
+ attributes: activityAttrs,
574
+ error_type: opts.errorType,
575
+ error_message: opts.errorMessage
576
+ });
577
+ },
578
+ reportHttp: (opts) => {
579
+ const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
580
+ if (opts.skillName || _instrument.skillName) enriched.skillName = opts.skillName ?? _instrument.skillName;
581
+ try {
582
+ channel.telemetry?.reportHttpCall(enriched);
583
+ } catch {
584
+ }
585
+ const activityAttrs = { "ai.agent.http.method": opts.method ?? "", "ai.agent.http.url": opts.url ?? "" };
586
+ if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
587
+ _sendActivity({
588
+ span_id: randomBytes(8).toString("hex"),
589
+ span_type: "http",
590
+ span_name: (() => {
591
+ try {
592
+ return new URL(opts.url).hostname;
593
+ } catch {
594
+ return opts.url?.slice(0, 40) ?? "http";
595
+ }
596
+ })(),
597
+ status: (opts.statusCode ?? 200) >= 400 ? "error" : "ok",
598
+ start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
599
+ end_time: (/* @__PURE__ */ new Date()).toISOString(),
600
+ duration_ms: opts.latencyMs ?? 0,
601
+ attributes: activityAttrs,
602
+ http_method: opts.method,
603
+ http_status_code: opts.statusCode,
604
+ http_url: opts.url
605
+ });
606
+ },
607
+ reportAction: (opts) => {
608
+ const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
609
+ if (opts.skillName || _instrument.skillName) enriched.skillName = opts.skillName ?? _instrument.skillName;
610
+ try {
611
+ channel.telemetry?.reportActionCall(enriched);
612
+ } catch {
613
+ }
614
+ const activityAttrs = { "ai.agent.action.type": opts.actionType ?? "", "ai.agent.action.target": opts.target ?? "" };
615
+ if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
616
+ _sendActivity({
617
+ span_id: randomBytes(8).toString("hex"),
618
+ span_type: "action",
619
+ span_name: `${opts.actionType ?? "action"}: ${opts.target ?? ""}`,
620
+ status: opts.success === false ? "error" : "ok",
621
+ start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
622
+ end_time: (/* @__PURE__ */ new Date()).toISOString(),
623
+ duration_ms: opts.latencyMs ?? 0,
624
+ attributes: activityAttrs,
625
+ action_type: opts.actionType,
626
+ action_target: opts.target
627
+ });
628
+ },
629
+ reportNav: (opts) => {
630
+ const enriched = { ...opts, traceId, parentSpanId: inferenceSpanId };
631
+ if (opts.skillName || _instrument.skillName) enriched.skillName = opts.skillName ?? _instrument.skillName;
632
+ try {
633
+ channel.telemetry?.reportNavCall(enriched);
634
+ } catch {
635
+ }
636
+ const activityAttrs = { "ai.agent.nav.to_url": opts.toUrl ?? "" };
637
+ if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
638
+ _sendActivity({
639
+ span_id: randomBytes(8).toString("hex"),
640
+ span_type: "nav",
641
+ span_name: opts.toUrl?.slice(0, 40) ?? "navigate",
642
+ status: opts.status === "error" ? "error" : "ok",
643
+ start_time: new Date(Date.now() - (opts.latencyMs ?? 0)).toISOString(),
644
+ end_time: (/* @__PURE__ */ new Date()).toISOString(),
645
+ duration_ms: opts.latencyMs ?? 0,
646
+ attributes: activityAttrs
647
+ });
648
+ },
649
+ skillName: void 0,
650
+ traceId,
651
+ parentSpanId: inferenceSpanId
652
+ };
653
+ let replyCount = 0;
654
+ let totalReplyChars = 0;
655
+ let firstReplyTime = null;
656
+ const replySpans = [];
657
+ _emitChildSpan(channel, {
658
+ traceId,
659
+ parentSpanId: rootSpanId,
660
+ name: "ai.agent.message.receive",
661
+ startTime,
662
+ endTime: startTime + 1,
663
+ // instant
664
+ attributes: {
665
+ "ai.agent.message.input_chars": plaintext.length,
666
+ "ai.agent.message.type": isA2AMessage ? "a2a" : metadata.roomId ? "room" : "direct"
667
+ },
668
+ status: "ok"
669
+ });
670
+ try {
671
+ channel.sendTyping();
672
+ } catch {
673
+ }
674
+ const core = _ocRuntime;
675
+ const route = core.channel.routing.resolveAgentRoute({
676
+ cfg,
677
+ channel: "agentvault",
678
+ accountId: account.accountId,
679
+ peer: {
680
+ kind: isA2AMessage ? "a2a" : "direct",
681
+ id: isA2AMessage ? `agentvault:a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner"
682
+ }
683
+ });
684
+ const storePath = core.channel.session.resolveStorePath(cfg?.session?.store, {
685
+ agentId: route.agentId
686
+ });
687
+ const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
688
+ const previousTimestamp = core.channel.session.readSessionUpdatedAt({
689
+ storePath,
690
+ sessionKey: route.sessionKey
691
+ });
692
+ const body = core.channel.reply.formatAgentEnvelope({
693
+ channel: "AgentVault",
694
+ from: isA2AMessage ? `Agent (${metadata.fromHubAddress})` : isRoomMessage ? "Room" : "Owner",
695
+ timestamp: new Date(metadata.timestamp).getTime(),
696
+ previousTimestamp,
697
+ envelope: envelopeOptions,
698
+ body: plaintext
699
+ });
700
+ const attachmentFields = {};
701
+ if (metadata.attachment) {
702
+ attachmentFields.AttachmentPath = metadata.attachment.filePath;
703
+ attachmentFields.AttachmentFilename = metadata.attachment.filename;
704
+ attachmentFields.AttachmentMime = metadata.attachment.mime;
705
+ if (metadata.attachment.base64) {
706
+ attachmentFields.MediaUrl = metadata.attachment.base64;
707
+ attachmentFields.NumMedia = "1";
708
+ }
709
+ }
710
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
711
+ Body: body,
712
+ RawBody: plaintext,
713
+ CommandBody: plaintext,
714
+ From: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner",
715
+ To: `agentvault:agent:${account.accountId}`,
716
+ SessionKey: route.sessionKey,
717
+ AccountId: account.accountId,
718
+ ChatType: isA2AMessage ? "a2a" : isRoomMessage ? "room" : "direct",
719
+ ConversationLabel: isA2AMessage ? `A2A: ${metadata.fromHubAddress}` : isRoomMessage ? "AgentVault Room" : "AgentVault",
720
+ SenderName: isA2AMessage ? metadata.fromHubAddress : isRoomMessage ? "Room" : "Owner",
721
+ SenderId: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner",
722
+ Provider: "agentvault",
723
+ Surface: "agentvault",
724
+ MessageSid: metadata.messageId,
725
+ Timestamp: new Date(metadata.timestamp).getTime(),
726
+ OriginatingChannel: "agentvault",
727
+ OriginatingTo: `agentvault:agent:${account.accountId}`,
728
+ CommandAuthorized: true,
729
+ Instrument: _instrument,
730
+ // OpenClaw ctx convention
731
+ AgentVaultTelemetry: _instrument,
732
+ // AgentVault-specific accessor
733
+ ...attachmentFields
734
+ });
735
+ await core.channel.session.recordInboundSession({
736
+ storePath,
737
+ sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
738
+ ctx: ctxPayload,
739
+ onRecordError: (err) => {
740
+ core.error?.(`[AgentVault] session record failed: ${String(err)}`);
741
+ }
742
+ });
743
+ try {
744
+ await runWithTraceContext(
745
+ { traceId, parentSpanId: inferenceSpanId },
746
+ () => core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
747
+ ctx: ctxPayload,
327
748
  cfg,
328
- channel: "agentvault",
329
- accountId: account.accountId,
330
- peer: {
331
- kind: isA2AMessage ? "a2a" : "direct",
332
- id: isA2AMessage
333
- ? `agentvault:a2a:${metadata.fromHubAddress}`
334
- : isRoomMessage
335
- ? `agentvault:room:${metadata.roomId}`
336
- : "agentvault:owner",
749
+ dispatcherOptions: {
750
+ deliver: async (payload) => {
751
+ if (payload.kind === "thinking" || payload.kind === "reasoning") return;
752
+ const text = (payload.text ?? "").trim();
753
+ if (!text) return;
754
+ if (/^(Reasoning|Thinking|Let me think|I need to|Let me check):/i.test(text)) return;
755
+ const replyStart = Date.now();
756
+ replyCount++;
757
+ totalReplyChars += text.length;
758
+ if (!firstReplyTime) firstReplyTime = replyStart;
759
+ if (isA2AMessage) {
760
+ if (!_a2aCanReply(metadata.a2aChannelId)) {
761
+ console.warn(`[AgentVault] A2A reply suppressed (rate limit) for channel ${metadata.a2aChannelId?.slice(0, 8)}...`);
762
+ return;
763
+ }
764
+ await channel.sendToAgent(metadata.fromHubAddress, text, {
765
+ parentSpanId: inferenceSpanId
766
+ });
767
+ _a2aRecordReply(metadata.a2aChannelId);
768
+ } else if (isRoomMessage) {
769
+ await channel.sendToRoom(metadata.roomId, text, {
770
+ metadata: { content_length: text.length }
771
+ });
772
+ } else {
773
+ await channel.send(text, {
774
+ conversationId: metadata.conversationId,
775
+ topicId: metadata.topicId
776
+ });
777
+ }
778
+ const replyEnd = Date.now();
779
+ replySpans.push({ startTime: replyStart, endTime: replyEnd, chars: text.length, index: replyCount });
780
+ },
781
+ onError: (err, info) => {
782
+ core.error?.(`[AgentVault] ${info?.kind ?? "reply"} error: ${String(err)}`);
783
+ }
337
784
  },
785
+ replyOptions: {}
786
+ })
787
+ );
788
+ const endTime = Date.now();
789
+ _emitHierarchicalSpans(channel, {
790
+ traceId,
791
+ rootSpanId,
792
+ inferenceSpanId,
793
+ startTime,
794
+ endTime,
795
+ firstReplyTime,
796
+ replySpans,
797
+ inputChars: plaintext.length,
798
+ replyCount,
799
+ totalReplyChars,
800
+ isRoom: isRoomMessage,
801
+ status: "ok"
338
802
  });
339
- const storePath = core.channel.session.resolveStorePath(cfg?.session?.store, {
340
- agentId: route.agentId,
341
- });
342
- const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
343
- const previousTimestamp = core.channel.session.readSessionUpdatedAt({
344
- storePath,
345
- sessionKey: route.sessionKey,
346
- });
347
- const body = core.channel.reply.formatAgentEnvelope({
348
- channel: "AgentVault",
349
- from: isA2AMessage ? `Agent (${metadata.fromHubAddress})` : isRoomMessage ? "Room" : "Owner",
350
- timestamp: new Date(metadata.timestamp).getTime(),
351
- previousTimestamp,
352
- envelope: envelopeOptions,
353
- body: plaintext,
803
+ } catch (err) {
804
+ const endTime = Date.now();
805
+ _emitHierarchicalSpans(channel, {
806
+ traceId,
807
+ rootSpanId,
808
+ inferenceSpanId,
809
+ startTime,
810
+ endTime,
811
+ firstReplyTime,
812
+ replySpans,
813
+ inputChars: plaintext.length,
814
+ replyCount,
815
+ totalReplyChars,
816
+ isRoom: isRoomMessage,
817
+ status: "error",
818
+ statusMessage: String(err)
354
819
  });
355
- // Build attachment fields for the context payload
356
- const attachmentFields = {};
357
- if (metadata.attachment) {
358
- attachmentFields.AttachmentPath = metadata.attachment.filePath;
359
- attachmentFields.AttachmentFilename = metadata.attachment.filename;
360
- attachmentFields.AttachmentMime = metadata.attachment.mime;
361
- // For images: include as MediaUrl so the LLM can see the visual content
362
- if (metadata.attachment.base64) {
363
- attachmentFields.MediaUrl = metadata.attachment.base64;
364
- attachmentFields.NumMedia = "1";
365
- }
366
- // For text files: content is already inlined in plaintext body
367
- }
368
- const ctxPayload = core.channel.reply.finalizeInboundContext({
369
- Body: body,
370
- RawBody: plaintext,
371
- CommandBody: plaintext,
372
- From: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner",
373
- To: `agentvault:agent:${account.accountId}`,
374
- SessionKey: route.sessionKey,
375
- AccountId: account.accountId,
376
- ChatType: isA2AMessage ? "a2a" : isRoomMessage ? "room" : "direct",
377
- ConversationLabel: isA2AMessage ? `A2A: ${metadata.fromHubAddress}` : isRoomMessage ? "AgentVault Room" : "AgentVault",
378
- SenderName: isA2AMessage ? metadata.fromHubAddress : isRoomMessage ? "Room" : "Owner",
379
- SenderId: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner",
380
- Provider: "agentvault",
381
- Surface: "agentvault",
382
- MessageSid: metadata.messageId,
383
- Timestamp: new Date(metadata.timestamp).getTime(),
384
- OriginatingChannel: "agentvault",
385
- OriginatingTo: `agentvault:agent:${account.accountId}`,
386
- CommandAuthorized: true,
387
- Instrument: _instrument, // OpenClaw ctx convention
388
- AgentVaultTelemetry: _instrument, // AgentVault-specific accessor
389
- ...attachmentFields,
390
- });
391
- await core.channel.session.recordInboundSession({
392
- storePath,
393
- sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
394
- ctx: ctxPayload,
395
- onRecordError: (err) => {
396
- core.error?.(`[AgentVault] session record failed: ${String(err)}`);
397
- },
820
+ _emitChildSpan(channel, {
821
+ traceId,
822
+ parentSpanId: rootSpanId,
823
+ name: "error",
824
+ startTime: endTime,
825
+ endTime,
826
+ attributes: {
827
+ "ai.agent.error.type": err?.constructor?.name ?? "Error",
828
+ "ai.agent.error.message": String(err)
829
+ },
830
+ status: "error",
831
+ statusMessage: String(err)
398
832
  });
399
- try {
400
- await runWithTraceContext({ traceId, parentSpanId: inferenceSpanId }, () => core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
401
- ctx: ctxPayload,
402
- cfg,
403
- dispatcherOptions: {
404
- deliver: async (payload) => {
405
- // Filter out thinking/reasoning blocks — only deliver actual responses
406
- if (payload.kind === "thinking" || payload.kind === "reasoning")
407
- return;
408
- const text = (payload.text ?? "").trim();
409
- if (!text)
410
- return;
411
- // Heuristic: skip blocks that look like leaked chain-of-thought
412
- if (/^(Reasoning|Thinking|Let me think|I need to|Let me check):/i.test(text))
413
- return;
414
- const replyStart = Date.now();
415
- replyCount++;
416
- totalReplyChars += text.length;
417
- if (!firstReplyTime)
418
- firstReplyTime = replyStart;
419
- // Route reply: A2A → sendToAgent, room → sendToRoom, 1:1 → send
420
- if (isA2AMessage) {
421
- // Loop prevention: rate limit A2A replies per channel
422
- if (!_a2aCanReply(metadata.a2aChannelId)) {
423
- console.warn(`[AgentVault] A2A reply suppressed (rate limit) for channel ${metadata.a2aChannelId?.slice(0, 8)}...`);
424
- return;
425
- }
426
- await channel.sendToAgent(metadata.fromHubAddress, text, {
427
- parentSpanId: inferenceSpanId,
428
- });
429
- _a2aRecordReply(metadata.a2aChannelId);
430
- }
431
- else if (isRoomMessage) {
432
- await channel.sendToRoom(metadata.roomId, text, {
433
- metadata: { content_length: text.length },
434
- });
435
- }
436
- else {
437
- await channel.send(text, {
438
- conversationId: metadata.conversationId,
439
- topicId: metadata.topicId,
440
- });
441
- }
442
- const replyEnd = Date.now();
443
- replySpans.push({ startTime: replyStart, endTime: replyEnd, chars: text.length, index: replyCount });
444
- },
445
- onError: (err, info) => {
446
- core.error?.(`[AgentVault] ${info?.kind ?? "reply"} error: ${String(err)}`);
447
- },
448
- },
449
- replyOptions: {},
450
- }));
451
- const endTime = Date.now();
452
- // Emit child spans for the completed message lifecycle
453
- _emitHierarchicalSpans(channel, {
454
- traceId,
455
- rootSpanId,
456
- inferenceSpanId,
457
- startTime,
458
- endTime,
459
- firstReplyTime,
460
- replySpans,
461
- inputChars: plaintext.length,
462
- replyCount,
463
- totalReplyChars,
464
- isRoom: isRoomMessage,
465
- status: "ok",
466
- });
467
- }
468
- catch (err) {
469
- const endTime = Date.now();
470
- // Emit spans even on error — shows where failure occurred
471
- _emitHierarchicalSpans(channel, {
472
- traceId,
473
- rootSpanId,
474
- inferenceSpanId,
475
- startTime,
476
- endTime,
477
- firstReplyTime,
478
- replySpans,
479
- inputChars: plaintext.length,
480
- replyCount,
481
- totalReplyChars,
482
- isRoom: isRoomMessage,
483
- status: "error",
484
- statusMessage: String(err),
485
- });
486
- // Dedicated error span for the Errors tab
487
- _emitChildSpan(channel, {
488
- traceId,
489
- parentSpanId: rootSpanId,
490
- name: "error",
491
- startTime: endTime,
492
- endTime: endTime,
493
- attributes: {
494
- "ai.agent.error.type": err?.constructor?.name ?? "Error",
495
- "ai.agent.error.message": String(err),
496
- },
497
- status: "error",
498
- statusMessage: String(err),
499
- });
500
- throw err;
501
- }
833
+ throw err;
834
+ }
502
835
  }
503
- /** Infer a span type from the span name for activity stream display. */
504
836
  function _inferSpanType(name) {
505
- if (name === "error" || name.includes("error"))
506
- return "error";
507
- if (name.startsWith("llm.") || name.includes("inference"))
508
- return "llm";
509
- if (name.startsWith("tool.") || name.includes("tool"))
510
- return "tool";
511
- if (name.startsWith("http.") || name.includes("http"))
512
- return "http";
513
- if (name.startsWith("nav.") || name.includes("nav"))
514
- return "nav";
515
- if (name.startsWith("action.") || name.includes("action"))
516
- return "action";
517
- return "action"; // default fallback
837
+ if (name === "error" || name.includes("error")) return "error";
838
+ if (name.startsWith("llm.") || name.includes("inference")) return "llm";
839
+ if (name.startsWith("tool.") || name.includes("tool")) return "tool";
840
+ if (name.startsWith("http.") || name.includes("http")) return "http";
841
+ if (name.startsWith("nav.") || name.includes("nav")) return "nav";
842
+ if (name.startsWith("action.") || name.includes("action")) return "action";
843
+ return "action";
518
844
  }
519
- /** Extract a human-readable span name from span attributes. */
520
845
  function _extractSpanName(name, attrs) {
521
- if (attrs["ai.agent.llm.model"])
522
- return String(attrs["ai.agent.llm.model"]);
523
- if (attrs["ai.agent.tool.name"])
524
- return String(attrs["ai.agent.tool.name"]);
525
- if (attrs["ai.agent.http.url"]) {
526
- try {
527
- return new URL(String(attrs["ai.agent.http.url"])).hostname;
528
- }
529
- catch { /* use raw */ }
530
- return String(attrs["ai.agent.http.url"]).slice(0, 40);
846
+ if (attrs["ai.agent.llm.model"]) return String(attrs["ai.agent.llm.model"]);
847
+ if (attrs["ai.agent.tool.name"]) return String(attrs["ai.agent.tool.name"]);
848
+ if (attrs["ai.agent.http.url"]) {
849
+ try {
850
+ return new URL(String(attrs["ai.agent.http.url"])).hostname;
851
+ } catch {
531
852
  }
532
- if (attrs["ai.agent.action.type"])
533
- return `${attrs["ai.agent.action.type"]}: ${attrs["ai.agent.action.target"] ?? ""}`;
534
- if (attrs["ai.agent.nav.to_url"])
535
- return String(attrs["ai.agent.nav.to_url"]).slice(0, 40);
536
- if (attrs["ai.agent.error.type"])
537
- return String(attrs["ai.agent.error.type"]);
538
- return name;
853
+ return String(attrs["ai.agent.http.url"]).slice(0, 40);
854
+ }
855
+ if (attrs["ai.agent.action.type"]) return `${attrs["ai.agent.action.type"]}: ${attrs["ai.agent.action.target"] ?? ""}`;
856
+ if (attrs["ai.agent.nav.to_url"]) return String(attrs["ai.agent.nav.to_url"]).slice(0, 40);
857
+ if (attrs["ai.agent.error.type"]) return String(attrs["ai.agent.error.type"]);
858
+ return name;
539
859
  }
540
- /** Emit a single child span via the channel's telemetry reporter + WS activity stream. */
541
860
  function _emitChildSpan(channel, opts) {
861
+ try {
862
+ const reporter = channel.telemetry;
863
+ if (!reporter) return;
864
+ const spanId = opts.spanId ?? randomBytes(8).toString("hex");
865
+ reporter.reportCustomSpan({
866
+ traceId: opts.traceId,
867
+ spanId,
868
+ parentSpanId: opts.parentSpanId,
869
+ name: opts.name,
870
+ kind: "internal",
871
+ startTime: opts.startTime,
872
+ endTime: opts.endTime,
873
+ attributes: opts.attributes,
874
+ status: {
875
+ code: opts.status === "ok" ? 1 : 2,
876
+ message: opts.statusMessage
877
+ }
878
+ });
542
879
  try {
543
- const reporter = channel.telemetry;
544
- if (!reporter)
545
- return;
546
- const spanId = opts.spanId ?? randomBytes(8).toString("hex");
547
- reporter.reportCustomSpan({
548
- traceId: opts.traceId,
549
- spanId,
550
- parentSpanId: opts.parentSpanId,
551
- name: opts.name,
552
- kind: "internal",
553
- startTime: opts.startTime,
554
- endTime: opts.endTime,
555
- attributes: opts.attributes,
556
- status: {
557
- code: opts.status === "ok" ? 1 : 2,
558
- message: opts.statusMessage,
559
- },
560
- });
561
- // Dual-path: also send via WS for real-time activity streaming
562
- try {
563
- const spanType = _inferSpanType(opts.name);
564
- const spanName = _extractSpanName(opts.name, opts.attributes);
565
- const durationMs = opts.endTime - opts.startTime;
566
- channel.sendActivitySpan({
567
- trace_id: opts.traceId,
568
- span_id: spanId,
569
- parent_span_id: opts.parentSpanId,
570
- span_type: spanType,
571
- span_name: spanName,
572
- status: opts.status,
573
- start_time: new Date(opts.startTime).toISOString(),
574
- end_time: new Date(opts.endTime).toISOString(),
575
- duration_ms: durationMs,
576
- attributes: opts.attributes,
577
- ...(spanType === "llm" ? {
578
- tokens_input: opts.attributes["ai.agent.llm.tokens_input"],
579
- tokens_output: opts.attributes["ai.agent.llm.tokens_output"],
580
- } : {}),
581
- ...(spanType === "http" ? {
582
- http_method: opts.attributes["ai.agent.http.method"],
583
- http_status_code: opts.attributes["ai.agent.http.status_code"],
584
- http_url: opts.attributes["ai.agent.http.url"],
585
- } : {}),
586
- ...(spanType === "tool" ? {
587
- tool_success: opts.attributes["ai.agent.tool.success"],
588
- } : {}),
589
- ...(spanType === "error" ? {
590
- error_type: opts.attributes["ai.agent.error.type"],
591
- error_message: opts.attributes["ai.agent.error.message"],
592
- } : {}),
593
- });
594
- }
595
- catch { /* WS activity is best-effort */ }
880
+ const spanType = _inferSpanType(opts.name);
881
+ const spanName = _extractSpanName(opts.name, opts.attributes);
882
+ const durationMs = opts.endTime - opts.startTime;
883
+ channel.sendActivitySpan({
884
+ trace_id: opts.traceId,
885
+ span_id: spanId,
886
+ parent_span_id: opts.parentSpanId,
887
+ span_type: spanType,
888
+ span_name: spanName,
889
+ status: opts.status,
890
+ start_time: new Date(opts.startTime).toISOString(),
891
+ end_time: new Date(opts.endTime).toISOString(),
892
+ duration_ms: durationMs,
893
+ attributes: opts.attributes,
894
+ ...spanType === "llm" ? {
895
+ tokens_input: opts.attributes["ai.agent.llm.tokens_input"],
896
+ tokens_output: opts.attributes["ai.agent.llm.tokens_output"]
897
+ } : {},
898
+ ...spanType === "http" ? {
899
+ http_method: opts.attributes["ai.agent.http.method"],
900
+ http_status_code: opts.attributes["ai.agent.http.status_code"],
901
+ http_url: opts.attributes["ai.agent.http.url"]
902
+ } : {},
903
+ ...spanType === "tool" ? {
904
+ tool_success: opts.attributes["ai.agent.tool.success"]
905
+ } : {},
906
+ ...spanType === "error" ? {
907
+ error_type: opts.attributes["ai.agent.error.type"],
908
+ error_message: opts.attributes["ai.agent.error.message"]
909
+ } : {}
910
+ });
911
+ } catch {
596
912
  }
597
- catch { /* telemetry is best-effort */ }
913
+ } catch {
914
+ }
598
915
  }
599
- /** Emit the full hierarchical span tree for a message lifecycle. */
600
916
  function _emitHierarchicalSpans(channel, opts) {
601
- try {
602
- const reporter = channel.telemetry;
603
- if (!reporter)
604
- return;
605
- // 1. Inference span: from message arrival to first reply (or end if no replies)
606
- const inferenceEnd = opts.firstReplyTime ?? opts.endTime;
607
- _emitChildSpan(channel, {
608
- traceId: opts.traceId,
609
- parentSpanId: opts.rootSpanId,
610
- spanId: opts.inferenceSpanId,
611
- name: "ai.agent.inference",
612
- startTime: opts.startTime + 1, // just after receive
613
- endTime: inferenceEnd,
614
- attributes: {
615
- "ai.agent.inference.latency_ms": inferenceEnd - opts.startTime,
616
- "ai.agent.message.input_chars": opts.inputChars,
617
- },
618
- status: opts.status,
619
- statusMessage: opts.status === "error" ? opts.statusMessage : undefined,
620
- });
621
- // 2. Individual reply spans
622
- for (const reply of opts.replySpans) {
623
- _emitChildSpan(channel, {
624
- traceId: opts.traceId,
625
- parentSpanId: opts.rootSpanId,
626
- name: "ai.agent.reply",
627
- startTime: reply.startTime,
628
- endTime: reply.endTime,
629
- attributes: {
630
- "ai.agent.reply.index": reply.index,
631
- "ai.agent.reply.chars": reply.chars,
632
- },
633
- status: "ok",
634
- });
635
- }
636
- // 3. Root span (wraps everything) — emitted last
637
- reporter.reportCustomSpan({
638
- traceId: opts.traceId,
639
- spanId: opts.rootSpanId,
640
- name: "ai.agent.message",
641
- kind: "server",
642
- startTime: opts.startTime,
643
- endTime: opts.endTime,
644
- attributes: {
645
- "ai.agent.message.input_chars": opts.inputChars,
646
- "ai.agent.message.reply_count": opts.replyCount,
647
- "ai.agent.message.reply_chars": opts.totalReplyChars,
648
- "ai.agent.message.latency_ms": opts.endTime - opts.startTime,
649
- "ai.agent.message.type": opts.isRoom ? "room" : "direct",
650
- },
651
- status: {
652
- code: opts.status === "ok" ? 1 : 2,
653
- message: opts.statusMessage,
654
- },
655
- });
917
+ try {
918
+ const reporter = channel.telemetry;
919
+ if (!reporter) return;
920
+ const inferenceEnd = opts.firstReplyTime ?? opts.endTime;
921
+ _emitChildSpan(channel, {
922
+ traceId: opts.traceId,
923
+ parentSpanId: opts.rootSpanId,
924
+ spanId: opts.inferenceSpanId,
925
+ name: "ai.agent.inference",
926
+ startTime: opts.startTime + 1,
927
+ // just after receive
928
+ endTime: inferenceEnd,
929
+ attributes: {
930
+ "ai.agent.inference.latency_ms": inferenceEnd - opts.startTime,
931
+ "ai.agent.message.input_chars": opts.inputChars
932
+ },
933
+ status: opts.status,
934
+ statusMessage: opts.status === "error" ? opts.statusMessage : void 0
935
+ });
936
+ for (const reply of opts.replySpans) {
937
+ _emitChildSpan(channel, {
938
+ traceId: opts.traceId,
939
+ parentSpanId: opts.rootSpanId,
940
+ name: "ai.agent.reply",
941
+ startTime: reply.startTime,
942
+ endTime: reply.endTime,
943
+ attributes: {
944
+ "ai.agent.reply.index": reply.index,
945
+ "ai.agent.reply.chars": reply.chars
946
+ },
947
+ status: "ok"
948
+ });
656
949
  }
657
- catch { /* telemetry is best-effort */ }
950
+ reporter.reportCustomSpan({
951
+ traceId: opts.traceId,
952
+ spanId: opts.rootSpanId,
953
+ name: "ai.agent.message",
954
+ kind: "server",
955
+ startTime: opts.startTime,
956
+ endTime: opts.endTime,
957
+ attributes: {
958
+ "ai.agent.message.input_chars": opts.inputChars,
959
+ "ai.agent.message.reply_count": opts.replyCount,
960
+ "ai.agent.message.reply_chars": opts.totalReplyChars,
961
+ "ai.agent.message.latency_ms": opts.endTime - opts.startTime,
962
+ "ai.agent.message.type": opts.isRoom ? "room" : "direct"
963
+ },
964
+ status: {
965
+ code: opts.status === "ok" ? 1 : 2,
966
+ message: opts.statusMessage
967
+ }
968
+ });
969
+ } catch {
970
+ }
658
971
  }
659
- // --- Channel plugin definition ---
660
- const agentVaultPlugin = {
972
+ var agentVaultPlugin = {
973
+ id: "agentvault",
974
+ meta: {
661
975
  id: "agentvault",
662
- meta: {
663
- id: "agentvault",
664
- label: "AgentVault",
665
- selectionLabel: "AgentVault (E2E Encrypted)",
666
- docsPath: "https://agentvault.chat/docs",
667
- blurb: "Zero-knowledge, end-to-end encrypted messaging between owners and their AI agents.",
668
- aliases: ["av", "agent-vault"],
976
+ label: "AgentVault",
977
+ selectionLabel: "AgentVault (E2E Encrypted)",
978
+ docsPath: "https://agentvault.chat/docs",
979
+ blurb: "Zero-knowledge, end-to-end encrypted messaging between owners and their AI agents.",
980
+ aliases: ["av", "agent-vault"]
981
+ },
982
+ capabilities: { chatTypes: ["direct", "room"] },
983
+ config: { listAccountIds, resolveAccount },
984
+ gateway: {
985
+ /** Health probe for `openclaw channels status --probe` */
986
+ probe: async (ctx) => {
987
+ const accountId = ctx?.accountId ?? "default";
988
+ const ch = _channels.get(accountId);
989
+ if (!ch) return { ok: false, status: "disconnected", error: "Channel not started" };
990
+ const state = ch.state;
991
+ return {
992
+ ok: state === "ready",
993
+ status: state,
994
+ deviceId: ch.deviceId ?? void 0,
995
+ sessions: ch.sessionCount
996
+ };
669
997
  },
670
- capabilities: { chatTypes: ["direct", "room"] },
671
- config: { listAccountIds, resolveAccount },
672
- gateway: {
673
- /** Health probe for `openclaw channels status --probe` */
674
- probe: async (ctx) => {
675
- const accountId = ctx?.accountId ?? "default";
676
- const ch = _channels.get(accountId);
677
- if (!ch)
678
- return { ok: false, status: "disconnected", error: "Channel not started" };
679
- const state = ch.state;
680
- return {
681
- ok: state === "ready",
682
- status: state,
683
- deviceId: ch.deviceId ?? undefined,
684
- sessions: ch.sessionCount,
685
- };
686
- },
687
- /** Status for `openclaw health --json` per-channel summary */
688
- status: (ctx) => {
689
- const accountId = ctx?.accountId ?? "default";
690
- const ch = _channels.get(accountId);
691
- if (!ch)
692
- return { connected: false, status: "not_started" };
693
- return {
694
- connected: ch.state === "ready",
695
- status: ch.state,
696
- deviceId: ch.deviceId ?? undefined,
697
- sessions: ch.sessionCount,
698
- encrypted: true,
699
- };
700
- },
701
- startAccount: async (ctx) => {
702
- const { account, cfg, log, abortSignal } = ctx;
703
- const _log = typeof log === "function" ? log : log?.info?.bind(log);
704
- if (!account.configured) {
705
- throw new Error("AgentVault channel not configured. Run: npx @agentvault/agentvault setup --token=av_tok_...\nThen restart OpenClaw.");
706
- }
707
- const dataDir = resolve(account.dataDir.replace(/^~/, process.env.HOME ?? "~"));
708
- _log?.(`[AgentVault] starting (dataDir=${dataDir})`);
709
- // startAccount must STAY PENDING while the channel is running.
710
- // Resolving signals "channel stopped" to the gateway health monitor,
711
- // which triggers auto-restart. We block here until the abortSignal
712
- // fires (gateway shutdown / config reload), then clean up.
713
- await new Promise((resolve, reject) => {
714
- let channel;
715
- const onAbort = async () => {
716
- await channel?.stop();
717
- _channels.delete(account.accountId);
718
- resolve();
719
- };
720
- abortSignal?.addEventListener("abort", () => void onAbort());
721
- // Lazy import — defers libsodium initialization until channel starts
722
- import("./index.js").then(({ SecureChannel }) => {
723
- channel = new SecureChannel({
724
- inviteToken: "",
725
- dataDir,
726
- apiUrl: account.apiUrl,
727
- agentName: account.agentName,
728
- onMessage: async (plaintext, metadata) => {
729
- if (!_ocRuntime) {
730
- _log?.("[AgentVault] runtime not ready, queuing message");
731
- _messageQueue.push(async () => {
732
- await handleInbound({ plaintext, metadata, channel, account, cfg });
733
- });
734
- return;
735
- }
736
- try {
737
- await handleInbound({ plaintext, metadata, channel, account, cfg });
738
- }
739
- catch (err) {
740
- _log?.(`[AgentVault] inbound error: ${String(err)}`);
741
- }
742
- },
743
- onA2AMessage: async (msg) => {
744
- const a2aMetadata = {
745
- a2aChannelId: msg.channelId,
746
- fromHubAddress: msg.fromHubAddress,
747
- conversationId: msg.conversationId,
748
- timestamp: msg.timestamp,
749
- parentSpanId: msg.parentSpanId,
750
- messageId: `a2a:${msg.channelId}:${Date.now()}`,
751
- };
752
- if (!_ocRuntime) {
753
- _log?.("[AgentVault] runtime not ready, queuing A2A message");
754
- _messageQueue.push(async () => {
755
- await handleInbound({ plaintext: msg.text, metadata: a2aMetadata, channel, account, cfg });
756
- });
757
- return;
758
- }
759
- try {
760
- await handleInbound({ plaintext: msg.text, metadata: a2aMetadata, channel, account, cfg });
761
- }
762
- catch (err) {
763
- _log?.(`[AgentVault] A2A inbound error: ${String(err)}`);
764
- }
765
- },
766
- onA2AChannelReady: async (info) => {
767
- // Register peer as valid outbound target (both roles)
768
- _registerA2ATarget(info.peerHubAddress, account.accountId);
769
- // Only initiator sends the seed message
770
- if (info.role !== "initiator") {
771
- _log?.(`[AgentVault] A2A channel ready (responder) — waiting for initiator: ${info.peerHubAddress}`);
772
- return;
773
- }
774
- _log?.(`[AgentVault] A2A channel ready (initiator) — sending seed to ${info.peerHubAddress}${info.topic ? ` [topic: ${info.topic}]` : ""}`);
775
- const seedText = info.topic
776
- ? `[System] A new A2A channel has been established with agent ${info.peerHubAddress}. ` +
777
- `Topic: "${info.topic}". ` +
778
- `Introduce yourself briefly and begin discussing this topic.`
779
- : `[System] A new A2A channel has been established with agent ${info.peerHubAddress}. ` +
780
- `Introduce yourself briefly and state what you can help with.`;
781
- const seedMetadata = {
782
- a2aChannelId: info.channelId,
783
- fromHubAddress: info.peerHubAddress,
784
- conversationId: info.conversationId,
785
- timestamp: new Date().toISOString(),
786
- messageId: `a2a-seed:${info.channelId}:${Date.now()}`,
787
- };
788
- if (!_ocRuntime) {
789
- _log?.("[AgentVault] runtime not ready, queuing A2A seed");
790
- _messageQueue.push(async () => {
791
- await handleInbound({ plaintext: seedText, metadata: seedMetadata, channel, account, cfg });
792
- });
793
- return;
794
- }
795
- try {
796
- await handleInbound({ plaintext: seedText, metadata: seedMetadata, channel, account, cfg });
797
- }
798
- catch (err) {
799
- _log?.(`[AgentVault] A2A seed error: ${String(err)}`);
800
- }
801
- },
802
- onStateChange: (state) => {
803
- _log?.(`[AgentVault] → ${state}`);
804
- // "error" is a permanent failure — reject so gateway can restart
805
- if (state === "error")
806
- reject(new Error("AgentVault channel permanent error"));
807
- // All other states (connecting/ready/disconnected) are handled
808
- // internally by SecureChannel's reconnect logic — do NOT resolve.
809
- },
810
- });
811
- _channels.set(account.accountId, channel);
812
- // Prevent unhandled "error" events from crashing the process.
813
- // Without this handler, Node.js EventEmitter throws on emit("error").
814
- channel.on("error", (err) => {
815
- _log?.(`[AgentVault] channel error (non-fatal): ${String(err)}`);
816
- });
817
- // Always start local HTTP server — managed routes are an overlay, not a replacement
818
- const httpPort = account.httpPort ?? 18790;
819
- channel.on("ready", () => {
820
- channel.startHttpServer(httpPort);
821
- _log?.(`[AgentVault] HTTP send server listening on http://127.0.0.1:${httpPort}`);
822
- if (isUsingManagedRoutes) {
823
- _log?.(`[AgentVault] OpenClaw managed routes also registered`);
824
- }
825
- // Register persisted A2A peers as valid outbound targets
826
- for (const peerAddress of channel.a2aPeerAddresses) {
827
- _registerA2ATarget(peerAddress, account.accountId);
828
- }
829
- // Register persisted rooms as valid outbound targets
830
- for (const room of channel.roomIds) {
831
- _registerRoomTarget(room.roomId, room.name, account.accountId);
832
- }
833
- });
834
- // Register new rooms as outbound targets when agent joins
835
- channel.on("room_joined", (info) => {
836
- _registerRoomTarget(info.roomId, info.name, account.accountId);
837
- });
838
- channel.start().catch(reject);
839
- }).catch(reject);
840
- });
841
- return { stop: async () => { } }; // Channel already stopped via abortSignal by this point
842
- },
998
+ /** Status for `openclaw health --json` per-channel summary */
999
+ status: (ctx) => {
1000
+ const accountId = ctx?.accountId ?? "default";
1001
+ const ch = _channels.get(accountId);
1002
+ if (!ch) return { connected: false, status: "not_started" };
1003
+ return {
1004
+ connected: ch.state === "ready",
1005
+ status: ch.state,
1006
+ deviceId: ch.deviceId ?? void 0,
1007
+ sessions: ch.sessionCount,
1008
+ encrypted: true
1009
+ };
843
1010
  },
844
- outbound: {
845
- deliveryMode: "direct",
846
- // Register valid send targets so OpenClaw's `message` tool can route
847
- // proactive (agent-initiated) sends — not just replies to inbound messages.
848
- targets: _outboundTargets,
849
- sendText: async ({ to, text, accountId }) => {
850
- const resolvedId = accountId ?? "default";
851
- const ch = _channels.get(resolvedId);
852
- if (!ch)
853
- return { ok: false, error: "AgentVault channel not connected" };
854
- try {
855
- const wasReady = ch.state === "ready";
856
- if (to.startsWith("a2a:")) {
857
- await ch.sendToAgent(to.slice(4), text);
858
- }
859
- else if (to.startsWith("room:")) {
860
- await ch.sendToRoom(to.slice(5), text);
861
- }
862
- else {
863
- // "owner"/"default" auto-route to room if context exists
864
- const roomId = ch.lastInboundRoomId;
865
- if (roomId) {
866
- await ch.sendToRoom(roomId, text);
867
- }
868
- else {
869
- await ch.send(text);
870
- }
871
- }
872
- return { ok: true, queued: !wasReady };
873
- }
874
- catch (err) {
875
- return { ok: false, error: String(err) };
876
- }
877
- },
878
- sendMedia: async ({ to, text, mediaUrl, accountId }) => {
879
- const resolvedId = accountId ?? "default";
880
- const ch = _channels.get(resolvedId);
881
- if (!ch)
882
- return { ok: false, error: "AgentVault channel not connected" };
883
- try {
884
- // For now, send media URL as text — AgentVault handles attachments separately
885
- const message = text ? `${text}\n${mediaUrl}` : mediaUrl;
886
- const wasReady = ch.state === "ready";
887
- if (to.startsWith("a2a:")) {
888
- await ch.sendToAgent(to.slice(4), message);
889
- }
890
- else if (to.startsWith("room:")) {
891
- await ch.sendToRoom(to.slice(5), message);
892
- }
893
- else {
894
- // "owner"/"default" auto-route to room if context exists
895
- const roomId = ch.lastInboundRoomId;
896
- if (roomId) {
897
- await ch.sendToRoom(roomId, message);
898
- }
899
- else {
900
- await ch.send(message);
901
- }
902
- }
903
- return { ok: true, queued: !wasReady };
1011
+ startAccount: async (ctx) => {
1012
+ const { account, cfg, log, abortSignal } = ctx;
1013
+ const _log = typeof log === "function" ? log : log?.info?.bind(log);
1014
+ if (!account.configured) {
1015
+ throw new Error(
1016
+ "AgentVault channel not configured. Run: npx @agentvault/agentvault setup --token=av_tok_...\nThen restart OpenClaw."
1017
+ );
1018
+ }
1019
+ const dataDir = resolve(account.dataDir.replace(/^~/, __require("node:os").homedir()));
1020
+ _log?.(`[AgentVault] starting (dataDir=${dataDir})`);
1021
+ await new Promise((resolve2, reject) => {
1022
+ let channel;
1023
+ const onAbort = async () => {
1024
+ await channel?.stop();
1025
+ _channels.delete(account.accountId);
1026
+ resolve2();
1027
+ };
1028
+ abortSignal?.addEventListener("abort", () => void onAbort());
1029
+ import("./index.js").then(({ SecureChannel }) => {
1030
+ channel = new SecureChannel({
1031
+ inviteToken: "",
1032
+ dataDir,
1033
+ apiUrl: account.apiUrl,
1034
+ agentName: account.agentName,
1035
+ onMessage: async (plaintext, metadata) => {
1036
+ if (!_ocRuntime) {
1037
+ _log?.("[AgentVault] runtime not ready, queuing message");
1038
+ _messageQueue.push(async () => {
1039
+ await handleInbound({ plaintext, metadata, channel, account, cfg });
1040
+ });
1041
+ return;
1042
+ }
1043
+ try {
1044
+ await handleInbound({ plaintext, metadata, channel, account, cfg });
1045
+ } catch (err) {
1046
+ _log?.(`[AgentVault] inbound error: ${String(err)}`);
1047
+ }
1048
+ },
1049
+ onA2AMessage: async (msg) => {
1050
+ const a2aMetadata = {
1051
+ a2aChannelId: msg.channelId,
1052
+ fromHubAddress: msg.fromHubAddress,
1053
+ conversationId: msg.conversationId,
1054
+ timestamp: msg.timestamp,
1055
+ parentSpanId: msg.parentSpanId,
1056
+ messageId: `a2a:${msg.channelId}:${Date.now()}`
1057
+ };
1058
+ if (!_ocRuntime) {
1059
+ _log?.("[AgentVault] runtime not ready, queuing A2A message");
1060
+ _messageQueue.push(async () => {
1061
+ await handleInbound({ plaintext: msg.text, metadata: a2aMetadata, channel, account, cfg });
1062
+ });
1063
+ return;
1064
+ }
1065
+ try {
1066
+ await handleInbound({ plaintext: msg.text, metadata: a2aMetadata, channel, account, cfg });
1067
+ } catch (err) {
1068
+ _log?.(`[AgentVault] A2A inbound error: ${String(err)}`);
1069
+ }
1070
+ },
1071
+ onA2AChannelReady: async (info) => {
1072
+ _registerA2ATarget(info.peerHubAddress, account.accountId);
1073
+ if (info.role !== "initiator") {
1074
+ _log?.(`[AgentVault] A2A channel ready (responder) \u2014 waiting for initiator: ${info.peerHubAddress}`);
1075
+ return;
1076
+ }
1077
+ _log?.(`[AgentVault] A2A channel ready (initiator) \u2014 sending seed to ${info.peerHubAddress}${info.topic ? ` [topic: ${info.topic}]` : ""}`);
1078
+ const seedText = info.topic ? `[System] A new A2A channel has been established with agent ${info.peerHubAddress}. Topic: "${info.topic}". Introduce yourself briefly and begin discussing this topic.` : `[System] A new A2A channel has been established with agent ${info.peerHubAddress}. Introduce yourself briefly and state what you can help with.`;
1079
+ const seedMetadata = {
1080
+ a2aChannelId: info.channelId,
1081
+ fromHubAddress: info.peerHubAddress,
1082
+ conversationId: info.conversationId,
1083
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1084
+ messageId: `a2a-seed:${info.channelId}:${Date.now()}`
1085
+ };
1086
+ if (!_ocRuntime) {
1087
+ _log?.("[AgentVault] runtime not ready, queuing A2A seed");
1088
+ _messageQueue.push(async () => {
1089
+ await handleInbound({ plaintext: seedText, metadata: seedMetadata, channel, account, cfg });
1090
+ });
1091
+ return;
1092
+ }
1093
+ try {
1094
+ await handleInbound({ plaintext: seedText, metadata: seedMetadata, channel, account, cfg });
1095
+ } catch (err) {
1096
+ _log?.(`[AgentVault] A2A seed error: ${String(err)}`);
1097
+ }
1098
+ },
1099
+ onStateChange: (state) => {
1100
+ _log?.(`[AgentVault] \u2192 ${state}`);
1101
+ if (state === "error") reject(new Error("AgentVault channel permanent error"));
904
1102
  }
905
- catch (err) {
906
- return { ok: false, error: String(err) };
1103
+ });
1104
+ _channels.set(account.accountId, channel);
1105
+ channel.on("error", (err) => {
1106
+ _log?.(`[AgentVault] channel error (non-fatal): ${String(err)}`);
1107
+ });
1108
+ const httpPort = account.httpPort ?? 18790;
1109
+ channel.on("ready", () => {
1110
+ channel.startHttpServer(httpPort);
1111
+ _log?.(`[AgentVault] HTTP send server listening on http://127.0.0.1:${httpPort}`);
1112
+ if (isUsingManagedRoutes) {
1113
+ _log?.(`[AgentVault] OpenClaw managed routes also registered`);
907
1114
  }
908
- },
909
- /** Rich payload delivery — OpenClaw v2026.3.2+ calls this for structured messages. */
910
- sendPayload: async (ctx) => {
911
- const { payload, accountId } = ctx;
912
- const resolvedId = accountId ?? "default";
913
- const ch = _channels.get(resolvedId);
914
- if (!ch)
915
- return { ok: false, error: "AgentVault channel not connected" };
916
- try {
917
- // Suppress reasoning blocks — E2E channel should only deliver actual responses
918
- if (payload.isReasoning)
919
- return { ok: true };
920
- // Wake agent proactively before sending (fire-and-forget)
921
- requestHeartbeatNow({ reason: "outbound-payload" }).catch(() => { });
922
- const text = (payload.text ?? "").trim();
923
- if (!text && !payload.mediaUrls?.length)
924
- return { ok: true };
925
- // Helper: route through A2A, room, or direct depending on target
926
- const _send = async (msg) => {
927
- const target = ctx.to;
928
- if (target && typeof target === "string" && target.startsWith("a2a:")) {
929
- await ch.sendToAgent(target.slice(4), msg);
930
- }
931
- else if (target && typeof target === "string" && target.startsWith("room:")) {
932
- await ch.sendToRoom(target.slice(5), msg);
933
- }
934
- else {
935
- // "owner"/"default" — auto-route to room if context exists
936
- const roomId = ch.lastInboundRoomId;
937
- if (roomId) {
938
- await ch.sendToRoom(roomId, msg);
939
- }
940
- else {
941
- await ch.send(msg);
942
- }
943
- }
944
- };
945
- // Encrypt and deliver text content
946
- if (text) {
947
- await _send(text);
948
- }
949
- // Deliver media URLs as text messages (E2E encrypted)
950
- if (payload.mediaUrls?.length) {
951
- for (const url of payload.mediaUrls) {
952
- await _send(url);
953
- }
954
- }
955
- // Forward suggested actions as a structured message
956
- if (payload.suggestedActions?.length) {
957
- const actionsText = payload.suggestedActions
958
- .map((a) => `- ${a.label}: ${a.action}`)
959
- .join("\n");
960
- await _send(`Suggested actions:\n${actionsText}`);
961
- }
962
- return { ok: true };
1115
+ for (const peerAddress of channel.a2aPeerAddresses) {
1116
+ _registerA2ATarget(peerAddress, account.accountId);
963
1117
  }
964
- catch (err) {
965
- return { ok: false, error: String(err) };
1118
+ for (const room of channel.roomIds) {
1119
+ _registerRoomTarget(room.roomId, room.name, account.accountId);
966
1120
  }
967
- },
1121
+ });
1122
+ channel.on("room_joined", (info) => {
1123
+ _registerRoomTarget(info.roomId, info.name, account.accountId);
1124
+ });
1125
+ channel.start().catch(reject);
1126
+ }).catch(reject);
1127
+ });
1128
+ return { stop: async () => {
1129
+ } };
1130
+ }
1131
+ },
1132
+ outbound: {
1133
+ deliveryMode: "direct",
1134
+ // Register valid send targets so OpenClaw's `message` tool can route
1135
+ // proactive (agent-initiated) sends — not just replies to inbound messages.
1136
+ targets: _outboundTargets,
1137
+ sendText: async ({ to, text, accountId }) => {
1138
+ const resolvedId = accountId ?? "default";
1139
+ const ch = _channels.get(resolvedId);
1140
+ if (!ch) return { ok: false, error: "AgentVault channel not connected" };
1141
+ try {
1142
+ const wasReady = ch.state === "ready";
1143
+ if (to.startsWith("a2a:")) {
1144
+ await ch.sendToAgent(to.slice(4), text);
1145
+ } else if (to.startsWith("room:")) {
1146
+ await ch.sendToRoom(to.slice(5), text);
1147
+ } else {
1148
+ const roomId = ch.lastInboundRoomId;
1149
+ if (roomId) {
1150
+ await ch.sendToRoom(roomId, text);
1151
+ } else {
1152
+ await ch.send(text);
1153
+ }
1154
+ }
1155
+ return { ok: true, queued: !wasReady };
1156
+ } catch (err) {
1157
+ return { ok: false, error: String(err) };
1158
+ }
968
1159
  },
969
- };
970
- // --- Exported for testing ---
971
- export { _parseMentions, _shouldProcessRoomMessage, _stripMentions };
972
- // --- Plugin export ---
973
- export default {
974
- id: "agentvault",
975
- name: "AgentVault",
976
- description: "End-to-end encrypted, zero-knowledge messaging between AI agent owners and their agents.",
977
- register(api) {
978
- _setRuntime(api.runtime);
979
- // Install fetch interceptor to capture all outbound HTTP from the gateway process.
980
- installFetchInterceptor({
981
- onHttpCall: (report) => {
982
- // Find an active channel to emit through
983
- const ch = _channels.values().next().value;
984
- if (!ch)
985
- return;
986
- // Telemetry reporter is optional — may not be initialized
987
- if (ch.telemetry) {
988
- try {
989
- ch.telemetry.reportHttpCall({
990
- method: report.method,
991
- url: report.url,
992
- statusCode: report.statusCode,
993
- latencyMs: report.latencyMs,
994
- ...(report.traceId ? { traceId: report.traceId } : {}),
995
- ...(report.parentSpanId ? { parentSpanId: report.parentSpanId } : {}),
996
- });
997
- }
998
- catch { /* best-effort */ }
999
- }
1000
- // Activity span always fires (uses WS, not telemetry reporter)
1001
- try {
1002
- const hostname = (() => { try {
1003
- return new URL(report.url).hostname;
1004
- }
1005
- catch {
1006
- return report.url.slice(0, 40);
1007
- } })();
1008
- ch.sendActivitySpan({
1009
- trace_id: report.traceId ?? "",
1010
- parent_span_id: report.parentSpanId ?? "",
1011
- span_id: randomBytes(8).toString("hex"),
1012
- span_type: "http",
1013
- span_name: hostname,
1014
- status: report.statusCode >= 400 || report.statusCode === 0 ? "error" : "ok",
1015
- start_time: new Date(Date.now() - report.latencyMs).toISOString(),
1016
- end_time: new Date().toISOString(),
1017
- duration_ms: report.latencyMs,
1018
- attributes: {
1019
- "ai.agent.http.method": report.method,
1020
- "ai.agent.http.url": report.url,
1021
- },
1022
- http_method: report.method,
1023
- http_status_code: report.statusCode,
1024
- http_url: report.url,
1025
- });
1026
- }
1027
- catch { /* best-effort */ }
1028
- },
1160
+ sendMedia: async ({ to, text, mediaUrl, accountId }) => {
1161
+ const resolvedId = accountId ?? "default";
1162
+ const ch = _channels.get(resolvedId);
1163
+ if (!ch) return { ok: false, error: "AgentVault channel not connected" };
1164
+ try {
1165
+ const message = text ? `${text}
1166
+ ${mediaUrl}` : mediaUrl;
1167
+ const wasReady = ch.state === "ready";
1168
+ if (to.startsWith("a2a:")) {
1169
+ await ch.sendToAgent(to.slice(4), message);
1170
+ } else if (to.startsWith("room:")) {
1171
+ await ch.sendToRoom(to.slice(5), message);
1172
+ } else {
1173
+ const roomId = ch.lastInboundRoomId;
1174
+ if (roomId) {
1175
+ await ch.sendToRoom(roomId, message);
1176
+ } else {
1177
+ await ch.send(message);
1178
+ }
1179
+ }
1180
+ return { ok: true, queued: !wasReady };
1181
+ } catch (err) {
1182
+ return { ok: false, error: String(err) };
1183
+ }
1184
+ },
1185
+ /** Rich payload delivery — OpenClaw v2026.3.2+ calls this for structured messages. */
1186
+ sendPayload: async (ctx) => {
1187
+ const { payload, accountId } = ctx;
1188
+ const resolvedId = accountId ?? "default";
1189
+ const ch = _channels.get(resolvedId);
1190
+ if (!ch) return { ok: false, error: "AgentVault channel not connected" };
1191
+ try {
1192
+ if (payload.isReasoning) return { ok: true };
1193
+ requestHeartbeatNow({ reason: "outbound-payload" }).catch(() => {
1029
1194
  });
1030
- api.registerChannel({ plugin: agentVaultPlugin });
1031
- // --- Managed HTTP routes (OpenClaw v2026.3.2+) ---
1032
- if (typeof api.registerHttpRoute === "function") {
1033
- try {
1034
- api.registerHttpRoute({
1035
- path: "/agentvault/send",
1036
- method: "POST",
1037
- handler: async (req) => {
1038
- const ch = _channels.values().next().value;
1039
- if (!ch)
1040
- return { status: 503, body: { ok: false, error: "Channel not started" } };
1041
- const parsed = (typeof req.body === "string" ? JSON.parse(req.body) : req.body);
1042
- const result = await handleSendRequest(parsed, ch);
1043
- return { status: result.status, body: result.body };
1044
- },
1045
- });
1046
- api.registerHttpRoute({
1047
- path: "/agentvault/action",
1048
- method: "POST",
1049
- handler: async (req) => {
1050
- const ch = _channels.values().next().value;
1051
- if (!ch)
1052
- return { status: 503, body: { ok: false, error: "Channel not started" } };
1053
- const parsed = (typeof req.body === "string" ? JSON.parse(req.body) : req.body);
1054
- const result = await handleActionRequest(parsed, ch);
1055
- return { status: result.status, body: result.body };
1056
- },
1057
- });
1058
- api.registerHttpRoute({
1059
- path: "/agentvault/decision",
1060
- method: "POST",
1061
- handler: async (req) => {
1062
- const ch = _channels.values().next().value;
1063
- if (!ch)
1064
- return { status: 503, body: { ok: false, error: "Channel not started" } };
1065
- const parsed = (typeof req.body === "string" ? JSON.parse(req.body) : req.body);
1066
- const result = await handleDecisionRequest(parsed, ch);
1067
- return { status: result.status, body: result.body };
1068
- },
1069
- });
1070
- api.registerHttpRoute({
1071
- path: "/agentvault/status",
1072
- method: "GET",
1073
- handler: async () => {
1074
- const ch = _channels.values().next().value;
1075
- if (!ch)
1076
- return { status: 503, body: { ok: false, error: "Channel not started" } };
1077
- const result = handleStatusRequest(ch);
1078
- return { status: result.status, body: result.body };
1079
- },
1080
- });
1081
- isUsingManagedRoutes = true;
1195
+ const text = (payload.text ?? "").trim();
1196
+ if (!text && !payload.mediaUrls?.length) return { ok: true };
1197
+ const _send = async (msg) => {
1198
+ const target = ctx.to;
1199
+ if (target && typeof target === "string" && target.startsWith("a2a:")) {
1200
+ await ch.sendToAgent(target.slice(4), msg);
1201
+ } else if (target && typeof target === "string" && target.startsWith("room:")) {
1202
+ await ch.sendToRoom(target.slice(5), msg);
1203
+ } else {
1204
+ const roomId = ch.lastInboundRoomId;
1205
+ if (roomId) {
1206
+ await ch.sendToRoom(roomId, msg);
1207
+ } else {
1208
+ await ch.send(msg);
1082
1209
  }
1083
- catch { /* registerHttpRoute failed — fall back to self-managed server */ }
1210
+ }
1211
+ };
1212
+ if (text) {
1213
+ await _send(text);
1084
1214
  }
1085
- // --- Event hooks (OpenClaw v2026.3.2+) ---
1086
- if (typeof api.on === "function") {
1087
- // Phase 4: message_sent — delivery confirmation tracking
1088
- api.on("message_sent", async (event) => {
1089
- try {
1090
- const ch = _channels.values().next().value;
1091
- if (!ch?.telemetry)
1092
- return;
1093
- ch.telemetry.reportCustomSpan({
1094
- traceId: randomBytes(16).toString("hex"),
1095
- spanId: randomBytes(8).toString("hex"),
1096
- name: "agentvault.message.delivered",
1097
- kind: "internal",
1098
- startTime: event.timestamp,
1099
- endTime: event.timestamp + 1,
1100
- attributes: {
1101
- "agentvault.message.id": event.messageId,
1102
- "agentvault.delivery.status": event.deliveryStatus,
1103
- "agentvault.channel.id": event.channelId,
1104
- },
1105
- status: { code: event.deliveryStatus === "failed" ? 2 : 1 },
1106
- });
1107
- }
1108
- catch { /* best-effort */ }
1109
- });
1110
- // Phase 6: session lifecycle hooks
1111
- api.on("session_start", async (event) => {
1112
- try {
1113
- const ch = _channels.values().next().value;
1114
- if (!ch?.telemetry)
1115
- return;
1116
- ch.telemetry.reportCustomSpan({
1117
- traceId: randomBytes(16).toString("hex"),
1118
- spanId: randomBytes(8).toString("hex"),
1119
- name: "agentvault.session.start",
1120
- kind: "internal",
1121
- startTime: event.timestamp,
1122
- endTime: event.timestamp + 1,
1123
- attributes: {
1124
- "agentvault.session.key": event.sessionKey,
1125
- "agentvault.agent.id": event.agentId,
1126
- },
1127
- status: { code: 1 },
1128
- });
1129
- }
1130
- catch { /* best-effort */ }
1131
- });
1132
- api.on("session_end", async (event) => {
1133
- try {
1134
- const ch = _channels.values().next().value;
1135
- if (!ch?.telemetry)
1136
- return;
1137
- ch.telemetry.reportCustomSpan({
1138
- traceId: randomBytes(16).toString("hex"),
1139
- spanId: randomBytes(8).toString("hex"),
1140
- name: "agentvault.session.end",
1141
- kind: "internal",
1142
- startTime: event.timestamp,
1143
- endTime: event.timestamp + 1,
1144
- attributes: {
1145
- "agentvault.session.key": event.sessionKey,
1146
- "agentvault.agent.id": event.agentId,
1147
- ...(event.reason ? { "agentvault.session.end_reason": event.reason } : {}),
1148
- },
1149
- status: { code: 1 },
1150
- });
1151
- }
1152
- catch { /* best-effort */ }
1215
+ if (payload.mediaUrls?.length) {
1216
+ for (const url of payload.mediaUrls) {
1217
+ await _send(url);
1218
+ }
1219
+ }
1220
+ if (payload.suggestedActions?.length) {
1221
+ const actionsText = payload.suggestedActions.map((a) => `- ${a.label}: ${a.action}`).join("\n");
1222
+ await _send(`Suggested actions:
1223
+ ${actionsText}`);
1224
+ }
1225
+ return { ok: true };
1226
+ } catch (err) {
1227
+ return { ok: false, error: String(err) };
1228
+ }
1229
+ }
1230
+ }
1231
+ };
1232
+ var openclaw_entry_default = {
1233
+ id: "agentvault",
1234
+ name: "AgentVault",
1235
+ description: "End-to-end encrypted, zero-knowledge messaging between AI agent owners and their agents.",
1236
+ register(api) {
1237
+ _setRuntime(api.runtime);
1238
+ installFetchInterceptor({
1239
+ onHttpCall: (report) => {
1240
+ const ch = _channels.values().next().value;
1241
+ if (!ch) return;
1242
+ if (ch.telemetry) {
1243
+ try {
1244
+ ch.telemetry.reportHttpCall({
1245
+ method: report.method,
1246
+ url: report.url,
1247
+ statusCode: report.statusCode,
1248
+ latencyMs: report.latencyMs,
1249
+ ...report.traceId ? { traceId: report.traceId } : {},
1250
+ ...report.parentSpanId ? { parentSpanId: report.parentSpanId } : {}
1153
1251
  });
1252
+ } catch {
1253
+ }
1154
1254
  }
1155
- // --- Phase 7: Agent events for trust telemetry ---
1156
- import("./openclaw-compat.js").then(async ({ onAgentEvent, onSessionTranscriptUpdate }) => {
1157
- onAgentEvent((event) => {
1158
- try {
1159
- const ch = _channels.values().next().value;
1160
- if (!ch?.telemetry)
1161
- return;
1162
- ch.telemetry.reportCustomSpan({
1163
- traceId: randomBytes(16).toString("hex"),
1164
- spanId: randomBytes(8).toString("hex"),
1165
- name: `ai.agent.event.${event.type}`,
1166
- kind: "internal",
1167
- startTime: event.timestamp,
1168
- endTime: event.timestamp + 1,
1169
- attributes: {
1170
- "ai.agent.event.type": event.type,
1171
- "ai.agent.id": event.agentId,
1172
- ...(event.data ? Object.fromEntries(Object.entries(event.data).map(([k, v]) => [`ai.agent.event.${k}`, String(v)])) : {}),
1173
- },
1174
- status: { code: 1 },
1175
- });
1176
- }
1177
- catch { /* best-effort */ }
1178
- }).catch(() => { });
1179
- onSessionTranscriptUpdate((update) => {
1180
- try {
1181
- const ch = _channels.values().next().value;
1182
- if (!ch?.telemetry)
1183
- return;
1184
- ch.telemetry.reportCustomSpan({
1185
- traceId: randomBytes(16).toString("hex"),
1186
- spanId: randomBytes(8).toString("hex"),
1187
- name: "ai.agent.transcript.update",
1188
- kind: "internal",
1189
- startTime: update.timestamp,
1190
- endTime: update.timestamp + 1,
1191
- attributes: {
1192
- "agentvault.session.key": update.sessionKey,
1193
- "ai.agent.transcript.role": update.role ?? "unknown",
1194
- "ai.agent.transcript.delta_chars": update.delta.length,
1195
- },
1196
- status: { code: 1 },
1197
- });
1198
- }
1199
- catch { /* best-effort */ }
1200
- }).catch(() => { });
1201
- }).catch(() => { });
1202
- // --- Agent tool: agentvault_status ---
1203
- // Lets the agent check its own encrypted channel status
1204
1255
  try {
1205
- api.registerTool?.({
1206
- name: "agentvault_status",
1207
- description: "Check the AgentVault encrypted channel status, connection state, and session count.",
1208
- parameters: {
1209
- type: "object",
1210
- properties: {
1211
- accountId: {
1212
- type: "string",
1213
- description: "Account ID to check (default: 'default')",
1214
- },
1215
- },
1216
- },
1217
- execute: async (_id, params) => {
1218
- const id = params.accountId ?? "default";
1219
- const ch = _channels.get(id);
1220
- if (!ch) {
1221
- return { content: [{ type: "text", text: JSON.stringify({ connected: false, error: "Channel not started" }) }] };
1222
- }
1223
- return {
1224
- content: [{
1225
- type: "text",
1226
- text: JSON.stringify({
1227
- connected: ch.state === "ready",
1228
- state: ch.state,
1229
- deviceId: ch.deviceId,
1230
- sessions: ch.sessionCount,
1231
- encrypted: true,
1232
- }),
1233
- }],
1234
- };
1235
- },
1236
- }, { optional: true });
1256
+ const hostname = (() => {
1257
+ try {
1258
+ return new URL(report.url).hostname;
1259
+ } catch {
1260
+ return report.url.slice(0, 40);
1261
+ }
1262
+ })();
1263
+ ch.sendActivitySpan({
1264
+ trace_id: report.traceId ?? "",
1265
+ parent_span_id: report.parentSpanId ?? "",
1266
+ span_id: randomBytes(8).toString("hex"),
1267
+ span_type: "http",
1268
+ span_name: hostname,
1269
+ status: report.statusCode >= 400 || report.statusCode === 0 ? "error" : "ok",
1270
+ start_time: new Date(Date.now() - report.latencyMs).toISOString(),
1271
+ end_time: (/* @__PURE__ */ new Date()).toISOString(),
1272
+ duration_ms: report.latencyMs,
1273
+ attributes: {
1274
+ "ai.agent.http.method": report.method,
1275
+ "ai.agent.http.url": report.url
1276
+ },
1277
+ http_method: report.method,
1278
+ http_status_code: report.statusCode,
1279
+ http_url: report.url
1280
+ });
1281
+ } catch {
1237
1282
  }
1238
- catch { /* registerTool may not be available in older OpenClaw versions */ }
1239
- // --- Auto-reply command: /agentvault ---
1240
- // Quick status check without AI involvement
1283
+ }
1284
+ });
1285
+ api.registerChannel({ plugin: agentVaultPlugin });
1286
+ if (typeof api.registerHttpRoute === "function") {
1287
+ try {
1288
+ api.registerHttpRoute({
1289
+ path: "/agentvault/send",
1290
+ method: "POST",
1291
+ handler: async (req) => {
1292
+ const ch = _channels.values().next().value;
1293
+ if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
1294
+ const parsed = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
1295
+ const result = await handleSendRequest(parsed, ch);
1296
+ return { status: result.status, body: result.body };
1297
+ }
1298
+ });
1299
+ api.registerHttpRoute({
1300
+ path: "/agentvault/action",
1301
+ method: "POST",
1302
+ handler: async (req) => {
1303
+ const ch = _channels.values().next().value;
1304
+ if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
1305
+ const parsed = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
1306
+ const result = await handleActionRequest(parsed, ch);
1307
+ return { status: result.status, body: result.body };
1308
+ }
1309
+ });
1310
+ api.registerHttpRoute({
1311
+ path: "/agentvault/decision",
1312
+ method: "POST",
1313
+ handler: async (req) => {
1314
+ const ch = _channels.values().next().value;
1315
+ if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
1316
+ const parsed = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
1317
+ const result = await handleDecisionRequest(parsed, ch);
1318
+ return { status: result.status, body: result.body };
1319
+ }
1320
+ });
1321
+ api.registerHttpRoute({
1322
+ path: "/agentvault/status",
1323
+ method: "GET",
1324
+ handler: async () => {
1325
+ const ch = _channels.values().next().value;
1326
+ if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
1327
+ const result = handleStatusRequest(ch);
1328
+ return { status: result.status, body: result.body };
1329
+ }
1330
+ });
1331
+ isUsingManagedRoutes = true;
1332
+ } catch {
1333
+ }
1334
+ }
1335
+ if (typeof api.on === "function") {
1336
+ api.on("message_sent", async (event) => {
1241
1337
  try {
1242
- api.registerCommand?.({
1243
- name: "agentvault",
1244
- description: "Show AgentVault encrypted channel status",
1245
- handler: () => {
1246
- const statuses = [];
1247
- if (_channels.size === 0) {
1248
- statuses.push("AgentVault: no active channels");
1249
- }
1250
- else {
1251
- for (const [id, ch] of _channels) {
1252
- statuses.push(`AgentVault [${id}]: ${ch.state} | sessions: ${ch.sessionCount} | encrypted: yes`);
1253
- }
1254
- }
1255
- return { text: statuses.join("\n") };
1256
- },
1257
- });
1338
+ const ch = _channels.values().next().value;
1339
+ if (!ch?.telemetry) return;
1340
+ ch.telemetry.reportCustomSpan({
1341
+ traceId: randomBytes(16).toString("hex"),
1342
+ spanId: randomBytes(8).toString("hex"),
1343
+ name: "agentvault.message.delivered",
1344
+ kind: "internal",
1345
+ startTime: event.timestamp,
1346
+ endTime: event.timestamp + 1,
1347
+ attributes: {
1348
+ "agentvault.message.id": event.messageId,
1349
+ "agentvault.delivery.status": event.deliveryStatus,
1350
+ "agentvault.channel.id": event.channelId
1351
+ },
1352
+ status: { code: event.deliveryStatus === "failed" ? 2 : 1 }
1353
+ });
1354
+ } catch {
1258
1355
  }
1259
- catch { /* registerCommand may not be available in older OpenClaw versions */ }
1260
- },
1356
+ });
1357
+ api.on("session_start", async (event) => {
1358
+ try {
1359
+ const ch = _channels.values().next().value;
1360
+ if (!ch?.telemetry) return;
1361
+ ch.telemetry.reportCustomSpan({
1362
+ traceId: randomBytes(16).toString("hex"),
1363
+ spanId: randomBytes(8).toString("hex"),
1364
+ name: "agentvault.session.start",
1365
+ kind: "internal",
1366
+ startTime: event.timestamp,
1367
+ endTime: event.timestamp + 1,
1368
+ attributes: {
1369
+ "agentvault.session.key": event.sessionKey,
1370
+ "agentvault.agent.id": event.agentId
1371
+ },
1372
+ status: { code: 1 }
1373
+ });
1374
+ } catch {
1375
+ }
1376
+ });
1377
+ api.on("session_end", async (event) => {
1378
+ try {
1379
+ const ch = _channels.values().next().value;
1380
+ if (!ch?.telemetry) return;
1381
+ ch.telemetry.reportCustomSpan({
1382
+ traceId: randomBytes(16).toString("hex"),
1383
+ spanId: randomBytes(8).toString("hex"),
1384
+ name: "agentvault.session.end",
1385
+ kind: "internal",
1386
+ startTime: event.timestamp,
1387
+ endTime: event.timestamp + 1,
1388
+ attributes: {
1389
+ "agentvault.session.key": event.sessionKey,
1390
+ "agentvault.agent.id": event.agentId,
1391
+ ...event.reason ? { "agentvault.session.end_reason": event.reason } : {}
1392
+ },
1393
+ status: { code: 1 }
1394
+ });
1395
+ } catch {
1396
+ }
1397
+ });
1398
+ }
1399
+ Promise.resolve().then(() => (init_openclaw_compat(), openclaw_compat_exports)).then(async ({ onAgentEvent: onAgentEvent2, onSessionTranscriptUpdate: onSessionTranscriptUpdate2 }) => {
1400
+ onAgentEvent2((event) => {
1401
+ try {
1402
+ const ch = _channels.values().next().value;
1403
+ if (!ch?.telemetry) return;
1404
+ ch.telemetry.reportCustomSpan({
1405
+ traceId: randomBytes(16).toString("hex"),
1406
+ spanId: randomBytes(8).toString("hex"),
1407
+ name: `ai.agent.event.${event.type}`,
1408
+ kind: "internal",
1409
+ startTime: event.timestamp,
1410
+ endTime: event.timestamp + 1,
1411
+ attributes: {
1412
+ "ai.agent.event.type": event.type,
1413
+ "ai.agent.id": event.agentId,
1414
+ ...event.data ? Object.fromEntries(
1415
+ Object.entries(event.data).map(([k, v]) => [`ai.agent.event.${k}`, String(v)])
1416
+ ) : {}
1417
+ },
1418
+ status: { code: 1 }
1419
+ });
1420
+ } catch {
1421
+ }
1422
+ }).catch(() => {
1423
+ });
1424
+ onSessionTranscriptUpdate2((update) => {
1425
+ try {
1426
+ const ch = _channels.values().next().value;
1427
+ if (!ch?.telemetry) return;
1428
+ ch.telemetry.reportCustomSpan({
1429
+ traceId: randomBytes(16).toString("hex"),
1430
+ spanId: randomBytes(8).toString("hex"),
1431
+ name: "ai.agent.transcript.update",
1432
+ kind: "internal",
1433
+ startTime: update.timestamp,
1434
+ endTime: update.timestamp + 1,
1435
+ attributes: {
1436
+ "agentvault.session.key": update.sessionKey,
1437
+ "ai.agent.transcript.role": update.role ?? "unknown",
1438
+ "ai.agent.transcript.delta_chars": update.delta.length
1439
+ },
1440
+ status: { code: 1 }
1441
+ });
1442
+ } catch {
1443
+ }
1444
+ }).catch(() => {
1445
+ });
1446
+ }).catch(() => {
1447
+ });
1448
+ try {
1449
+ api.registerTool?.({
1450
+ name: "agentvault_status",
1451
+ description: "Check the AgentVault encrypted channel status, connection state, and session count.",
1452
+ parameters: {
1453
+ type: "object",
1454
+ properties: {
1455
+ accountId: {
1456
+ type: "string",
1457
+ description: "Account ID to check (default: 'default')"
1458
+ }
1459
+ }
1460
+ },
1461
+ execute: async (_id, params) => {
1462
+ const id = params.accountId ?? "default";
1463
+ const ch = _channels.get(id);
1464
+ if (!ch) {
1465
+ return { content: [{ type: "text", text: JSON.stringify({ connected: false, error: "Channel not started" }) }] };
1466
+ }
1467
+ return {
1468
+ content: [{
1469
+ type: "text",
1470
+ text: JSON.stringify({
1471
+ connected: ch.state === "ready",
1472
+ state: ch.state,
1473
+ deviceId: ch.deviceId,
1474
+ sessions: ch.sessionCount,
1475
+ encrypted: true
1476
+ })
1477
+ }]
1478
+ };
1479
+ }
1480
+ }, { optional: true });
1481
+ } catch {
1482
+ }
1483
+ try {
1484
+ api.registerCommand?.({
1485
+ name: "agentvault",
1486
+ description: "Show AgentVault encrypted channel status",
1487
+ handler: () => {
1488
+ const statuses = [];
1489
+ if (_channels.size === 0) {
1490
+ statuses.push("AgentVault: no active channels");
1491
+ } else {
1492
+ for (const [id, ch] of _channels) {
1493
+ statuses.push(`AgentVault [${id}]: ${ch.state} | sessions: ${ch.sessionCount} | encrypted: yes`);
1494
+ }
1495
+ }
1496
+ return { text: statuses.join("\n") };
1497
+ }
1498
+ });
1499
+ } catch {
1500
+ }
1501
+ }
1502
+ };
1503
+ export {
1504
+ _parseMentions,
1505
+ _shouldProcessRoomMessage,
1506
+ _stripMentions,
1507
+ openclaw_entry_default as default,
1508
+ isUsingManagedRoutes
1261
1509
  };
1262
- //# sourceMappingURL=openclaw-entry.js.map
1510
+ //# sourceMappingURL=openclaw-entry.js.map