@agentvault/agentvault 0.23.71 → 0.23.72

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 (71) hide show
  1. package/README.md +3 -1
  2. package/dist/atomic-file.d.ts +11 -0
  3. package/dist/atomic-file.d.ts.map +1 -0
  4. package/dist/channel.d.ts +675 -44
  5. package/dist/channel.d.ts.map +1 -1
  6. package/dist/cli.js +8162 -2403
  7. package/dist/cli.js.map +4 -4
  8. package/dist/dm-group-pins.d.ts +190 -0
  9. package/dist/dm-group-pins.d.ts.map +1 -0
  10. package/dist/dr-refusal.d.ts +54 -0
  11. package/dist/dr-refusal.d.ts.map +1 -0
  12. package/dist/file-send-failure.d.ts +115 -0
  13. package/dist/file-send-failure.d.ts.map +1 -0
  14. package/dist/file-send-policy.d.ts +251 -0
  15. package/dist/file-send-policy.d.ts.map +1 -0
  16. package/dist/full-permissions.d.ts +479 -0
  17. package/dist/full-permissions.d.ts.map +1 -0
  18. package/dist/gateway-send.d.ts +8 -0
  19. package/dist/gateway-send.d.ts.map +1 -1
  20. package/dist/harness-compat.d.ts +12 -0
  21. package/dist/harness-compat.d.ts.map +1 -1
  22. package/dist/http-handlers.d.ts +5 -1
  23. package/dist/http-handlers.d.ts.map +1 -1
  24. package/dist/index.d.ts +13 -2
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +8653 -2417
  27. package/dist/index.js.map +4 -4
  28. package/dist/local-api-server.d.ts +71 -0
  29. package/dist/local-api-server.d.ts.map +1 -0
  30. package/dist/local-api.d.ts +107 -0
  31. package/dist/local-api.d.ts.map +1 -0
  32. package/dist/mcp-handlers.d.ts +15 -1
  33. package/dist/mcp-handlers.d.ts.map +1 -1
  34. package/dist/mcp-server.d.ts +4 -1
  35. package/dist/mcp-server.d.ts.map +1 -1
  36. package/dist/off-sequence-report.d.ts +74 -0
  37. package/dist/off-sequence-report.d.ts.map +1 -0
  38. package/dist/onturn-stop.d.ts +253 -0
  39. package/dist/onturn-stop.d.ts.map +1 -0
  40. package/dist/openclaw-entry.d.ts +32 -2
  41. package/dist/openclaw-entry.d.ts.map +1 -1
  42. package/dist/openclaw-entry.js +1377 -171
  43. package/dist/openclaw-entry.js.map +4 -4
  44. package/dist/openclaw-file-send.d.ts +308 -0
  45. package/dist/openclaw-file-send.d.ts.map +1 -0
  46. package/dist/openclaw-plugin.d.ts +7 -2
  47. package/dist/openclaw-plugin.d.ts.map +1 -1
  48. package/dist/openclaw-room-taint.d.ts +43 -0
  49. package/dist/openclaw-room-taint.d.ts.map +1 -0
  50. package/dist/openclaw-sender.d.ts +47 -0
  51. package/dist/openclaw-sender.d.ts.map +1 -0
  52. package/dist/openclaw-types.d.ts +7 -1
  53. package/dist/openclaw-types.d.ts.map +1 -1
  54. package/dist/owner-devices.d.ts +71 -0
  55. package/dist/owner-devices.d.ts.map +1 -0
  56. package/dist/owner-epoch.d.ts +36 -0
  57. package/dist/owner-epoch.d.ts.map +1 -0
  58. package/dist/room-send-error.d.ts +17 -0
  59. package/dist/room-send-error.d.ts.map +1 -0
  60. package/dist/sender-binding.d.ts +130 -0
  61. package/dist/sender-binding.d.ts.map +1 -0
  62. package/dist/tool-telemetry.d.ts +1 -1
  63. package/dist/tool-telemetry.d.ts.map +1 -1
  64. package/dist/turn-token.d.ts +168 -0
  65. package/dist/turn-token.d.ts.map +1 -0
  66. package/dist/types.d.ts +160 -6
  67. package/dist/types.d.ts.map +1 -1
  68. package/openclaw.plugin.json +1 -1
  69. package/package.json +1 -1
  70. package/dist/workspace-handlers.d.ts +0 -62
  71. package/dist/workspace-handlers.d.ts.map +0 -1
@@ -42,9 +42,24 @@ var init_owner_routing = __esm({
42
42
  }
43
43
  });
44
44
 
45
+ // src/room-send-error.ts
46
+ var RoomSendNotWritten;
47
+ var init_room_send_error = __esm({
48
+ "src/room-send-error.ts"() {
49
+ "use strict";
50
+ RoomSendNotWritten = class extends Error {
51
+ code = "relay_not_connected";
52
+ constructor(roomId) {
53
+ super(`Room ${String(roomId).slice(0, 8)}...: frame not written \u2014 relay socket is not open`);
54
+ this.name = "RoomSendNotWritten";
55
+ }
56
+ };
57
+ }
58
+ });
59
+
45
60
  // src/tool-telemetry.ts
46
61
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
47
- import { randomBytes } from "node:crypto";
62
+ import { randomBytes as randomBytes2 } from "node:crypto";
48
63
  function safeErrorKind(value) {
49
64
  if (typeof value !== "string") return UNCLASSIFIED_ERROR;
50
65
  if (KNOWN_CODES.has(value)) return value;
@@ -59,6 +74,7 @@ function codeForText(text) {
59
74
  }
60
75
  function classifyToolError(err) {
61
76
  try {
77
+ if (err instanceof RoomSendNotWritten) return err.code;
62
78
  if (err instanceof Error) {
63
79
  return codeForText(err.message) ?? safeErrorKind(err.constructor?.name);
64
80
  }
@@ -126,8 +142,8 @@ function buildToolInvokeSpan(report) {
126
142
  attributes["av.conversation_id"] = conv.id.slice(0, 64);
127
143
  }
128
144
  return {
129
- traceId: randomBytes(16).toString("hex"),
130
- spanId: randomBytes(8).toString("hex"),
145
+ traceId: randomBytes2(16).toString("hex"),
146
+ spanId: randomBytes2(8).toString("hex"),
131
147
  name: TOOL_INVOKE_SPAN_NAME,
132
148
  kind: "internal",
133
149
  startTime: endTime - durationMs,
@@ -149,6 +165,7 @@ var TOOL_INVOKE_SPAN_NAME, UNCLASSIFIED_ERROR, KNOWN_TOOL_ERROR_CODES, KNOWN_COD
149
165
  var init_tool_telemetry = __esm({
150
166
  "src/tool-telemetry.ts"() {
151
167
  "use strict";
168
+ init_room_send_error();
152
169
  TOOL_INVOKE_SPAN_NAME = "ai.agent.tool.invoke";
153
170
  UNCLASSIFIED_ERROR = "unclassified";
154
171
  KNOWN_TOOL_ERROR_CODES = [
@@ -181,6 +198,22 @@ var init_tool_telemetry = __esm({
181
198
  "model_unavailable",
182
199
  "provider_unreachable",
183
200
  "ai_tool_unsupported",
201
+ // #1762: SecureChannel.sendFile (design §4.2) and the turn-end prose check.
202
+ "file_not_allowed",
203
+ "file_not_found",
204
+ "file_too_large",
205
+ "upload_failed",
206
+ "room_file_not_permitted",
207
+ "file_target_mismatch",
208
+ "file_send_disabled",
209
+ "workspace_required",
210
+ "unclaimed_attachment",
211
+ "turn_ended",
212
+ "turn_no_consumer",
213
+ // #1762 PR-P1c-2: the off sequence (or the not-"on" bound) could not stop the on-turns' work.
214
+ "off_sequence_failed",
215
+ // #1800 PR B: the sender-binding canary failed at start — no message carries owner power.
216
+ "sender_binding_self_test_failed",
184
217
  UNCLASSIFIED_ERROR
185
218
  ];
186
219
  KNOWN_CODES = new Set(KNOWN_TOOL_ERROR_CODES);
@@ -201,7 +234,22 @@ var init_tool_telemetry = __esm({
201
234
  [/can only be sent to owner|cannot be sent to A2A targets/, "unsupported_destination"],
202
235
  [/^Delivery timed out$/, "delivery_timeout"],
203
236
  [/^Delivery cancelled$/, "delivery_cancelled"],
204
- [/^Delivery failed$/, "delivery_failed"]
237
+ [/^Delivery failed$/, "delivery_failed"],
238
+ // #1762: deliver()/sendArtifact surface a failed sendFile as "<code>: <reason>".
239
+ [/^no_conversation_ready: /, "no_conversation_ready"],
240
+ [/^relay_not_connected: /, "relay_not_connected"],
241
+ [/^blocked_by_policy: /, "blocked_by_policy"],
242
+ [/^room_not_found: /, "room_not_found"],
243
+ [/^file_not_allowed: /, "file_not_allowed"],
244
+ [/^file_not_found: /, "file_not_found"],
245
+ [/^file_too_large: /, "file_too_large"],
246
+ [/^upload_failed: /, "upload_failed"],
247
+ [/^room_file_not_permitted: /, "room_file_not_permitted"],
248
+ [/^file_target_mismatch: /, "file_target_mismatch"],
249
+ [/^file_send_disabled: /, "file_send_disabled"],
250
+ [/^workspace_required: /, "workspace_required"],
251
+ [/^turn_ended: /, "turn_ended"],
252
+ [/^turn_no_consumer: /, "turn_no_consumer"]
205
253
  ];
206
254
  _conversation = new AsyncLocalStorage2();
207
255
  }
@@ -241,6 +289,27 @@ function statusOf(receipt) {
241
289
  if (receipt.ambiguous) return 409;
242
290
  return receipt.ok ? 200 : 500;
243
291
  }
292
+ function fileStatusOf(code) {
293
+ switch (code) {
294
+ case "room_file_not_permitted":
295
+ case "file_target_mismatch":
296
+ case "file_not_allowed":
297
+ case "blocked_by_policy":
298
+ return 403;
299
+ case "file_not_found":
300
+ case "room_not_found":
301
+ return 404;
302
+ case "file_too_large":
303
+ return 413;
304
+ case "file_send_disabled":
305
+ case "workspace_required":
306
+ case "no_conversation_ready":
307
+ case "relay_not_connected":
308
+ return 503;
309
+ default:
310
+ return 502;
311
+ }
312
+ }
244
313
  async function handleSendRequest(parsed, channel) {
245
314
  const startedAt = Date.now();
246
315
  const result = await _handleSendRequest(parsed, channel);
@@ -299,6 +368,9 @@ async function _handleSendRequest(parsed, channel) {
299
368
  }
300
369
  if (a2aTarget && typeof a2aTarget === "string") {
301
370
  target = { kind: "a2a", hubAddress: a2aTarget };
371
+ } else if (typeof parsed.room_id === "string" && typeof parsed.file_path === "string") {
372
+ const res = await channel.sendFile({ kind: "room", roomId: parsed.room_id }, parsed.file_path, text, null);
373
+ return res.ok ? { status: 200, body: { ok: true, destination: { kind: "room", id: parsed.room_id } } } : { status: fileStatusOf(res.code), body: { ok: false, code: res.code, error: res.error } };
302
374
  } else if (typeof parsed.room_id === "string") {
303
375
  target = { kind: "room", roomId: parsed.room_id };
304
376
  } else if (parsed.target === "context") {
@@ -450,21 +522,22 @@ function handleTrustRequest(channel) {
450
522
  }
451
523
  };
452
524
  }
453
- function handleMcpConfigRequest(agentName, port, mcpSkillCount) {
525
+ function handleMcpConfigRequest(agentName, port, mcpSkillCount, token) {
454
526
  return {
455
527
  status: 200,
456
528
  body: {
457
529
  mcpServers: {
458
530
  [`agentvault-${agentName}`]: {
459
- url: `http://127.0.0.1:${port}/mcp`
531
+ url: `http://127.0.0.1:${port}/mcp`,
532
+ ...token ? { headers: { "X-AgentVault-Local-Token": token } } : {}
460
533
  }
461
534
  },
462
535
  _meta: {
463
536
  agent: agentName,
464
537
  skills_count: mcpSkillCount,
465
538
  transport: "streamable-http",
466
- auth: "none (localhost)",
467
- instructions: "Add the mcpServers block to your MCP configuration file (e.g., .mcp.json or mcp_config.json)"
539
+ auth: "X-AgentVault-Local-Token header (the agent's local-api.token file)",
540
+ instructions: "Add the mcpServers block to your MCP configuration file (e.g., .mcp.json or mcp_config.json). It holds the agent's local token: keep that file private and out of git."
468
541
  }
469
542
  }
470
543
  };
@@ -577,8 +650,11 @@ var init_mcp_server = __esm({
577
650
  * so the single McpServer instance is ready for the next caller.
578
651
  *
579
652
  * Local requests from 127.0.0.1/::1 bypass SPT validation (owner access).
653
+ * #1791: the loopback server authenticates them first (Origin, Host, local
654
+ * token) and reads the POST body itself under its 64 KB cap; it hands the
655
+ * parsed body in as `parsedBody`, so the transport never reads the stream.
580
656
  */
581
- async handleRequest(req, res) {
657
+ async handleRequest(req, res, parsedBody) {
582
658
  if (!this.initialized) {
583
659
  this.initialize();
584
660
  }
@@ -605,7 +681,7 @@ var init_mcp_server = __esm({
605
681
  });
606
682
  await this.server.connect(transport);
607
683
  try {
608
- await transport.handleRequest(req, res);
684
+ await transport.handleRequest(req, res, parsedBody);
609
685
  } finally {
610
686
  await transport.close();
611
687
  }
@@ -689,8 +765,8 @@ __export(skill_manifest_exports, {
689
765
  mergeSkills: () => mergeSkills,
690
766
  parseSkillMd: () => parseSkillMd
691
767
  });
692
- import { readFileSync as readFileSync2, existsSync as existsSync2, readdirSync } from "node:fs";
693
- import { resolve, join } from "node:path";
768
+ import { readFileSync as readFileSync3, existsSync as existsSync2, readdirSync } from "node:fs";
769
+ import { resolve, join as join2 } from "node:path";
694
770
  function parseSkillMd(content) {
695
771
  const lines = content.split("\n");
696
772
  if (lines[0]?.trim() !== "---") return null;
@@ -798,7 +874,7 @@ function loadSkillsFromDirectory(dir) {
798
874
  if (seen.has(filePath)) return;
799
875
  seen.add(filePath);
800
876
  try {
801
- const content = readFileSync2(filePath, "utf-8");
877
+ const content = readFileSync3(filePath, "utf-8");
802
878
  const skill = parseSkillMd(content);
803
879
  if (skill) skills.push(skill);
804
880
  } catch {
@@ -808,9 +884,9 @@ function loadSkillsFromDirectory(dir) {
808
884
  const entries = readdirSync(absDir, { withFileTypes: true });
809
885
  for (const entry of entries) {
810
886
  if (entry.isFile() && entry.name.endsWith("SKILL.md")) {
811
- tryLoad(join(absDir, entry.name));
887
+ tryLoad(join2(absDir, entry.name));
812
888
  } else if (entry.isDirectory()) {
813
- const subSkill = join(absDir, entry.name, "SKILL.md");
889
+ const subSkill = join2(absDir, entry.name, "SKILL.md");
814
890
  if (existsSync2(subSkill)) {
815
891
  tryLoad(subSkill);
816
892
  }
@@ -6593,6 +6669,14 @@ var init_epochReceiverData = __esm({
6593
6669
  }
6594
6670
  });
6595
6671
 
6672
+ // ../crypto/node_modules/ts-mls/dist/src/agentvaultIdentityRules.js
6673
+ var init_agentvaultIdentityRules = __esm({
6674
+ "../crypto/node_modules/ts-mls/dist/src/agentvaultIdentityRules.js"() {
6675
+ init_mlsError();
6676
+ init_treemath();
6677
+ }
6678
+ });
6679
+
6596
6680
  // ../crypto/node_modules/ts-mls/dist/src/clientState.js
6597
6681
  var groupStateEncoder, encodeGroupState, decodeGroupState, groupStateEncoderWithoutTree, encodeGroupStateWithoutTree;
6598
6682
  var init_clientState = __esm({
@@ -6634,6 +6718,7 @@ var init_clientState = __esm({
6634
6718
  init_epochReceiverData();
6635
6719
  init_tlsDecoder();
6636
6720
  init_kdf();
6721
+ init_agentvaultIdentityRules();
6637
6722
  groupStateEncoder = contramapBufferEncoders([
6638
6723
  groupContextEncoder,
6639
6724
  keyScheduleEncoder,
@@ -6762,6 +6847,7 @@ var init_createMessage = __esm({
6762
6847
  init_messageProtection();
6763
6848
  init_messageProtectionPublic();
6764
6849
  init_unappliedProposals();
6850
+ init_agentvaultIdentityRules();
6765
6851
  }
6766
6852
  });
6767
6853
 
@@ -6792,6 +6878,7 @@ var init_createCommit = __esm({
6792
6878
  init_clientConfig();
6793
6879
  init_extension();
6794
6880
  init_tlsEncoder();
6881
+ init_agentvaultIdentityRules();
6795
6882
  }
6796
6883
  });
6797
6884
 
@@ -6818,6 +6905,7 @@ var init_processMessages = __esm({
6818
6905
  init_updatePath();
6819
6906
  init_addToMap();
6820
6907
  init_byteArray();
6908
+ init_agentvaultIdentityRules();
6821
6909
  }
6822
6910
  });
6823
6911
 
@@ -7052,7 +7140,7 @@ function aexists(instance, checkFinished = true) {
7052
7140
  throw new Error("Hash#digest() has already been called");
7053
7141
  }
7054
7142
  }
7055
- function clean2(...arrays) {
7143
+ function clean3(...arrays) {
7056
7144
  for (let i2 = 0; i2 < arrays.length; i2++) {
7057
7145
  arrays[i2].fill(0);
7058
7146
  }
@@ -7144,7 +7232,7 @@ var init_hmac = __esm({
7144
7232
  for (let i2 = 0; i2 < pad.length; i2++)
7145
7233
  pad[i2] ^= 54 ^ 92;
7146
7234
  this.oHash.update(pad);
7147
- clean2(pad);
7235
+ clean3(pad);
7148
7236
  }
7149
7237
  update(buf) {
7150
7238
  aexists(this);
@@ -7812,11 +7900,19 @@ var init_src = __esm({
7812
7900
  }
7813
7901
  });
7814
7902
 
7903
+ // ../crypto/dist/mls-sender-binding.js
7904
+ var init_mls_sender_binding = __esm({
7905
+ "../crypto/dist/mls-sender-binding.js"() {
7906
+ "use strict";
7907
+ }
7908
+ });
7909
+
7815
7910
  // ../crypto/dist/mls-group.js
7816
7911
  var init_mls_group = __esm({
7817
7912
  "../crypto/dist/mls-group.js"() {
7818
7913
  "use strict";
7819
7914
  init_src();
7915
+ init_mls_sender_binding();
7820
7916
  }
7821
7917
  });
7822
7918
 
@@ -7872,6 +7968,7 @@ var init_dist = __esm({
7872
7968
  init_history_backup();
7873
7969
  init_approval();
7874
7970
  init_mls_group();
7971
+ init_mls_sender_binding();
7875
7972
  init_owner_sync();
7876
7973
  init_mls_delivery_order();
7877
7974
  init_mls_presend_epoch();
@@ -7917,10 +8014,10 @@ __export(state_exports, {
7917
8014
  });
7918
8015
  import { chmod as chmod2, open, readFile, rename, rm } from "node:fs/promises";
7919
8016
  import { randomUUID } from "node:crypto";
7920
- import { join as join2 } from "node:path";
8017
+ import { join as join3 } from "node:path";
7921
8018
  async function saveState(dataDir, state, options = {}) {
7922
8019
  await ensureSecureDir(dataDir);
7923
- const filePath = join2(dataDir, STATE_FILE);
8020
+ const filePath = join3(dataDir, STATE_FILE);
7924
8021
  const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID()}`;
7925
8022
  let handle = null;
7926
8023
  try {
@@ -7954,18 +8051,18 @@ async function saveState(dataDir, state, options = {}) {
7954
8051
  });
7955
8052
  }
7956
8053
  try {
7957
- await rm(join2(dataDir, LEGACY_STATE_FILE));
8054
+ await rm(join3(dataDir, LEGACY_STATE_FILE));
7958
8055
  } catch {
7959
8056
  }
7960
8057
  }
7961
8058
  async function loadState(dataDir) {
7962
- const filePath = join2(dataDir, STATE_FILE);
8059
+ const filePath = join3(dataDir, STATE_FILE);
7963
8060
  try {
7964
8061
  const raw = await readFile(filePath, "utf-8");
7965
8062
  return JSON.parse(raw);
7966
8063
  } catch {
7967
8064
  }
7968
- const legacyPath = join2(dataDir, LEGACY_STATE_FILE);
8065
+ const legacyPath = join3(dataDir, LEGACY_STATE_FILE);
7969
8066
  try {
7970
8067
  const raw = await readFile(legacyPath, "utf-8");
7971
8068
  const parsed = JSON.parse(raw);
@@ -7979,7 +8076,7 @@ async function loadState(dataDir) {
7979
8076
  }
7980
8077
  async function isStateValid(dataDir) {
7981
8078
  try {
7982
- const filePath = join2(dataDir, STATE_FILE);
8079
+ const filePath = join3(dataDir, STATE_FILE);
7983
8080
  const raw = await readFile(filePath, "utf-8");
7984
8081
  const parsed = JSON.parse(raw);
7985
8082
  return !!(parsed && parsed.deviceId && parsed.deviceJwt && parsed.sessions && Object.keys(parsed.sessions).length > 0);
@@ -7988,9 +8085,9 @@ async function isStateValid(dataDir) {
7988
8085
  }
7989
8086
  }
7990
8087
  async function backupState(dataDir) {
7991
- const src = join2(dataDir, STATE_FILE);
7992
- const bak = join2(dataDir, `${STATE_FILE}.bak`);
7993
- const tmp = join2(dataDir, `${STATE_FILE}.bak.tmp`);
8088
+ const src = join3(dataDir, STATE_FILE);
8089
+ const bak = join3(dataDir, `${STATE_FILE}.bak`);
8090
+ const tmp = join3(dataDir, `${STATE_FILE}.bak.tmp`);
7994
8091
  try {
7995
8092
  const data = await readFile(src, "utf-8");
7996
8093
  await writeSecureFile(tmp, data);
@@ -8001,7 +8098,7 @@ async function backupState(dataDir) {
8001
8098
  async function restoreState(dataDir) {
8002
8099
  const primaryValid = await isStateValid(dataDir);
8003
8100
  if (primaryValid) return false;
8004
- const bak = join2(dataDir, `${STATE_FILE}.bak`);
8101
+ const bak = join3(dataDir, `${STATE_FILE}.bak`);
8005
8102
  try {
8006
8103
  const data = await readFile(bak, "utf-8");
8007
8104
  const parsed = JSON.parse(data);
@@ -8009,7 +8106,7 @@ async function restoreState(dataDir) {
8009
8106
  return false;
8010
8107
  }
8011
8108
  await ensureSecureDir(dataDir);
8012
- await writeSecureFile(join2(dataDir, STATE_FILE), data);
8109
+ await writeSecureFile(join3(dataDir, STATE_FILE), data);
8013
8110
  return true;
8014
8111
  } catch {
8015
8112
  return false;
@@ -8065,7 +8162,7 @@ async function uploadBackupToServer(state, backupCode, apiUrl, deviceJwt) {
8065
8162
  async function clearState(dataDir) {
8066
8163
  for (const filename of [STATE_FILE, LEGACY_STATE_FILE]) {
8067
8164
  try {
8068
- await rm(join2(dataDir, filename));
8165
+ await rm(join3(dataDir, filename));
8069
8166
  } catch {
8070
8167
  }
8071
8168
  }
@@ -8083,7 +8180,7 @@ var init_state = __esm({
8083
8180
 
8084
8181
  // src/openclaw-entry.ts
8085
8182
  import { resolve as pathResolve } from "node:path";
8086
- import { randomBytes as randomBytes2 } from "node:crypto";
8183
+ import { randomBytes as randomBytes3 } from "node:crypto";
8087
8184
  import { homedir as osHomedir } from "node:os";
8088
8185
 
8089
8186
  // src/room-protocol.ts
@@ -9258,8 +9355,330 @@ function runWithTraceContext(ctx, fn) {
9258
9355
  return traceStore.run(ctx, fn);
9259
9356
  }
9260
9357
 
9261
- // src/openclaw-entry.ts
9262
- init_http_handlers();
9358
+ // src/local-api.ts
9359
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
9360
+ var LOCAL_API_TOKEN_HEADER = "x-agentvault-local-token";
9361
+ var LOCAL_API_BODY_LIMIT = 64 * 1024;
9362
+ var LOCAL_API_TOKEN_HINT = "Send the X-AgentVault-Local-Token header with the contents of local-api.token in the agent's data folder, to http://127.0.0.1:<port> (not localhost), or use `agentvault send`.";
9363
+ function tokenMatches(presented, expected) {
9364
+ if (typeof presented !== "string" || presented.length === 0 || expected.length === 0) return false;
9365
+ const a2 = createHash("sha256").update(presented, "utf8").digest();
9366
+ const b2 = createHash("sha256").update(expected, "utf8").digest();
9367
+ return timingSafeEqual(a2, b2);
9368
+ }
9369
+ var LOOPBACK_REMOTES = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
9370
+ var LOOPBACK_HOSTNAMES = ["127.0.0.1", "localhost", "[::1]"];
9371
+ function hostAllowed(host, port) {
9372
+ if (typeof host !== "string") return false;
9373
+ const h2 = host.toLowerCase();
9374
+ for (const name of LOOPBACK_HOSTNAMES) {
9375
+ if (port !== null) {
9376
+ if (h2 === `${name}:${port}`) return true;
9377
+ } else if (h2.startsWith(`${name}:`) && /^\d{1,5}$/.test(h2.slice(name.length + 1))) {
9378
+ return true;
9379
+ }
9380
+ }
9381
+ return false;
9382
+ }
9383
+ function headerValue(headers, name) {
9384
+ if (name in headers) return headers[name];
9385
+ for (const key of Object.keys(headers)) if (key.toLowerCase() === name) return headers[key];
9386
+ return void 0;
9387
+ }
9388
+ function checkLocalRequest(req, opts) {
9389
+ if (opts.checkRemote !== false) {
9390
+ const remote = req.socket?.remoteAddress;
9391
+ if (!remote || !LOOPBACK_REMOTES.has(remote)) return "remote";
9392
+ }
9393
+ if (headerValue(req.headers, "origin") !== void 0) return "origin";
9394
+ const host = headerValue(req.headers, "host");
9395
+ if (!hostAllowed(typeof host === "string" ? host : void 0, opts.port)) return "host";
9396
+ if (!tokenMatches(headerValue(req.headers, LOCAL_API_TOKEN_HEADER), opts.token)) return "token";
9397
+ return null;
9398
+ }
9399
+ var BodyTooLargeError = class extends Error {
9400
+ constructor() {
9401
+ super("body too large");
9402
+ this.name = "BodyTooLargeError";
9403
+ }
9404
+ };
9405
+ function readLimitedBody(req, limit = LOCAL_API_BODY_LIMIT) {
9406
+ return new Promise((resolve2, reject) => {
9407
+ const declared = Number(req.headers["content-length"]);
9408
+ if (Number.isFinite(declared) && declared > limit) {
9409
+ reject(new BodyTooLargeError());
9410
+ return;
9411
+ }
9412
+ const chunks = [];
9413
+ let size = 0;
9414
+ let done = false;
9415
+ const finish = (err) => {
9416
+ if (done) return;
9417
+ done = true;
9418
+ req.off("data", onData);
9419
+ req.off("end", onEnd);
9420
+ req.off("error", onError);
9421
+ req.off("aborted", onAborted);
9422
+ if (err) reject(err);
9423
+ else resolve2(Buffer.concat(chunks, size));
9424
+ };
9425
+ const onData = (chunk) => {
9426
+ size += chunk.length;
9427
+ if (size > limit) {
9428
+ req.pause();
9429
+ finish(new BodyTooLargeError());
9430
+ return;
9431
+ }
9432
+ chunks.push(chunk);
9433
+ };
9434
+ const onEnd = () => finish();
9435
+ const onError = (err) => finish(err);
9436
+ const onAborted = () => finish(new Error("aborted"));
9437
+ req.on("data", onData);
9438
+ req.on("end", onEnd);
9439
+ req.on("error", onError);
9440
+ req.on("aborted", onAborted);
9441
+ });
9442
+ }
9443
+ var REFUSAL_RESPONSE = {
9444
+ remote: { status: 403, error: "Forbidden" },
9445
+ origin: { status: 403, error: "Forbidden" },
9446
+ host: { status: 403, error: "Forbidden" },
9447
+ token: { status: 401, error: "Unauthorized" },
9448
+ too_large: { status: 413, error: "Payload too large" }
9449
+ };
9450
+ function sendJson(res, status, body2, close = false) {
9451
+ if (res.headersSent || res.destroyed) {
9452
+ res.destroy();
9453
+ return;
9454
+ }
9455
+ const headers = { "Content-Type": "application/json" };
9456
+ if (close) headers.Connection = "close";
9457
+ res.writeHead(status, headers);
9458
+ res.end(JSON.stringify(body2));
9459
+ }
9460
+ function refusalBody(reason) {
9461
+ const r2 = REFUSAL_RESPONSE[reason];
9462
+ return reason === "token" ? { ok: false, error: r2.error, hint: LOCAL_API_TOKEN_HINT } : { ok: false, error: r2.error };
9463
+ }
9464
+ function refuse(res, reason) {
9465
+ sendJson(res, REFUSAL_RESPONSE[reason].status, refusalBody(reason), true);
9466
+ }
9467
+ var KNOWN_ROUTES = /* @__PURE__ */ new Set(["/send", "/decision", "/action", "/status", "/targets", "/trust", "/mcp", "/mcp-config"]);
9468
+ function localRouteLabel(url) {
9469
+ if (!url) return "other";
9470
+ const path = url.split("?")[0].replace(/^\/agentvault(?=\/)/, "");
9471
+ return KNOWN_ROUTES.has(path) ? path : "other";
9472
+ }
9473
+
9474
+ // src/local-api-server.ts
9475
+ var InvalidJsonError = class extends Error {
9476
+ };
9477
+ function parseJsonObject(text) {
9478
+ let parsed;
9479
+ try {
9480
+ parsed = JSON.parse(text);
9481
+ } catch {
9482
+ throw new InvalidJsonError();
9483
+ }
9484
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new InvalidJsonError();
9485
+ return parsed;
9486
+ }
9487
+ async function localApiReply(method, route, readJson, channel, ctx) {
9488
+ const handlers = await Promise.resolve().then(() => (init_http_handlers(), http_handlers_exports));
9489
+ const api = channel;
9490
+ const post = {
9491
+ "/send": handlers.handleSendRequest,
9492
+ "/decision": handlers.handleDecisionRequest,
9493
+ "/action": handlers.handleActionRequest
9494
+ };
9495
+ const postHandler = method === "POST" ? post[route] : void 0;
9496
+ if (postHandler) {
9497
+ let parsed;
9498
+ try {
9499
+ parsed = await readJson();
9500
+ } catch (err) {
9501
+ if (err instanceof BodyTooLargeError) {
9502
+ api.reportLocalApiRefusal(route, "too_large");
9503
+ const r2 = REFUSAL_RESPONSE.too_large;
9504
+ return { status: r2.status, body: { ok: false, error: r2.error }, close: true };
9505
+ }
9506
+ if (err instanceof InvalidJsonError) return { status: 400, body: { ok: false, error: "Invalid JSON" } };
9507
+ return { status: 400, body: { ok: false, error: "Bad request" }, close: true };
9508
+ }
9509
+ try {
9510
+ const result = await postHandler(parsed, channel);
9511
+ return { status: result.status, body: result.body };
9512
+ } catch (err) {
9513
+ console.error(`[SecureChannel] local API ${route} failed:`, err);
9514
+ return { status: 500, body: { ok: false, error: "Internal error" } };
9515
+ }
9516
+ }
9517
+ if (method === "GET") {
9518
+ try {
9519
+ if (route === "/status") return handlers.handleStatusRequest(channel);
9520
+ if (route === "/targets") return handlers.handleTargetsRequest(channel);
9521
+ if (route === "/trust") return handlers.handleTrustRequest(channel);
9522
+ if (route === "/mcp-config") {
9523
+ const agentName = api.config?.agentName ?? "agent";
9524
+ return handlers.handleMcpConfigRequest(agentName, ctx.advertisedPort, api.mcpServer?.skillCount ?? 0, ctx.token);
9525
+ }
9526
+ } catch (err) {
9527
+ console.error(`[SecureChannel] local API ${route} failed:`, err);
9528
+ return { status: 500, body: { ok: false, error: "Internal error" } };
9529
+ }
9530
+ }
9531
+ return { status: 404, body: { ok: false, error: "Not found" } };
9532
+ }
9533
+ function pathOf(url) {
9534
+ return (url ?? "").split("?")[0];
9535
+ }
9536
+ async function serveLocalApi(req, res, channel, ctx) {
9537
+ req.on("error", () => {
9538
+ });
9539
+ res.on("error", () => {
9540
+ });
9541
+ const api = channel;
9542
+ const route = ctx.route ?? pathOf(req.url);
9543
+ const label = localRouteLabel(route);
9544
+ const refusal = checkLocalRequest(req, { port: ctx.port, token: ctx.token });
9545
+ if (refusal) {
9546
+ api.reportLocalApiRefusal(label, refusal);
9547
+ refuse(res, refusal);
9548
+ return;
9549
+ }
9550
+ if (route === "/mcp" && ctx.route === void 0) {
9551
+ if (req.method !== "POST" && req.method !== "GET" && req.method !== "DELETE") {
9552
+ sendJson(res, 404, { ok: false, error: "Not found" });
9553
+ return;
9554
+ }
9555
+ const mcp = api.mcpServer;
9556
+ if (!mcp) {
9557
+ sendJson(res, 503, { ok: false, error: "Unavailable" });
9558
+ return;
9559
+ }
9560
+ let parsedBody;
9561
+ if (req.method === "POST") {
9562
+ try {
9563
+ parsedBody = JSON.parse((await readLimitedBody(req)).toString("utf8"));
9564
+ } catch (err) {
9565
+ if (err instanceof BodyTooLargeError) {
9566
+ api.reportLocalApiRefusal(label, "too_large");
9567
+ refuse(res, "too_large");
9568
+ } else {
9569
+ sendJson(res, 400, { ok: false, error: "Invalid JSON" }, true);
9570
+ }
9571
+ return;
9572
+ }
9573
+ }
9574
+ try {
9575
+ await mcp.handleRequest(req, res, parsedBody);
9576
+ } catch (err) {
9577
+ console.error("[MCP] Request handling error:", err);
9578
+ if (!res.headersSent) sendJson(res, 500, { ok: false, error: "Internal error" });
9579
+ }
9580
+ return;
9581
+ }
9582
+ const preRead = req.body;
9583
+ const readJson = async () => {
9584
+ if (preRead === void 0) return parseJsonObject((await readLimitedBody(req)).toString("utf8"));
9585
+ return preParsedBody(preRead);
9586
+ };
9587
+ const reply = await localApiReply(req.method, route, readJson, channel, ctx);
9588
+ sendJson(res, reply.status, reply.body, reply.close);
9589
+ }
9590
+ function preParsedBody(body2) {
9591
+ if (typeof body2 === "string") {
9592
+ if (Buffer.byteLength(body2, "utf8") > LOCAL_API_BODY_LIMIT) throw new BodyTooLargeError();
9593
+ return parseJsonObject(body2);
9594
+ }
9595
+ if (Buffer.isBuffer(body2)) {
9596
+ if (body2.length > LOCAL_API_BODY_LIMIT) throw new BodyTooLargeError();
9597
+ return parseJsonObject(body2.toString("utf8"));
9598
+ }
9599
+ let size;
9600
+ try {
9601
+ size = Buffer.byteLength(JSON.stringify(body2) ?? "", "utf8");
9602
+ } catch {
9603
+ throw new InvalidJsonError();
9604
+ }
9605
+ if (size > LOCAL_API_BODY_LIMIT) throw new BodyTooLargeError();
9606
+ if (body2 === null || typeof body2 !== "object" || Array.isArray(body2)) throw new InvalidJsonError();
9607
+ return body2;
9608
+ }
9609
+ function managedLocalApiHandler(route, getChannels) {
9610
+ const label = localRouteLabel(route);
9611
+ return async (req, res) => {
9612
+ const isNode = !!res && typeof res.writeHead === "function";
9613
+ const nodeReq = req;
9614
+ const nodeRes = res;
9615
+ const simple = req ?? {};
9616
+ if (isNode) nodeReq.on("error", () => {
9617
+ });
9618
+ const headers = isNode ? nodeReq.headers : simple.headers ?? {};
9619
+ const probe = { headers, socket: { remoteAddress: isNode ? nodeReq.socket?.remoteAddress : simple.remoteAddress } };
9620
+ const channels = [...getChannels()];
9621
+ const reportOn = channels[0];
9622
+ const answer = (status, body2) => {
9623
+ if (!isNode) return { status, body: body2 };
9624
+ sendJson(nodeRes, status, body2, status >= 400);
9625
+ return true;
9626
+ };
9627
+ const pre = checkLocalRequest(probe, { port: null, token: "" });
9628
+ if (pre && pre !== "token") {
9629
+ reportOn?.reportLocalApiRefusal(label, pre);
9630
+ return answer(REFUSAL_RESPONSE[pre].status, refusalBody(pre));
9631
+ }
9632
+ const presented = headerValue(headers, LOCAL_API_TOKEN_HEADER);
9633
+ let match;
9634
+ let anyToken = false;
9635
+ for (const channel of channels) {
9636
+ const ctx = managedContext(channel, route);
9637
+ if (!ctx) continue;
9638
+ anyToken = true;
9639
+ if (tokenMatches(presented, ctx.token) && !match) match = { channel, ctx };
9640
+ }
9641
+ if (!match) {
9642
+ if (!anyToken) return answer(503, { ok: false, error: "Unavailable" });
9643
+ reportOn?.reportLocalApiRefusal(label, "token");
9644
+ return answer(REFUSAL_RESPONSE.token.status, refusalBody("token"));
9645
+ }
9646
+ if (isNode) {
9647
+ await serveLocalApi(nodeReq, nodeRes, match.channel, match.ctx);
9648
+ return true;
9649
+ }
9650
+ const reply = await localApiReply(simple.method, route, async () => preParsedBody(simple.body), match.channel, match.ctx);
9651
+ return { status: reply.status, body: reply.body };
9652
+ };
9653
+ }
9654
+ function managedContext(channel, route) {
9655
+ const ch = channel;
9656
+ const token = ch.localApiToken();
9657
+ if (!token) return null;
9658
+ return { token, port: null, advertisedPort: ch.localApiPort ?? 18790, route };
9659
+ }
9660
+ function startLocalApiWithLog(channel, port, log) {
9661
+ const ch = channel;
9662
+ if (ch.localApiServing) return;
9663
+ const cleanup = () => {
9664
+ ch.off("http-ready", onReady);
9665
+ ch.off("http-failed", onFailed);
9666
+ };
9667
+ const onReady = () => {
9668
+ cleanup();
9669
+ log(`[AgentVault] HTTP send server listening on http://127.0.0.1:${port} (requests need the X-AgentVault-Local-Token header)`);
9670
+ };
9671
+ const onFailed = () => {
9672
+ cleanup();
9673
+ log(`[AgentVault] HTTP send server NOT started on port ${port} (see the error above)`);
9674
+ };
9675
+ ch.on("http-ready", onReady);
9676
+ ch.on("http-failed", onFailed);
9677
+ if (!ch.startHttpServer(port)) {
9678
+ cleanup();
9679
+ log(`[AgentVault] HTTP send server NOT started: the local API token file is unsafe (see the error above)`);
9680
+ }
9681
+ }
9263
9682
 
9264
9683
  // src/openclaw-compat.ts
9265
9684
  var defaultImporter = (specifier) => import(
@@ -9381,6 +9800,15 @@ var nodeFs = {
9381
9800
  };
9382
9801
  var MIN_OPENCLAW_VERSION = "2026.3.0";
9383
9802
  var TESTED_THROUGH_OPENCLAW_VERSION = "2026.10.8";
9803
+ var COMMAND_SUPPRESSION_VERIFIED_OPENCLAW_VERSION = "2026.10.8";
9804
+ function commandSuppressionWarning(version = detectOpenClawVersion()) {
9805
+ try {
9806
+ if (!version || version === COMMAND_SUPPRESSION_VERIFIED_OPENCLAW_VERSION) return null;
9807
+ return `[AgentVault] #1800: non-owner turns rely on OpenClaw honouring CommandInterpretationSuppressed, verified on ${COMMAND_SUPPRESSION_VERIFIED_OPENCLAW_VERSION}; this is ${version}. If commands.allowFrom is set, re-check that a non-owner cannot run slash commands on this version.`;
9808
+ } catch {
9809
+ return null;
9810
+ }
9811
+ }
9384
9812
  function compareVersions(a2, b2) {
9385
9813
  const pa2 = a2.split(".").map((n2) => parseInt(n2, 10) || 0);
9386
9814
  const pb = b2.split(".").map((n2) => parseInt(n2, 10) || 0);
@@ -9885,6 +10313,656 @@ function parseTarget(raw) {
9885
10313
  throw new Error(`Unrecognized delivery target: "${raw}". Use "owner", "room:<id>", "a2a:<addr>", "channel:<id>", or "context".`);
9886
10314
  }
9887
10315
 
10316
+ // src/file-send-failure.ts
10317
+ var ROOM_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
10318
+ var REASON = {
10319
+ file_not_allowed: "the file is not in a folder files can be sent from",
10320
+ file_not_found: "the file does not exist",
10321
+ file_too_large: "the file is over 5 MB",
10322
+ upload_failed: "the upload did not finish",
10323
+ // #1762 PR-P1c-2 (§13.4, §13.13): the refusal names the switch that lifts it.
10324
+ room_file_not_permitted: "files can be shared in a room only when your owner asks there, or when your owner turns on Full permissions for this agent",
10325
+ file_target_mismatch: "a file can only go to the conversation you are answering",
10326
+ file_send_disabled: "file sending is turned off for now",
10327
+ workspace_required: "this agent needs a workspace folder to send files",
10328
+ turn_ended: "the turn ended before the file went",
10329
+ turn_no_consumer: "this message was not handed to the agent's turn handler, so it cannot carry a file",
10330
+ no_conversation_ready: "the chat is not ready to receive a file",
10331
+ relay_not_connected: "the agent is not connected right now",
10332
+ blocked_by_policy: "a scan rule blocked it",
10333
+ unsupported_destination: "files cannot be sent there",
10334
+ delivery_failed: "it could not be delivered",
10335
+ room_not_found: "the room was not found"
10336
+ };
10337
+ function fileSendReason(code) {
10338
+ return REASON[code] ?? REASON.delivery_failed;
10339
+ }
10340
+ function clean2(value, max) {
10341
+ if (typeof value !== "string") return "";
10342
+ return value.replace(/@/g, "").replace(/\s+/g, " ").trim().slice(0, max).trim();
10343
+ }
10344
+ function sizeLabel(bytes) {
10345
+ if (bytes < 1024) return `${bytes} B`;
10346
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
10347
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
10348
+ }
10349
+ function fileSendToolResult(result, target, folder) {
10350
+ if (result.ok) return `File sent: ${clean2(result.filename, 200)} (${sizeLabel(result.size)}).`;
10351
+ let reason = fileSendReason(result.code);
10352
+ if ((result.code === "file_not_allowed" || result.code === "file_not_found") && folder) {
10353
+ reason = target.kind === "room" ? `files for this room must be in ${folder}` : `${reason}; stage it in ${folder}`;
10354
+ }
10355
+ return `File NOT sent: ${reason}. Tell the person it was not sent.`;
10356
+ }
10357
+ function stagingLineFor(target, opts) {
10358
+ const folder = opts.folder;
10359
+ if (target.kind === "owner") return folder ? `Files for this chat: stage them in your outbox at ${folder}.` : FILE_SEND_UNAVAILABLE;
10360
+ if (!folder || !ROOM_ID_RE.test(target.roomId) || opts.roomsAllowed === false) return "Files cannot be shared in this room on this turn.";
10361
+ return `Files for this room: stage them in your outbox at ${folder} (only when your owner asks).`;
10362
+ }
10363
+ function FILE_SEND_RULE(tool) {
10364
+ const t2 = clean2(tool, 60) || "send_file";
10365
+ return `You can send a file only by calling \`${t2}\`. Each conversation has its own staging folder, and the turn tells you which one. Put files for this chat there. In a room, only files in that room's own folder can be shared, and only when your owner asked you in that room. Files over 5 MB, hidden files and credential files cannot be sent. A file has been sent only when \`${t2}\` answers "File sent". Never say a file is attached, sent or shared otherwise. If it returns an error, tell the person the file was not sent and why.`;
10366
+ }
10367
+ var FILE_SEND_UNAVAILABLE = "You cannot send files or attachments in this conversation. Never say you attached, sent or shared a file. If asked, say so and paste short text inline instead.";
10368
+ function safeLineName(name) {
10369
+ return neutralizeSystemPrefix(clean2(name, 200)).replace(/[[\]\uff3b\uff3d]/g, "").replace(/agentvault-system \(quoted\):/gi, "AgentVault-system (quoted)");
10370
+ }
10371
+ var RENDERED_LINES = /* @__PURE__ */ new Set();
10372
+ var RENDERED_MAX = 1e3;
10373
+ function renderHistoryFiles(files) {
10374
+ const parts = files.map((f2) => `${safeLineName(f2.filename)} (${sizeLabel(f2.size)})`);
10375
+ const line = parts.length === 1 ? `[AgentVault system: you sent the file ${parts[0]}]` : `[AgentVault system: you sent the files ${parts.join(", ")}]`;
10376
+ RENDERED_LINES.delete(line);
10377
+ RENDERED_LINES.add(line);
10378
+ while (RENDERED_LINES.size > RENDERED_MAX) {
10379
+ const oldest = RENDERED_LINES.values().next().value;
10380
+ if (oldest === void 0) break;
10381
+ RENDERED_LINES.delete(oldest);
10382
+ }
10383
+ return line;
10384
+ }
10385
+ function normalizeForMatch(text) {
10386
+ return text.normalize("NFKC").replace(new RegExp("\\p{Cf}", "gu"), "").replace(/\s+/g, " ").toLowerCase();
10387
+ }
10388
+ var SYSTEM_PREFIX_RE = /\[\s*agentvault\s*system\s*:/;
10389
+ var CF_RE = new RegExp("\\p{Cf}", "u");
10390
+ function neutralizeSystemPrefix(text) {
10391
+ if (typeof text !== "string" || text === "") return text;
10392
+ return text.split("\n").map((line) => SYSTEM_PREFIX_RE.test(normalizeForMatch(line)) ? rewriteLine(line) : line).join("\n");
10393
+ }
10394
+ function neutralizeForeignLine(text) {
10395
+ return neutralizeSystemPrefix(text);
10396
+ }
10397
+ function rewriteLine(line) {
10398
+ let out = "";
10399
+ let i2 = 0;
10400
+ while (i2 < line.length) {
10401
+ const ch = line[i2];
10402
+ if (ch === "[" || ch === "\uFF3B") {
10403
+ const end = matchSystemAfter(line, i2 + 1);
10404
+ if (end > 0) {
10405
+ out += "[AgentVault-system (quoted):";
10406
+ i2 = end;
10407
+ continue;
10408
+ }
10409
+ }
10410
+ out += ch;
10411
+ i2 += 1;
10412
+ }
10413
+ return out;
10414
+ }
10415
+ function matchSystemAfter(line, from) {
10416
+ const want = "agentvaultsystem:";
10417
+ let w2 = 0;
10418
+ let i2 = from;
10419
+ while (i2 < line.length && w2 < want.length) {
10420
+ const ch = line[i2];
10421
+ if (CF_RE.test(ch) || /\s/.test(ch)) {
10422
+ i2 += 1;
10423
+ continue;
10424
+ }
10425
+ const n2 = ch.normalize("NFKC").toLowerCase();
10426
+ if (n2 !== want[w2]) return -1;
10427
+ w2 += 1;
10428
+ i2 += 1;
10429
+ }
10430
+ return w2 === want.length ? i2 : -1;
10431
+ }
10432
+ var CLAIM_MAX = 16 * 1024;
10433
+ var ATTACHABLE = "(?:file|files|report|pdf|doc|docs|document|spreadsheet|image|images|attachment|csv|zip|screenshot|screenshots|photo|photos|chart|charts|deck|slides|[\\w-]+\\.(?=[a-z0-9]{0,4}[a-z])[a-z0-9]{2,5})";
10434
+ var PASSIVE = new RegExp(
10435
+ `^(?!(?:no|not|nothing|without|any)\\b)(?:(?:the|your|a|my|this|these|that|those) )?(?:[\\w.-]+ ){0,2}?${ATTACHABLE}(?: (?:is|are))? attached\\b(?! to\\b)`
10436
+ );
10437
+
10438
+ // src/openclaw-file-send.ts
10439
+ import { fileURLToPath } from "node:url";
10440
+
10441
+ // src/turn-token.ts
10442
+ var TURN_TOKEN_TTL_MS = 15 * 6e4;
10443
+
10444
+ // src/openclaw-file-send.ts
10445
+ async function sdkFn(candidates, importer) {
10446
+ try {
10447
+ return await resolveSdkFn(candidates, importer);
10448
+ } catch {
10449
+ return false;
10450
+ }
10451
+ }
10452
+ var OPENCLAW_FILE_TOOL = "message";
10453
+ function classifyMediaRef(raw) {
10454
+ if (typeof raw !== "string") return { kind: "refused" };
10455
+ const t2 = raw.trim();
10456
+ if (!t2 || t2.includes("\0")) return { kind: "refused" };
10457
+ if (/^https?:\/\//i.test(t2)) {
10458
+ try {
10459
+ const u2 = new URL(t2);
10460
+ return u2.protocol === "http:" || u2.protocol === "https:" ? { kind: "link", url: u2.href } : { kind: "refused" };
10461
+ } catch {
10462
+ return { kind: "refused" };
10463
+ }
10464
+ }
10465
+ if (/^file:/i.test(t2)) {
10466
+ try {
10467
+ return { kind: "local", path: fileURLToPath(t2) };
10468
+ } catch {
10469
+ return { kind: "refused" };
10470
+ }
10471
+ }
10472
+ return { kind: "local", path: t2 };
10473
+ }
10474
+ function mediaRefsOf(payload) {
10475
+ if (!payload || typeof payload !== "object") return [];
10476
+ const p2 = payload;
10477
+ const out = [];
10478
+ const add2 = (v2) => {
10479
+ if (typeof v2 === "string" && v2.trim() && !out.includes(v2)) out.push(v2);
10480
+ };
10481
+ add2(p2.mediaUrl);
10482
+ if (Array.isArray(p2.mediaUrls)) for (const v2 of p2.mediaUrls) add2(v2);
10483
+ return out;
10484
+ }
10485
+ function fileTargetFor(target) {
10486
+ if (!target) return null;
10487
+ if (target.kind === "owner") return { kind: "owner" };
10488
+ if (target.kind === "room") return { kind: "room", roomId: target.roomId };
10489
+ return null;
10490
+ }
10491
+ function hostFromSendContext(ctx, sandboxed) {
10492
+ const c2 = ctx && typeof ctx === "object" ? ctx : {};
10493
+ const host = {};
10494
+ if (Array.isArray(c2.mediaLocalRoots)) host.limitRoots = c2.mediaLocalRoots.filter((r2) => typeof r2 === "string");
10495
+ if (sandboxed) {
10496
+ host.sandboxed = true;
10497
+ const reader = typeof c2.mediaReadFile === "function" ? c2.mediaReadFile : null;
10498
+ if (reader) host.readFile = async (p2) => toBytes(await reader(p2));
10499
+ }
10500
+ return host;
10501
+ }
10502
+ var _turnSandbox = /* @__PURE__ */ new Map();
10503
+ function noteTurnSandbox(token, sandboxed) {
10504
+ if (!token) return;
10505
+ _turnSandbox.set(token.id, sandboxed);
10506
+ while (_turnSandbox.size > 2e3) {
10507
+ const oldest = _turnSandbox.keys().next().value;
10508
+ if (oldest === void 0) break;
10509
+ _turnSandbox.delete(oldest);
10510
+ }
10511
+ }
10512
+ function forgetTurnSandbox(token) {
10513
+ if (token) _turnSandbox.delete(token.id);
10514
+ }
10515
+ async function sandboxedForSend(cfg, accountId, turn, importer) {
10516
+ const known = turn ? _turnSandbox.get(turn.id) : void 0;
10517
+ if (known !== void 0) return known;
10518
+ return replySandboxed(cfg, openclawAgentIdFor(cfg, accountId), void 0, importer);
10519
+ }
10520
+ function toBytes(v2) {
10521
+ if (v2 instanceof Uint8Array) return v2;
10522
+ if (v2 instanceof ArrayBuffer) return new Uint8Array(v2);
10523
+ if (v2 && typeof v2 === "object" && v2.buffer instanceof Uint8Array) {
10524
+ return v2.buffer;
10525
+ }
10526
+ throw new Error("media reader returned no bytes");
10527
+ }
10528
+ var MEDIA_ROOTS_CANDIDATES = [
10529
+ { specifier: "openclaw/plugin-sdk/media-local-roots", symbol: "getAgentScopedMediaLocalRoots" }
10530
+ ];
10531
+ var _mediaRootsFn = null;
10532
+ var _mediaRootsGapLogged = false;
10533
+ async function replyMediaRoots(cfg, agentId, importer, log = (m2) => console.warn(m2)) {
10534
+ if (_mediaRootsFn === null) _mediaRootsFn = await sdkFn(MEDIA_ROOTS_CANDIDATES, importer);
10535
+ if (typeof _mediaRootsFn === "function") {
10536
+ try {
10537
+ const roots = _mediaRootsFn(cfg, agentId);
10538
+ if (Array.isArray(roots)) return roots.filter((r2) => typeof r2 === "string");
10539
+ } catch {
10540
+ }
10541
+ }
10542
+ if (!_mediaRootsGapLogged) {
10543
+ _mediaRootsGapLogged = true;
10544
+ log("[AgentVault] file-send: OpenClaw media roots unavailable \u2014 reply media limited to AgentVault roots (OpenClaw-generated media will be refused)");
10545
+ }
10546
+ return void 0;
10547
+ }
10548
+ function sandboxedByConfig(cfg, agentId, sessionKey) {
10549
+ const c2 = cfg;
10550
+ const entry = Array.isArray(c2?.agents?.list) ? c2.agents.list.find((a2) => a2?.id === agentId) : void 0;
10551
+ const mode = entry?.sandbox?.mode ?? c2?.agents?.defaults?.sandbox?.mode ?? "off";
10552
+ if (mode === "off") return false;
10553
+ if (mode === "all") return true;
10554
+ if (mode !== "non-main") return true;
10555
+ const mainKey = c2?.session?.scope === "global" ? "global" : `agent:${(agentId ?? "main").toLowerCase()}:${typeof c2?.session?.mainKey === "string" && c2.session.mainKey ? c2.session.mainKey : "main"}`;
10556
+ return (sessionKey ?? "").trim().toLowerCase() !== mainKey.toLowerCase();
10557
+ }
10558
+ async function sendMediaPart(channel, target, raw, caption, turn, host, deliverOptions) {
10559
+ const fileTarget = fileTargetFor(target);
10560
+ if (!fileTarget) return { ok: false, code: "unsupported_destination", error: fileSendReason("unsupported_destination") };
10561
+ const ref = classifyMediaRef(raw);
10562
+ try {
10563
+ if (ref.kind === "link") {
10564
+ const text = caption ? `${caption}
10565
+ Link: ${ref.url}` : `Link: ${ref.url}`;
10566
+ const receipt = await channel.deliver(target, { type: "text", text }, deliverOptions);
10567
+ return receipt?.ok === false ? { ok: false, code: "delivery_failed", error: fileSendReason("delivery_failed") } : { ok: true, via: "link" };
10568
+ }
10569
+ const res = await channel.sendFile(fileTarget, ref.kind === "local" ? ref.path : raw, caption, turn, host);
10570
+ return res.ok ? { ok: true, via: "file", filename: res.filename, size: res.size } : { ok: false, code: res.code, error: res.error, ...res.filename ? { filename: res.filename } : {} };
10571
+ } catch {
10572
+ return { ok: false, code: "delivery_failed", error: fileSendReason("delivery_failed") };
10573
+ }
10574
+ }
10575
+ function mediaPartToolText(channel, target, res) {
10576
+ const fileTarget = fileTargetFor(target);
10577
+ if (res.ok) {
10578
+ return res.via === "link" ? "Link sent." : fileSendToolResult({ ok: true, filename: res.filename ?? "file", size: res.size ?? 0, mime: "", clientMessageId: "" }, fileTarget ?? { kind: "owner" }, null);
10579
+ }
10580
+ const folder = fileTarget ? channel.stagingPathFor?.(fileTarget) ?? null : null;
10581
+ return fileSendToolResult({ ok: false, code: res.code, error: res.error }, fileTarget ?? { kind: "owner" }, folder);
10582
+ }
10583
+ function openclawFileLines(channel, target, opts) {
10584
+ const folder = target ? channel?.stagingPathFor?.(target) ?? null : null;
10585
+ if (!target || target.kind === "owner" && !folder) return FILE_SEND_UNAVAILABLE;
10586
+ const line = stagingLineFor(target, { folder, roomsAllowed: opts.roomsAllowed });
10587
+ return `${FILE_SEND_RULE(OPENCLAW_FILE_TOOL)}
10588
+ ${line}`;
10589
+ }
10590
+ function takeFileTurn(metadata) {
10591
+ const m2 = metadata && typeof metadata === "object" ? metadata : {};
10592
+ const lease = m2.turnLease && typeof m2.turnLease === "object" ? m2.turnLease : null;
10593
+ const token = lease?.token ?? (m2.turnToken && typeof m2.turnToken === "object" ? m2.turnToken : null);
10594
+ return { lease, token, replies: [], runs: /* @__PURE__ */ new Set(), ended: false, absorbedPending: false };
10595
+ }
10596
+ async function endFileTurn(channel, ft2, waitMs = TURN_TOKEN_TTL_MS) {
10597
+ if (!ft2) return;
10598
+ if (ft2.runs.size > 0) {
10599
+ let timer;
10600
+ await Promise.race([
10601
+ Promise.allSettled([...ft2.runs]),
10602
+ new Promise((r2) => {
10603
+ timer = setTimeout(r2, waitMs);
10604
+ timer.unref?.();
10605
+ })
10606
+ ]);
10607
+ if (timer) clearTimeout(timer);
10608
+ }
10609
+ if (ft2.ended || ft2.absorbedPending) return;
10610
+ ft2.ended = true;
10611
+ forgetTurnSandbox(ft2.token);
10612
+ if (!ft2.lease || typeof channel?.endTurn !== "function") return;
10613
+ try {
10614
+ await channel.endTurn(ft2.lease, { replies: ft2.replies });
10615
+ } catch {
10616
+ }
10617
+ }
10618
+ function foldFileTurn(channel, folded, into) {
10619
+ if (!folded || folded.ended || !folded.lease || !into?.lease || into === folded || typeof channel?.foldTurn !== "function") return false;
10620
+ const ok = channel.foldTurn(folded.lease, into.lease) === true;
10621
+ if (ok) folded.ended = true;
10622
+ return ok;
10623
+ }
10624
+ var OpenClawTurnRuns = class _OpenClawTurnRuns {
10625
+ active = /* @__PURE__ */ new Map();
10626
+ pending = /* @__PURE__ */ new Map();
10627
+ /** Dispatch start order, and the order each tracked dispatch started at. */
10628
+ seq = 0;
10629
+ started = /* @__PURE__ */ new WeakMap();
10630
+ /** The last dispatch start before each waiting token was deferred. */
10631
+ waitedAt = /* @__PURE__ */ new WeakMap();
10632
+ /** Run one OpenClaw dispatch for `ft` on `sessionKey`, tracked until it settles (also after a turn-budget timeout). */
10633
+ track(sessionKey, ft2, run) {
10634
+ const startSeq = ++this.seq;
10635
+ if (!ft2) {
10636
+ const untracked = run.then((v2) => v2);
10637
+ this.started.set(untracked, startSeq);
10638
+ return untracked;
10639
+ }
10640
+ let set = this.active.get(sessionKey);
10641
+ if (!set) {
10642
+ set = /* @__PURE__ */ new Set();
10643
+ this.active.set(sessionKey, set);
10644
+ }
10645
+ set.add(ft2);
10646
+ const done = () => {
10647
+ ft2.runs.delete(tracked);
10648
+ if (ft2.runs.size === 0) {
10649
+ const s2 = this.active.get(sessionKey);
10650
+ s2?.delete(ft2);
10651
+ if (s2 && s2.size === 0) this.active.delete(sessionKey);
10652
+ }
10653
+ };
10654
+ const tracked = run.then((v2) => {
10655
+ done();
10656
+ return v2;
10657
+ }, (e) => {
10658
+ done();
10659
+ throw e;
10660
+ });
10661
+ ft2.runs.add(tracked);
10662
+ this.started.set(tracked, startSeq);
10663
+ return tracked;
10664
+ }
10665
+ /**
10666
+ * After a dispatch returned (dr-evil #1784, MEDIUM 3).
10667
+ * - "steer": the text was injected into the run that is active NOW → fold
10668
+ * into the AgentVault turn that owns that run.
10669
+ * - "followup" (2026.10.8 reports collect the same way: both go through
10670
+ * `enqueueFollowupRun`, `agent-runner-run-*.mjs:7930-7950`): the content
10671
+ * runs in a LATER run (`scheduleFollowupDrainAfterReplyOperationClear`),
10672
+ * which belongs to no AgentVault turn → never folded into the active
10673
+ * turn (that would end it before its content ran); it waits.
10674
+ * - A steer with no AgentVault owner (another surface, a heartbeat) waits
10675
+ * too. A waiting token ends at the session's next dispatch that ran its
10676
+ * own run (evidence the absorbing runs are over), or as a drop at the
10677
+ * bound (MEDIUM/LOW 4). Room file authority does not depend on it: the
10678
+ * content already tainted the room's session (openclaw-room-taint.ts).
10679
+ * - Not deferred: this dispatch ran its own run → every waiting token ends.
10680
+ */
10681
+ async afterDispatch(channel, sessionKey, ft2, result, run) {
10682
+ const deferred = result?.deferredToActiveRun;
10683
+ if (deferred === "steer" || deferred === "followup") {
10684
+ if (!ft2 || !ft2.lease || ft2.ended) return;
10685
+ if (this.active.get(sessionKey)?.has(ft2)) return;
10686
+ if (deferred === "steer") {
10687
+ const absorber = [...this.active.get(sessionKey) ?? []].reverse().find((t2) => t2 !== ft2 && !t2.ended && t2.lease);
10688
+ if (absorber && foldFileTurn(channel, ft2, absorber)) return;
10689
+ }
10690
+ this.wait(channel, sessionKey, ft2);
10691
+ return;
10692
+ }
10693
+ const waiting = this.pending.get(sessionKey);
10694
+ if (!waiting) return;
10695
+ const startedAt = run ? this.started.get(run) : void 0;
10696
+ if (startedAt === void 0) return;
10697
+ const over = waiting.filter((w2) => (this.waitedAt.get(w2) ?? Infinity) < startedAt);
10698
+ const still = waiting.filter((w2) => !over.includes(w2));
10699
+ if (still.length > 0) this.pending.set(sessionKey, still);
10700
+ else this.pending.delete(sessionKey);
10701
+ for (const w2 of over) await this.release(channel, w2);
10702
+ }
10703
+ /** Bounds on waiting tokens (test seam: `OpenClawTurnRuns.bounds`). */
10704
+ static bounds = { maxMs: TURN_TOKEN_TTL_MS, perSession: 100, total: 1e3 };
10705
+ timers = /* @__PURE__ */ new WeakMap();
10706
+ wait(channel, sessionKey, ft2) {
10707
+ ft2.absorbedPending = true;
10708
+ this.waitedAt.set(ft2, this.seq);
10709
+ const list = this.pending.get(sessionKey) ?? [];
10710
+ list.push(ft2);
10711
+ this.pending.set(sessionKey, list);
10712
+ const timer = setTimeout(() => {
10713
+ const l2 = this.pending.get(sessionKey);
10714
+ if (l2) {
10715
+ const i2 = l2.indexOf(ft2);
10716
+ if (i2 >= 0) l2.splice(i2, 1);
10717
+ if (l2.length === 0) this.pending.delete(sessionKey);
10718
+ }
10719
+ void this.release(channel, ft2);
10720
+ }, _OpenClawTurnRuns.bounds.maxMs);
10721
+ timer.unref?.();
10722
+ this.timers.set(ft2, timer);
10723
+ while (list.length > _OpenClawTurnRuns.bounds.perSession) void this.release(channel, list.shift());
10724
+ let total = [...this.pending.values()].reduce((n2, l2) => n2 + l2.length, 0);
10725
+ while (total > _OpenClawTurnRuns.bounds.total) {
10726
+ const [key, l2] = this.pending.entries().next().value;
10727
+ void this.release(channel, l2.shift());
10728
+ if (l2.length === 0) this.pending.delete(key);
10729
+ total--;
10730
+ }
10731
+ }
10732
+ async release(channel, ft2) {
10733
+ const t2 = this.timers.get(ft2);
10734
+ if (t2) clearTimeout(t2);
10735
+ ft2.absorbedPending = false;
10736
+ await endFileTurn(channel, ft2, 0);
10737
+ }
10738
+ /** Test seam. */
10739
+ _sizes() {
10740
+ return { active: [...this.active.values()].reduce((n2, s2) => n2 + s2.size, 0), pending: [...this.pending.values()].reduce((n2, l2) => n2 + l2.length, 0) };
10741
+ }
10742
+ };
10743
+ var WORKSPACE_CANDIDATES = [
10744
+ { specifier: "openclaw/plugin-sdk/agent-runtime", symbol: "resolveAgentWorkspaceDir" }
10745
+ ];
10746
+ var SANDBOX_STATUS_CANDIDATES = [
10747
+ { specifier: "openclaw/plugin-sdk/sandbox", symbol: "resolveSandboxRuntimeStatus" }
10748
+ ];
10749
+ function openclawAgentIdFor(cfg, accountId) {
10750
+ const bindings = cfg?.bindings;
10751
+ const b2 = Array.isArray(bindings) ? bindings.find((x2) => x2?.match?.channel === "agentvault" && x2?.match?.accountId === accountId) : void 0;
10752
+ return typeof b2?.agentId === "string" && b2.agentId ? b2.agentId : "main";
10753
+ }
10754
+ async function resolveOpenClawWorkspace(cfg, agentId, home, importer) {
10755
+ const fn = await sdkFn(WORKSPACE_CANDIDATES, importer);
10756
+ if (typeof fn === "function") {
10757
+ try {
10758
+ const ws = fn(cfg, agentId);
10759
+ if (typeof ws === "string" && ws.trim()) return ws;
10760
+ } catch {
10761
+ }
10762
+ }
10763
+ const c2 = cfg;
10764
+ const entry = Array.isArray(c2?.agents?.list) ? c2.agents.list.find((a2) => a2?.id === agentId) : void 0;
10765
+ const raw = typeof entry?.workspace === "string" && entry.workspace.trim() ? entry.workspace : typeof c2?.agents?.defaults?.workspace === "string" && c2.agents.defaults.workspace.trim() ? c2.agents.defaults.workspace : void 0;
10766
+ if (!raw) return void 0;
10767
+ const expanded = raw.trim().replace(/^~(?=$|\/)/, home);
10768
+ return expanded.startsWith("/") ? expanded : void 0;
10769
+ }
10770
+ async function replySandboxed(cfg, agentId, sessionKey, importer) {
10771
+ const fn = await sdkFn(SANDBOX_STATUS_CANDIDATES, importer);
10772
+ if (typeof fn === "function") {
10773
+ try {
10774
+ const st2 = fn({ cfg, sessionKey, agentId });
10775
+ const status = st2 && typeof st2.then === "function" ? await st2 : st2;
10776
+ if (status && typeof status === "object" && typeof status.sandboxed === "boolean") {
10777
+ return status.sandboxed;
10778
+ }
10779
+ } catch {
10780
+ }
10781
+ }
10782
+ return sandboxedByConfig(cfg, agentId, sessionKey);
10783
+ }
10784
+ var OpenClawFileSendError = class extends Error {
10785
+ constructor(code, message) {
10786
+ super(message);
10787
+ this.code = code;
10788
+ this.name = "OpenClawFileSendError";
10789
+ }
10790
+ code;
10791
+ retryable = false;
10792
+ };
10793
+ function deliveredResult(messageId) {
10794
+ return { ok: true, channel: "agentvault", messageId: messageId || `av-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}` };
10795
+ }
10796
+ var SESSION_ENTRY_CANDIDATES = [
10797
+ { specifier: "openclaw/plugin-sdk/session-store-runtime", symbol: "getSessionEntry" }
10798
+ ];
10799
+ var _sessionEntryReader = null;
10800
+ async function openclawSessionState(core, params, importer) {
10801
+ const session = core?.channel?.session;
10802
+ const reader = typeof session?.readSessionUpdatedAtAsync === "function" ? session.readSessionUpdatedAtAsync.bind(session) : typeof session?.readSessionUpdatedAt === "function" ? session.readSessionUpdatedAt.bind(session) : null;
10803
+ let exists = true;
10804
+ if (reader) {
10805
+ try {
10806
+ const v2 = reader({ storePath: params.storePath, sessionKey: params.sessionKey });
10807
+ const at2 = v2 && typeof v2.then === "function" ? await v2 : v2;
10808
+ exists = at2 !== void 0 && at2 !== null;
10809
+ } catch {
10810
+ exists = true;
10811
+ }
10812
+ }
10813
+ if (!exists) return { exists: false };
10814
+ if (_sessionEntryReader === null) _sessionEntryReader = await sdkFn(SESSION_ENTRY_CANDIDATES, importer);
10815
+ if (typeof _sessionEntryReader === "function") {
10816
+ try {
10817
+ const e = _sessionEntryReader({ storePath: params.storePath, sessionKey: params.sessionKey, ...params.agentId ? { agentId: params.agentId } : {} });
10818
+ const entry = e && typeof e.then === "function" ? await e : e;
10819
+ const id = entry?.sessionId;
10820
+ if (typeof id === "string" && id) {
10821
+ const lineage = [entry?.previousSessionId, entry?.parentSessionId, entry?.parentSessionKey, entry?.spawnedBy].some((x2) => typeof x2 === "string" && x2 !== "") || entry?.forkSource !== void 0 && entry?.forkSource !== null || entry?.forkedFromParent === true;
10822
+ const createdAt = typeof entry?.createdAt === "number" ? entry.createdAt : void 0;
10823
+ return { exists: true, sessionId: id, lineage, ...createdAt !== void 0 ? { createdAt } : {} };
10824
+ }
10825
+ } catch {
10826
+ }
10827
+ }
10828
+ return { exists: true };
10829
+ }
10830
+ async function readSessionUpdatedAtSafe(core, params) {
10831
+ const session = core?.channel?.session;
10832
+ try {
10833
+ const v2 = typeof session?.readSessionUpdatedAtAsync === "function" ? await session.readSessionUpdatedAtAsync(params) : typeof session?.readSessionUpdatedAt === "function" ? session.readSessionUpdatedAt(params) : void 0;
10834
+ return typeof v2 === "number" ? v2 : void 0;
10835
+ } catch {
10836
+ return void 0;
10837
+ }
10838
+ }
10839
+
10840
+ // src/openclaw-room-taint.ts
10841
+ import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
10842
+ import { join } from "node:path";
10843
+ var ROOM_TAINT_FILE = "openclaw-room-taint.json";
10844
+ var RoomTaintStore = class {
10845
+ constructor(dataDir, log = (m2) => console.warn(m2)) {
10846
+ this.log = log;
10847
+ this.path = join(dataDir, ROOM_TAINT_FILE);
10848
+ }
10849
+ log;
10850
+ path;
10851
+ cache = null;
10852
+ /** Rooms whose taint could not be written: tainted for this process whatever the file says. */
10853
+ poisoned = /* @__PURE__ */ new Set();
10854
+ load() {
10855
+ if (this.cache) return this.cache;
10856
+ let parsed;
10857
+ try {
10858
+ parsed = JSON.parse(readFileSync2(this.path, "utf8"));
10859
+ } catch {
10860
+ parsed = {};
10861
+ }
10862
+ const out = {};
10863
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
10864
+ for (const [room, v2] of Object.entries(parsed)) {
10865
+ if (v2 && typeof v2 === "object" && typeof v2.tainted === "boolean") {
10866
+ out[room] = { tainted: v2.tainted, at: Number(v2.at) || 0, ...typeof v2.sessionId === "string" ? { sessionId: v2.sessionId } : {} };
10867
+ }
10868
+ }
10869
+ }
10870
+ this.cache = out;
10871
+ return out;
10872
+ }
10873
+ /**
10874
+ * Is the room's session tainted, given what OpenClaw reports? Also resets a
10875
+ * record whose session is genuinely new (no session, or a different id).
10876
+ */
10877
+ isTainted(key, oc) {
10878
+ if (this.poisoned.has(key)) return true;
10879
+ const rec = this.load()[key];
10880
+ if (!oc.exists) {
10881
+ return rec && !rec.sessionId ? rec.tainted : false;
10882
+ }
10883
+ if (!rec) return true;
10884
+ if (rec.sessionId && oc.sessionId && rec.sessionId !== oc.sessionId) {
10885
+ const fresh = oc.lineage === false && typeof oc.createdAt === "number" && oc.createdAt > rec.at;
10886
+ return fresh ? false : rec.tainted;
10887
+ }
10888
+ return rec.tainted;
10889
+ }
10890
+ /**
10891
+ * Record the room's state for the session about to receive this turn.
10892
+ * `tainted` is sticky within a session: a clean turn never clears a taint
10893
+ * (only a genuinely new session does, through `isTainted`'s answer).
10894
+ */
10895
+ record(key, oc, turnTaints) {
10896
+ const all = this.load();
10897
+ const wasTainted = this.isTainted(key, oc);
10898
+ const tainted = wasTainted || turnTaints;
10899
+ const prev = all[key];
10900
+ const sessionId = oc.sessionId ?? (oc.exists ? prev?.sessionId : void 0);
10901
+ const next = { tainted, at: Date.now(), ...sessionId ? { sessionId } : {} };
10902
+ if (prev && prev.tainted === next.tainted && prev.sessionId === next.sessionId) return;
10903
+ all[key] = next;
10904
+ if (!this.write(all) && tainted) {
10905
+ this.poisoned.add(key);
10906
+ delete all[key];
10907
+ if (!this.write(all)) {
10908
+ try {
10909
+ rmSync(this.path, { force: true });
10910
+ } catch {
10911
+ }
10912
+ this.cache = null;
10913
+ }
10914
+ this.log("[AgentVault] file-send: a room session taint was not saved \u2014 room files stay refused for that session");
10915
+ }
10916
+ }
10917
+ /**
10918
+ * The session the record describes now exists (OpenClaw created it while
10919
+ * recording this turn): remember its id, so a later reset — a NEW id — is
10920
+ * recognised. Only fills a missing id; never changes `tainted`.
10921
+ */
10922
+ bindSession(key, oc) {
10923
+ const all = this.load();
10924
+ const rec = all[key];
10925
+ if (!rec || rec.sessionId || !oc.exists || !oc.sessionId) return;
10926
+ all[key] = { ...rec, sessionId: oc.sessionId };
10927
+ if (!this.write(all)) all[key] = rec;
10928
+ }
10929
+ write(all) {
10930
+ const tmp = `${this.path}.${process.pid}.tmp`;
10931
+ try {
10932
+ writeFileSync(tmp, JSON.stringify(all), { mode: 384 });
10933
+ renameSync(tmp, this.path);
10934
+ return true;
10935
+ } catch {
10936
+ try {
10937
+ rmSync(tmp, { force: true });
10938
+ } catch {
10939
+ }
10940
+ return false;
10941
+ }
10942
+ }
10943
+ };
10944
+
10945
+ // src/openclaw-sender.ts
10946
+ function hexish(id, max) {
10947
+ if (typeof id !== "string") return "unknown";
10948
+ const clean4 = id.toLowerCase().replace(/[^0-9a-f-]/g, "");
10949
+ return clean4 === "" ? "unknown" : clean4.slice(0, max);
10950
+ }
10951
+ function dmSenderIdentity(metadata) {
10952
+ if (metadata?.ownerDm1to1 === true && metadata.senderIsOwnerDevice === true && metadata.senderBinding === "bound") {
10953
+ return { id: "agentvault:owner", name: "Owner", owner: true };
10954
+ }
10955
+ if (metadata?.senderBinding === "bound" && typeof metadata.senderDeviceId === "string" && metadata.senderDeviceId !== "") {
10956
+ const name = metadata.senderOwnerStatus === "unknown" ? "Owner status unconfirmed" : "Not the owner";
10957
+ return { id: `agentvault:device:${hexish(metadata.senderDeviceId, 36)}`, name, owner: false };
10958
+ }
10959
+ const conv = typeof metadata?.conversationId === "string" && metadata.conversationId !== "" ? metadata.conversationId : metadata?.conversationGroupId;
10960
+ return { id: `agentvault:unverified:${hexish(conv, 8)}`, name: "Unverified sender", owner: false };
10961
+ }
10962
+ function unverifiedRoomFragment(claimed) {
10963
+ return `#unverified:${hexish(claimed, 8)}`;
10964
+ }
10965
+
9888
10966
  // src/openclaw-entry.ts
9889
10967
  var _ocRuntime = null;
9890
10968
  var _channels = /* @__PURE__ */ new Map();
@@ -9998,7 +11076,7 @@ function _stripThinkBlocks(text) {
9998
11076
  function _looksLikeReasoningLeak(text) {
9999
11077
  return /^(Reasoning|Thinking|Let me think|I need to|Let me check):/i.test(text) || /^<think[\s>]/i.test(text) || /^think$/im.test(text) || /^\[\[[\w_]+\]\]/.test(text) || /^<think>[\s\S]*<\/think>$/i.test(text);
10000
11078
  }
10001
- function _resolveRoomIdentity(channel, roomId, fallbackName, privateRoom = false) {
11079
+ function _resolveRoomIdentity(channel, roomId, fallbackName, privateRoom = false, roomLabel, redactForeignNames = false) {
10002
11080
  const fallback = { selfName: fallbackName, preamble: "" };
10003
11081
  if (!roomId) return fallback;
10004
11082
  try {
@@ -10008,20 +11086,26 @@ function _resolveRoomIdentity(channel, roomId, fallbackName, privateRoom = false
10008
11086
  const ownDeviceId = channel.deviceId;
10009
11087
  const self2 = room.members?.find((m2) => m2.deviceId === ownDeviceId);
10010
11088
  const selfName = self2?.displayName || fallbackName;
10011
- const others = (room.members ?? []).filter((m2) => m2.deviceId !== ownDeviceId).map((m2) => `${m2.displayName} (${m2.entityType === "agent" ? "agent" : "person"})`);
11089
+ const jwtTenant = typeof channel.ownTenantId === "function" ? channel.ownTenantId() : null;
11090
+ const ownTenant = typeof jwtTenant === "string" && jwtTenant ? jwtTenant.toLowerCase() : null;
11091
+ const ownAccount = (m2) => ownTenant !== null && typeof m2?.tenantId === "string" && m2.tenantId.toLowerCase() === ownTenant;
11092
+ const others = (room.members ?? []).filter((m2) => m2.deviceId !== ownDeviceId).map((m2) => redactForeignNames && !ownAccount(m2) ? `${m2.entityType === "agent" ? "agent" : "member"} ${String(m2.deviceId ?? "").slice(0, 8)} (other account)` : `${m2.displayName} (${m2.entityType === "agent" ? "agent" : "person"})`);
10012
11093
  const membersStr = others.length > 0 ? others.join(", ") : "(still loading \u2014 more members may be joining; this is NOT a 1:1)";
10013
11094
  if (privateRoom) {
10014
11095
  return {
10015
11096
  selfName,
10016
- preamble: `[chat_type: room | conversation: private | room: "${room.name ?? "this room"}" (private room: just you and your person \u2014 never a group, never a 1:1 DM) | you are ${selfName} (agent) | other members: ${membersStr} | every message here is for you \u2014 answer it | if a tool fails, do not tell the room about it \u2014 just give your answer]`
11097
+ preamble: `[chat_type: room | conversation: private | room: "${roomLabel ?? room.name ?? "this room"}" (private room: just you and your person \u2014 never a group, never a 1:1 DM) | you are ${selfName} (agent) | other members: ${membersStr} | every message here is for you \u2014 answer it | if a tool fails, do not tell the room about it \u2014 just give your answer]`
10017
11098
  };
10018
11099
  }
10019
- const preamble = `[chat_type: room | conversation: group | room: "${room.name ?? "this room"}" (MULTI-PARTY GROUP ROOM, never a 1:1/direct message) | you are ${selfName} (agent) | other members: ${membersStr} | this is a shared group room with multiple participants \u2014 do NOT describe it as a direct chat or a DM; reply here to reach everyone in this room, including agents on other frameworks \u2014 to bring another agent in, mention it as @name | if a tool fails, do not tell the room about it \u2014 just give your answer]`;
11100
+ const preamble = `[chat_type: room | conversation: group | room: "${roomLabel ?? room.name ?? "this room"}" (MULTI-PARTY GROUP ROOM, never a 1:1/direct message) | you are ${selfName} (agent) | other members: ${membersStr} | this is a shared group room with multiple participants \u2014 do NOT describe it as a direct chat or a DM; reply here to reach everyone in this room, including agents on other frameworks \u2014 to bring another agent in, mention it as @name | if a tool fails, do not tell the room about it \u2014 just give your answer]`;
10020
11101
  return { selfName, preamble };
10021
11102
  } catch {
10022
11103
  return fallback;
10023
11104
  }
10024
11105
  }
11106
+ function _shortRoomLabel(roomId) {
11107
+ return `room ${String(roomId ?? "").slice(0, 8)}`;
11108
+ }
10025
11109
  function _buildDmPreamble(selfName, hubAddress) {
10026
11110
  if (!selfName) return "";
10027
11111
  const at2 = hubAddress ? ` at ${hubAddress}` : "";
@@ -10079,8 +11163,9 @@ function _selectInboundPreamble(opts) {
10079
11163
  }
10080
11164
  return "";
10081
11165
  }
10082
- function _buildRoomSenderId(roomId, senderDeviceId, senderName) {
11166
+ function _buildRoomSenderId(roomId, senderDeviceId, senderName, unverifiedClaim) {
10083
11167
  const base = `agentvault:room:${roomId}`;
11168
+ if (unverifiedClaim !== void 0) return `${base}${unverifiedRoomFragment(unverifiedClaim)}`;
10084
11169
  if (senderDeviceId) return `${base}#device:${senderDeviceId}`;
10085
11170
  const name = (senderName ?? "").trim();
10086
11171
  if (name) return `${base}#sender:${encodeURIComponent(name.toLowerCase())}`;
@@ -10183,6 +11268,27 @@ function _withSessionSerial(key, fn) {
10183
11268
  return run;
10184
11269
  }
10185
11270
  var TURN_BUDGET_MS = 12e4;
11271
+ function _setTurnBudgetMsForTest(ms) {
11272
+ const prev = TURN_BUDGET_MS;
11273
+ TURN_BUDGET_MS = ms;
11274
+ return prev;
11275
+ }
11276
+ var _turnRuns = new OpenClawTurnRuns();
11277
+ var _roomTaints = /* @__PURE__ */ new Map();
11278
+ function _roomTaintFor(channel) {
11279
+ const dataDir = channel?.config?.dataDir;
11280
+ if (typeof dataDir !== "string" || !dataDir) return null;
11281
+ let store = _roomTaints.get(dataDir);
11282
+ if (!store) {
11283
+ store = new RoomTaintStore(dataDir);
11284
+ _roomTaints.set(dataDir, store);
11285
+ }
11286
+ return store;
11287
+ }
11288
+ function _resetRoomTaintsForTest() {
11289
+ _roomTaints.clear();
11290
+ }
11291
+ var _notReadyBound = { maxMs: TURN_TOKEN_TTL_MS };
10186
11292
  function _withTurnTimeout(ms, fn, onTimeout) {
10187
11293
  return new Promise((resolve2, reject) => {
10188
11294
  let settled = false;
@@ -10294,10 +11400,27 @@ function _makeOnMessage(deps) {
10294
11400
  return target.kind === "owner" && typeof channel?.runForConversation === "function" ? channel.runForConversation(metadata?.conversationId, send, { groupId: metadata?.conversationGroupId }) : send();
10295
11401
  };
10296
11402
  return async (plaintext, metadata) => {
11403
+ const fileTurn = takeFileTurn(metadata);
11404
+ const endThisTurn = () => {
11405
+ let ch;
11406
+ try {
11407
+ ch = deps.getChannel();
11408
+ } catch {
11409
+ ch = void 0;
11410
+ }
11411
+ return endFileTurn(ch, fileTurn);
11412
+ };
10297
11413
  const turn = newInboundTurnState();
10298
11414
  if (!deps.isRuntimeReady()) {
10299
11415
  deps.log?.("[AgentVault] runtime not ready, queuing message");
10300
- deps.enqueue(() => deps.inbound({ plaintext, metadata, turn }));
11416
+ const bound = setTimeout(() => {
11417
+ void endThisTurn();
11418
+ }, _notReadyBound.maxMs);
11419
+ bound.unref?.();
11420
+ deps.enqueue(() => {
11421
+ clearTimeout(bound);
11422
+ return deps.inbound({ plaintext, metadata, turn, fileTurn }).finally(endThisTurn);
11423
+ });
10301
11424
  return;
10302
11425
  }
10303
11426
  const startedAt = Date.now();
@@ -10311,7 +11434,7 @@ function _makeOnMessage(deps) {
10311
11434
  provider: providerName
10312
11435
  };
10313
11436
  notices.opened(open2);
10314
- await _dispatchInboundWithRetry(() => deps.inbound({ plaintext, metadata, turn }), {
11437
+ await _dispatchInboundWithRetry(() => deps.inbound({ plaintext, metadata, turn, fileTurn }), {
10315
11438
  notifyOwner: async (lastErr) => {
10316
11439
  const channel = deps.getChannel();
10317
11440
  const target = _failureNoticeTarget(metadata, turn);
@@ -10339,11 +11462,18 @@ function _makeOnMessage(deps) {
10339
11462
  else console.warn(m2);
10340
11463
  } catch {
10341
11464
  }
10342
- }).finally(() => notices.closed(open2));
11465
+ }).finally(async () => {
11466
+ try {
11467
+ await notices.closed(open2);
11468
+ } finally {
11469
+ await endThisTurn();
11470
+ }
11471
+ });
10343
11472
  };
10344
11473
  }
10345
11474
  async function handleInbound(params) {
10346
11475
  const { plaintext: rawPlaintext, metadata, channel, account, cfg } = params;
11476
+ const fileTurn = params.fileTurn;
10347
11477
  const turn = params.turn ?? newInboundTurnState();
10348
11478
  const isRoomMessage = Boolean(metadata.roomId);
10349
11479
  const isA2AMessage = Boolean(metadata.a2aChannelId);
@@ -10358,7 +11488,8 @@ async function handleInbound(params) {
10358
11488
  const selfResolved = !!ownDisplayName || !!roomIdentity.selfName && roomIdentity.selfName !== (account.agentName ?? "") || !genericAgentName;
10359
11489
  if (isRoomMessage) {
10360
11490
  const gateText = metadata.caption ?? rawPlaintext;
10361
- if (!owesRoomReply(gateText, account.agentName ?? "", account.accountId ?? "", metadata.senderIsAgent, roomIdentity.selfName, ownDisplayName, selfResolved, metadata.roomAudience)) {
11491
+ const gateSenderIsAgent = metadata.senderBinding === "bound" ? metadata.senderIsAgent : true;
11492
+ if (!owesRoomReply(gateText, account.agentName ?? "", account.accountId ?? "", gateSenderIsAgent, roomIdentity.selfName, ownDisplayName, selfResolved, metadata.roomAudience)) {
10362
11493
  console.log(
10363
11494
  `[AgentVault] room message read, not answered \u2014 no @mention for this agent (#1107) room=${String(metadata.roomId ?? "").slice(0, 8)}`
10364
11495
  );
@@ -10379,9 +11510,9 @@ async function handleInbound(params) {
10379
11510
  }
10380
11511
  }
10381
11512
  const startTime = Date.now();
10382
- const traceId = randomBytes2(16).toString("hex");
10383
- const rootSpanId = randomBytes2(8).toString("hex");
10384
- const inferenceSpanId = randomBytes2(8).toString("hex");
11513
+ const traceId = randomBytes3(16).toString("hex");
11514
+ const rootSpanId = randomBytes3(8).toString("hex");
11515
+ const inferenceSpanId = randomBytes3(8).toString("hex");
10385
11516
  const _sendActivity = (spanData) => {
10386
11517
  try {
10387
11518
  channel.sendActivitySpan({ ...redactFreeText(spanData), trace_id: traceId, parent_span_id: inferenceSpanId });
@@ -10399,7 +11530,7 @@ async function handleInbound(params) {
10399
11530
  const activityAttrs = { "ai.agent.llm.model": opts.model ?? "" };
10400
11531
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10401
11532
  _sendActivity({
10402
- span_id: randomBytes2(8).toString("hex"),
11533
+ span_id: randomBytes3(8).toString("hex"),
10403
11534
  span_type: "llm",
10404
11535
  span_name: opts.model ?? "LLM",
10405
11536
  status: opts.status === "error" ? "error" : "ok",
@@ -10421,7 +11552,7 @@ async function handleInbound(params) {
10421
11552
  const activityAttrs = { "ai.agent.tool.name": opts.toolName ?? "" };
10422
11553
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10423
11554
  _sendActivity({
10424
- span_id: randomBytes2(8).toString("hex"),
11555
+ span_id: randomBytes3(8).toString("hex"),
10425
11556
  span_type: "tool",
10426
11557
  span_name: opts.toolName ?? "tool",
10427
11558
  status: opts.success === false ? "error" : "ok",
@@ -10442,7 +11573,7 @@ async function handleInbound(params) {
10442
11573
  const activityAttrs = { "ai.agent.error.type": opts.errorType ?? "" };
10443
11574
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10444
11575
  _sendActivity({
10445
- span_id: randomBytes2(8).toString("hex"),
11576
+ span_id: randomBytes3(8).toString("hex"),
10446
11577
  span_type: "error",
10447
11578
  span_name: opts.errorType ?? "error",
10448
11579
  status: "error",
@@ -10465,7 +11596,7 @@ async function handleInbound(params) {
10465
11596
  const activityAttrs = { "ai.agent.http.method": opts.method ?? "", "ai.agent.http.url": site };
10466
11597
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10467
11598
  _sendActivity({
10468
- span_id: randomBytes2(8).toString("hex"),
11599
+ span_id: randomBytes3(8).toString("hex"),
10469
11600
  span_type: "http",
10470
11601
  span_name: urlHost(site) || "http",
10471
11602
  status: (opts.statusCode ?? 200) >= 400 ? "error" : "ok",
@@ -10488,7 +11619,7 @@ async function handleInbound(params) {
10488
11619
  const activityAttrs = { "ai.agent.action.type": opts.actionType ?? "", "ai.agent.action.target": opts.target ?? "" };
10489
11620
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10490
11621
  _sendActivity({
10491
- span_id: randomBytes2(8).toString("hex"),
11622
+ span_id: randomBytes3(8).toString("hex"),
10492
11623
  span_type: "action",
10493
11624
  span_name: `${opts.actionType ?? "action"}: ${opts.target ?? ""}`,
10494
11625
  status: opts.success === false ? "error" : "ok",
@@ -10511,7 +11642,7 @@ async function handleInbound(params) {
10511
11642
  const activityAttrs = { "ai.agent.nav.to_url": site };
10512
11643
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10513
11644
  _sendActivity({
10514
- span_id: randomBytes2(8).toString("hex"),
11645
+ span_id: randomBytes3(8).toString("hex"),
10515
11646
  span_type: "nav",
10516
11647
  span_name: site || "navigate",
10517
11648
  status: opts.status === "error" ? "error" : "ok",
@@ -10574,23 +11705,21 @@ async function handleInbound(params) {
10574
11705
  }
10575
11706
  }
10576
11707
  }
11708
+ const dmIdentity = !isRoomMessage && !isA2AMessage ? dmSenderIdentity(metadata) : null;
10577
11709
  const route = core.channel.routing.resolveAgentRoute({
10578
11710
  cfg,
10579
11711
  channel: "agentvault",
10580
11712
  accountId: account.accountId,
10581
11713
  peer: {
10582
11714
  kind: isRoomMessage ? "group" : "direct",
10583
- id: isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner"
11715
+ id: isRoomMessage ? `agentvault:room:${metadata.roomId}` : dmIdentity?.id ?? "agentvault:owner"
10584
11716
  }
10585
11717
  });
10586
11718
  const storePath = core.channel.session.resolveStorePath(cfg?.session?.store, {
10587
11719
  agentId: route.agentId
10588
11720
  });
10589
11721
  const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
10590
- const previousTimestamp = core.channel.session.readSessionUpdatedAt({
10591
- storePath,
10592
- sessionKey: route.sessionKey
10593
- });
11722
+ const previousTimestamp = await readSessionUpdatedAtSafe(core, { storePath, sessionKey: route.sessionKey });
10594
11723
  const recallQuery = isRoomMessage || isA2AMessage ? plaintext : metadata?.reason || metadata?.triggerName || plaintext;
10595
11724
  const recallWorthwhile = (recallQuery?.trim().length ?? 0) >= 10;
10596
11725
  if (recallWorthwhile) {
@@ -10607,27 +11736,66 @@ async function handleInbound(params) {
10607
11736
  plaintext = memoryContext + "\n---\n\n" + plaintext;
10608
11737
  }
10609
11738
  }
10610
- let contextBody = plaintext;
11739
+ let contextBody = neutralizeForeignLine(plaintext);
11740
+ let roomHistoryAttached = false;
10611
11741
  if (isRoomMessage && metadata.roomId && channel.getRoomHistory) {
10612
11742
  const recentHistory = channel.getRoomHistory(metadata.roomId, 20);
10613
11743
  const prior = recentHistory.slice(0, -1);
10614
11744
  if (prior.length > 0) {
10615
11745
  const historyBlock = prior.map((h2) => {
10616
- const role = h2.sender === "agent" ? "You" : "Room Member";
10617
- return `[${role}]: ${h2.text}`;
11746
+ if (h2.sender === "agent") {
11747
+ const files = Array.isArray(h2.files) && h2.files.length > 0 ? `
11748
+ ${renderHistoryFiles(h2.files)}` : "";
11749
+ return `[You]: ${h2.text}${files}`;
11750
+ }
11751
+ const who = h2.sender === "unverified" ? "Unverified sender" : "Room Member";
11752
+ return `[${who}]: ${neutralizeForeignLine(String(h2.text ?? ""))}`;
10618
11753
  }).join("\n");
10619
11754
  contextBody = `[Recent room conversation]
10620
11755
  ${historyBlock}
10621
11756
 
10622
11757
  [Current message]
10623
- ${plaintext}`;
11758
+ ${contextBody}`;
11759
+ roomHistoryAttached = true;
11760
+ }
11761
+ }
11762
+ const fileSendOn = typeof channel.stagingPathFor === "function" && channel.stagingPathFor({ kind: "owner" }) !== null;
11763
+ let replyHost = {};
11764
+ if (fileSendOn && !isA2AMessage) {
11765
+ const [limitRoots, sandboxed] = await Promise.all([
11766
+ replyMediaRoots(cfg, route.agentId),
11767
+ replySandboxed(cfg, route.agentId, route.sessionKey)
11768
+ ]);
11769
+ replyHost = { ...limitRoots !== void 0 ? { limitRoots } : {}, ...sandboxed ? { sandboxed: true } : {} };
11770
+ }
11771
+ let roomTainted = true;
11772
+ if (isRoomMessage && typeof metadata.roomId === "string" && typeof route.sessionKey === "string" && route.sessionKey) {
11773
+ const store = _roomTaintFor(channel);
11774
+ if (store) {
11775
+ const oc = await openclawSessionState(core, { storePath, sessionKey: route.sessionKey, agentId: route.agentId });
11776
+ roomTainted = store.isTainted(route.sessionKey, oc);
11777
+ const cleanTurn = metadata.senderIsAgent === false && metadata.senderIsOwner === true && metadata.foreignContent === false && !roomHistoryAttached;
11778
+ store.record(route.sessionKey, oc, !cleanTurn);
10624
11779
  }
10625
11780
  }
11781
+ let attested = false;
11782
+ if (isRoomMessage && fileTurn?.lease && !roomHistoryAttached && !roomTainted && typeof channel.attestCleanTurn === "function") {
11783
+ attested = channel.attestCleanTurn(fileTurn.lease) === true;
11784
+ }
11785
+ noteTurnSandbox(fileTurn?.token, replyHost.sandboxed === true);
10626
11786
  if (!isRoomMessage && !isA2AMessage && !channel.ownDisplayName && typeof channel.ensureOwnIdentityResolved === "function") {
10627
11787
  void channel.ensureOwnIdentityResolved();
10628
11788
  }
11789
+ const roomForModel = isRoomMessage && attested ? _resolveRoomIdentity(
11790
+ channel,
11791
+ metadata.roomId,
11792
+ account.agentName ?? "",
11793
+ isPrivatePairHumanMessage(metadata.senderIsAgent, metadata.roomAudience),
11794
+ _shortRoomLabel(metadata.roomId),
11795
+ true
11796
+ ) : roomIdentity;
10629
11797
  const inboundPreamble = _selectInboundPreamble({
10630
- roomPreamble: roomIdentity.preamble,
11798
+ roomPreamble: roomForModel.preamble,
10631
11799
  isRoomMessage,
10632
11800
  isA2AMessage,
10633
11801
  ownDisplayName: channel.ownDisplayName ?? "",
@@ -10636,10 +11804,16 @@ ${plaintext}`;
10636
11804
  if (inboundPreamble) {
10637
11805
  contextBody = `${inboundPreamble}
10638
11806
  ${contextBody}`;
11807
+ }
11808
+ if (fileSendOn) {
11809
+ const fileTarget = isA2AMessage ? null : isRoomMessage ? { kind: "room", roomId: metadata.roomId } : { kind: "owner" };
11810
+ contextBody = `${contextBody}
11811
+
11812
+ ${openclawFileLines(channel, fileTarget, { roomsAllowed: attested && replyHost.sandboxed !== true })}`;
10639
11813
  }
10640
11814
  const body2 = core.channel.reply.formatAgentEnvelope({
10641
11815
  channel: "AgentVault",
10642
- from: isA2AMessage ? `Agent (${metadata.fromHubAddress})` : isRoomMessage ? senderDisplayName ?? "Room Member" : "Owner",
11816
+ from: isA2AMessage ? `Agent (${metadata.fromHubAddress})` : isRoomMessage ? senderDisplayName ?? "Room Member" : dmIdentity?.name ?? "Unverified sender",
10643
11817
  timestamp: new Date(metadata.timestamp).getTime(),
10644
11818
  previousTimestamp,
10645
11819
  envelope: envelopeOptions,
@@ -10664,13 +11838,13 @@ ${contextBody}`;
10664
11838
  credentialFields.RenterCredentialCount = creds.length;
10665
11839
  }
10666
11840
  }
10667
- const commandAuthorized = isA2AMessage ? false : isRoomMessage ? metadata.senderIsOwner === true && metadata.foreignContent === false : true;
11841
+ const commandAuthorized = isA2AMessage ? false : isRoomMessage ? metadata.senderIsOwner === true && metadata.foreignContent === false : metadata.ownerDm1to1 === true && metadata.senderIsOwnerDevice === true && dmIdentity?.owner === true;
10668
11842
  const isCommandTurn = commandAuthorized && commandBody.trim().startsWith("/");
10669
11843
  const ctxPayload = core.channel.reply.finalizeInboundContext({
10670
11844
  Body: body2,
10671
11845
  RawBody: plaintext,
10672
11846
  CommandBody: commandBody,
10673
- From: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner",
11847
+ From: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : dmIdentity?.id ?? "agentvault:unverified:unknown",
10674
11848
  // GH #366 iter 3: room `To` must be ROOM-scoped (matches `From`), not
10675
11849
  // agent-scoped — an agent-scoped `To` reads as a 1:1 address and triggers
10676
11850
  // the `chat_type: "direct"` confabulation. Only the ROOM case changes;
@@ -10688,8 +11862,9 @@ ${contextBody}`;
10688
11862
  // @mention this agent, so a room turn that gets here is a mention.
10689
11863
  // OpenClaw reads it for group typing and reply rules.
10690
11864
  ...isRoomMessage ? { WasMentioned: true } : {},
10691
- ConversationLabel: isA2AMessage ? `A2A: ${metadata.fromHubAddress}` : isRoomMessage ? roomName ?? "AgentVault Room" : "AgentVault",
10692
- SenderName: isA2AMessage ? metadata.fromHubAddress : isRoomMessage ? senderDisplayName ?? "Room Member" : "Owner",
11865
+ // #1784 item 8: an attested room turn is labelled by the room's short id, never its name.
11866
+ ConversationLabel: isA2AMessage ? `A2A: ${metadata.fromHubAddress}` : isRoomMessage ? attested ? _shortRoomLabel(metadata.roomId) : roomName ?? "AgentVault Room" : "AgentVault",
11867
+ SenderName: isA2AMessage ? metadata.fromHubAddress : isRoomMessage ? senderDisplayName ?? "Room Member" : dmIdentity?.name ?? "Unverified sender",
10693
11868
  // GH #366: room SenderId must encode the ROOM, not the sender's device id.
10694
11869
  // The old form `agentvault:room:${senderDeviceId}` stamped the device id
10695
11870
  // with a `room:` prefix → agent read it as a per-device DM channel.
@@ -10697,7 +11872,12 @@ ${contextBody}`;
10697
11872
  // scope primary while still identifying the specific sender within it. The
10698
11873
  // no-senderDeviceId case is hardened in _buildRoomSenderId (sender-name
10699
11874
  // fragment) so the binding exact-match can't pass for every member.
10700
- SenderId: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? _buildRoomSenderId(metadata.roomId, metadata.senderDeviceId, senderDisplayName) : "agentvault:owner",
11875
+ SenderId: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? _buildRoomSenderId(
11876
+ metadata.roomId,
11877
+ metadata.senderDeviceId,
11878
+ senderDisplayName,
11879
+ typeof metadata.senderBinding === "string" && metadata.senderBinding !== "bound" ? metadata.claimedSenderDeviceId ?? null : void 0
11880
+ ) : dmIdentity?.id ?? "agentvault:unverified:unknown",
10701
11881
  Provider: "agentvault",
10702
11882
  Surface: "agentvault",
10703
11883
  MessageSid: metadata.messageId,
@@ -10709,6 +11889,9 @@ ${contextBody}`;
10709
11889
  OriginatingTo: isRoomMessage ? _buildRoomTo(metadata.roomId, account.accountId) : `agentvault:agent:${account.accountId}`,
10710
11890
  // Who may run a slash command: see `commandAuthorized` above.
10711
11891
  CommandAuthorized: commandAuthorized,
11892
+ // #1800 PR B §1.3: every non-owner turn also suppresses command
11893
+ // interpretation — `commands.allowFrom` would bypass CommandAuthorized.
11894
+ ...commandAuthorized ? {} : { CommandInterpretationSuppressed: true },
10712
11895
  Instrument: _instrument,
10713
11896
  // OpenClaw ctx convention
10714
11897
  AgentVaultTelemetry: _instrument,
@@ -10720,7 +11903,8 @@ ${contextBody}`;
10720
11903
  const _asTurn = (fn) => !isRoomMessage && !isA2AMessage && typeof channel.runForConversation === "function" ? channel.runForConversation(metadata.conversationId, fn, { groupId: metadata.conversationGroupId }) : fn();
10721
11904
  const attempt = { expired: false };
10722
11905
  let failureCode;
10723
- await _withSessionSerial(_turnSessionKey, () => runWithToolConversation(_toolConversationFor(metadata), () => _asTurn(() => _withTurnTimeout(TURN_BUDGET_MS, async () => {
11906
+ const _asNonOwner = (fn) => dmIdentity && !dmIdentity.owner && typeof channel.runAsNonOwnerTurn === "function" ? channel.runAsNonOwnerTurn(fn) : fn();
11907
+ await _asNonOwner(() => _withSessionSerial(_turnSessionKey, () => runWithToolConversation(_toolConversationFor(metadata), () => _asTurn(() => _withTurnTimeout(TURN_BUDGET_MS, async () => {
10724
11908
  await core.channel.session.recordInboundSession({
10725
11909
  storePath,
10726
11910
  sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
@@ -10729,6 +11913,10 @@ ${contextBody}`;
10729
11913
  core.error?.(`[AgentVault] session record failed: ${String(err)}`);
10730
11914
  }
10731
11915
  });
11916
+ if (isRoomMessage && typeof route.sessionKey === "string" && route.sessionKey) {
11917
+ const store = _roomTaintFor(channel);
11918
+ if (store) store.bindSession(route.sessionKey, await openclawSessionState(core, { storePath, sessionKey: route.sessionKey, agentId: route.agentId }));
11919
+ }
10732
11920
  try {
10733
11921
  const heldFailurePayloads = [];
10734
11922
  const deliverPayload = async (payload, info) => {
@@ -10742,7 +11930,11 @@ ${contextBody}`;
10742
11930
  }
10743
11931
  const payloadText = (payload.text ?? "").trim();
10744
11932
  const text = isOpenClawRestartLine(payloadText) ? ownerNoticeFor("model_error", { agentName: _noticeAgentName(channel, account.agentName), provider: _noticeProvider(cfg, route.agentId) }) : payloadText;
10745
- if (!text) return;
11933
+ const mediaRefs = mediaRefsOf(payload);
11934
+ if (!text) {
11935
+ if (mediaRefs.length > 0) await deliverMedia(mediaRefs, info);
11936
+ return;
11937
+ }
10746
11938
  {
10747
11939
  const recoverable = _stripThinkBlocks(text);
10748
11940
  if (recoverable && !_looksLikeReasoningLeak(recoverable)) lastFilteredText = recoverable;
@@ -10793,8 +11985,28 @@ ${contextBody}`;
10793
11985
  }
10794
11986
  const replyEnd = Date.now();
10795
11987
  replySpans.push({ startTime: replyStart, endTime: replyEnd, chars: text.length, index: replyCount });
11988
+ if (replyReceipt?.ok !== false) fileTurn?.replies.push(text);
11989
+ if (mediaRefs.length > 0) await deliverMedia(mediaRefs, info);
11990
+ };
11991
+ const deliverMedia = async (refs, info) => {
11992
+ const target = isA2AMessage ? void 0 : isRoomMessage ? { kind: "room", roomId: metadata.roomId } : { kind: "owner" };
11993
+ if (!target || typeof channel.sendFile !== "function") {
11994
+ console.warn(`[AgentVault] reply media not sent (${refs.length} part(s)): files cannot go to this conversation`);
11995
+ return;
11996
+ }
11997
+ for (const ref of refs) {
11998
+ const res = await sendMediaPart(channel, target, ref, "", fileTurn?.token ?? null, replyHost, {
11999
+ conversationId: metadata.conversationId,
12000
+ topicId: metadata.topicId,
12001
+ parentSpanId: inferenceSpanId
12002
+ });
12003
+ if (res.ok) {
12004
+ turn.spoke = true;
12005
+ if (info?.kind === "final") turn.delivered = true;
12006
+ }
12007
+ }
10796
12008
  };
10797
- const dispatchResult = await runWithTraceContext(
12009
+ const runDispatch = () => runWithTraceContext(
10798
12010
  { traceId, parentSpanId: inferenceSpanId },
10799
12011
  () => core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
10800
12012
  ctx: ctxPayload,
@@ -10808,6 +12020,10 @@ ${contextBody}`;
10808
12020
  replyOptions: {}
10809
12021
  })
10810
12022
  );
12023
+ const dispatchRun = fileTurn?.token && typeof channel.runWithTurnToken === "function" ? channel.runWithTurnToken(fileTurn.token, runDispatch) : runDispatch();
12024
+ const trackedRun = _turnRuns.track(_turnSessionKey, fileTurn, Promise.resolve(dispatchRun));
12025
+ const dispatchResult = await trackedRun;
12026
+ await _turnRuns.afterDispatch(channel, _turnSessionKey, fileTurn, dispatchResult, trackedRun);
10811
12027
  if (heldFailurePayloads.length > 0) {
10812
12028
  if (openclawRunFailed(dispatchResult)) {
10813
12029
  for (const held of heldFailurePayloads)
@@ -10837,7 +12053,10 @@ ${contextBody}`;
10837
12053
  throw err;
10838
12054
  }
10839
12055
  _reportAvToolCall(channel, "reply", fallbackStart, fallbackReceipt?.ok === false ? classifyDeliveryReceipt(fallbackReceipt) : void 0, _toolConversationFor(metadata));
10840
- if (fallbackReceipt?.ok !== false) turn.spoke = true;
12056
+ if (fallbackReceipt?.ok !== false) {
12057
+ turn.spoke = true;
12058
+ fileTurn?.replies.push(lastFilteredText);
12059
+ }
10841
12060
  replyCount++;
10842
12061
  totalReplyChars += lastFilteredText.length;
10843
12062
  if (!firstReplyTime) firstReplyTime = Date.now();
@@ -10923,7 +12142,7 @@ ${contextBody}`;
10923
12142
  }
10924
12143
  }, () => {
10925
12144
  attempt.expired = true;
10926
- }))));
12145
+ })))));
10927
12146
  }
10928
12147
  function _inferSpanType(name) {
10929
12148
  if (name === "error" || name.includes("error")) return "error";
@@ -10953,7 +12172,7 @@ function _emitChildSpan(channel, opts) {
10953
12172
  attributes: scrubUrlAttributes(opts.attributes),
10954
12173
  statusMessage: redactUrls(opts.statusMessage)
10955
12174
  };
10956
- const spanId = opts.spanId ?? randomBytes2(8).toString("hex");
12175
+ const spanId = opts.spanId ?? randomBytes3(8).toString("hex");
10957
12176
  reporter.reportCustomSpan({
10958
12177
  traceId: opts.traceId,
10959
12178
  spanId,
@@ -11075,7 +12294,8 @@ var agentVaultPlugin = {
11075
12294
  },
11076
12295
  // #1474: OpenClaw's word for a room is "group". 2026.10 refuses to start a
11077
12296
  // channel that declares a chat type outside direct/group/channel/thread.
11078
- capabilities: { chatTypes: ["direct", "group"] },
12297
+ // #1762 PR-O: media — files go through SecureChannel.sendFile (policy, turn token, no queue).
12298
+ capabilities: { chatTypes: ["direct", "group"], media: true },
11079
12299
  config: { listAccountIds, resolveAccount },
11080
12300
  // Tells OC core's resolveMessagingTarget that any plausible AgentVault target
11081
12301
  // string is an ID, short-circuiting the directory lookup that would otherwise
@@ -11144,13 +12364,15 @@ var agentVaultPlugin = {
11144
12364
  };
11145
12365
  abortSignal?.addEventListener("abort", () => void onAbort());
11146
12366
  import("./index.js").then(async ({ SecureChannel }) => {
12367
+ const fileWorkspace = await resolveOpenClawWorkspace(cfg, openclawAgentIdFor(cfg, account.accountId), osHomedir()).catch(() => void 0);
11147
12368
  channel = new SecureChannel({
11148
12369
  inviteToken: "",
11149
12370
  dataDir,
11150
12371
  apiUrl: account.apiUrl,
11151
12372
  agentName: account.agentName,
12373
+ fileSend: { ...fileWorkspace ? { workspaceDir: fileWorkspace } : {} },
11152
12374
  onMessage: _makeOnMessage({
11153
- inbound: ({ plaintext, metadata, turn }) => handleInbound({ plaintext, metadata, channel, account, cfg, turn }),
12375
+ inbound: ({ plaintext, metadata, turn, fileTurn }) => handleInbound({ plaintext, metadata, channel, account, cfg, turn, fileTurn }),
11154
12376
  getChannel: () => channel,
11155
12377
  isRuntimeReady: () => !!_ocRuntime,
11156
12378
  enqueue: (fn) => {
@@ -11347,8 +12569,7 @@ var agentVaultPlugin = {
11347
12569
  }
11348
12570
  const httpPort = account.httpPort ?? 18790;
11349
12571
  channel.on("ready", () => {
11350
- channel.startHttpServer(httpPort);
11351
- _log?.(`[AgentVault] HTTP send server listening on http://127.0.0.1:${httpPort}`);
12572
+ startLocalApiWithLog(channel, httpPort, (m2) => _log?.(m2));
11352
12573
  if (managedRoutesRequested) {
11353
12574
  _log?.(`[AgentVault] OpenClaw managed routes requested under /agentvault/* (auth=gateway); the gateway reports any rejection in its [plugins] diagnostics \u2014 check \`openclaw plugins doctor\``);
11354
12575
  }
@@ -11400,36 +12621,55 @@ var agentVaultPlugin = {
11400
12621
  return { ok: false, error: String(err) };
11401
12622
  }
11402
12623
  },
11403
- sendMedia: async ({ to: rawTo, text, mediaUrl, accountId }) => {
12624
+ // #1762 PR-O (§2.1) — media from the `message` tool. The model names `to`;
12625
+ // the turn token of this call chain (ALS: OpenClaw calls the adapter inline
12626
+ // in the run) makes it equal the turn's own conversation, or the send is
12627
+ // refused. a2a / channel / context targets never take media. Roots are the
12628
+ // AgentVault roots ∩ ctx.mediaLocalRoots; a session with mediaReadFile /
12629
+ // mediaAccess counts as sandboxed (§2.1, N4). A file that did not go is a
12630
+ // THROW (see OpenClawFileSendError), never `{ok:false}`, which OpenClaw's
12631
+ // delivery core would show the model only as "suppressed".
12632
+ sendMedia: async (ctx) => {
12633
+ const { to: rawTo, text, mediaUrl, accountId } = ctx;
11404
12634
  const startedAt = Date.now();
11405
12635
  const resolvedId = accountId ?? "default";
11406
12636
  const ch = _channels.get(resolvedId);
11407
12637
  if (!ch) return { ok: false, error: "AgentVault channel not connected" };
11408
12638
  let target;
11409
12639
  try {
11410
- const message = text ? `${text}
11411
- ${mediaUrl}` : mediaUrl;
11412
12640
  target = parseTarget(_normalizeOutboundTo(rawTo));
11413
- const receipt = await ch.deliver(target, { type: "text", text: message });
11414
- _reportAvToolCall(ch, "message", startedAt, receipt.ok ? void 0 : classifyDeliveryReceipt(receipt), conversationForTarget(target));
11415
- return { ok: receipt.ok, queued: receipt.queued, error: receipt.error };
11416
12641
  } catch (err) {
11417
- _reportAvToolCall(ch, "message", startedAt, classifyToolError(err), conversationForTarget(target));
11418
- return { ok: false, error: String(err) };
12642
+ _reportAvToolCall(ch, "message", startedAt, classifyToolError(err), conversationForTarget(void 0));
12643
+ throw err;
11419
12644
  }
12645
+ const turnToken = ch.currentTurnToken?.() ?? null;
12646
+ const host = hostFromSendContext(ctx, await sandboxedForSend(ctx.cfg, resolvedId, turnToken));
12647
+ const res = await sendMediaPart(ch, target, mediaUrl, typeof text === "string" ? text : "", turnToken, host);
12648
+ _reportAvToolCall(ch, "message", startedAt, res.ok ? void 0 : res.code, conversationForTarget(target));
12649
+ if (!res.ok) throw new OpenClawFileSendError(res.code, mediaPartToolText(ch, target, res));
12650
+ return deliveredResult(void 0);
11420
12651
  },
11421
12652
  /** Rich payload delivery — OpenClaw v2026.3.2+ calls this for structured messages. */
11422
12653
  sendPayload: async (ctx) => {
11423
12654
  const { payload, accountId } = ctx;
11424
12655
  if (payload.isReasoning) return { ok: true };
11425
12656
  const text = (payload.text ?? "").trim();
11426
- if (!text && !payload.mediaUrls?.length) return { ok: true };
12657
+ const mediaRefs = mediaRefsOf(payload);
12658
+ if (!text && mediaRefs.length === 0) return { ok: true };
11427
12659
  const startedAt = Date.now();
11428
12660
  const resolvedId = accountId ?? "default";
11429
12661
  const ch = _channels.get(resolvedId);
11430
12662
  if (!ch) return { ok: false, error: "AgentVault channel not connected" };
11431
12663
  let failedKind;
12664
+ const failedMedia = [];
11432
12665
  let payloadConversation = conversationForTarget(void 0);
12666
+ const onDeliveryResult = typeof ctx.onDeliveryResult === "function" ? (r2) => {
12667
+ try {
12668
+ ctx.onDeliveryResult(r2);
12669
+ } catch {
12670
+ }
12671
+ } : () => {
12672
+ };
11433
12673
  try {
11434
12674
  requestHeartbeatNow({ reason: "outbound-payload" }).catch(() => {
11435
12675
  });
@@ -11443,14 +12683,24 @@ ${mediaUrl}` : mediaUrl;
11443
12683
  }
11444
12684
  const _send = async (msg) => {
11445
12685
  const receipt = await ch.deliver(target, { type: "text", text: msg });
11446
- if (receipt && receipt.ok === false && !failedKind) failedKind = classifyDeliveryReceipt(receipt);
12686
+ if (receipt && receipt.ok === false) {
12687
+ if (!failedKind) failedKind = classifyDeliveryReceipt(receipt);
12688
+ } else {
12689
+ onDeliveryResult(deliveredResult(void 0));
12690
+ }
11447
12691
  };
11448
12692
  if (text) {
11449
12693
  await _send(text);
11450
12694
  }
11451
- if (payload.mediaUrls?.length) {
11452
- for (const url of payload.mediaUrls) {
11453
- await _send(url);
12695
+ const turnToken = ch.currentTurnToken?.() ?? null;
12696
+ const host = hostFromSendContext(ctx, await sandboxedForSend(ctx.cfg, resolvedId, turnToken));
12697
+ for (const ref of mediaRefs) {
12698
+ const res = await sendMediaPart(ch, target, ref, "", turnToken, host);
12699
+ if (res.ok) {
12700
+ onDeliveryResult(deliveredResult(void 0));
12701
+ } else {
12702
+ failedMedia.push({ target, res });
12703
+ if (!failedKind) failedKind = res.code;
11454
12704
  }
11455
12705
  }
11456
12706
  if (payload.suggestedActions?.length) {
@@ -11458,12 +12708,17 @@ ${mediaUrl}` : mediaUrl;
11458
12708
  await _send(`Suggested actions:
11459
12709
  ${actionsText}`);
11460
12710
  }
11461
- _reportAvToolCall(ch, "message", startedAt, failedKind, payloadConversation);
11462
- return { ok: true };
11463
12711
  } catch (err) {
11464
12712
  _reportAvToolCall(ch, "message", startedAt, failedKind ?? classifyToolError(err), payloadConversation);
11465
12713
  return { ok: false, error: String(err) };
11466
12714
  }
12715
+ _reportAvToolCall(ch, "message", startedAt, failedKind, payloadConversation);
12716
+ if (failedMedia.length > 0) {
12717
+ const first = failedMedia[0];
12718
+ throw new OpenClawFileSendError(first.res.code, mediaPartToolText(ch, first.target, first.res));
12719
+ }
12720
+ if (failedKind) return { ok: false, error: failedKind };
12721
+ return deliveredResult(void 0);
11467
12722
  }
11468
12723
  }
11469
12724
  };
@@ -11475,6 +12730,8 @@ var openclaw_entry_default = {
11475
12730
  try {
11476
12731
  const compat = checkHarnessCompat();
11477
12732
  if (compat?.message) console.warn(compat.message);
12733
+ const suppression = commandSuppressionWarning(compat?.version ?? null);
12734
+ if (suppression) console.warn(suppression);
11478
12735
  } catch {
11479
12736
  }
11480
12737
  _setRuntime(api.runtime);
@@ -11501,7 +12758,7 @@ var openclaw_entry_default = {
11501
12758
  ch.sendActivitySpan({
11502
12759
  trace_id: report.traceId ?? "",
11503
12760
  parent_span_id: report.parentSpanId ?? "",
11504
- span_id: randomBytes2(8).toString("hex"),
12761
+ span_id: randomBytes3(8).toString("hex"),
11505
12762
  span_type: "http",
11506
12763
  span_name: hostname,
11507
12764
  status: report.statusCode >= 400 || report.statusCode === 0 ? "error" : "ok",
@@ -11541,7 +12798,7 @@ var openclaw_entry_default = {
11541
12798
  ch.sendActivitySpan({
11542
12799
  trace_id: report.traceId ?? "",
11543
12800
  parent_span_id: report.parentSpanId ?? "",
11544
- span_id: randomBytes2(8).toString("hex"),
12801
+ span_id: randomBytes3(8).toString("hex"),
11545
12802
  span_type: "llm",
11546
12803
  span_name: report.model,
11547
12804
  status: "ok",
@@ -11563,78 +12820,22 @@ var openclaw_entry_default = {
11563
12820
  api.registerChannel({ plugin: agentVaultPlugin });
11564
12821
  if (typeof api.registerHttpRoute === "function") {
11565
12822
  try {
11566
- api.registerHttpRoute({
11567
- path: "/agentvault/send",
11568
- method: "POST",
11569
- auth: "gateway",
11570
- handler: async (req) => {
11571
- const ch = _channels.values().next().value;
11572
- if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
11573
- const parsed = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
11574
- const result = await handleSendRequest(parsed, ch);
11575
- return { status: result.status, body: result.body };
11576
- }
11577
- });
11578
- api.registerHttpRoute({
11579
- path: "/agentvault/action",
11580
- method: "POST",
11581
- auth: "gateway",
11582
- handler: async (req) => {
11583
- const ch = _channels.values().next().value;
11584
- if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
11585
- const parsed = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
11586
- const result = await handleActionRequest(parsed, ch);
11587
- return { status: result.status, body: result.body };
11588
- }
11589
- });
11590
- api.registerHttpRoute({
11591
- path: "/agentvault/decision",
11592
- method: "POST",
11593
- auth: "gateway",
11594
- handler: async (req) => {
11595
- const ch = _channels.values().next().value;
11596
- if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
11597
- const parsed = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
11598
- const result = await handleDecisionRequest(parsed, ch);
11599
- return { status: result.status, body: result.body };
11600
- }
11601
- });
11602
- api.registerHttpRoute({
11603
- path: "/agentvault/status",
11604
- method: "GET",
11605
- auth: "gateway",
11606
- handler: async () => {
11607
- const ch = _channels.values().next().value;
11608
- if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
11609
- const result = handleStatusRequest(ch);
11610
- return { status: result.status, body: result.body };
11611
- }
11612
- });
11613
- api.registerHttpRoute({
11614
- path: "/agentvault/targets",
11615
- method: "GET",
11616
- auth: "gateway",
11617
- handler: async () => {
11618
- const ch = _channels.values().next().value;
11619
- if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
11620
- const result = handleTargetsRequest(ch);
11621
- return { status: result.status, body: result.body };
11622
- }
11623
- });
11624
- api.registerHttpRoute({
11625
- path: "/agentvault/mcp-config",
11626
- method: "GET",
11627
- auth: "gateway",
11628
- handler: async () => {
11629
- const ch = _channels.values().next().value;
11630
- if (!ch) return { status: 503, body: { ok: false, error: "Channel not started" } };
11631
- const { handleMcpConfigRequest: handleMcpConfigRequest2 } = await Promise.resolve().then(() => (init_http_handlers(), http_handlers_exports));
11632
- const agentName = ch.config?.agentName ?? "agent";
11633
- const mcpSkillCount = ch.mcpServer?.skillCount ?? 0;
11634
- const result = handleMcpConfigRequest2(agentName, 18790, mcpSkillCount);
11635
- return { status: result.status, body: result.body };
11636
- }
11637
- });
12823
+ const allChannels = () => _channels.values();
12824
+ for (const [route, method] of [
12825
+ ["/send", "POST"],
12826
+ ["/action", "POST"],
12827
+ ["/decision", "POST"],
12828
+ ["/status", "GET"],
12829
+ ["/targets", "GET"],
12830
+ ["/mcp-config", "GET"]
12831
+ ]) {
12832
+ api.registerHttpRoute({
12833
+ path: `/agentvault${route}`,
12834
+ method,
12835
+ auth: "gateway",
12836
+ handler: managedLocalApiHandler(route, allChannels)
12837
+ });
12838
+ }
11638
12839
  managedRoutesRequested = true;
11639
12840
  } catch {
11640
12841
  }
@@ -11645,8 +12846,8 @@ var openclaw_entry_default = {
11645
12846
  const ch = _channels.values().next().value;
11646
12847
  if (!ch?.telemetry) return;
11647
12848
  ch.telemetry.reportCustomSpan({
11648
- traceId: randomBytes2(16).toString("hex"),
11649
- spanId: randomBytes2(8).toString("hex"),
12849
+ traceId: randomBytes3(16).toString("hex"),
12850
+ spanId: randomBytes3(8).toString("hex"),
11650
12851
  name: "agentvault.message.delivered",
11651
12852
  kind: "internal",
11652
12853
  startTime: event.timestamp,
@@ -11669,8 +12870,8 @@ var openclaw_entry_default = {
11669
12870
  const ch = _channels.values().next().value;
11670
12871
  if (!ch?.telemetry) return;
11671
12872
  ch.telemetry.reportCustomSpan({
11672
- traceId: randomBytes2(16).toString("hex"),
11673
- spanId: randomBytes2(8).toString("hex"),
12873
+ traceId: randomBytes3(16).toString("hex"),
12874
+ spanId: randomBytes3(8).toString("hex"),
11674
12875
  name: "agentvault.session.start",
11675
12876
  kind: "internal",
11676
12877
  startTime: event.timestamp,
@@ -11689,8 +12890,8 @@ var openclaw_entry_default = {
11689
12890
  const ch = _channels.values().next().value;
11690
12891
  if (!ch?.telemetry) return;
11691
12892
  ch.telemetry.reportCustomSpan({
11692
- traceId: randomBytes2(16).toString("hex"),
11693
- spanId: randomBytes2(8).toString("hex"),
12893
+ traceId: randomBytes3(16).toString("hex"),
12894
+ spanId: randomBytes3(8).toString("hex"),
11694
12895
  name: "agentvault.session.end",
11695
12896
  kind: "internal",
11696
12897
  startTime: event.timestamp,
@@ -11804,18 +13005,23 @@ export {
11804
13005
  _inboundRetryDelayMs,
11805
13006
  _looksLikeReasoningLeak,
11806
13007
  _makeOnMessage,
13008
+ _notReadyBound,
11807
13009
  owesRoomReply as _owesRoomReply,
11808
13010
  parseMentions as _parseMentions,
11809
13011
  _reportAvToolCall,
13012
+ _resetRoomTaintsForTest,
11810
13013
  _resolveRoomIdentity,
11811
13014
  _roomRecordReply,
11812
13015
  _roomReplyAllowed,
11813
13016
  _selectInboundPreamble,
13017
+ _setTurnBudgetMsForTest,
13018
+ _shortRoomLabel,
11814
13019
  _shutdownNotices,
11815
13020
  stripCaptionMentions as _stripCaptionMentions,
11816
13021
  stripMentions as _stripMentions,
11817
13022
  _stripThinkBlocks,
11818
13023
  _toolConversationFor,
13024
+ _turnRuns,
11819
13025
  _withSessionSerial,
11820
13026
  _withTurnTimeout,
11821
13027
  openclaw_entry_default as default,