@agentvault/agentvault 0.23.71 → 0.23.73

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 (73) 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 +677 -46
  5. package/dist/channel.d.ts.map +1 -1
  6. package/dist/cli.js +8169 -2405
  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 +8672 -2421
  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 +44 -6
  41. package/dist/openclaw-entry.d.ts.map +1 -1
  42. package/dist/openclaw-entry.js +1384 -177
  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-protocol.d.ts +22 -2
  59. package/dist/room-protocol.d.ts.map +1 -1
  60. package/dist/room-send-error.d.ts +17 -0
  61. package/dist/room-send-error.d.ts.map +1 -0
  62. package/dist/sender-binding.d.ts +130 -0
  63. package/dist/sender-binding.d.ts.map +1 -0
  64. package/dist/tool-telemetry.d.ts +1 -1
  65. package/dist/tool-telemetry.d.ts.map +1 -1
  66. package/dist/turn-token.d.ts +168 -0
  67. package/dist/turn-token.d.ts.map +1 -0
  68. package/dist/types.d.ts +162 -6
  69. package/dist/types.d.ts.map +1 -1
  70. package/openclaw.plugin.json +1 -1
  71. package/package.json +1 -1
  72. package/dist/workspace-handlers.d.ts +0 -62
  73. 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
@@ -8107,7 +8204,8 @@ function resolveOwn(mention, names) {
8107
8204
  }
8108
8205
  return null;
8109
8206
  }
8110
- function owesRoomReply(plaintext, agentName, accountId, senderIsAgent, roomDisplayName, ownDisplayName, selfResolved = true, roomAudience) {
8207
+ function owesRoomReply(plaintext, agentName, accountId, senderIsAgent, roomDisplayName, ownDisplayName, selfResolved = true, roomAudience, senderBinding) {
8208
+ if (senderBinding !== void 0 && senderBinding !== "bound") senderIsAgent = true;
8111
8209
  if (isPrivatePairHumanMessage(senderIsAgent, roomAudience)) return true;
8112
8210
  const mentions = parseMentions(plaintext);
8113
8211
  if (senderIsAgent === false && namesAgentPlainly(plaintext, agentName, roomDisplayName, ownDisplayName)) {
@@ -8117,7 +8215,7 @@ function owesRoomReply(plaintext, agentName, accountId, senderIsAgent, roomDispl
8117
8215
  const ownNames = ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName);
8118
8216
  if (mentions.some((m2) => resolveOwn(m2, ownNames) !== null)) return true;
8119
8217
  if (mentions.some((m2) => resolveOwn(m2, BROADCAST_NAMES) !== null)) {
8120
- return senderIsAgent !== true;
8218
+ return senderBinding === "bound" && senderIsAgent !== true;
8121
8219
  }
8122
8220
  if (!selfResolved) return true;
8123
8221
  return false;
@@ -9258,8 +9356,330 @@ function runWithTraceContext(ctx, fn) {
9258
9356
  return traceStore.run(ctx, fn);
9259
9357
  }
9260
9358
 
9261
- // src/openclaw-entry.ts
9262
- init_http_handlers();
9359
+ // src/local-api.ts
9360
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
9361
+ var LOCAL_API_TOKEN_HEADER = "x-agentvault-local-token";
9362
+ var LOCAL_API_BODY_LIMIT = 64 * 1024;
9363
+ 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`.";
9364
+ function tokenMatches(presented, expected) {
9365
+ if (typeof presented !== "string" || presented.length === 0 || expected.length === 0) return false;
9366
+ const a2 = createHash("sha256").update(presented, "utf8").digest();
9367
+ const b2 = createHash("sha256").update(expected, "utf8").digest();
9368
+ return timingSafeEqual(a2, b2);
9369
+ }
9370
+ var LOOPBACK_REMOTES = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
9371
+ var LOOPBACK_HOSTNAMES = ["127.0.0.1", "localhost", "[::1]"];
9372
+ function hostAllowed(host, port) {
9373
+ if (typeof host !== "string") return false;
9374
+ const h2 = host.toLowerCase();
9375
+ for (const name of LOOPBACK_HOSTNAMES) {
9376
+ if (port !== null) {
9377
+ if (h2 === `${name}:${port}`) return true;
9378
+ } else if (h2.startsWith(`${name}:`) && /^\d{1,5}$/.test(h2.slice(name.length + 1))) {
9379
+ return true;
9380
+ }
9381
+ }
9382
+ return false;
9383
+ }
9384
+ function headerValue(headers, name) {
9385
+ if (name in headers) return headers[name];
9386
+ for (const key of Object.keys(headers)) if (key.toLowerCase() === name) return headers[key];
9387
+ return void 0;
9388
+ }
9389
+ function checkLocalRequest(req, opts) {
9390
+ if (opts.checkRemote !== false) {
9391
+ const remote = req.socket?.remoteAddress;
9392
+ if (!remote || !LOOPBACK_REMOTES.has(remote)) return "remote";
9393
+ }
9394
+ if (headerValue(req.headers, "origin") !== void 0) return "origin";
9395
+ const host = headerValue(req.headers, "host");
9396
+ if (!hostAllowed(typeof host === "string" ? host : void 0, opts.port)) return "host";
9397
+ if (!tokenMatches(headerValue(req.headers, LOCAL_API_TOKEN_HEADER), opts.token)) return "token";
9398
+ return null;
9399
+ }
9400
+ var BodyTooLargeError = class extends Error {
9401
+ constructor() {
9402
+ super("body too large");
9403
+ this.name = "BodyTooLargeError";
9404
+ }
9405
+ };
9406
+ function readLimitedBody(req, limit = LOCAL_API_BODY_LIMIT) {
9407
+ return new Promise((resolve2, reject) => {
9408
+ const declared = Number(req.headers["content-length"]);
9409
+ if (Number.isFinite(declared) && declared > limit) {
9410
+ reject(new BodyTooLargeError());
9411
+ return;
9412
+ }
9413
+ const chunks = [];
9414
+ let size = 0;
9415
+ let done = false;
9416
+ const finish = (err) => {
9417
+ if (done) return;
9418
+ done = true;
9419
+ req.off("data", onData);
9420
+ req.off("end", onEnd);
9421
+ req.off("error", onError);
9422
+ req.off("aborted", onAborted);
9423
+ if (err) reject(err);
9424
+ else resolve2(Buffer.concat(chunks, size));
9425
+ };
9426
+ const onData = (chunk) => {
9427
+ size += chunk.length;
9428
+ if (size > limit) {
9429
+ req.pause();
9430
+ finish(new BodyTooLargeError());
9431
+ return;
9432
+ }
9433
+ chunks.push(chunk);
9434
+ };
9435
+ const onEnd = () => finish();
9436
+ const onError = (err) => finish(err);
9437
+ const onAborted = () => finish(new Error("aborted"));
9438
+ req.on("data", onData);
9439
+ req.on("end", onEnd);
9440
+ req.on("error", onError);
9441
+ req.on("aborted", onAborted);
9442
+ });
9443
+ }
9444
+ var REFUSAL_RESPONSE = {
9445
+ remote: { status: 403, error: "Forbidden" },
9446
+ origin: { status: 403, error: "Forbidden" },
9447
+ host: { status: 403, error: "Forbidden" },
9448
+ token: { status: 401, error: "Unauthorized" },
9449
+ too_large: { status: 413, error: "Payload too large" }
9450
+ };
9451
+ function sendJson(res, status, body2, close = false) {
9452
+ if (res.headersSent || res.destroyed) {
9453
+ res.destroy();
9454
+ return;
9455
+ }
9456
+ const headers = { "Content-Type": "application/json" };
9457
+ if (close) headers.Connection = "close";
9458
+ res.writeHead(status, headers);
9459
+ res.end(JSON.stringify(body2));
9460
+ }
9461
+ function refusalBody(reason) {
9462
+ const r2 = REFUSAL_RESPONSE[reason];
9463
+ return reason === "token" ? { ok: false, error: r2.error, hint: LOCAL_API_TOKEN_HINT } : { ok: false, error: r2.error };
9464
+ }
9465
+ function refuse(res, reason) {
9466
+ sendJson(res, REFUSAL_RESPONSE[reason].status, refusalBody(reason), true);
9467
+ }
9468
+ var KNOWN_ROUTES = /* @__PURE__ */ new Set(["/send", "/decision", "/action", "/status", "/targets", "/trust", "/mcp", "/mcp-config"]);
9469
+ function localRouteLabel(url) {
9470
+ if (!url) return "other";
9471
+ const path = url.split("?")[0].replace(/^\/agentvault(?=\/)/, "");
9472
+ return KNOWN_ROUTES.has(path) ? path : "other";
9473
+ }
9474
+
9475
+ // src/local-api-server.ts
9476
+ var InvalidJsonError = class extends Error {
9477
+ };
9478
+ function parseJsonObject(text) {
9479
+ let parsed;
9480
+ try {
9481
+ parsed = JSON.parse(text);
9482
+ } catch {
9483
+ throw new InvalidJsonError();
9484
+ }
9485
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new InvalidJsonError();
9486
+ return parsed;
9487
+ }
9488
+ async function localApiReply(method, route, readJson, channel, ctx) {
9489
+ const handlers = await Promise.resolve().then(() => (init_http_handlers(), http_handlers_exports));
9490
+ const api = channel;
9491
+ const post = {
9492
+ "/send": handlers.handleSendRequest,
9493
+ "/decision": handlers.handleDecisionRequest,
9494
+ "/action": handlers.handleActionRequest
9495
+ };
9496
+ const postHandler = method === "POST" ? post[route] : void 0;
9497
+ if (postHandler) {
9498
+ let parsed;
9499
+ try {
9500
+ parsed = await readJson();
9501
+ } catch (err) {
9502
+ if (err instanceof BodyTooLargeError) {
9503
+ api.reportLocalApiRefusal(route, "too_large");
9504
+ const r2 = REFUSAL_RESPONSE.too_large;
9505
+ return { status: r2.status, body: { ok: false, error: r2.error }, close: true };
9506
+ }
9507
+ if (err instanceof InvalidJsonError) return { status: 400, body: { ok: false, error: "Invalid JSON" } };
9508
+ return { status: 400, body: { ok: false, error: "Bad request" }, close: true };
9509
+ }
9510
+ try {
9511
+ const result = await postHandler(parsed, channel);
9512
+ return { status: result.status, body: result.body };
9513
+ } catch (err) {
9514
+ console.error(`[SecureChannel] local API ${route} failed:`, err);
9515
+ return { status: 500, body: { ok: false, error: "Internal error" } };
9516
+ }
9517
+ }
9518
+ if (method === "GET") {
9519
+ try {
9520
+ if (route === "/status") return handlers.handleStatusRequest(channel);
9521
+ if (route === "/targets") return handlers.handleTargetsRequest(channel);
9522
+ if (route === "/trust") return handlers.handleTrustRequest(channel);
9523
+ if (route === "/mcp-config") {
9524
+ const agentName = api.config?.agentName ?? "agent";
9525
+ return handlers.handleMcpConfigRequest(agentName, ctx.advertisedPort, api.mcpServer?.skillCount ?? 0, ctx.token);
9526
+ }
9527
+ } catch (err) {
9528
+ console.error(`[SecureChannel] local API ${route} failed:`, err);
9529
+ return { status: 500, body: { ok: false, error: "Internal error" } };
9530
+ }
9531
+ }
9532
+ return { status: 404, body: { ok: false, error: "Not found" } };
9533
+ }
9534
+ function pathOf(url) {
9535
+ return (url ?? "").split("?")[0];
9536
+ }
9537
+ async function serveLocalApi(req, res, channel, ctx) {
9538
+ req.on("error", () => {
9539
+ });
9540
+ res.on("error", () => {
9541
+ });
9542
+ const api = channel;
9543
+ const route = ctx.route ?? pathOf(req.url);
9544
+ const label = localRouteLabel(route);
9545
+ const refusal = checkLocalRequest(req, { port: ctx.port, token: ctx.token });
9546
+ if (refusal) {
9547
+ api.reportLocalApiRefusal(label, refusal);
9548
+ refuse(res, refusal);
9549
+ return;
9550
+ }
9551
+ if (route === "/mcp" && ctx.route === void 0) {
9552
+ if (req.method !== "POST" && req.method !== "GET" && req.method !== "DELETE") {
9553
+ sendJson(res, 404, { ok: false, error: "Not found" });
9554
+ return;
9555
+ }
9556
+ const mcp = api.mcpServer;
9557
+ if (!mcp) {
9558
+ sendJson(res, 503, { ok: false, error: "Unavailable" });
9559
+ return;
9560
+ }
9561
+ let parsedBody;
9562
+ if (req.method === "POST") {
9563
+ try {
9564
+ parsedBody = JSON.parse((await readLimitedBody(req)).toString("utf8"));
9565
+ } catch (err) {
9566
+ if (err instanceof BodyTooLargeError) {
9567
+ api.reportLocalApiRefusal(label, "too_large");
9568
+ refuse(res, "too_large");
9569
+ } else {
9570
+ sendJson(res, 400, { ok: false, error: "Invalid JSON" }, true);
9571
+ }
9572
+ return;
9573
+ }
9574
+ }
9575
+ try {
9576
+ await mcp.handleRequest(req, res, parsedBody);
9577
+ } catch (err) {
9578
+ console.error("[MCP] Request handling error:", err);
9579
+ if (!res.headersSent) sendJson(res, 500, { ok: false, error: "Internal error" });
9580
+ }
9581
+ return;
9582
+ }
9583
+ const preRead = req.body;
9584
+ const readJson = async () => {
9585
+ if (preRead === void 0) return parseJsonObject((await readLimitedBody(req)).toString("utf8"));
9586
+ return preParsedBody(preRead);
9587
+ };
9588
+ const reply = await localApiReply(req.method, route, readJson, channel, ctx);
9589
+ sendJson(res, reply.status, reply.body, reply.close);
9590
+ }
9591
+ function preParsedBody(body2) {
9592
+ if (typeof body2 === "string") {
9593
+ if (Buffer.byteLength(body2, "utf8") > LOCAL_API_BODY_LIMIT) throw new BodyTooLargeError();
9594
+ return parseJsonObject(body2);
9595
+ }
9596
+ if (Buffer.isBuffer(body2)) {
9597
+ if (body2.length > LOCAL_API_BODY_LIMIT) throw new BodyTooLargeError();
9598
+ return parseJsonObject(body2.toString("utf8"));
9599
+ }
9600
+ let size;
9601
+ try {
9602
+ size = Buffer.byteLength(JSON.stringify(body2) ?? "", "utf8");
9603
+ } catch {
9604
+ throw new InvalidJsonError();
9605
+ }
9606
+ if (size > LOCAL_API_BODY_LIMIT) throw new BodyTooLargeError();
9607
+ if (body2 === null || typeof body2 !== "object" || Array.isArray(body2)) throw new InvalidJsonError();
9608
+ return body2;
9609
+ }
9610
+ function managedLocalApiHandler(route, getChannels) {
9611
+ const label = localRouteLabel(route);
9612
+ return async (req, res) => {
9613
+ const isNode = !!res && typeof res.writeHead === "function";
9614
+ const nodeReq = req;
9615
+ const nodeRes = res;
9616
+ const simple = req ?? {};
9617
+ if (isNode) nodeReq.on("error", () => {
9618
+ });
9619
+ const headers = isNode ? nodeReq.headers : simple.headers ?? {};
9620
+ const probe = { headers, socket: { remoteAddress: isNode ? nodeReq.socket?.remoteAddress : simple.remoteAddress } };
9621
+ const channels = [...getChannels()];
9622
+ const reportOn = channels[0];
9623
+ const answer = (status, body2) => {
9624
+ if (!isNode) return { status, body: body2 };
9625
+ sendJson(nodeRes, status, body2, status >= 400);
9626
+ return true;
9627
+ };
9628
+ const pre = checkLocalRequest(probe, { port: null, token: "" });
9629
+ if (pre && pre !== "token") {
9630
+ reportOn?.reportLocalApiRefusal(label, pre);
9631
+ return answer(REFUSAL_RESPONSE[pre].status, refusalBody(pre));
9632
+ }
9633
+ const presented = headerValue(headers, LOCAL_API_TOKEN_HEADER);
9634
+ let match;
9635
+ let anyToken = false;
9636
+ for (const channel of channels) {
9637
+ const ctx = managedContext(channel, route);
9638
+ if (!ctx) continue;
9639
+ anyToken = true;
9640
+ if (tokenMatches(presented, ctx.token) && !match) match = { channel, ctx };
9641
+ }
9642
+ if (!match) {
9643
+ if (!anyToken) return answer(503, { ok: false, error: "Unavailable" });
9644
+ reportOn?.reportLocalApiRefusal(label, "token");
9645
+ return answer(REFUSAL_RESPONSE.token.status, refusalBody("token"));
9646
+ }
9647
+ if (isNode) {
9648
+ await serveLocalApi(nodeReq, nodeRes, match.channel, match.ctx);
9649
+ return true;
9650
+ }
9651
+ const reply = await localApiReply(simple.method, route, async () => preParsedBody(simple.body), match.channel, match.ctx);
9652
+ return { status: reply.status, body: reply.body };
9653
+ };
9654
+ }
9655
+ function managedContext(channel, route) {
9656
+ const ch = channel;
9657
+ const token = ch.localApiToken();
9658
+ if (!token) return null;
9659
+ return { token, port: null, advertisedPort: ch.localApiPort ?? 18790, route };
9660
+ }
9661
+ function startLocalApiWithLog(channel, port, log) {
9662
+ const ch = channel;
9663
+ if (ch.localApiServing) return;
9664
+ const cleanup = () => {
9665
+ ch.off("http-ready", onReady);
9666
+ ch.off("http-failed", onFailed);
9667
+ };
9668
+ const onReady = () => {
9669
+ cleanup();
9670
+ log(`[AgentVault] HTTP send server listening on http://127.0.0.1:${port} (requests need the X-AgentVault-Local-Token header)`);
9671
+ };
9672
+ const onFailed = () => {
9673
+ cleanup();
9674
+ log(`[AgentVault] HTTP send server NOT started on port ${port} (see the error above)`);
9675
+ };
9676
+ ch.on("http-ready", onReady);
9677
+ ch.on("http-failed", onFailed);
9678
+ if (!ch.startHttpServer(port)) {
9679
+ cleanup();
9680
+ log(`[AgentVault] HTTP send server NOT started: the local API token file is unsafe (see the error above)`);
9681
+ }
9682
+ }
9263
9683
 
9264
9684
  // src/openclaw-compat.ts
9265
9685
  var defaultImporter = (specifier) => import(
@@ -9381,6 +9801,15 @@ var nodeFs = {
9381
9801
  };
9382
9802
  var MIN_OPENCLAW_VERSION = "2026.3.0";
9383
9803
  var TESTED_THROUGH_OPENCLAW_VERSION = "2026.10.8";
9804
+ var COMMAND_SUPPRESSION_VERIFIED_OPENCLAW_VERSION = "2026.10.8";
9805
+ function commandSuppressionWarning(version = detectOpenClawVersion()) {
9806
+ try {
9807
+ if (!version || version === COMMAND_SUPPRESSION_VERIFIED_OPENCLAW_VERSION) return null;
9808
+ 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.`;
9809
+ } catch {
9810
+ return null;
9811
+ }
9812
+ }
9384
9813
  function compareVersions(a2, b2) {
9385
9814
  const pa2 = a2.split(".").map((n2) => parseInt(n2, 10) || 0);
9386
9815
  const pb = b2.split(".").map((n2) => parseInt(n2, 10) || 0);
@@ -9885,6 +10314,656 @@ function parseTarget(raw) {
9885
10314
  throw new Error(`Unrecognized delivery target: "${raw}". Use "owner", "room:<id>", "a2a:<addr>", "channel:<id>", or "context".`);
9886
10315
  }
9887
10316
 
10317
+ // src/file-send-failure.ts
10318
+ var ROOM_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
10319
+ var REASON = {
10320
+ file_not_allowed: "the file is not in a folder files can be sent from",
10321
+ file_not_found: "the file does not exist",
10322
+ file_too_large: "the file is over 5 MB",
10323
+ upload_failed: "the upload did not finish",
10324
+ // #1762 PR-P1c-2 (§13.4, §13.13): the refusal names the switch that lifts it.
10325
+ 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",
10326
+ file_target_mismatch: "a file can only go to the conversation you are answering",
10327
+ file_send_disabled: "file sending is turned off for now",
10328
+ workspace_required: "this agent needs a workspace folder to send files",
10329
+ turn_ended: "the turn ended before the file went",
10330
+ turn_no_consumer: "this message was not handed to the agent's turn handler, so it cannot carry a file",
10331
+ no_conversation_ready: "the chat is not ready to receive a file",
10332
+ relay_not_connected: "the agent is not connected right now",
10333
+ blocked_by_policy: "a scan rule blocked it",
10334
+ unsupported_destination: "files cannot be sent there",
10335
+ delivery_failed: "it could not be delivered",
10336
+ room_not_found: "the room was not found"
10337
+ };
10338
+ function fileSendReason(code) {
10339
+ return REASON[code] ?? REASON.delivery_failed;
10340
+ }
10341
+ function clean2(value, max) {
10342
+ if (typeof value !== "string") return "";
10343
+ return value.replace(/@/g, "").replace(/\s+/g, " ").trim().slice(0, max).trim();
10344
+ }
10345
+ function sizeLabel(bytes) {
10346
+ if (bytes < 1024) return `${bytes} B`;
10347
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
10348
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
10349
+ }
10350
+ function fileSendToolResult(result, target, folder) {
10351
+ if (result.ok) return `File sent: ${clean2(result.filename, 200)} (${sizeLabel(result.size)}).`;
10352
+ let reason = fileSendReason(result.code);
10353
+ if ((result.code === "file_not_allowed" || result.code === "file_not_found") && folder) {
10354
+ reason = target.kind === "room" ? `files for this room must be in ${folder}` : `${reason}; stage it in ${folder}`;
10355
+ }
10356
+ return `File NOT sent: ${reason}. Tell the person it was not sent.`;
10357
+ }
10358
+ function stagingLineFor(target, opts) {
10359
+ const folder = opts.folder;
10360
+ if (target.kind === "owner") return folder ? `Files for this chat: stage them in your outbox at ${folder}.` : FILE_SEND_UNAVAILABLE;
10361
+ if (!folder || !ROOM_ID_RE.test(target.roomId) || opts.roomsAllowed === false) return "Files cannot be shared in this room on this turn.";
10362
+ return `Files for this room: stage them in your outbox at ${folder} (only when your owner asks).`;
10363
+ }
10364
+ function FILE_SEND_RULE(tool) {
10365
+ const t2 = clean2(tool, 60) || "send_file";
10366
+ 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.`;
10367
+ }
10368
+ 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.";
10369
+ function safeLineName(name) {
10370
+ return neutralizeSystemPrefix(clean2(name, 200)).replace(/[[\]\uff3b\uff3d]/g, "").replace(/agentvault-system \(quoted\):/gi, "AgentVault-system (quoted)");
10371
+ }
10372
+ var RENDERED_LINES = /* @__PURE__ */ new Set();
10373
+ var RENDERED_MAX = 1e3;
10374
+ function renderHistoryFiles(files) {
10375
+ const parts = files.map((f2) => `${safeLineName(f2.filename)} (${sizeLabel(f2.size)})`);
10376
+ const line = parts.length === 1 ? `[AgentVault system: you sent the file ${parts[0]}]` : `[AgentVault system: you sent the files ${parts.join(", ")}]`;
10377
+ RENDERED_LINES.delete(line);
10378
+ RENDERED_LINES.add(line);
10379
+ while (RENDERED_LINES.size > RENDERED_MAX) {
10380
+ const oldest = RENDERED_LINES.values().next().value;
10381
+ if (oldest === void 0) break;
10382
+ RENDERED_LINES.delete(oldest);
10383
+ }
10384
+ return line;
10385
+ }
10386
+ function normalizeForMatch(text) {
10387
+ return text.normalize("NFKC").replace(new RegExp("\\p{Cf}", "gu"), "").replace(/\s+/g, " ").toLowerCase();
10388
+ }
10389
+ var SYSTEM_PREFIX_RE = /\[\s*agentvault\s*system\s*:/;
10390
+ var CF_RE = new RegExp("\\p{Cf}", "u");
10391
+ function neutralizeSystemPrefix(text) {
10392
+ if (typeof text !== "string" || text === "") return text;
10393
+ return text.split("\n").map((line) => SYSTEM_PREFIX_RE.test(normalizeForMatch(line)) ? rewriteLine(line) : line).join("\n");
10394
+ }
10395
+ function neutralizeForeignLine(text) {
10396
+ return neutralizeSystemPrefix(text);
10397
+ }
10398
+ function rewriteLine(line) {
10399
+ let out = "";
10400
+ let i2 = 0;
10401
+ while (i2 < line.length) {
10402
+ const ch = line[i2];
10403
+ if (ch === "[" || ch === "\uFF3B") {
10404
+ const end = matchSystemAfter(line, i2 + 1);
10405
+ if (end > 0) {
10406
+ out += "[AgentVault-system (quoted):";
10407
+ i2 = end;
10408
+ continue;
10409
+ }
10410
+ }
10411
+ out += ch;
10412
+ i2 += 1;
10413
+ }
10414
+ return out;
10415
+ }
10416
+ function matchSystemAfter(line, from) {
10417
+ const want = "agentvaultsystem:";
10418
+ let w2 = 0;
10419
+ let i2 = from;
10420
+ while (i2 < line.length && w2 < want.length) {
10421
+ const ch = line[i2];
10422
+ if (CF_RE.test(ch) || /\s/.test(ch)) {
10423
+ i2 += 1;
10424
+ continue;
10425
+ }
10426
+ const n2 = ch.normalize("NFKC").toLowerCase();
10427
+ if (n2 !== want[w2]) return -1;
10428
+ w2 += 1;
10429
+ i2 += 1;
10430
+ }
10431
+ return w2 === want.length ? i2 : -1;
10432
+ }
10433
+ var CLAIM_MAX = 16 * 1024;
10434
+ 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})";
10435
+ var PASSIVE = new RegExp(
10436
+ `^(?!(?:no|not|nothing|without|any)\\b)(?:(?:the|your|a|my|this|these|that|those) )?(?:[\\w.-]+ ){0,2}?${ATTACHABLE}(?: (?:is|are))? attached\\b(?! to\\b)`
10437
+ );
10438
+
10439
+ // src/openclaw-file-send.ts
10440
+ import { fileURLToPath } from "node:url";
10441
+
10442
+ // src/turn-token.ts
10443
+ var TURN_TOKEN_TTL_MS = 15 * 6e4;
10444
+
10445
+ // src/openclaw-file-send.ts
10446
+ async function sdkFn(candidates, importer) {
10447
+ try {
10448
+ return await resolveSdkFn(candidates, importer);
10449
+ } catch {
10450
+ return false;
10451
+ }
10452
+ }
10453
+ var OPENCLAW_FILE_TOOL = "message";
10454
+ function classifyMediaRef(raw) {
10455
+ if (typeof raw !== "string") return { kind: "refused" };
10456
+ const t2 = raw.trim();
10457
+ if (!t2 || t2.includes("\0")) return { kind: "refused" };
10458
+ if (/^https?:\/\//i.test(t2)) {
10459
+ try {
10460
+ const u2 = new URL(t2);
10461
+ return u2.protocol === "http:" || u2.protocol === "https:" ? { kind: "link", url: u2.href } : { kind: "refused" };
10462
+ } catch {
10463
+ return { kind: "refused" };
10464
+ }
10465
+ }
10466
+ if (/^file:/i.test(t2)) {
10467
+ try {
10468
+ return { kind: "local", path: fileURLToPath(t2) };
10469
+ } catch {
10470
+ return { kind: "refused" };
10471
+ }
10472
+ }
10473
+ return { kind: "local", path: t2 };
10474
+ }
10475
+ function mediaRefsOf(payload) {
10476
+ if (!payload || typeof payload !== "object") return [];
10477
+ const p2 = payload;
10478
+ const out = [];
10479
+ const add2 = (v2) => {
10480
+ if (typeof v2 === "string" && v2.trim() && !out.includes(v2)) out.push(v2);
10481
+ };
10482
+ add2(p2.mediaUrl);
10483
+ if (Array.isArray(p2.mediaUrls)) for (const v2 of p2.mediaUrls) add2(v2);
10484
+ return out;
10485
+ }
10486
+ function fileTargetFor(target) {
10487
+ if (!target) return null;
10488
+ if (target.kind === "owner") return { kind: "owner" };
10489
+ if (target.kind === "room") return { kind: "room", roomId: target.roomId };
10490
+ return null;
10491
+ }
10492
+ function hostFromSendContext(ctx, sandboxed) {
10493
+ const c2 = ctx && typeof ctx === "object" ? ctx : {};
10494
+ const host = {};
10495
+ if (Array.isArray(c2.mediaLocalRoots)) host.limitRoots = c2.mediaLocalRoots.filter((r2) => typeof r2 === "string");
10496
+ if (sandboxed) {
10497
+ host.sandboxed = true;
10498
+ const reader = typeof c2.mediaReadFile === "function" ? c2.mediaReadFile : null;
10499
+ if (reader) host.readFile = async (p2) => toBytes(await reader(p2));
10500
+ }
10501
+ return host;
10502
+ }
10503
+ var _turnSandbox = /* @__PURE__ */ new Map();
10504
+ function noteTurnSandbox(token, sandboxed) {
10505
+ if (!token) return;
10506
+ _turnSandbox.set(token.id, sandboxed);
10507
+ while (_turnSandbox.size > 2e3) {
10508
+ const oldest = _turnSandbox.keys().next().value;
10509
+ if (oldest === void 0) break;
10510
+ _turnSandbox.delete(oldest);
10511
+ }
10512
+ }
10513
+ function forgetTurnSandbox(token) {
10514
+ if (token) _turnSandbox.delete(token.id);
10515
+ }
10516
+ async function sandboxedForSend(cfg, accountId, turn, importer) {
10517
+ const known = turn ? _turnSandbox.get(turn.id) : void 0;
10518
+ if (known !== void 0) return known;
10519
+ return replySandboxed(cfg, openclawAgentIdFor(cfg, accountId), void 0, importer);
10520
+ }
10521
+ function toBytes(v2) {
10522
+ if (v2 instanceof Uint8Array) return v2;
10523
+ if (v2 instanceof ArrayBuffer) return new Uint8Array(v2);
10524
+ if (v2 && typeof v2 === "object" && v2.buffer instanceof Uint8Array) {
10525
+ return v2.buffer;
10526
+ }
10527
+ throw new Error("media reader returned no bytes");
10528
+ }
10529
+ var MEDIA_ROOTS_CANDIDATES = [
10530
+ { specifier: "openclaw/plugin-sdk/media-local-roots", symbol: "getAgentScopedMediaLocalRoots" }
10531
+ ];
10532
+ var _mediaRootsFn = null;
10533
+ var _mediaRootsGapLogged = false;
10534
+ async function replyMediaRoots(cfg, agentId, importer, log = (m2) => console.warn(m2)) {
10535
+ if (_mediaRootsFn === null) _mediaRootsFn = await sdkFn(MEDIA_ROOTS_CANDIDATES, importer);
10536
+ if (typeof _mediaRootsFn === "function") {
10537
+ try {
10538
+ const roots = _mediaRootsFn(cfg, agentId);
10539
+ if (Array.isArray(roots)) return roots.filter((r2) => typeof r2 === "string");
10540
+ } catch {
10541
+ }
10542
+ }
10543
+ if (!_mediaRootsGapLogged) {
10544
+ _mediaRootsGapLogged = true;
10545
+ log("[AgentVault] file-send: OpenClaw media roots unavailable \u2014 reply media limited to AgentVault roots (OpenClaw-generated media will be refused)");
10546
+ }
10547
+ return void 0;
10548
+ }
10549
+ function sandboxedByConfig(cfg, agentId, sessionKey) {
10550
+ const c2 = cfg;
10551
+ const entry = Array.isArray(c2?.agents?.list) ? c2.agents.list.find((a2) => a2?.id === agentId) : void 0;
10552
+ const mode = entry?.sandbox?.mode ?? c2?.agents?.defaults?.sandbox?.mode ?? "off";
10553
+ if (mode === "off") return false;
10554
+ if (mode === "all") return true;
10555
+ if (mode !== "non-main") return true;
10556
+ const mainKey = c2?.session?.scope === "global" ? "global" : `agent:${(agentId ?? "main").toLowerCase()}:${typeof c2?.session?.mainKey === "string" && c2.session.mainKey ? c2.session.mainKey : "main"}`;
10557
+ return (sessionKey ?? "").trim().toLowerCase() !== mainKey.toLowerCase();
10558
+ }
10559
+ async function sendMediaPart(channel, target, raw, caption, turn, host, deliverOptions) {
10560
+ const fileTarget = fileTargetFor(target);
10561
+ if (!fileTarget) return { ok: false, code: "unsupported_destination", error: fileSendReason("unsupported_destination") };
10562
+ const ref = classifyMediaRef(raw);
10563
+ try {
10564
+ if (ref.kind === "link") {
10565
+ const text = caption ? `${caption}
10566
+ Link: ${ref.url}` : `Link: ${ref.url}`;
10567
+ const receipt = await channel.deliver(target, { type: "text", text }, deliverOptions);
10568
+ return receipt?.ok === false ? { ok: false, code: "delivery_failed", error: fileSendReason("delivery_failed") } : { ok: true, via: "link" };
10569
+ }
10570
+ const res = await channel.sendFile(fileTarget, ref.kind === "local" ? ref.path : raw, caption, turn, host);
10571
+ 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 } : {} };
10572
+ } catch {
10573
+ return { ok: false, code: "delivery_failed", error: fileSendReason("delivery_failed") };
10574
+ }
10575
+ }
10576
+ function mediaPartToolText(channel, target, res) {
10577
+ const fileTarget = fileTargetFor(target);
10578
+ if (res.ok) {
10579
+ return res.via === "link" ? "Link sent." : fileSendToolResult({ ok: true, filename: res.filename ?? "file", size: res.size ?? 0, mime: "", clientMessageId: "" }, fileTarget ?? { kind: "owner" }, null);
10580
+ }
10581
+ const folder = fileTarget ? channel.stagingPathFor?.(fileTarget) ?? null : null;
10582
+ return fileSendToolResult({ ok: false, code: res.code, error: res.error }, fileTarget ?? { kind: "owner" }, folder);
10583
+ }
10584
+ function openclawFileLines(channel, target, opts) {
10585
+ const folder = target ? channel?.stagingPathFor?.(target) ?? null : null;
10586
+ if (!target || target.kind === "owner" && !folder) return FILE_SEND_UNAVAILABLE;
10587
+ const line = stagingLineFor(target, { folder, roomsAllowed: opts.roomsAllowed });
10588
+ return `${FILE_SEND_RULE(OPENCLAW_FILE_TOOL)}
10589
+ ${line}`;
10590
+ }
10591
+ function takeFileTurn(metadata) {
10592
+ const m2 = metadata && typeof metadata === "object" ? metadata : {};
10593
+ const lease = m2.turnLease && typeof m2.turnLease === "object" ? m2.turnLease : null;
10594
+ const token = lease?.token ?? (m2.turnToken && typeof m2.turnToken === "object" ? m2.turnToken : null);
10595
+ return { lease, token, replies: [], runs: /* @__PURE__ */ new Set(), ended: false, absorbedPending: false };
10596
+ }
10597
+ async function endFileTurn(channel, ft2, waitMs = TURN_TOKEN_TTL_MS) {
10598
+ if (!ft2) return;
10599
+ if (ft2.runs.size > 0) {
10600
+ let timer;
10601
+ await Promise.race([
10602
+ Promise.allSettled([...ft2.runs]),
10603
+ new Promise((r2) => {
10604
+ timer = setTimeout(r2, waitMs);
10605
+ timer.unref?.();
10606
+ })
10607
+ ]);
10608
+ if (timer) clearTimeout(timer);
10609
+ }
10610
+ if (ft2.ended || ft2.absorbedPending) return;
10611
+ ft2.ended = true;
10612
+ forgetTurnSandbox(ft2.token);
10613
+ if (!ft2.lease || typeof channel?.endTurn !== "function") return;
10614
+ try {
10615
+ await channel.endTurn(ft2.lease, { replies: ft2.replies });
10616
+ } catch {
10617
+ }
10618
+ }
10619
+ function foldFileTurn(channel, folded, into) {
10620
+ if (!folded || folded.ended || !folded.lease || !into?.lease || into === folded || typeof channel?.foldTurn !== "function") return false;
10621
+ const ok = channel.foldTurn(folded.lease, into.lease) === true;
10622
+ if (ok) folded.ended = true;
10623
+ return ok;
10624
+ }
10625
+ var OpenClawTurnRuns = class _OpenClawTurnRuns {
10626
+ active = /* @__PURE__ */ new Map();
10627
+ pending = /* @__PURE__ */ new Map();
10628
+ /** Dispatch start order, and the order each tracked dispatch started at. */
10629
+ seq = 0;
10630
+ started = /* @__PURE__ */ new WeakMap();
10631
+ /** The last dispatch start before each waiting token was deferred. */
10632
+ waitedAt = /* @__PURE__ */ new WeakMap();
10633
+ /** Run one OpenClaw dispatch for `ft` on `sessionKey`, tracked until it settles (also after a turn-budget timeout). */
10634
+ track(sessionKey, ft2, run) {
10635
+ const startSeq = ++this.seq;
10636
+ if (!ft2) {
10637
+ const untracked = run.then((v2) => v2);
10638
+ this.started.set(untracked, startSeq);
10639
+ return untracked;
10640
+ }
10641
+ let set = this.active.get(sessionKey);
10642
+ if (!set) {
10643
+ set = /* @__PURE__ */ new Set();
10644
+ this.active.set(sessionKey, set);
10645
+ }
10646
+ set.add(ft2);
10647
+ const done = () => {
10648
+ ft2.runs.delete(tracked);
10649
+ if (ft2.runs.size === 0) {
10650
+ const s2 = this.active.get(sessionKey);
10651
+ s2?.delete(ft2);
10652
+ if (s2 && s2.size === 0) this.active.delete(sessionKey);
10653
+ }
10654
+ };
10655
+ const tracked = run.then((v2) => {
10656
+ done();
10657
+ return v2;
10658
+ }, (e) => {
10659
+ done();
10660
+ throw e;
10661
+ });
10662
+ ft2.runs.add(tracked);
10663
+ this.started.set(tracked, startSeq);
10664
+ return tracked;
10665
+ }
10666
+ /**
10667
+ * After a dispatch returned (dr-evil #1784, MEDIUM 3).
10668
+ * - "steer": the text was injected into the run that is active NOW → fold
10669
+ * into the AgentVault turn that owns that run.
10670
+ * - "followup" (2026.10.8 reports collect the same way: both go through
10671
+ * `enqueueFollowupRun`, `agent-runner-run-*.mjs:7930-7950`): the content
10672
+ * runs in a LATER run (`scheduleFollowupDrainAfterReplyOperationClear`),
10673
+ * which belongs to no AgentVault turn → never folded into the active
10674
+ * turn (that would end it before its content ran); it waits.
10675
+ * - A steer with no AgentVault owner (another surface, a heartbeat) waits
10676
+ * too. A waiting token ends at the session's next dispatch that ran its
10677
+ * own run (evidence the absorbing runs are over), or as a drop at the
10678
+ * bound (MEDIUM/LOW 4). Room file authority does not depend on it: the
10679
+ * content already tainted the room's session (openclaw-room-taint.ts).
10680
+ * - Not deferred: this dispatch ran its own run → every waiting token ends.
10681
+ */
10682
+ async afterDispatch(channel, sessionKey, ft2, result, run) {
10683
+ const deferred = result?.deferredToActiveRun;
10684
+ if (deferred === "steer" || deferred === "followup") {
10685
+ if (!ft2 || !ft2.lease || ft2.ended) return;
10686
+ if (this.active.get(sessionKey)?.has(ft2)) return;
10687
+ if (deferred === "steer") {
10688
+ const absorber = [...this.active.get(sessionKey) ?? []].reverse().find((t2) => t2 !== ft2 && !t2.ended && t2.lease);
10689
+ if (absorber && foldFileTurn(channel, ft2, absorber)) return;
10690
+ }
10691
+ this.wait(channel, sessionKey, ft2);
10692
+ return;
10693
+ }
10694
+ const waiting = this.pending.get(sessionKey);
10695
+ if (!waiting) return;
10696
+ const startedAt = run ? this.started.get(run) : void 0;
10697
+ if (startedAt === void 0) return;
10698
+ const over = waiting.filter((w2) => (this.waitedAt.get(w2) ?? Infinity) < startedAt);
10699
+ const still = waiting.filter((w2) => !over.includes(w2));
10700
+ if (still.length > 0) this.pending.set(sessionKey, still);
10701
+ else this.pending.delete(sessionKey);
10702
+ for (const w2 of over) await this.release(channel, w2);
10703
+ }
10704
+ /** Bounds on waiting tokens (test seam: `OpenClawTurnRuns.bounds`). */
10705
+ static bounds = { maxMs: TURN_TOKEN_TTL_MS, perSession: 100, total: 1e3 };
10706
+ timers = /* @__PURE__ */ new WeakMap();
10707
+ wait(channel, sessionKey, ft2) {
10708
+ ft2.absorbedPending = true;
10709
+ this.waitedAt.set(ft2, this.seq);
10710
+ const list = this.pending.get(sessionKey) ?? [];
10711
+ list.push(ft2);
10712
+ this.pending.set(sessionKey, list);
10713
+ const timer = setTimeout(() => {
10714
+ const l2 = this.pending.get(sessionKey);
10715
+ if (l2) {
10716
+ const i2 = l2.indexOf(ft2);
10717
+ if (i2 >= 0) l2.splice(i2, 1);
10718
+ if (l2.length === 0) this.pending.delete(sessionKey);
10719
+ }
10720
+ void this.release(channel, ft2);
10721
+ }, _OpenClawTurnRuns.bounds.maxMs);
10722
+ timer.unref?.();
10723
+ this.timers.set(ft2, timer);
10724
+ while (list.length > _OpenClawTurnRuns.bounds.perSession) void this.release(channel, list.shift());
10725
+ let total = [...this.pending.values()].reduce((n2, l2) => n2 + l2.length, 0);
10726
+ while (total > _OpenClawTurnRuns.bounds.total) {
10727
+ const [key, l2] = this.pending.entries().next().value;
10728
+ void this.release(channel, l2.shift());
10729
+ if (l2.length === 0) this.pending.delete(key);
10730
+ total--;
10731
+ }
10732
+ }
10733
+ async release(channel, ft2) {
10734
+ const t2 = this.timers.get(ft2);
10735
+ if (t2) clearTimeout(t2);
10736
+ ft2.absorbedPending = false;
10737
+ await endFileTurn(channel, ft2, 0);
10738
+ }
10739
+ /** Test seam. */
10740
+ _sizes() {
10741
+ return { active: [...this.active.values()].reduce((n2, s2) => n2 + s2.size, 0), pending: [...this.pending.values()].reduce((n2, l2) => n2 + l2.length, 0) };
10742
+ }
10743
+ };
10744
+ var WORKSPACE_CANDIDATES = [
10745
+ { specifier: "openclaw/plugin-sdk/agent-runtime", symbol: "resolveAgentWorkspaceDir" }
10746
+ ];
10747
+ var SANDBOX_STATUS_CANDIDATES = [
10748
+ { specifier: "openclaw/plugin-sdk/sandbox", symbol: "resolveSandboxRuntimeStatus" }
10749
+ ];
10750
+ function openclawAgentIdFor(cfg, accountId) {
10751
+ const bindings = cfg?.bindings;
10752
+ const b2 = Array.isArray(bindings) ? bindings.find((x2) => x2?.match?.channel === "agentvault" && x2?.match?.accountId === accountId) : void 0;
10753
+ return typeof b2?.agentId === "string" && b2.agentId ? b2.agentId : "main";
10754
+ }
10755
+ async function resolveOpenClawWorkspace(cfg, agentId, home, importer) {
10756
+ const fn = await sdkFn(WORKSPACE_CANDIDATES, importer);
10757
+ if (typeof fn === "function") {
10758
+ try {
10759
+ const ws = fn(cfg, agentId);
10760
+ if (typeof ws === "string" && ws.trim()) return ws;
10761
+ } catch {
10762
+ }
10763
+ }
10764
+ const c2 = cfg;
10765
+ const entry = Array.isArray(c2?.agents?.list) ? c2.agents.list.find((a2) => a2?.id === agentId) : void 0;
10766
+ 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;
10767
+ if (!raw) return void 0;
10768
+ const expanded = raw.trim().replace(/^~(?=$|\/)/, home);
10769
+ return expanded.startsWith("/") ? expanded : void 0;
10770
+ }
10771
+ async function replySandboxed(cfg, agentId, sessionKey, importer) {
10772
+ const fn = await sdkFn(SANDBOX_STATUS_CANDIDATES, importer);
10773
+ if (typeof fn === "function") {
10774
+ try {
10775
+ const st2 = fn({ cfg, sessionKey, agentId });
10776
+ const status = st2 && typeof st2.then === "function" ? await st2 : st2;
10777
+ if (status && typeof status === "object" && typeof status.sandboxed === "boolean") {
10778
+ return status.sandboxed;
10779
+ }
10780
+ } catch {
10781
+ }
10782
+ }
10783
+ return sandboxedByConfig(cfg, agentId, sessionKey);
10784
+ }
10785
+ var OpenClawFileSendError = class extends Error {
10786
+ constructor(code, message) {
10787
+ super(message);
10788
+ this.code = code;
10789
+ this.name = "OpenClawFileSendError";
10790
+ }
10791
+ code;
10792
+ retryable = false;
10793
+ };
10794
+ function deliveredResult(messageId) {
10795
+ return { ok: true, channel: "agentvault", messageId: messageId || `av-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}` };
10796
+ }
10797
+ var SESSION_ENTRY_CANDIDATES = [
10798
+ { specifier: "openclaw/plugin-sdk/session-store-runtime", symbol: "getSessionEntry" }
10799
+ ];
10800
+ var _sessionEntryReader = null;
10801
+ async function openclawSessionState(core, params, importer) {
10802
+ const session = core?.channel?.session;
10803
+ const reader = typeof session?.readSessionUpdatedAtAsync === "function" ? session.readSessionUpdatedAtAsync.bind(session) : typeof session?.readSessionUpdatedAt === "function" ? session.readSessionUpdatedAt.bind(session) : null;
10804
+ let exists = true;
10805
+ if (reader) {
10806
+ try {
10807
+ const v2 = reader({ storePath: params.storePath, sessionKey: params.sessionKey });
10808
+ const at2 = v2 && typeof v2.then === "function" ? await v2 : v2;
10809
+ exists = at2 !== void 0 && at2 !== null;
10810
+ } catch {
10811
+ exists = true;
10812
+ }
10813
+ }
10814
+ if (!exists) return { exists: false };
10815
+ if (_sessionEntryReader === null) _sessionEntryReader = await sdkFn(SESSION_ENTRY_CANDIDATES, importer);
10816
+ if (typeof _sessionEntryReader === "function") {
10817
+ try {
10818
+ const e = _sessionEntryReader({ storePath: params.storePath, sessionKey: params.sessionKey, ...params.agentId ? { agentId: params.agentId } : {} });
10819
+ const entry = e && typeof e.then === "function" ? await e : e;
10820
+ const id = entry?.sessionId;
10821
+ if (typeof id === "string" && id) {
10822
+ 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;
10823
+ const createdAt = typeof entry?.createdAt === "number" ? entry.createdAt : void 0;
10824
+ return { exists: true, sessionId: id, lineage, ...createdAt !== void 0 ? { createdAt } : {} };
10825
+ }
10826
+ } catch {
10827
+ }
10828
+ }
10829
+ return { exists: true };
10830
+ }
10831
+ async function readSessionUpdatedAtSafe(core, params) {
10832
+ const session = core?.channel?.session;
10833
+ try {
10834
+ const v2 = typeof session?.readSessionUpdatedAtAsync === "function" ? await session.readSessionUpdatedAtAsync(params) : typeof session?.readSessionUpdatedAt === "function" ? session.readSessionUpdatedAt(params) : void 0;
10835
+ return typeof v2 === "number" ? v2 : void 0;
10836
+ } catch {
10837
+ return void 0;
10838
+ }
10839
+ }
10840
+
10841
+ // src/openclaw-room-taint.ts
10842
+ import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
10843
+ import { join } from "node:path";
10844
+ var ROOM_TAINT_FILE = "openclaw-room-taint.json";
10845
+ var RoomTaintStore = class {
10846
+ constructor(dataDir, log = (m2) => console.warn(m2)) {
10847
+ this.log = log;
10848
+ this.path = join(dataDir, ROOM_TAINT_FILE);
10849
+ }
10850
+ log;
10851
+ path;
10852
+ cache = null;
10853
+ /** Rooms whose taint could not be written: tainted for this process whatever the file says. */
10854
+ poisoned = /* @__PURE__ */ new Set();
10855
+ load() {
10856
+ if (this.cache) return this.cache;
10857
+ let parsed;
10858
+ try {
10859
+ parsed = JSON.parse(readFileSync2(this.path, "utf8"));
10860
+ } catch {
10861
+ parsed = {};
10862
+ }
10863
+ const out = {};
10864
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
10865
+ for (const [room, v2] of Object.entries(parsed)) {
10866
+ if (v2 && typeof v2 === "object" && typeof v2.tainted === "boolean") {
10867
+ out[room] = { tainted: v2.tainted, at: Number(v2.at) || 0, ...typeof v2.sessionId === "string" ? { sessionId: v2.sessionId } : {} };
10868
+ }
10869
+ }
10870
+ }
10871
+ this.cache = out;
10872
+ return out;
10873
+ }
10874
+ /**
10875
+ * Is the room's session tainted, given what OpenClaw reports? Also resets a
10876
+ * record whose session is genuinely new (no session, or a different id).
10877
+ */
10878
+ isTainted(key, oc) {
10879
+ if (this.poisoned.has(key)) return true;
10880
+ const rec = this.load()[key];
10881
+ if (!oc.exists) {
10882
+ return rec && !rec.sessionId ? rec.tainted : false;
10883
+ }
10884
+ if (!rec) return true;
10885
+ if (rec.sessionId && oc.sessionId && rec.sessionId !== oc.sessionId) {
10886
+ const fresh = oc.lineage === false && typeof oc.createdAt === "number" && oc.createdAt > rec.at;
10887
+ return fresh ? false : rec.tainted;
10888
+ }
10889
+ return rec.tainted;
10890
+ }
10891
+ /**
10892
+ * Record the room's state for the session about to receive this turn.
10893
+ * `tainted` is sticky within a session: a clean turn never clears a taint
10894
+ * (only a genuinely new session does, through `isTainted`'s answer).
10895
+ */
10896
+ record(key, oc, turnTaints) {
10897
+ const all = this.load();
10898
+ const wasTainted = this.isTainted(key, oc);
10899
+ const tainted = wasTainted || turnTaints;
10900
+ const prev = all[key];
10901
+ const sessionId = oc.sessionId ?? (oc.exists ? prev?.sessionId : void 0);
10902
+ const next = { tainted, at: Date.now(), ...sessionId ? { sessionId } : {} };
10903
+ if (prev && prev.tainted === next.tainted && prev.sessionId === next.sessionId) return;
10904
+ all[key] = next;
10905
+ if (!this.write(all) && tainted) {
10906
+ this.poisoned.add(key);
10907
+ delete all[key];
10908
+ if (!this.write(all)) {
10909
+ try {
10910
+ rmSync(this.path, { force: true });
10911
+ } catch {
10912
+ }
10913
+ this.cache = null;
10914
+ }
10915
+ this.log("[AgentVault] file-send: a room session taint was not saved \u2014 room files stay refused for that session");
10916
+ }
10917
+ }
10918
+ /**
10919
+ * The session the record describes now exists (OpenClaw created it while
10920
+ * recording this turn): remember its id, so a later reset — a NEW id — is
10921
+ * recognised. Only fills a missing id; never changes `tainted`.
10922
+ */
10923
+ bindSession(key, oc) {
10924
+ const all = this.load();
10925
+ const rec = all[key];
10926
+ if (!rec || rec.sessionId || !oc.exists || !oc.sessionId) return;
10927
+ all[key] = { ...rec, sessionId: oc.sessionId };
10928
+ if (!this.write(all)) all[key] = rec;
10929
+ }
10930
+ write(all) {
10931
+ const tmp = `${this.path}.${process.pid}.tmp`;
10932
+ try {
10933
+ writeFileSync(tmp, JSON.stringify(all), { mode: 384 });
10934
+ renameSync(tmp, this.path);
10935
+ return true;
10936
+ } catch {
10937
+ try {
10938
+ rmSync(tmp, { force: true });
10939
+ } catch {
10940
+ }
10941
+ return false;
10942
+ }
10943
+ }
10944
+ };
10945
+
10946
+ // src/openclaw-sender.ts
10947
+ function hexish(id, max) {
10948
+ if (typeof id !== "string") return "unknown";
10949
+ const clean4 = id.toLowerCase().replace(/[^0-9a-f-]/g, "");
10950
+ return clean4 === "" ? "unknown" : clean4.slice(0, max);
10951
+ }
10952
+ function dmSenderIdentity(metadata) {
10953
+ if (metadata?.ownerDm1to1 === true && metadata.senderIsOwnerDevice === true && metadata.senderBinding === "bound") {
10954
+ return { id: "agentvault:owner", name: "Owner", owner: true };
10955
+ }
10956
+ if (metadata?.senderBinding === "bound" && typeof metadata.senderDeviceId === "string" && metadata.senderDeviceId !== "") {
10957
+ const name = metadata.senderOwnerStatus === "unknown" ? "Owner status unconfirmed" : "Not the owner";
10958
+ return { id: `agentvault:device:${hexish(metadata.senderDeviceId, 36)}`, name, owner: false };
10959
+ }
10960
+ const conv = typeof metadata?.conversationId === "string" && metadata.conversationId !== "" ? metadata.conversationId : metadata?.conversationGroupId;
10961
+ return { id: `agentvault:unverified:${hexish(conv, 8)}`, name: "Unverified sender", owner: false };
10962
+ }
10963
+ function unverifiedRoomFragment(claimed) {
10964
+ return `#unverified:${hexish(claimed, 8)}`;
10965
+ }
10966
+
9888
10967
  // src/openclaw-entry.ts
9889
10968
  var _ocRuntime = null;
9890
10969
  var _channels = /* @__PURE__ */ new Map();
@@ -9931,8 +11010,8 @@ function _a2aRecordReply(channelId) {
9931
11010
  function _roomCanReply(roomId) {
9932
11011
  return _canReply(`room:${roomId}`);
9933
11012
  }
9934
- function _roomReplyAllowed(senderIsAgent, roomId) {
9935
- if (senderIsAgent !== true) return true;
11013
+ function _roomReplyAllowed(senderIsAgent, roomId, senderBinding) {
11014
+ if (senderBinding === "bound" && senderIsAgent !== true) return true;
9936
11015
  return _roomCanReply(roomId);
9937
11016
  }
9938
11017
  function _roomRecordReply(roomId) {
@@ -9998,7 +11077,7 @@ function _stripThinkBlocks(text) {
9998
11077
  function _looksLikeReasoningLeak(text) {
9999
11078
  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
11079
  }
10001
- function _resolveRoomIdentity(channel, roomId, fallbackName, privateRoom = false) {
11080
+ function _resolveRoomIdentity(channel, roomId, fallbackName, privateRoom = false, roomLabel, redactForeignNames = false) {
10002
11081
  const fallback = { selfName: fallbackName, preamble: "" };
10003
11082
  if (!roomId) return fallback;
10004
11083
  try {
@@ -10008,20 +11087,26 @@ function _resolveRoomIdentity(channel, roomId, fallbackName, privateRoom = false
10008
11087
  const ownDeviceId = channel.deviceId;
10009
11088
  const self2 = room.members?.find((m2) => m2.deviceId === ownDeviceId);
10010
11089
  const selfName = self2?.displayName || fallbackName;
10011
- const others = (room.members ?? []).filter((m2) => m2.deviceId !== ownDeviceId).map((m2) => `${m2.displayName} (${m2.entityType === "agent" ? "agent" : "person"})`);
11090
+ const jwtTenant = typeof channel.ownTenantId === "function" ? channel.ownTenantId() : null;
11091
+ const ownTenant = typeof jwtTenant === "string" && jwtTenant ? jwtTenant.toLowerCase() : null;
11092
+ const ownAccount = (m2) => ownTenant !== null && typeof m2?.tenantId === "string" && m2.tenantId.toLowerCase() === ownTenant;
11093
+ 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
11094
  const membersStr = others.length > 0 ? others.join(", ") : "(still loading \u2014 more members may be joining; this is NOT a 1:1)";
10013
11095
  if (privateRoom) {
10014
11096
  return {
10015
11097
  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]`
11098
+ 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
11099
  };
10018
11100
  }
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]`;
11101
+ 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
11102
  return { selfName, preamble };
10021
11103
  } catch {
10022
11104
  return fallback;
10023
11105
  }
10024
11106
  }
11107
+ function _shortRoomLabel(roomId) {
11108
+ return `room ${String(roomId ?? "").slice(0, 8)}`;
11109
+ }
10025
11110
  function _buildDmPreamble(selfName, hubAddress) {
10026
11111
  if (!selfName) return "";
10027
11112
  const at2 = hubAddress ? ` at ${hubAddress}` : "";
@@ -10079,8 +11164,9 @@ function _selectInboundPreamble(opts) {
10079
11164
  }
10080
11165
  return "";
10081
11166
  }
10082
- function _buildRoomSenderId(roomId, senderDeviceId, senderName) {
11167
+ function _buildRoomSenderId(roomId, senderDeviceId, senderName, unverifiedClaim) {
10083
11168
  const base = `agentvault:room:${roomId}`;
11169
+ if (unverifiedClaim !== void 0) return `${base}${unverifiedRoomFragment(unverifiedClaim)}`;
10084
11170
  if (senderDeviceId) return `${base}#device:${senderDeviceId}`;
10085
11171
  const name = (senderName ?? "").trim();
10086
11172
  if (name) return `${base}#sender:${encodeURIComponent(name.toLowerCase())}`;
@@ -10183,6 +11269,27 @@ function _withSessionSerial(key, fn) {
10183
11269
  return run;
10184
11270
  }
10185
11271
  var TURN_BUDGET_MS = 12e4;
11272
+ function _setTurnBudgetMsForTest(ms) {
11273
+ const prev = TURN_BUDGET_MS;
11274
+ TURN_BUDGET_MS = ms;
11275
+ return prev;
11276
+ }
11277
+ var _turnRuns = new OpenClawTurnRuns();
11278
+ var _roomTaints = /* @__PURE__ */ new Map();
11279
+ function _roomTaintFor(channel) {
11280
+ const dataDir = channel?.config?.dataDir;
11281
+ if (typeof dataDir !== "string" || !dataDir) return null;
11282
+ let store = _roomTaints.get(dataDir);
11283
+ if (!store) {
11284
+ store = new RoomTaintStore(dataDir);
11285
+ _roomTaints.set(dataDir, store);
11286
+ }
11287
+ return store;
11288
+ }
11289
+ function _resetRoomTaintsForTest() {
11290
+ _roomTaints.clear();
11291
+ }
11292
+ var _notReadyBound = { maxMs: TURN_TOKEN_TTL_MS };
10186
11293
  function _withTurnTimeout(ms, fn, onTimeout) {
10187
11294
  return new Promise((resolve2, reject) => {
10188
11295
  let settled = false;
@@ -10294,10 +11401,27 @@ function _makeOnMessage(deps) {
10294
11401
  return target.kind === "owner" && typeof channel?.runForConversation === "function" ? channel.runForConversation(metadata?.conversationId, send, { groupId: metadata?.conversationGroupId }) : send();
10295
11402
  };
10296
11403
  return async (plaintext, metadata) => {
11404
+ const fileTurn = takeFileTurn(metadata);
11405
+ const endThisTurn = () => {
11406
+ let ch;
11407
+ try {
11408
+ ch = deps.getChannel();
11409
+ } catch {
11410
+ ch = void 0;
11411
+ }
11412
+ return endFileTurn(ch, fileTurn);
11413
+ };
10297
11414
  const turn = newInboundTurnState();
10298
11415
  if (!deps.isRuntimeReady()) {
10299
11416
  deps.log?.("[AgentVault] runtime not ready, queuing message");
10300
- deps.enqueue(() => deps.inbound({ plaintext, metadata, turn }));
11417
+ const bound = setTimeout(() => {
11418
+ void endThisTurn();
11419
+ }, _notReadyBound.maxMs);
11420
+ bound.unref?.();
11421
+ deps.enqueue(() => {
11422
+ clearTimeout(bound);
11423
+ return deps.inbound({ plaintext, metadata, turn, fileTurn }).finally(endThisTurn);
11424
+ });
10301
11425
  return;
10302
11426
  }
10303
11427
  const startedAt = Date.now();
@@ -10311,7 +11435,7 @@ function _makeOnMessage(deps) {
10311
11435
  provider: providerName
10312
11436
  };
10313
11437
  notices.opened(open2);
10314
- await _dispatchInboundWithRetry(() => deps.inbound({ plaintext, metadata, turn }), {
11438
+ await _dispatchInboundWithRetry(() => deps.inbound({ plaintext, metadata, turn, fileTurn }), {
10315
11439
  notifyOwner: async (lastErr) => {
10316
11440
  const channel = deps.getChannel();
10317
11441
  const target = _failureNoticeTarget(metadata, turn);
@@ -10339,11 +11463,18 @@ function _makeOnMessage(deps) {
10339
11463
  else console.warn(m2);
10340
11464
  } catch {
10341
11465
  }
10342
- }).finally(() => notices.closed(open2));
11466
+ }).finally(async () => {
11467
+ try {
11468
+ await notices.closed(open2);
11469
+ } finally {
11470
+ await endThisTurn();
11471
+ }
11472
+ });
10343
11473
  };
10344
11474
  }
10345
11475
  async function handleInbound(params) {
10346
11476
  const { plaintext: rawPlaintext, metadata, channel, account, cfg } = params;
11477
+ const fileTurn = params.fileTurn;
10347
11478
  const turn = params.turn ?? newInboundTurnState();
10348
11479
  const isRoomMessage = Boolean(metadata.roomId);
10349
11480
  const isA2AMessage = Boolean(metadata.a2aChannelId);
@@ -10358,7 +11489,8 @@ async function handleInbound(params) {
10358
11489
  const selfResolved = !!ownDisplayName || !!roomIdentity.selfName && roomIdentity.selfName !== (account.agentName ?? "") || !genericAgentName;
10359
11490
  if (isRoomMessage) {
10360
11491
  const gateText = metadata.caption ?? rawPlaintext;
10361
- if (!owesRoomReply(gateText, account.agentName ?? "", account.accountId ?? "", metadata.senderIsAgent, roomIdentity.selfName, ownDisplayName, selfResolved, metadata.roomAudience)) {
11492
+ const gateSenderIsAgent = metadata.senderBinding === "bound" ? metadata.senderIsAgent : true;
11493
+ if (!owesRoomReply(gateText, account.agentName ?? "", account.accountId ?? "", gateSenderIsAgent, roomIdentity.selfName, ownDisplayName, selfResolved, metadata.roomAudience, metadata.senderBinding)) {
10362
11494
  console.log(
10363
11495
  `[AgentVault] room message read, not answered \u2014 no @mention for this agent (#1107) room=${String(metadata.roomId ?? "").slice(0, 8)}`
10364
11496
  );
@@ -10379,9 +11511,9 @@ async function handleInbound(params) {
10379
11511
  }
10380
11512
  }
10381
11513
  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");
11514
+ const traceId = randomBytes3(16).toString("hex");
11515
+ const rootSpanId = randomBytes3(8).toString("hex");
11516
+ const inferenceSpanId = randomBytes3(8).toString("hex");
10385
11517
  const _sendActivity = (spanData) => {
10386
11518
  try {
10387
11519
  channel.sendActivitySpan({ ...redactFreeText(spanData), trace_id: traceId, parent_span_id: inferenceSpanId });
@@ -10399,7 +11531,7 @@ async function handleInbound(params) {
10399
11531
  const activityAttrs = { "ai.agent.llm.model": opts.model ?? "" };
10400
11532
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10401
11533
  _sendActivity({
10402
- span_id: randomBytes2(8).toString("hex"),
11534
+ span_id: randomBytes3(8).toString("hex"),
10403
11535
  span_type: "llm",
10404
11536
  span_name: opts.model ?? "LLM",
10405
11537
  status: opts.status === "error" ? "error" : "ok",
@@ -10421,7 +11553,7 @@ async function handleInbound(params) {
10421
11553
  const activityAttrs = { "ai.agent.tool.name": opts.toolName ?? "" };
10422
11554
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10423
11555
  _sendActivity({
10424
- span_id: randomBytes2(8).toString("hex"),
11556
+ span_id: randomBytes3(8).toString("hex"),
10425
11557
  span_type: "tool",
10426
11558
  span_name: opts.toolName ?? "tool",
10427
11559
  status: opts.success === false ? "error" : "ok",
@@ -10442,7 +11574,7 @@ async function handleInbound(params) {
10442
11574
  const activityAttrs = { "ai.agent.error.type": opts.errorType ?? "" };
10443
11575
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10444
11576
  _sendActivity({
10445
- span_id: randomBytes2(8).toString("hex"),
11577
+ span_id: randomBytes3(8).toString("hex"),
10446
11578
  span_type: "error",
10447
11579
  span_name: opts.errorType ?? "error",
10448
11580
  status: "error",
@@ -10465,7 +11597,7 @@ async function handleInbound(params) {
10465
11597
  const activityAttrs = { "ai.agent.http.method": opts.method ?? "", "ai.agent.http.url": site };
10466
11598
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10467
11599
  _sendActivity({
10468
- span_id: randomBytes2(8).toString("hex"),
11600
+ span_id: randomBytes3(8).toString("hex"),
10469
11601
  span_type: "http",
10470
11602
  span_name: urlHost(site) || "http",
10471
11603
  status: (opts.statusCode ?? 200) >= 400 ? "error" : "ok",
@@ -10488,7 +11620,7 @@ async function handleInbound(params) {
10488
11620
  const activityAttrs = { "ai.agent.action.type": opts.actionType ?? "", "ai.agent.action.target": opts.target ?? "" };
10489
11621
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10490
11622
  _sendActivity({
10491
- span_id: randomBytes2(8).toString("hex"),
11623
+ span_id: randomBytes3(8).toString("hex"),
10492
11624
  span_type: "action",
10493
11625
  span_name: `${opts.actionType ?? "action"}: ${opts.target ?? ""}`,
10494
11626
  status: opts.success === false ? "error" : "ok",
@@ -10511,7 +11643,7 @@ async function handleInbound(params) {
10511
11643
  const activityAttrs = { "ai.agent.nav.to_url": site };
10512
11644
  if (enriched.skillName) activityAttrs["ai.agent.skill.name"] = enriched.skillName;
10513
11645
  _sendActivity({
10514
- span_id: randomBytes2(8).toString("hex"),
11646
+ span_id: randomBytes3(8).toString("hex"),
10515
11647
  span_type: "nav",
10516
11648
  span_name: site || "navigate",
10517
11649
  status: opts.status === "error" ? "error" : "ok",
@@ -10574,23 +11706,21 @@ async function handleInbound(params) {
10574
11706
  }
10575
11707
  }
10576
11708
  }
11709
+ const dmIdentity = !isRoomMessage && !isA2AMessage ? dmSenderIdentity(metadata) : null;
10577
11710
  const route = core.channel.routing.resolveAgentRoute({
10578
11711
  cfg,
10579
11712
  channel: "agentvault",
10580
11713
  accountId: account.accountId,
10581
11714
  peer: {
10582
11715
  kind: isRoomMessage ? "group" : "direct",
10583
- id: isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner"
11716
+ id: isRoomMessage ? `agentvault:room:${metadata.roomId}` : dmIdentity?.id ?? "agentvault:owner"
10584
11717
  }
10585
11718
  });
10586
11719
  const storePath = core.channel.session.resolveStorePath(cfg?.session?.store, {
10587
11720
  agentId: route.agentId
10588
11721
  });
10589
11722
  const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
10590
- const previousTimestamp = core.channel.session.readSessionUpdatedAt({
10591
- storePath,
10592
- sessionKey: route.sessionKey
10593
- });
11723
+ const previousTimestamp = await readSessionUpdatedAtSafe(core, { storePath, sessionKey: route.sessionKey });
10594
11724
  const recallQuery = isRoomMessage || isA2AMessage ? plaintext : metadata?.reason || metadata?.triggerName || plaintext;
10595
11725
  const recallWorthwhile = (recallQuery?.trim().length ?? 0) >= 10;
10596
11726
  if (recallWorthwhile) {
@@ -10607,27 +11737,66 @@ async function handleInbound(params) {
10607
11737
  plaintext = memoryContext + "\n---\n\n" + plaintext;
10608
11738
  }
10609
11739
  }
10610
- let contextBody = plaintext;
11740
+ let contextBody = neutralizeForeignLine(plaintext);
11741
+ let roomHistoryAttached = false;
10611
11742
  if (isRoomMessage && metadata.roomId && channel.getRoomHistory) {
10612
11743
  const recentHistory = channel.getRoomHistory(metadata.roomId, 20);
10613
11744
  const prior = recentHistory.slice(0, -1);
10614
11745
  if (prior.length > 0) {
10615
11746
  const historyBlock = prior.map((h2) => {
10616
- const role = h2.sender === "agent" ? "You" : "Room Member";
10617
- return `[${role}]: ${h2.text}`;
11747
+ if (h2.sender === "agent") {
11748
+ const files = Array.isArray(h2.files) && h2.files.length > 0 ? `
11749
+ ${renderHistoryFiles(h2.files)}` : "";
11750
+ return `[You]: ${h2.text}${files}`;
11751
+ }
11752
+ const who = h2.sender === "unverified" ? "Unverified sender" : "Room Member";
11753
+ return `[${who}]: ${neutralizeForeignLine(String(h2.text ?? ""))}`;
10618
11754
  }).join("\n");
10619
11755
  contextBody = `[Recent room conversation]
10620
11756
  ${historyBlock}
10621
11757
 
10622
11758
  [Current message]
10623
- ${plaintext}`;
11759
+ ${contextBody}`;
11760
+ roomHistoryAttached = true;
11761
+ }
11762
+ }
11763
+ const fileSendOn = typeof channel.stagingPathFor === "function" && channel.stagingPathFor({ kind: "owner" }) !== null;
11764
+ let replyHost = {};
11765
+ if (fileSendOn && !isA2AMessage) {
11766
+ const [limitRoots, sandboxed] = await Promise.all([
11767
+ replyMediaRoots(cfg, route.agentId),
11768
+ replySandboxed(cfg, route.agentId, route.sessionKey)
11769
+ ]);
11770
+ replyHost = { ...limitRoots !== void 0 ? { limitRoots } : {}, ...sandboxed ? { sandboxed: true } : {} };
11771
+ }
11772
+ let roomTainted = true;
11773
+ if (isRoomMessage && typeof metadata.roomId === "string" && typeof route.sessionKey === "string" && route.sessionKey) {
11774
+ const store = _roomTaintFor(channel);
11775
+ if (store) {
11776
+ const oc = await openclawSessionState(core, { storePath, sessionKey: route.sessionKey, agentId: route.agentId });
11777
+ roomTainted = store.isTainted(route.sessionKey, oc);
11778
+ const cleanTurn = metadata.senderIsAgent === false && metadata.senderIsOwner === true && metadata.foreignContent === false && !roomHistoryAttached;
11779
+ store.record(route.sessionKey, oc, !cleanTurn);
10624
11780
  }
10625
11781
  }
11782
+ let attested = false;
11783
+ if (isRoomMessage && fileTurn?.lease && !roomHistoryAttached && !roomTainted && typeof channel.attestCleanTurn === "function") {
11784
+ attested = channel.attestCleanTurn(fileTurn.lease) === true;
11785
+ }
11786
+ noteTurnSandbox(fileTurn?.token, replyHost.sandboxed === true);
10626
11787
  if (!isRoomMessage && !isA2AMessage && !channel.ownDisplayName && typeof channel.ensureOwnIdentityResolved === "function") {
10627
11788
  void channel.ensureOwnIdentityResolved();
10628
11789
  }
11790
+ const roomForModel = isRoomMessage && attested ? _resolveRoomIdentity(
11791
+ channel,
11792
+ metadata.roomId,
11793
+ account.agentName ?? "",
11794
+ isPrivatePairHumanMessage(metadata.senderIsAgent, metadata.roomAudience),
11795
+ _shortRoomLabel(metadata.roomId),
11796
+ true
11797
+ ) : roomIdentity;
10629
11798
  const inboundPreamble = _selectInboundPreamble({
10630
- roomPreamble: roomIdentity.preamble,
11799
+ roomPreamble: roomForModel.preamble,
10631
11800
  isRoomMessage,
10632
11801
  isA2AMessage,
10633
11802
  ownDisplayName: channel.ownDisplayName ?? "",
@@ -10636,10 +11805,16 @@ ${plaintext}`;
10636
11805
  if (inboundPreamble) {
10637
11806
  contextBody = `${inboundPreamble}
10638
11807
  ${contextBody}`;
11808
+ }
11809
+ if (fileSendOn) {
11810
+ const fileTarget = isA2AMessage ? null : isRoomMessage ? { kind: "room", roomId: metadata.roomId } : { kind: "owner" };
11811
+ contextBody = `${contextBody}
11812
+
11813
+ ${openclawFileLines(channel, fileTarget, { roomsAllowed: attested && replyHost.sandboxed !== true })}`;
10639
11814
  }
10640
11815
  const body2 = core.channel.reply.formatAgentEnvelope({
10641
11816
  channel: "AgentVault",
10642
- from: isA2AMessage ? `Agent (${metadata.fromHubAddress})` : isRoomMessage ? senderDisplayName ?? "Room Member" : "Owner",
11817
+ from: isA2AMessage ? `Agent (${metadata.fromHubAddress})` : isRoomMessage ? senderDisplayName ?? "Room Member" : dmIdentity?.name ?? "Unverified sender",
10643
11818
  timestamp: new Date(metadata.timestamp).getTime(),
10644
11819
  previousTimestamp,
10645
11820
  envelope: envelopeOptions,
@@ -10664,13 +11839,13 @@ ${contextBody}`;
10664
11839
  credentialFields.RenterCredentialCount = creds.length;
10665
11840
  }
10666
11841
  }
10667
- const commandAuthorized = isA2AMessage ? false : isRoomMessage ? metadata.senderIsOwner === true && metadata.foreignContent === false : true;
11842
+ const commandAuthorized = isA2AMessage ? false : isRoomMessage ? metadata.senderIsOwner === true && metadata.foreignContent === false : metadata.ownerDm1to1 === true && metadata.senderIsOwnerDevice === true && dmIdentity?.owner === true;
10668
11843
  const isCommandTurn = commandAuthorized && commandBody.trim().startsWith("/");
10669
11844
  const ctxPayload = core.channel.reply.finalizeInboundContext({
10670
11845
  Body: body2,
10671
11846
  RawBody: plaintext,
10672
11847
  CommandBody: commandBody,
10673
- From: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : "agentvault:owner",
11848
+ From: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? `agentvault:room:${metadata.roomId}` : dmIdentity?.id ?? "agentvault:unverified:unknown",
10674
11849
  // GH #366 iter 3: room `To` must be ROOM-scoped (matches `From`), not
10675
11850
  // agent-scoped — an agent-scoped `To` reads as a 1:1 address and triggers
10676
11851
  // the `chat_type: "direct"` confabulation. Only the ROOM case changes;
@@ -10688,8 +11863,9 @@ ${contextBody}`;
10688
11863
  // @mention this agent, so a room turn that gets here is a mention.
10689
11864
  // OpenClaw reads it for group typing and reply rules.
10690
11865
  ...isRoomMessage ? { WasMentioned: true } : {},
10691
- ConversationLabel: isA2AMessage ? `A2A: ${metadata.fromHubAddress}` : isRoomMessage ? roomName ?? "AgentVault Room" : "AgentVault",
10692
- SenderName: isA2AMessage ? metadata.fromHubAddress : isRoomMessage ? senderDisplayName ?? "Room Member" : "Owner",
11866
+ // #1784 item 8: an attested room turn is labelled by the room's short id, never its name.
11867
+ ConversationLabel: isA2AMessage ? `A2A: ${metadata.fromHubAddress}` : isRoomMessage ? attested ? _shortRoomLabel(metadata.roomId) : roomName ?? "AgentVault Room" : "AgentVault",
11868
+ SenderName: isA2AMessage ? metadata.fromHubAddress : isRoomMessage ? senderDisplayName ?? "Room Member" : dmIdentity?.name ?? "Unverified sender",
10693
11869
  // GH #366: room SenderId must encode the ROOM, not the sender's device id.
10694
11870
  // The old form `agentvault:room:${senderDeviceId}` stamped the device id
10695
11871
  // with a `room:` prefix → agent read it as a per-device DM channel.
@@ -10697,7 +11873,12 @@ ${contextBody}`;
10697
11873
  // scope primary while still identifying the specific sender within it. The
10698
11874
  // no-senderDeviceId case is hardened in _buildRoomSenderId (sender-name
10699
11875
  // 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",
11876
+ SenderId: isA2AMessage ? `a2a:${metadata.fromHubAddress}` : isRoomMessage ? _buildRoomSenderId(
11877
+ metadata.roomId,
11878
+ metadata.senderDeviceId,
11879
+ senderDisplayName,
11880
+ typeof metadata.senderBinding === "string" && metadata.senderBinding !== "bound" ? metadata.claimedSenderDeviceId ?? null : void 0
11881
+ ) : dmIdentity?.id ?? "agentvault:unverified:unknown",
10701
11882
  Provider: "agentvault",
10702
11883
  Surface: "agentvault",
10703
11884
  MessageSid: metadata.messageId,
@@ -10709,6 +11890,9 @@ ${contextBody}`;
10709
11890
  OriginatingTo: isRoomMessage ? _buildRoomTo(metadata.roomId, account.accountId) : `agentvault:agent:${account.accountId}`,
10710
11891
  // Who may run a slash command: see `commandAuthorized` above.
10711
11892
  CommandAuthorized: commandAuthorized,
11893
+ // #1800 PR B §1.3: every non-owner turn also suppresses command
11894
+ // interpretation — `commands.allowFrom` would bypass CommandAuthorized.
11895
+ ...commandAuthorized ? {} : { CommandInterpretationSuppressed: true },
10712
11896
  Instrument: _instrument,
10713
11897
  // OpenClaw ctx convention
10714
11898
  AgentVaultTelemetry: _instrument,
@@ -10720,7 +11904,8 @@ ${contextBody}`;
10720
11904
  const _asTurn = (fn) => !isRoomMessage && !isA2AMessage && typeof channel.runForConversation === "function" ? channel.runForConversation(metadata.conversationId, fn, { groupId: metadata.conversationGroupId }) : fn();
10721
11905
  const attempt = { expired: false };
10722
11906
  let failureCode;
10723
- await _withSessionSerial(_turnSessionKey, () => runWithToolConversation(_toolConversationFor(metadata), () => _asTurn(() => _withTurnTimeout(TURN_BUDGET_MS, async () => {
11907
+ const _asNonOwner = (fn) => dmIdentity && !dmIdentity.owner && typeof channel.runAsNonOwnerTurn === "function" ? channel.runAsNonOwnerTurn(fn) : fn();
11908
+ await _asNonOwner(() => _withSessionSerial(_turnSessionKey, () => runWithToolConversation(_toolConversationFor(metadata), () => _asTurn(() => _withTurnTimeout(TURN_BUDGET_MS, async () => {
10724
11909
  await core.channel.session.recordInboundSession({
10725
11910
  storePath,
10726
11911
  sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
@@ -10729,6 +11914,10 @@ ${contextBody}`;
10729
11914
  core.error?.(`[AgentVault] session record failed: ${String(err)}`);
10730
11915
  }
10731
11916
  });
11917
+ if (isRoomMessage && typeof route.sessionKey === "string" && route.sessionKey) {
11918
+ const store = _roomTaintFor(channel);
11919
+ if (store) store.bindSession(route.sessionKey, await openclawSessionState(core, { storePath, sessionKey: route.sessionKey, agentId: route.agentId }));
11920
+ }
10732
11921
  try {
10733
11922
  const heldFailurePayloads = [];
10734
11923
  const deliverPayload = async (payload, info) => {
@@ -10742,7 +11931,11 @@ ${contextBody}`;
10742
11931
  }
10743
11932
  const payloadText = (payload.text ?? "").trim();
10744
11933
  const text = isOpenClawRestartLine(payloadText) ? ownerNoticeFor("model_error", { agentName: _noticeAgentName(channel, account.agentName), provider: _noticeProvider(cfg, route.agentId) }) : payloadText;
10745
- if (!text) return;
11934
+ const mediaRefs = mediaRefsOf(payload);
11935
+ if (!text) {
11936
+ if (mediaRefs.length > 0) await deliverMedia(mediaRefs, info);
11937
+ return;
11938
+ }
10746
11939
  {
10747
11940
  const recoverable = _stripThinkBlocks(text);
10748
11941
  if (recoverable && !_looksLikeReasoningLeak(recoverable)) lastFilteredText = recoverable;
@@ -10760,7 +11953,7 @@ ${contextBody}`;
10760
11953
  }
10761
11954
  replyTarget = { kind: "a2a", hubAddress: metadata.fromHubAddress };
10762
11955
  } else if (isRoomMessage) {
10763
- if (!_roomReplyAllowed(metadata.senderIsAgent, metadata.roomId)) {
11956
+ if (!_roomReplyAllowed(metadata.senderIsAgent, metadata.roomId, metadata.senderBinding)) {
10764
11957
  console.warn(`[AgentVault] Room reply suppressed (rate limit) for room ${metadata.roomId?.slice(0, 8)}...`);
10765
11958
  return;
10766
11959
  }
@@ -10793,8 +11986,28 @@ ${contextBody}`;
10793
11986
  }
10794
11987
  const replyEnd = Date.now();
10795
11988
  replySpans.push({ startTime: replyStart, endTime: replyEnd, chars: text.length, index: replyCount });
11989
+ if (replyReceipt?.ok !== false) fileTurn?.replies.push(text);
11990
+ if (mediaRefs.length > 0) await deliverMedia(mediaRefs, info);
11991
+ };
11992
+ const deliverMedia = async (refs, info) => {
11993
+ const target = isA2AMessage ? void 0 : isRoomMessage ? { kind: "room", roomId: metadata.roomId } : { kind: "owner" };
11994
+ if (!target || typeof channel.sendFile !== "function") {
11995
+ console.warn(`[AgentVault] reply media not sent (${refs.length} part(s)): files cannot go to this conversation`);
11996
+ return;
11997
+ }
11998
+ for (const ref of refs) {
11999
+ const res = await sendMediaPart(channel, target, ref, "", fileTurn?.token ?? null, replyHost, {
12000
+ conversationId: metadata.conversationId,
12001
+ topicId: metadata.topicId,
12002
+ parentSpanId: inferenceSpanId
12003
+ });
12004
+ if (res.ok) {
12005
+ turn.spoke = true;
12006
+ if (info?.kind === "final") turn.delivered = true;
12007
+ }
12008
+ }
10796
12009
  };
10797
- const dispatchResult = await runWithTraceContext(
12010
+ const runDispatch = () => runWithTraceContext(
10798
12011
  { traceId, parentSpanId: inferenceSpanId },
10799
12012
  () => core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
10800
12013
  ctx: ctxPayload,
@@ -10808,6 +12021,10 @@ ${contextBody}`;
10808
12021
  replyOptions: {}
10809
12022
  })
10810
12023
  );
12024
+ const dispatchRun = fileTurn?.token && typeof channel.runWithTurnToken === "function" ? channel.runWithTurnToken(fileTurn.token, runDispatch) : runDispatch();
12025
+ const trackedRun = _turnRuns.track(_turnSessionKey, fileTurn, Promise.resolve(dispatchRun));
12026
+ const dispatchResult = await trackedRun;
12027
+ await _turnRuns.afterDispatch(channel, _turnSessionKey, fileTurn, dispatchResult, trackedRun);
10811
12028
  if (heldFailurePayloads.length > 0) {
10812
12029
  if (openclawRunFailed(dispatchResult)) {
10813
12030
  for (const held of heldFailurePayloads)
@@ -10817,7 +12034,7 @@ ${contextBody}`;
10817
12034
  }
10818
12035
  }
10819
12036
  if (replyCount === 0 && lastFilteredText) {
10820
- const canReply = isA2AMessage ? _a2aCanReply(metadata.a2aChannelId) : isRoomMessage ? _roomReplyAllowed(metadata.senderIsAgent, metadata.roomId) : true;
12037
+ const canReply = isA2AMessage ? _a2aCanReply(metadata.a2aChannelId) : isRoomMessage ? _roomReplyAllowed(metadata.senderIsAgent, metadata.roomId, metadata.senderBinding) : true;
10821
12038
  if (canReply) {
10822
12039
  const replyTarget = isA2AMessage ? { kind: "a2a", hubAddress: metadata.fromHubAddress } : isRoomMessage ? { kind: "room", roomId: metadata.roomId } : { kind: "owner" };
10823
12040
  console.warn(
@@ -10837,7 +12054,10 @@ ${contextBody}`;
10837
12054
  throw err;
10838
12055
  }
10839
12056
  _reportAvToolCall(channel, "reply", fallbackStart, fallbackReceipt?.ok === false ? classifyDeliveryReceipt(fallbackReceipt) : void 0, _toolConversationFor(metadata));
10840
- if (fallbackReceipt?.ok !== false) turn.spoke = true;
12057
+ if (fallbackReceipt?.ok !== false) {
12058
+ turn.spoke = true;
12059
+ fileTurn?.replies.push(lastFilteredText);
12060
+ }
10841
12061
  replyCount++;
10842
12062
  totalReplyChars += lastFilteredText.length;
10843
12063
  if (!firstReplyTime) firstReplyTime = Date.now();
@@ -10923,7 +12143,7 @@ ${contextBody}`;
10923
12143
  }
10924
12144
  }, () => {
10925
12145
  attempt.expired = true;
10926
- }))));
12146
+ })))));
10927
12147
  }
10928
12148
  function _inferSpanType(name) {
10929
12149
  if (name === "error" || name.includes("error")) return "error";
@@ -10953,7 +12173,7 @@ function _emitChildSpan(channel, opts) {
10953
12173
  attributes: scrubUrlAttributes(opts.attributes),
10954
12174
  statusMessage: redactUrls(opts.statusMessage)
10955
12175
  };
10956
- const spanId = opts.spanId ?? randomBytes2(8).toString("hex");
12176
+ const spanId = opts.spanId ?? randomBytes3(8).toString("hex");
10957
12177
  reporter.reportCustomSpan({
10958
12178
  traceId: opts.traceId,
10959
12179
  spanId,
@@ -11075,7 +12295,8 @@ var agentVaultPlugin = {
11075
12295
  },
11076
12296
  // #1474: OpenClaw's word for a room is "group". 2026.10 refuses to start a
11077
12297
  // channel that declares a chat type outside direct/group/channel/thread.
11078
- capabilities: { chatTypes: ["direct", "group"] },
12298
+ // #1762 PR-O: media — files go through SecureChannel.sendFile (policy, turn token, no queue).
12299
+ capabilities: { chatTypes: ["direct", "group"], media: true },
11079
12300
  config: { listAccountIds, resolveAccount },
11080
12301
  // Tells OC core's resolveMessagingTarget that any plausible AgentVault target
11081
12302
  // string is an ID, short-circuiting the directory lookup that would otherwise
@@ -11144,13 +12365,15 @@ var agentVaultPlugin = {
11144
12365
  };
11145
12366
  abortSignal?.addEventListener("abort", () => void onAbort());
11146
12367
  import("./index.js").then(async ({ SecureChannel }) => {
12368
+ const fileWorkspace = await resolveOpenClawWorkspace(cfg, openclawAgentIdFor(cfg, account.accountId), osHomedir()).catch(() => void 0);
11147
12369
  channel = new SecureChannel({
11148
12370
  inviteToken: "",
11149
12371
  dataDir,
11150
12372
  apiUrl: account.apiUrl,
11151
12373
  agentName: account.agentName,
12374
+ fileSend: { ...fileWorkspace ? { workspaceDir: fileWorkspace } : {} },
11152
12375
  onMessage: _makeOnMessage({
11153
- inbound: ({ plaintext, metadata, turn }) => handleInbound({ plaintext, metadata, channel, account, cfg, turn }),
12376
+ inbound: ({ plaintext, metadata, turn, fileTurn }) => handleInbound({ plaintext, metadata, channel, account, cfg, turn, fileTurn }),
11154
12377
  getChannel: () => channel,
11155
12378
  isRuntimeReady: () => !!_ocRuntime,
11156
12379
  enqueue: (fn) => {
@@ -11347,8 +12570,7 @@ var agentVaultPlugin = {
11347
12570
  }
11348
12571
  const httpPort = account.httpPort ?? 18790;
11349
12572
  channel.on("ready", () => {
11350
- channel.startHttpServer(httpPort);
11351
- _log?.(`[AgentVault] HTTP send server listening on http://127.0.0.1:${httpPort}`);
12573
+ startLocalApiWithLog(channel, httpPort, (m2) => _log?.(m2));
11352
12574
  if (managedRoutesRequested) {
11353
12575
  _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
12576
  }
@@ -11400,36 +12622,55 @@ var agentVaultPlugin = {
11400
12622
  return { ok: false, error: String(err) };
11401
12623
  }
11402
12624
  },
11403
- sendMedia: async ({ to: rawTo, text, mediaUrl, accountId }) => {
12625
+ // #1762 PR-O (§2.1) — media from the `message` tool. The model names `to`;
12626
+ // the turn token of this call chain (ALS: OpenClaw calls the adapter inline
12627
+ // in the run) makes it equal the turn's own conversation, or the send is
12628
+ // refused. a2a / channel / context targets never take media. Roots are the
12629
+ // AgentVault roots ∩ ctx.mediaLocalRoots; a session with mediaReadFile /
12630
+ // mediaAccess counts as sandboxed (§2.1, N4). A file that did not go is a
12631
+ // THROW (see OpenClawFileSendError), never `{ok:false}`, which OpenClaw's
12632
+ // delivery core would show the model only as "suppressed".
12633
+ sendMedia: async (ctx) => {
12634
+ const { to: rawTo, text, mediaUrl, accountId } = ctx;
11404
12635
  const startedAt = Date.now();
11405
12636
  const resolvedId = accountId ?? "default";
11406
12637
  const ch = _channels.get(resolvedId);
11407
12638
  if (!ch) return { ok: false, error: "AgentVault channel not connected" };
11408
12639
  let target;
11409
12640
  try {
11410
- const message = text ? `${text}
11411
- ${mediaUrl}` : mediaUrl;
11412
12641
  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
12642
  } catch (err) {
11417
- _reportAvToolCall(ch, "message", startedAt, classifyToolError(err), conversationForTarget(target));
11418
- return { ok: false, error: String(err) };
12643
+ _reportAvToolCall(ch, "message", startedAt, classifyToolError(err), conversationForTarget(void 0));
12644
+ throw err;
11419
12645
  }
12646
+ const turnToken = ch.currentTurnToken?.() ?? null;
12647
+ const host = hostFromSendContext(ctx, await sandboxedForSend(ctx.cfg, resolvedId, turnToken));
12648
+ const res = await sendMediaPart(ch, target, mediaUrl, typeof text === "string" ? text : "", turnToken, host);
12649
+ _reportAvToolCall(ch, "message", startedAt, res.ok ? void 0 : res.code, conversationForTarget(target));
12650
+ if (!res.ok) throw new OpenClawFileSendError(res.code, mediaPartToolText(ch, target, res));
12651
+ return deliveredResult(void 0);
11420
12652
  },
11421
12653
  /** Rich payload delivery — OpenClaw v2026.3.2+ calls this for structured messages. */
11422
12654
  sendPayload: async (ctx) => {
11423
12655
  const { payload, accountId } = ctx;
11424
12656
  if (payload.isReasoning) return { ok: true };
11425
12657
  const text = (payload.text ?? "").trim();
11426
- if (!text && !payload.mediaUrls?.length) return { ok: true };
12658
+ const mediaRefs = mediaRefsOf(payload);
12659
+ if (!text && mediaRefs.length === 0) return { ok: true };
11427
12660
  const startedAt = Date.now();
11428
12661
  const resolvedId = accountId ?? "default";
11429
12662
  const ch = _channels.get(resolvedId);
11430
12663
  if (!ch) return { ok: false, error: "AgentVault channel not connected" };
11431
12664
  let failedKind;
12665
+ const failedMedia = [];
11432
12666
  let payloadConversation = conversationForTarget(void 0);
12667
+ const onDeliveryResult = typeof ctx.onDeliveryResult === "function" ? (r2) => {
12668
+ try {
12669
+ ctx.onDeliveryResult(r2);
12670
+ } catch {
12671
+ }
12672
+ } : () => {
12673
+ };
11433
12674
  try {
11434
12675
  requestHeartbeatNow({ reason: "outbound-payload" }).catch(() => {
11435
12676
  });
@@ -11443,14 +12684,24 @@ ${mediaUrl}` : mediaUrl;
11443
12684
  }
11444
12685
  const _send = async (msg) => {
11445
12686
  const receipt = await ch.deliver(target, { type: "text", text: msg });
11446
- if (receipt && receipt.ok === false && !failedKind) failedKind = classifyDeliveryReceipt(receipt);
12687
+ if (receipt && receipt.ok === false) {
12688
+ if (!failedKind) failedKind = classifyDeliveryReceipt(receipt);
12689
+ } else {
12690
+ onDeliveryResult(deliveredResult(void 0));
12691
+ }
11447
12692
  };
11448
12693
  if (text) {
11449
12694
  await _send(text);
11450
12695
  }
11451
- if (payload.mediaUrls?.length) {
11452
- for (const url of payload.mediaUrls) {
11453
- await _send(url);
12696
+ const turnToken = ch.currentTurnToken?.() ?? null;
12697
+ const host = hostFromSendContext(ctx, await sandboxedForSend(ctx.cfg, resolvedId, turnToken));
12698
+ for (const ref of mediaRefs) {
12699
+ const res = await sendMediaPart(ch, target, ref, "", turnToken, host);
12700
+ if (res.ok) {
12701
+ onDeliveryResult(deliveredResult(void 0));
12702
+ } else {
12703
+ failedMedia.push({ target, res });
12704
+ if (!failedKind) failedKind = res.code;
11454
12705
  }
11455
12706
  }
11456
12707
  if (payload.suggestedActions?.length) {
@@ -11458,12 +12709,17 @@ ${mediaUrl}` : mediaUrl;
11458
12709
  await _send(`Suggested actions:
11459
12710
  ${actionsText}`);
11460
12711
  }
11461
- _reportAvToolCall(ch, "message", startedAt, failedKind, payloadConversation);
11462
- return { ok: true };
11463
12712
  } catch (err) {
11464
12713
  _reportAvToolCall(ch, "message", startedAt, failedKind ?? classifyToolError(err), payloadConversation);
11465
12714
  return { ok: false, error: String(err) };
11466
12715
  }
12716
+ _reportAvToolCall(ch, "message", startedAt, failedKind, payloadConversation);
12717
+ if (failedMedia.length > 0) {
12718
+ const first = failedMedia[0];
12719
+ throw new OpenClawFileSendError(first.res.code, mediaPartToolText(ch, first.target, first.res));
12720
+ }
12721
+ if (failedKind) return { ok: false, error: failedKind };
12722
+ return deliveredResult(void 0);
11467
12723
  }
11468
12724
  }
11469
12725
  };
@@ -11475,6 +12731,8 @@ var openclaw_entry_default = {
11475
12731
  try {
11476
12732
  const compat = checkHarnessCompat();
11477
12733
  if (compat?.message) console.warn(compat.message);
12734
+ const suppression = commandSuppressionWarning(compat?.version ?? null);
12735
+ if (suppression) console.warn(suppression);
11478
12736
  } catch {
11479
12737
  }
11480
12738
  _setRuntime(api.runtime);
@@ -11501,7 +12759,7 @@ var openclaw_entry_default = {
11501
12759
  ch.sendActivitySpan({
11502
12760
  trace_id: report.traceId ?? "",
11503
12761
  parent_span_id: report.parentSpanId ?? "",
11504
- span_id: randomBytes2(8).toString("hex"),
12762
+ span_id: randomBytes3(8).toString("hex"),
11505
12763
  span_type: "http",
11506
12764
  span_name: hostname,
11507
12765
  status: report.statusCode >= 400 || report.statusCode === 0 ? "error" : "ok",
@@ -11541,7 +12799,7 @@ var openclaw_entry_default = {
11541
12799
  ch.sendActivitySpan({
11542
12800
  trace_id: report.traceId ?? "",
11543
12801
  parent_span_id: report.parentSpanId ?? "",
11544
- span_id: randomBytes2(8).toString("hex"),
12802
+ span_id: randomBytes3(8).toString("hex"),
11545
12803
  span_type: "llm",
11546
12804
  span_name: report.model,
11547
12805
  status: "ok",
@@ -11563,78 +12821,22 @@ var openclaw_entry_default = {
11563
12821
  api.registerChannel({ plugin: agentVaultPlugin });
11564
12822
  if (typeof api.registerHttpRoute === "function") {
11565
12823
  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
- });
12824
+ const allChannels = () => _channels.values();
12825
+ for (const [route, method] of [
12826
+ ["/send", "POST"],
12827
+ ["/action", "POST"],
12828
+ ["/decision", "POST"],
12829
+ ["/status", "GET"],
12830
+ ["/targets", "GET"],
12831
+ ["/mcp-config", "GET"]
12832
+ ]) {
12833
+ api.registerHttpRoute({
12834
+ path: `/agentvault${route}`,
12835
+ method,
12836
+ auth: "gateway",
12837
+ handler: managedLocalApiHandler(route, allChannels)
12838
+ });
12839
+ }
11638
12840
  managedRoutesRequested = true;
11639
12841
  } catch {
11640
12842
  }
@@ -11645,8 +12847,8 @@ var openclaw_entry_default = {
11645
12847
  const ch = _channels.values().next().value;
11646
12848
  if (!ch?.telemetry) return;
11647
12849
  ch.telemetry.reportCustomSpan({
11648
- traceId: randomBytes2(16).toString("hex"),
11649
- spanId: randomBytes2(8).toString("hex"),
12850
+ traceId: randomBytes3(16).toString("hex"),
12851
+ spanId: randomBytes3(8).toString("hex"),
11650
12852
  name: "agentvault.message.delivered",
11651
12853
  kind: "internal",
11652
12854
  startTime: event.timestamp,
@@ -11669,8 +12871,8 @@ var openclaw_entry_default = {
11669
12871
  const ch = _channels.values().next().value;
11670
12872
  if (!ch?.telemetry) return;
11671
12873
  ch.telemetry.reportCustomSpan({
11672
- traceId: randomBytes2(16).toString("hex"),
11673
- spanId: randomBytes2(8).toString("hex"),
12874
+ traceId: randomBytes3(16).toString("hex"),
12875
+ spanId: randomBytes3(8).toString("hex"),
11674
12876
  name: "agentvault.session.start",
11675
12877
  kind: "internal",
11676
12878
  startTime: event.timestamp,
@@ -11689,8 +12891,8 @@ var openclaw_entry_default = {
11689
12891
  const ch = _channels.values().next().value;
11690
12892
  if (!ch?.telemetry) return;
11691
12893
  ch.telemetry.reportCustomSpan({
11692
- traceId: randomBytes2(16).toString("hex"),
11693
- spanId: randomBytes2(8).toString("hex"),
12894
+ traceId: randomBytes3(16).toString("hex"),
12895
+ spanId: randomBytes3(8).toString("hex"),
11694
12896
  name: "agentvault.session.end",
11695
12897
  kind: "internal",
11696
12898
  startTime: event.timestamp,
@@ -11804,18 +13006,23 @@ export {
11804
13006
  _inboundRetryDelayMs,
11805
13007
  _looksLikeReasoningLeak,
11806
13008
  _makeOnMessage,
13009
+ _notReadyBound,
11807
13010
  owesRoomReply as _owesRoomReply,
11808
13011
  parseMentions as _parseMentions,
11809
13012
  _reportAvToolCall,
13013
+ _resetRoomTaintsForTest,
11810
13014
  _resolveRoomIdentity,
11811
13015
  _roomRecordReply,
11812
13016
  _roomReplyAllowed,
11813
13017
  _selectInboundPreamble,
13018
+ _setTurnBudgetMsForTest,
13019
+ _shortRoomLabel,
11814
13020
  _shutdownNotices,
11815
13021
  stripCaptionMentions as _stripCaptionMentions,
11816
13022
  stripMentions as _stripMentions,
11817
13023
  _stripThinkBlocks,
11818
13024
  _toolConversationFor,
13025
+ _turnRuns,
11819
13026
  _withSessionSerial,
11820
13027
  _withTurnTimeout,
11821
13028
  openclaw_entry_default as default,