@agentunion/fastaun-browser 0.5.14 → 0.5.16

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 (50) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/_packed_docs/CHANGELOG.md +44 -0
  3. package/_packed_docs/agent.md/SCHEMA.md +15 -8
  4. package/_packed_docs/aun/345/210/206/345/270/203/345/274/217/346/265/213/350/257/225/350/277/220/350/241/214/346/214/207/345/215/227.md +85 -4
  5. package/_packed_docs/aun/346/265/213/350/257/225/350/277/220/350/241/214/346/214/207/345/215/227.md +1 -1
  6. package/dist/agent-md-schema.d.ts.map +1 -1
  7. package/dist/agent-md-schema.js +6 -0
  8. package/dist/agent-md-schema.js.map +1 -1
  9. package/dist/agent-md.d.ts +1 -0
  10. package/dist/agent-md.d.ts.map +1 -1
  11. package/dist/agent-md.js +2 -0
  12. package/dist/agent-md.js.map +1 -1
  13. package/dist/bundle.js +421 -264
  14. package/dist/client/delivery.d.ts.map +1 -1
  15. package/dist/client/delivery.js +2 -4
  16. package/dist/client/delivery.js.map +1 -1
  17. package/dist/client/lifecycle.d.ts.map +1 -1
  18. package/dist/client/lifecycle.js +5 -1
  19. package/dist/client/lifecycle.js.map +1 -1
  20. package/dist/client/rpc-pipeline.d.ts +1 -0
  21. package/dist/client/rpc-pipeline.d.ts.map +1 -1
  22. package/dist/client/rpc-pipeline.js +10 -8
  23. package/dist/client/rpc-pipeline.js.map +1 -1
  24. package/dist/client/v2-e2ee.d.ts.map +1 -1
  25. package/dist/client/v2-e2ee.js +24 -13
  26. package/dist/client/v2-e2ee.js.map +1 -1
  27. package/dist/client.d.ts.map +1 -1
  28. package/dist/client.js +46 -28
  29. package/dist/client.js.map +1 -1
  30. package/dist/events.d.ts +25 -12
  31. package/dist/events.d.ts.map +1 -1
  32. package/dist/events.js +164 -79
  33. package/dist/events.js.map +1 -1
  34. package/dist/group-index.js +1 -1
  35. package/dist/group-index.js.map +1 -1
  36. package/dist/logger.d.ts +9 -1
  37. package/dist/logger.d.ts.map +1 -1
  38. package/dist/logger.js +29 -7
  39. package/dist/logger.js.map +1 -1
  40. package/dist/result.d.ts +1 -2
  41. package/dist/result.d.ts.map +1 -1
  42. package/dist/result.js +2 -2
  43. package/dist/result.js.map +1 -1
  44. package/dist/transport.d.ts +5 -1
  45. package/dist/transport.d.ts.map +1 -1
  46. package/dist/transport.js +57 -32
  47. package/dist/transport.js.map +1 -1
  48. package/dist/version.d.ts +1 -1
  49. package/dist/version.js +1 -1
  50. package/package.json +1 -1
package/dist/bundle.js CHANGED
@@ -460,7 +460,7 @@ var init_indexeddb_store = __esm({
460
460
  });
461
461
 
462
462
  // src/version.ts
463
- var VERSION = "0.5.13";
463
+ var VERSION = "0.5.16";
464
464
 
465
465
  // src/types.ts
466
466
  var ConnectionState = /* @__PURE__ */ ((ConnectionState2) => {
@@ -778,36 +778,59 @@ var _noopLog = { error: () => {
778
778
  }, info: () => {
779
779
  }, debug: () => {
780
780
  } };
781
+ function createQueueState() {
782
+ return {
783
+ handlers: /* @__PURE__ */ new Map(),
784
+ queue: [],
785
+ draining: false,
786
+ drainScheduled: false,
787
+ handlerDepth: 0,
788
+ synchronousHandlerDepth: 0,
789
+ drainPromise: null,
790
+ drainResolve: null,
791
+ closing: false,
792
+ closed: false
793
+ };
794
+ }
795
+ function cloneEventPayload(value) {
796
+ if (Array.isArray(value)) return value.map((item) => cloneEventPayload(item));
797
+ if (value instanceof Error) {
798
+ const error = value;
799
+ const rawCode = error.localCode ?? error.stringCode ?? error.code;
800
+ const code = rawCode === void 0 || rawCode === null || rawCode === "" || rawCode === -1 ? "INTERNAL_ERROR" : rawCode;
801
+ return { code, message: error.message || error.name };
802
+ }
803
+ if (value !== null && typeof value === "object") {
804
+ const clone = {};
805
+ for (const [key, item] of Object.entries(value)) clone[key] = cloneEventPayload(item);
806
+ return clone;
807
+ }
808
+ return value;
809
+ }
781
810
  var Subscription = class {
782
- constructor(dispatcher, event, handler) {
811
+ constructor(dispatcher, event, handler, protocol = false) {
783
812
  __publicField(this, "_dispatcher");
784
813
  __publicField(this, "_event");
785
814
  __publicField(this, "_handler");
815
+ __publicField(this, "_protocol");
786
816
  __publicField(this, "_active", true);
787
817
  this._dispatcher = dispatcher;
788
818
  this._event = event;
789
819
  this._handler = handler;
820
+ this._protocol = protocol;
790
821
  }
791
822
  /** 取消订阅 */
792
823
  unsubscribe() {
793
824
  if (!this._active) return;
794
- this._dispatcher.unsubscribe(this._event, this._handler);
825
+ this._dispatcher.unsubscribe(this._event, this._handler, this._protocol);
795
826
  this._active = false;
796
827
  }
797
828
  };
798
829
  var EventDispatcher = class {
799
830
  constructor() {
800
831
  __publicField(this, "_log", _noopLog);
801
- __publicField(this, "_handlers", /* @__PURE__ */ new Map());
802
- __publicField(this, "_queue", []);
803
- __publicField(this, "_draining", false);
804
- __publicField(this, "_drainScheduled", false);
805
- __publicField(this, "_handlerDepth", 0);
806
- __publicField(this, "_synchronousHandlerDepth", 0);
807
- __publicField(this, "_drainPromise", null);
808
- __publicField(this, "_drainResolve", null);
809
- __publicField(this, "_closing", false);
810
- __publicField(this, "_closed", false);
832
+ __publicField(this, "_app", createQueueState());
833
+ __publicField(this, "_protocol", createQueueState());
811
834
  }
812
835
  setLogger(log) {
813
836
  this._log = log;
@@ -820,99 +843,148 @@ var EventDispatcher = class {
820
843
  * 对象调用 unsubscribe() 来取消。
821
844
  */
822
845
  subscribe(event, handler) {
823
- const list = this._handlers.get(event) ?? [];
846
+ return this._subscribe(this._app, event, handler, false);
847
+ }
848
+ /** 订阅 SDK 内部协议事件。 */
849
+ subscribeProtocol(event, handler) {
850
+ return this._subscribe(this._protocol, event, handler, true);
851
+ }
852
+ _subscribe(state, event, handler, protocol) {
853
+ const list = state.handlers.get(event) ?? [];
824
854
  list.push(handler);
825
- this._handlers.set(event, list);
826
- return new Subscription(this, event, handler);
855
+ state.handlers.set(event, list);
856
+ return new Subscription(this, event, handler, protocol);
827
857
  }
828
858
  /** 取消订阅 */
829
- unsubscribe(event, handler) {
830
- const list = this._handlers.get(event);
859
+ unsubscribe(event, handler, protocol = false) {
860
+ const state = protocol ? this._protocol : this._app;
861
+ const list = state.handlers.get(event);
831
862
  if (!list) return;
832
863
  const filtered = list.filter((h) => h !== handler);
833
864
  if (filtered.length > 0) {
834
- this._handlers.set(event, filtered);
865
+ state.handlers.set(event, filtered);
835
866
  } else {
836
- this._handlers.delete(event);
867
+ state.handlers.delete(event);
837
868
  }
838
869
  }
870
+ /** 取消协议事件订阅。 */
871
+ unsubscribeProtocol(event, handler) {
872
+ this.unsubscribe(event, handler, true);
873
+ }
839
874
  /**
840
875
  * 发布事件。事件总是异步进入 FIFO 队列;调用方 await 时等待该事件处理完成。
841
876
  * drain 中派生事件只入队,不等待自身,避免事件处理器互相等待形成死锁。
842
877
  */
843
878
  async publish(event, payload) {
844
- if (this._closed || this._closing) return;
879
+ await this._publish(this._app, event, payload);
880
+ }
881
+ /** 发布协议事件。调用方 await 时等待协议处理完成。 */
882
+ async publishProtocol(event, payload) {
883
+ await this._publish(this._protocol, event, payload);
884
+ }
885
+ async _publish(state, event, payload) {
886
+ if (state.closed || state.closing) return;
845
887
  let resolveItem;
846
888
  const itemDone = new Promise((resolve) => {
847
889
  resolveItem = resolve;
848
890
  });
849
- this._queue.push({
850
- run: () => this.dispatchNow(event, payload),
891
+ state.queue.push({
892
+ run: () => this.dispatchNow(state, event, payload),
851
893
  resolve: resolveItem
852
894
  });
853
- if (this._handlerDepth > 0) return;
854
- if (this._drainPromise === null) {
855
- this._drainPromise = new Promise((resolve) => {
856
- this._drainResolve = resolve;
895
+ if (state.handlerDepth > 0) return;
896
+ if (state.drainPromise === null) {
897
+ state.drainPromise = new Promise((resolve) => {
898
+ state.drainResolve = resolve;
857
899
  });
858
900
  }
859
- this.scheduleDrain();
901
+ this.scheduleDrain(state);
902
+ if (state === this._app && this._protocol.handlerDepth > 0) return;
860
903
  await itemDone;
861
904
  }
862
905
  /** 将事件放入异步 FIFO 队列,不等待处理器执行完成。 */
863
906
  enqueue(event, payload) {
864
- void this.publish(event, payload).catch((exc) => {
907
+ this._enqueue(this._app, event, payload);
908
+ }
909
+ /** 将协议事件放入独立异步 FIFO 队列,不等待处理器执行完成。 */
910
+ enqueueProtocol(event, payload) {
911
+ this._enqueue(this._protocol, event, payload);
912
+ }
913
+ _enqueue(state, event, payload) {
914
+ const publish = state === this._protocol ? this.publishProtocol(event, payload) : this.publish(event, payload);
915
+ void publish.catch((exc) => {
865
916
  this._log.warn(`event ${event} enqueue failed:`, exc);
866
917
  });
867
918
  }
868
919
  /** 将非事件 observer 放入同一 FIFO 队列。 */
869
920
  enqueueTask(task) {
870
- if (this._closed || this._closing) return;
871
- this._queue.push({
872
- run: () => this.dispatchTask(task),
921
+ this._enqueueTask(this._app, task);
922
+ }
923
+ /** 将协议层 observer 放入协议 FIFO 队列。 */
924
+ enqueueProtocolTask(task) {
925
+ this._enqueueTask(this._protocol, task);
926
+ }
927
+ _enqueueTask(state, task) {
928
+ if (state.closed || state.closing) return;
929
+ state.queue.push({
930
+ run: () => this.dispatchTask(state, task),
873
931
  resolve: () => {
874
932
  }
875
933
  });
876
- if (this._drainPromise === null) {
877
- this._drainPromise = new Promise((resolve) => {
878
- this._drainResolve = resolve;
934
+ if (state.drainPromise === null) {
935
+ state.drainPromise = new Promise((resolve) => {
936
+ state.drainResolve = resolve;
879
937
  });
880
938
  }
881
- this.scheduleDrain();
939
+ this.scheduleDrain(state);
882
940
  }
883
941
  /** 关闭调度器,排空已经入队的应用事件后拒绝后续事件。 */
884
942
  async close() {
885
- if (this._closed) return;
886
- this._closing = true;
887
- if (this._synchronousHandlerDepth > 0) return;
888
- if (this._drainPromise !== null) await this._drainPromise;
889
- this.finishClose();
943
+ await this._close(this._app);
944
+ }
945
+ /** 关闭协议调度器,排空已经入队的协议事件后拒绝后续事件。 */
946
+ async closeProtocol() {
947
+ await this._close(this._protocol);
948
+ }
949
+ async _close(state) {
950
+ if (state.closed) return;
951
+ state.closing = true;
952
+ if (state.synchronousHandlerDepth > 0) return;
953
+ if (state.drainPromise !== null) await state.drainPromise;
954
+ this.finishClose(state);
890
955
  }
891
956
  /** 等待当前队列排空;事件 handler 重入时直接返回,避免自等待。 */
892
957
  async flush() {
893
- if (this._synchronousHandlerDepth > 0) return;
894
- if (this._drainPromise !== null) await this._drainPromise;
958
+ await this._flush(this._app);
959
+ }
960
+ /** 等待协议层当前队列排空。 */
961
+ async flushProtocol() {
962
+ await this._flush(this._protocol);
963
+ }
964
+ async _flush(state) {
965
+ if (state.synchronousHandlerDepth > 0) return;
966
+ if (state.drainPromise !== null) await state.drainPromise;
895
967
  await Promise.resolve();
896
968
  }
897
- finishClose() {
898
- if (!this._closing || this._closed || this._draining || this._drainScheduled || this._queue.length > 0) return;
899
- this._closed = true;
900
- this._handlers.clear();
969
+ finishClose(state) {
970
+ if (!state.closing || state.closed || state.draining || state.drainScheduled || state.queue.length > 0) return;
971
+ state.closed = true;
972
+ state.handlers.clear();
901
973
  }
902
- scheduleDrain() {
903
- if (this._draining || this._drainScheduled || this._queue.length === 0) return;
904
- this._drainScheduled = true;
974
+ scheduleDrain(state) {
975
+ if (state.draining || state.drainScheduled || state.queue.length === 0) return;
976
+ state.drainScheduled = true;
905
977
  queueMicrotask(() => {
906
- this._drainScheduled = false;
907
- void this._drain();
978
+ state.drainScheduled = false;
979
+ void this._drain(state);
908
980
  });
909
981
  }
910
- async _drain() {
911
- if (this._draining) return;
912
- this._draining = true;
982
+ async _drain(state) {
983
+ if (state.draining) return;
984
+ state.draining = true;
913
985
  try {
914
- while (this._queue.length > 0) {
915
- const item = this._queue.shift();
986
+ while (state.queue.length > 0) {
987
+ const item = state.queue.shift();
916
988
  try {
917
989
  await item.run();
918
990
  } catch (exc) {
@@ -922,70 +994,74 @@ var EventDispatcher = class {
922
994
  }
923
995
  }
924
996
  } finally {
925
- this._draining = false;
926
- const resolve = this._drainResolve;
927
- this._drainResolve = null;
928
- this._drainPromise = null;
997
+ state.draining = false;
998
+ const resolve = state.drainResolve;
999
+ state.drainResolve = null;
1000
+ state.drainPromise = null;
929
1001
  resolve?.();
930
- this.finishClose();
931
- if (this._queue.length > 0 && !this._closed) {
932
- if (this._drainPromise === null) {
933
- this._drainPromise = new Promise((nextResolve) => {
934
- this._drainResolve = nextResolve;
1002
+ this.finishClose(state);
1003
+ if (state.queue.length > 0 && !state.closed) {
1004
+ if (state.drainPromise === null) {
1005
+ state.drainPromise = new Promise((nextResolve) => {
1006
+ state.drainResolve = nextResolve;
935
1007
  });
936
1008
  }
937
- this.scheduleDrain();
1009
+ this.scheduleDrain(state);
938
1010
  }
939
1011
  }
940
1012
  }
941
1013
  /** 当前是否正在调用应用 handler 或 observer。供生命周期入口识别重入。 */
942
1014
  isDispatchingHandler() {
943
- return this._handlerDepth > 0;
1015
+ return this._app.handlerDepth > 0 || this._protocol.handlerDepth > 0;
944
1016
  }
945
- async dispatchTask(task) {
1017
+ async dispatchTask(state, task) {
946
1018
  let result;
947
- this._handlerDepth += 1;
1019
+ state.handlerDepth += 1;
948
1020
  try {
949
- this._synchronousHandlerDepth += 1;
1021
+ state.synchronousHandlerDepth += 1;
950
1022
  result = task();
951
1023
  } catch (exc) {
952
1024
  this._log.warn("event task execution exception:", exc);
953
- this._handlerDepth -= 1;
1025
+ state.handlerDepth -= 1;
954
1026
  return;
955
1027
  } finally {
956
- this._synchronousHandlerDepth -= 1;
1028
+ state.synchronousHandlerDepth -= 1;
957
1029
  }
958
1030
  try {
959
1031
  await result;
960
1032
  } catch (exc) {
961
1033
  this._log.warn("event task execution exception:", exc);
962
1034
  } finally {
963
- this._handlerDepth -= 1;
1035
+ state.handlerDepth -= 1;
964
1036
  }
965
1037
  }
966
- async dispatchNow(event, payload) {
967
- const handlers = [...this._handlers.get(event) ?? []];
1038
+ async dispatchNow(state, event, payload) {
1039
+ const handlers = [...state.handlers.get(event) ?? []];
1040
+ const applicationPayload = state === this._protocol && this._app.handlers.has(event) ? cloneEventPayload(payload) : void 0;
968
1041
  for (const handler of handlers) {
969
1042
  let result;
970
- this._handlerDepth += 1;
1043
+ state.handlerDepth += 1;
971
1044
  try {
972
- this._synchronousHandlerDepth += 1;
1045
+ state.synchronousHandlerDepth += 1;
973
1046
  result = handler(payload);
974
1047
  } catch (exc) {
975
1048
  this._log.warn(`event ${event} handler execution exception:`, exc);
976
- this._handlerDepth -= 1;
1049
+ state.handlerDepth -= 1;
977
1050
  continue;
978
1051
  } finally {
979
- this._synchronousHandlerDepth -= 1;
1052
+ state.synchronousHandlerDepth -= 1;
980
1053
  }
981
1054
  try {
982
1055
  await result;
983
1056
  } catch (exc) {
984
1057
  this._log.warn(`event ${event} handler execution exception:`, exc);
985
1058
  } finally {
986
- this._handlerDepth -= 1;
1059
+ state.handlerDepth -= 1;
987
1060
  }
988
1061
  }
1062
+ if (applicationPayload !== void 0) {
1063
+ this.enqueue(event, applicationPayload);
1064
+ }
989
1065
  }
990
1066
  };
991
1067
 
@@ -1292,6 +1368,119 @@ var GatewayDiscovery = class {
1292
1368
  }
1293
1369
  };
1294
1370
 
1371
+ // src/logger.ts
1372
+ function trafficLogContext(direction, data) {
1373
+ const params2 = data && typeof data === "object" && !Array.isArray(data) ? data : {};
1374
+ const target = params2.target && typeof params2.target === "object" ? params2.target : {};
1375
+ const notify = params2._notify && typeof params2._notify === "object" ? params2._notify : {};
1376
+ const text3 = (value) => typeof value === "string" ? value.trim() : "";
1377
+ const group = text3(params2.group_aid) || text3(params2.group_id) || text3(target.group_aid) || text3(target.group_id);
1378
+ const groupAid = normalizeGroupAid(group);
1379
+ const peerAid = group ? groupAid.includes(".") && !groupAid.includes("/") ? groupAid : "" : direction === "outbound" ? text3(target.aid) || text3(params2.to) || text3(params2.to_aid) || text3(params2.peer_aid) : text3(notify.from_aid) || text3(params2.from_aid) || text3(params2.sender_aid) || text3(params2.from);
1380
+ return { direction, peerAid };
1381
+ }
1382
+ function withLogContext(logger, context) {
1383
+ return logger.withContext?.(context) ?? logger;
1384
+ }
1385
+ var LEVEL_ORDER = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3 };
1386
+ function formatMessage(template, args) {
1387
+ if (args.length === 0) return template;
1388
+ let i = 0;
1389
+ let result = "";
1390
+ let consumed = 0;
1391
+ for (let p = 0; p < template.length; p++) {
1392
+ const ch = template[p];
1393
+ if (ch === "%" && template[p + 1] === "s" && i < args.length) {
1394
+ result += String(args[i++]);
1395
+ consumed++;
1396
+ p++;
1397
+ } else {
1398
+ result += ch;
1399
+ }
1400
+ }
1401
+ if (i < args.length) {
1402
+ const tail = args.slice(i).map((a) => a instanceof Error ? a.message : String(a)).join(" ");
1403
+ if (tail) result += " " + tail;
1404
+ }
1405
+ return result;
1406
+ }
1407
+ var AUNLogger = class {
1408
+ constructor(opts) {
1409
+ __publicField(this, "_debug");
1410
+ __publicField(this, "_aunPath");
1411
+ __publicField(this, "_deviceId", "-");
1412
+ __publicField(this, "_aid", null);
1413
+ __publicField(this, "_minLevel");
1414
+ this._debug = opts.debug;
1415
+ this._aunPath = String(opts.aunPath || "-");
1416
+ this._minLevel = this._debug ? LEVEL_ORDER.DEBUG : LEVEL_ORDER.INFO;
1417
+ }
1418
+ for(module, context) {
1419
+ const snapshot = context ? { ...context, aid: context.aid ?? this._aid ?? "" } : void 0;
1420
+ return {
1421
+ error: (msg, ...args) => this._emit("ERROR", module, msg, args, snapshot),
1422
+ warn: (msg, ...args) => this._emit("WARN", module, msg, args, snapshot),
1423
+ info: (msg, ...args) => this._emit("INFO", module, msg, args, snapshot),
1424
+ debug: (msg, ...args) => this._emit("DEBUG", module, msg, args, snapshot),
1425
+ isDebugEnabled: () => this.isDebugEnabled(),
1426
+ withContext: (next) => this.for(module, { ...next, aid: next.aid ?? snapshot?.aid })
1427
+ };
1428
+ }
1429
+ isDebugEnabled() {
1430
+ return this._debug && this._minLevel <= LEVEL_ORDER.DEBUG;
1431
+ }
1432
+ bindAid(aid) {
1433
+ this._aid = aid || null;
1434
+ }
1435
+ bindDeviceId(deviceId) {
1436
+ this._deviceId = String(deviceId || "").trim() || "-";
1437
+ }
1438
+ close() {
1439
+ }
1440
+ _emit(level, module, msg, args, context) {
1441
+ if (LEVEL_ORDER[level] < this._minLevel) return;
1442
+ if (level === "DEBUG" && !this._debug) return;
1443
+ const { date, time, ms } = this._now();
1444
+ const head = `[${date} ${time}.${ms}][${level}][${module}][aun_path=${this._aunPath || "-"}][device_id=${this._deviceId || "-"}]`;
1445
+ const aidPart = context ? ` [${context.aid || "-"} ${context.direction === "outbound" ? "->" : "<-"} ${context.peerAid || "-"}]` : this._aid ? ` [${this._aid}]` : "";
1446
+ const formatted = formatMessage(msg, args);
1447
+ const line = `${head}${aidPart} ${formatted}`;
1448
+ let errArg;
1449
+ for (let i = args.length - 1; i >= 0; i--) {
1450
+ if (args[i] instanceof Error) {
1451
+ errArg = args[i];
1452
+ break;
1453
+ }
1454
+ }
1455
+ switch (level) {
1456
+ case "ERROR":
1457
+ if (errArg) {
1458
+ console.error(line, errArg);
1459
+ } else {
1460
+ console.error(line);
1461
+ }
1462
+ break;
1463
+ case "WARN":
1464
+ console.warn(line);
1465
+ break;
1466
+ case "INFO":
1467
+ console.info(line);
1468
+ break;
1469
+ case "DEBUG":
1470
+ console.debug(line);
1471
+ break;
1472
+ }
1473
+ }
1474
+ _now() {
1475
+ const d = /* @__PURE__ */ new Date();
1476
+ const pad = (n, w = 2) => String(n).padStart(w, "0");
1477
+ const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
1478
+ const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
1479
+ const ms = pad(d.getMilliseconds(), 3);
1480
+ return { date, time, ms };
1481
+ }
1482
+ };
1483
+
1295
1484
  // src/transport.ts
1296
1485
  var MAX_WS_PAYLOAD_SIZE = 1e6;
1297
1486
  var MAX_RPC_INFLIGHT = 16;
@@ -1835,6 +2024,7 @@ var RPCTransport = class {
1835
2024
  __publicField(this, "_timeout");
1836
2025
  __publicField(this, "_connectTimeout");
1837
2026
  __publicField(this, "_onDisconnect");
2027
+ __publicField(this, "_onDisconnectIsProtocol", false);
1838
2028
  __publicField(this, "_ws", null);
1839
2029
  __publicField(this, "_closed", true);
1840
2030
  __publicField(this, "_lastCloseCode", null);
@@ -1852,6 +2042,7 @@ var RPCTransport = class {
1852
2042
  // Gateway 在 RPC envelope 注入 _meta 字段(与 result 同级),由 client 层 observer 接收。
1853
2043
  // 注入失败 / 字段缺失时 observer 不会被调用,不影响业务路径。
1854
2044
  __publicField(this, "_metaObserver", null);
2045
+ __publicField(this, "_metaObserverIsProtocol", false);
1855
2046
  // Trace 模式:off / log / diag
1856
2047
  __publicField(this, "_traceMode", "off");
1857
2048
  // Trace observer:observer(traceInfo) 在每次 RPC/事件携带 _trace 时调用
@@ -1861,13 +2052,17 @@ var RPCTransport = class {
1861
2052
  __publicField(this, "_actorTail", Promise.resolve());
1862
2053
  __publicField(this, "_actorBusy", false);
1863
2054
  this._dispatcher = opts.eventDispatcher;
1864
- this._timeout = opts.timeout ?? 10;
2055
+ this._timeout = opts.timeout ?? 35;
1865
2056
  this._connectTimeout = opts.timeout ?? 10;
1866
2057
  this._onDisconnect = opts.onDisconnect ?? null;
1867
2058
  }
1868
2059
  setLogger(log) {
1869
2060
  this._log = log;
1870
2061
  }
2062
+ setProtocolDisconnectCallback(callback) {
2063
+ this._onDisconnect = callback;
2064
+ this._onDisconnectIsProtocol = true;
2065
+ }
1871
2066
  /** 设置默认超时(秒) */
1872
2067
  setTimeout(timeout) {
1873
2068
  this._timeout = timeout;
@@ -1888,19 +2083,26 @@ var RPCTransport = class {
1888
2083
  */
1889
2084
  setMetaObserver(observer) {
1890
2085
  this._metaObserver = observer;
2086
+ this._metaObserverIsProtocol = false;
2087
+ }
2088
+ setProtocolMetaObserver(observer) {
2089
+ this._metaObserver = observer;
2090
+ this._metaObserverIsProtocol = true;
1891
2091
  }
1892
2092
  _notifyMetaObserver(message) {
1893
2093
  const observer = this._metaObserver;
1894
2094
  if (observer === null) return;
1895
2095
  const meta = message._meta;
1896
2096
  if (!isJsonObject(meta)) return;
1897
- this._dispatcher.enqueueTask(async () => {
2097
+ const task = async () => {
1898
2098
  try {
1899
2099
  await observer(meta);
1900
2100
  } catch (exc) {
1901
2101
  this._log.debug(`meta_observer raised: ${String(exc)}`);
1902
2102
  }
1903
- });
2103
+ };
2104
+ if (this._metaObserverIsProtocol) this._dispatcher.enqueueProtocolTask(task);
2105
+ else this._dispatcher.enqueueTask(task);
1904
2106
  }
1905
2107
  /** 设置 trace 模式:off / log / diag */
1906
2108
  setTraceMode(mode) {
@@ -2170,6 +2372,9 @@ var RPCTransport = class {
2170
2372
  const localParams = sendParams;
2171
2373
  const backgroundRpc = background || localParams._rpc_background === true;
2172
2374
  delete localParams._rpc_background;
2375
+ const requestContext = trafficLogContext("outbound", sendParams);
2376
+ const requestLog = withLogContext(this._log, requestContext);
2377
+ const responseLog = withLogContext(requestLog, { direction: "inbound", peerAid: requestContext.peerAid });
2173
2378
  if (effectiveTraceMode !== "off") {
2174
2379
  traceId = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID().replace(/-/g, "") : Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
2175
2380
  const tracePayload = { trace_id: traceId, mode: effectiveTraceMode };
@@ -2177,7 +2382,7 @@ var RPCTransport = class {
2177
2382
  tracePayload.spans = [{ node: "sdk", ts: tStart, action: "send" }];
2178
2383
  }
2179
2384
  localParams._trace = tracePayload;
2180
- this._log.info(`[trace=${traceId}] rpc_send method=${method} rpc_id=${rpcId}`);
2385
+ requestLog.info(`[trace=${traceId}] rpc_send method=${method} rpc_id=${rpcId}`);
2181
2386
  }
2182
2387
  const payload = JSON.stringify({
2183
2388
  jsonrpc: "2.0",
@@ -2193,7 +2398,7 @@ var RPCTransport = class {
2193
2398
  const promise = new Promise((resolve, reject) => {
2194
2399
  const timer = globalThis.setTimeout(() => {
2195
2400
  this._removeRpc(rpcId, pending);
2196
- this._log.warn(`RPC timeout: method=${method}, id=${rpcId}, elapsed=${Date.now() - tStart}ms, timeout=${effectiveTimeout}ms`);
2401
+ requestLog.warn(`RPC timeout: method=${method}, id=${rpcId}, elapsed=${Date.now() - tStart}ms, timeout=${effectiveTimeout}ms`);
2197
2402
  reject(new TimeoutError(`rpc timeout: ${method}`, { retryable: true }));
2198
2403
  this._drainRpcQueue();
2199
2404
  }, effectiveTimeout);
@@ -2202,28 +2407,28 @@ var RPCTransport = class {
2202
2407
  clearTimeout(timer);
2203
2408
  const elapsed = Date.now() - tStart;
2204
2409
  if (response.error !== void 0) {
2205
- this._log.debug(`RPC error response: method=${method}, id=${rpcId}, elapsed=${elapsed}ms, error=${JSON.stringify(response.error)}`);
2410
+ responseLog.debug(`RPC error response: method=${method}, id=${rpcId}, elapsed=${elapsed}ms, error=${JSON.stringify(response.error)}`);
2206
2411
  if (traceId) {
2207
- this._log.info(`[trace=${traceId}] rpc_recv method=${method} rpc_id=${rpcId} duration_ms=${elapsed} status=error`);
2412
+ responseLog.info(`[trace=${traceId}] rpc_recv method=${method} rpc_id=${rpcId} duration_ms=${elapsed} status=error`);
2208
2413
  }
2209
2414
  const respTrace = response._trace;
2210
2415
  if (respTrace && typeof respTrace === "object" && !Array.isArray(respTrace)) {
2211
- this._handleResponseTrace(method, "error", elapsed, respTrace);
2416
+ this._handleResponseTrace(method, "error", elapsed, respTrace, responseLog);
2212
2417
  }
2213
2418
  reject(mapRemoteError(response.error));
2214
2419
  } else if (response.result !== void 0) {
2215
- this._log.debug(`RPC response ok: method=${method}, id=${rpcId}, elapsed=${elapsed}ms ${summarizeDict(response.result, DIAG_RESULT_FIELDS)}`);
2420
+ responseLog.debug(`RPC response ok: method=${method}, id=${rpcId}, elapsed=${elapsed}ms ${summarizeDict(response.result, DIAG_RESULT_FIELDS)}`);
2216
2421
  if (traceId) {
2217
- this._log.info(`[trace=${traceId}] rpc_recv method=${method} rpc_id=${rpcId} duration_ms=${elapsed} status=ok`);
2422
+ responseLog.info(`[trace=${traceId}] rpc_recv method=${method} rpc_id=${rpcId} duration_ms=${elapsed} status=ok`);
2218
2423
  }
2219
2424
  this._notifyMetaObserver(response);
2220
2425
  const respTrace = response._trace;
2221
2426
  if (respTrace && typeof respTrace === "object" && !Array.isArray(respTrace)) {
2222
- this._handleResponseTrace(method, "ok", elapsed, respTrace);
2427
+ this._handleResponseTrace(method, "ok", elapsed, respTrace, responseLog);
2223
2428
  }
2224
2429
  resolve(response.result);
2225
2430
  } else {
2226
- this._log.warn(`RPC response missing result or error: method=${method}, id=${rpcId}, elapsed=${elapsed}ms`);
2431
+ responseLog.warn(`RPC response missing result or error: method=${method}, id=${rpcId}, elapsed=${elapsed}ms`);
2227
2432
  reject(new SerializationError(`rpc response missing result and error: ${method}`));
2228
2433
  }
2229
2434
  },
@@ -2246,7 +2451,8 @@ var RPCTransport = class {
2246
2451
  pending,
2247
2452
  tStart,
2248
2453
  timeoutMs: effectiveTimeout,
2249
- background: true
2454
+ background: true,
2455
+ logger: requestLog
2250
2456
  });
2251
2457
  } else {
2252
2458
  this._rpcQueue.push({
@@ -2256,7 +2462,8 @@ var RPCTransport = class {
2256
2462
  pending,
2257
2463
  tStart,
2258
2464
  timeoutMs: effectiveTimeout,
2259
- background: false
2465
+ background: false,
2466
+ logger: requestLog
2260
2467
  });
2261
2468
  }
2262
2469
  this._drainRpcQueue();
@@ -2287,8 +2494,9 @@ var RPCTransport = class {
2287
2494
  if (payloadSize > MAX_WS_PAYLOAD_SIZE) {
2288
2495
  throw new ValidationError("payload is too large");
2289
2496
  }
2497
+ const notifyLog = withLogContext(this._log, trafficLogContext("outbound", params2 ?? {}));
2290
2498
  await this._sendText(payload, `notification ${normalizedMethod}`);
2291
- this._log.debug(`notification sent: method=${normalizedMethod}, size=${payloadSize}`);
2499
+ notifyLog.debug(`notification sent: method=${normalizedMethod}, size=${payloadSize}`);
2292
2500
  }
2293
2501
  _enqueueSend(task) {
2294
2502
  const run = this._sendChain.then(() => Promise.resolve(task()), () => Promise.resolve(task()));
@@ -2440,7 +2648,7 @@ var RPCTransport = class {
2440
2648
  const elapsed = Date.now() - entry.tStart;
2441
2649
  if (elapsed >= entry.timeoutMs) {
2442
2650
  clearTimeout(entry.pending.timer);
2443
- this._log.warn(`RPC queue timeout: method=${entry.method}, id=${entry.rpcId}, elapsed=${elapsed}ms, timeout=${entry.timeoutMs}ms`);
2651
+ entry.logger.warn(`RPC queue timeout: method=${entry.method}, id=${entry.rpcId}, elapsed=${elapsed}ms, timeout=${entry.timeoutMs}ms`);
2444
2652
  entry.pending.reject(new TimeoutError(`rpc timeout before send: ${entry.method}`, { retryable: true }));
2445
2653
  continue;
2446
2654
  }
@@ -2453,11 +2661,11 @@ var RPCTransport = class {
2453
2661
  `rpc ${entry.method}`,
2454
2662
  () => this._pending.get(entry.rpcId) === entry.pending
2455
2663
  ).then(() => {
2456
- this._log.debug(`RPC request sent: method=${entry.method}, id=${entry.rpcId}, background=${entry.background}`);
2664
+ entry.logger.debug(`RPC request sent: method=${entry.method}, id=${entry.rpcId}, background=${entry.background}`);
2457
2665
  }).catch((err) => {
2458
2666
  if (this._pending.get(entry.rpcId) !== entry.pending) return;
2459
2667
  this._removeRpc(entry.rpcId, entry.pending);
2460
- this._log.error(`RPC send failed: method=${entry.method}, id=${entry.rpcId}, error=${String(err)}`, err instanceof Error ? err : void 0);
2668
+ entry.logger.error(`RPC send failed: method=${entry.method}, id=${entry.rpcId}, error=${String(err)}`, err instanceof Error ? err : void 0);
2461
2669
  entry.pending.reject(
2462
2670
  err instanceof ConnectionError ? err : new ConnectionError(`failed to send rpc ${entry.method}: ${err instanceof Error ? err.message : String(err)}`)
2463
2671
  );
@@ -2469,7 +2677,7 @@ var RPCTransport = class {
2469
2677
  }
2470
2678
  }
2471
2679
  /** 处理 RPC 响应中的 _trace 字段:追加 sdk.recv span,格式化输出,通知 observer */
2472
- _handleResponseTrace(method, status, elapsedMs, respTrace) {
2680
+ _handleResponseTrace(method, status, elapsedMs, respTrace, logger = this._log) {
2473
2681
  try {
2474
2682
  const sdkRecvSpan = {
2475
2683
  node: "sdk",
@@ -2480,7 +2688,7 @@ var RPCTransport = class {
2480
2688
  const existingSpans = Array.isArray(respTrace.spans) ? respTrace.spans : [];
2481
2689
  const spans = [...existingSpans, sdkRecvSpan];
2482
2690
  const enriched = { ...respTrace, spans };
2483
- this._log.info(traceDisplay(method, status, elapsedMs, respTrace, spans));
2691
+ logger.info(traceDisplay(method, status, elapsedMs, respTrace, spans));
2484
2692
  if (this._traceObserver !== null) {
2485
2693
  const observer = this._traceObserver;
2486
2694
  this._dispatcher.enqueueTask(async () => {
@@ -2492,7 +2700,7 @@ var RPCTransport = class {
2492
2700
  });
2493
2701
  }
2494
2702
  } catch (err) {
2495
- this._log.debug(`trace handling raised: ${err instanceof Error ? err.message : String(err)}`);
2703
+ logger.debug(`trace handling raised: ${err instanceof Error ? err.message : String(err)}`);
2496
2704
  }
2497
2705
  }
2498
2706
  // ── 内部消息处理 ──────────────────────────────────
@@ -2532,15 +2740,17 @@ var RPCTransport = class {
2532
2740
  const error = new ConnectionError(`websocket closed: code=${event.code} reason=${event.reason}`);
2533
2741
  if (this._onDisconnect) {
2534
2742
  const onDisconnect = this._onDisconnect;
2535
- this._dispatcher.enqueueTask(async () => {
2743
+ const task = async () => {
2536
2744
  try {
2537
2745
  await onDisconnect(error, event.code);
2538
2746
  } catch (exc) {
2539
2747
  this._log.warn("[aun_core.transport] disconnect callback exception:", exc);
2540
2748
  }
2541
- });
2749
+ };
2750
+ if (this._onDisconnectIsProtocol) this._dispatcher.enqueueProtocolTask(task);
2751
+ else this._dispatcher.enqueueTask(task);
2542
2752
  }
2543
- this._dispatcher.enqueue("connection.error", { error });
2753
+ this._dispatcher.enqueueProtocol("connection.error", { error });
2544
2754
  }
2545
2755
  }
2546
2756
  _notConnectedError() {
@@ -2560,21 +2770,22 @@ var RPCTransport = class {
2560
2770
  pending.resolve(message);
2561
2771
  this._drainRpcQueue();
2562
2772
  } else {
2563
- this._log.warn("[aun_core.transport] recv unknown rpc response (maybe arrived after timeout): id=" + rpcId);
2773
+ withLogContext(this._log, { direction: "inbound", peerAid: "" }).warn("[aun_core.transport] recv unknown rpc response (maybe arrived after timeout): id=" + rpcId);
2564
2774
  }
2565
2775
  return;
2566
2776
  }
2567
2777
  const method = String(message.method ?? "");
2568
2778
  if (method === "challenge") {
2569
2779
  this._challenge = message;
2570
- this._log.debug("challenge received");
2571
- this._dispatcher.enqueue("connection.challenge", message.params ?? {});
2780
+ withLogContext(this._log, trafficLogContext("inbound", message.params ?? message)).debug("challenge received");
2781
+ this._dispatcher.enqueueProtocol("connection.challenge", message.params ?? {});
2572
2782
  return;
2573
2783
  }
2574
2784
  if (method.startsWith("event/")) {
2575
2785
  const protocolEvent = method.slice(6);
2576
2786
  const sdkEvent = EVENT_NAME_MAP[protocolEvent] ?? protocolEvent;
2577
- this._log.debug(`event recv: event=${sdkEvent} ${summarizeDict(message.params, DIAG_RESULT_FIELDS)}`);
2787
+ const eventLog = withLogContext(this._log, trafficLogContext("inbound", message.params ?? message));
2788
+ eventLog.debug(`event recv: event=${sdkEvent} ${summarizeDict(message.params, DIAG_RESULT_FIELDS)}`);
2578
2789
  this._notifyMetaObserver(message);
2579
2790
  const params2 = message.params ?? {};
2580
2791
  if ("_trace" in params2) {
@@ -2592,19 +2803,19 @@ var RPCTransport = class {
2592
2803
  });
2593
2804
  }
2594
2805
  const traceObj = eventTrace;
2595
- this._log.info(`[trace=${String(traceObj.trace_id ?? "")}] event_recv event=${sdkEvent}`);
2806
+ eventLog.info(`[trace=${String(traceObj.trace_id ?? "")}] event_recv event=${sdkEvent}`);
2596
2807
  }
2597
2808
  }
2598
2809
  if (sdkEvent.startsWith("app.")) {
2599
2810
  this._dispatcher.enqueue(sdkEvent, params2);
2600
2811
  return;
2601
2812
  }
2602
- this._dispatcher.enqueue(`_raw.${sdkEvent}`, params2);
2813
+ this._dispatcher.enqueueProtocol(`_raw.${sdkEvent}`, params2);
2603
2814
  return;
2604
2815
  }
2605
2816
  this._notifyMetaObserver(message);
2606
- this._log.debug(`notification recv: method=${method || "<no-method>"}`);
2607
- this._dispatcher.enqueue("notification", message);
2817
+ withLogContext(this._log, trafficLogContext("inbound", message.params ?? {})).debug(`notification recv: method=${method || "<no-method>"}`);
2818
+ this._dispatcher.enqueueProtocol("notification", message);
2608
2819
  }
2609
2820
  _decodeMessage(raw) {
2610
2821
  if (isJsonObject(raw)) {
@@ -7028,8 +7239,7 @@ var MessageDeliveryEngine = class {
7028
7239
  max_pages: 1
7029
7240
  };
7030
7241
  const invoke = async () => {
7031
- const after = this.syncState(ns).ack;
7032
- const messages = await client._pullV2(after, pageLimit, { gateLocked: true, maxPages: 1 });
7242
+ const messages = await client._pullV2(Number(request.after_seq), pageLimit, { gateLocked: true, maxPages: 1 });
7033
7243
  return { messages, raw_count: messages.length };
7034
7244
  };
7035
7245
  const pipeline = client._rpcPipeline;
@@ -7048,8 +7258,7 @@ var MessageDeliveryEngine = class {
7048
7258
  max_pages: maxPages
7049
7259
  };
7050
7260
  const invoke = async () => {
7051
- const after = this.syncState(ns).ack;
7052
- const messages = await client._pullGroupV2(groupId, after, pageLimit, { gateLocked: true, maxPages });
7261
+ const messages = await client._pullGroupV2(groupId, Number(request.after_seq), pageLimit, { gateLocked: true, maxPages });
7053
7262
  return { messages, raw_count: messages.length };
7054
7263
  };
7055
7264
  const pipeline = client._rpcPipeline;
@@ -8783,7 +8992,9 @@ var LifecycleController = class {
8783
8992
  client._resetSeqTrackingState();
8784
8993
  client._clientLog.debug(`close exit: elapsed=${Date.now() - tStart}ms`);
8785
8994
  } finally {
8786
- const closing = client._dispatcher.close();
8995
+ const closeProtocol = client._dispatcher.closeProtocol;
8996
+ const protocolClosing = typeof closeProtocol === "function" ? closeProtocol.call(client._dispatcher) : Promise.resolve();
8997
+ const closing = protocolClosing.then(() => client._dispatcher.close());
8787
8998
  if (!calledFromHandler) await closing;
8788
8999
  }
8789
9000
  }, "close");
@@ -15347,6 +15558,10 @@ function validateAgentMdDocument(content, opts = {}) {
15347
15558
  if (typeof meta.description !== "string") throw new ValidationError("agent.md frontmatter description must be a string");
15348
15559
  if (Array.from(meta.description).length > 100) throw new ValidationError("agent.md description exceeds 100 characters");
15349
15560
  }
15561
+ if ("avatar" in meta) {
15562
+ if (typeof meta.avatar !== "string") throw new ValidationError("agent.md frontmatter avatar must be a string");
15563
+ if (Array.from(meta.avatar).length > 256) throw new ValidationError("agent.md avatar exceeds 256 characters");
15564
+ }
15350
15565
  if (meta.tags !== void 0 && (!Array.isArray(meta.tags) || meta.tags.some((item) => typeof item !== "string"))) throw new ValidationError("agent.md tags must be an array of strings");
15351
15566
  const fields = parsed.fields;
15352
15567
  if (fields) {
@@ -15384,8 +15599,8 @@ function validateAgentMdCertificate(certPem, expectedAid, timestamp2, now, requi
15384
15599
  function resultOk(data) {
15385
15600
  return { ok: true, data };
15386
15601
  }
15387
- function resultErr(code, message, cause) {
15388
- return { ok: false, error: { code, message, ...cause !== void 0 ? { cause } : {} } };
15602
+ function resultErr(code, message, _cause) {
15603
+ return { ok: false, error: { code, message } };
15389
15604
  }
15390
15605
 
15391
15606
  // src/aid.ts
@@ -15755,8 +15970,8 @@ async function signingCertFingerprint(certPem) {
15755
15970
  }
15756
15971
  return await cached;
15757
15972
  }
15758
- var PULL_GATE_STALE_MS = 3e4;
15759
- var PULL_GATE_OPERATION_TIMEOUT_MS = 3e3;
15973
+ var PULL_GATE_STALE_MS = 35e3;
15974
+ var PULL_GATE_OPERATION_TIMEOUT_MS = 35e3;
15760
15975
  function sameIdentityAdmissionRejection(error, original) {
15761
15976
  const errorCode2 = Number(error?.code);
15762
15977
  const originalCode = Number(original?.code);
@@ -16246,7 +16461,8 @@ var RpcPipeline = class {
16246
16461
  if (!client._aid) return "";
16247
16462
  const mode = method === "message.history" ? "history" : params2.window_mode === "tail" ? "tail" : "forward";
16248
16463
  const cursor = mode === "history" ? `before=${String(params2.before_seq)}` : `after=${String(params2.after_seq ?? 0)}`;
16249
- return `p2p:${client._aid}|mode=${mode}|cursor=${cursor}|force=${String(Boolean(params2.force))}|limit=${String(params2.limit)}`;
16464
+ const limit = mode === "forward" ? Number(params2.limit ?? 50) || 50 : params2.limit;
16465
+ return `p2p:${client._aid}|mode=${mode}|cursor=${cursor}|force=${String(Boolean(params2.force))}|limit=${String(limit)}`;
16250
16466
  }
16251
16467
  if (method === "group.pull" || method === "group.v2.pull" || method === "group.history") {
16252
16468
  const gid = String(params2.group_id ?? params2.group_aid ?? "").trim();
@@ -16255,7 +16471,8 @@ var RpcPipeline = class {
16255
16471
  const cursor = mode === "history" ? `before=${String(params2.before_seq)}` : `after=${String(params2.after_seq ?? params2.after_message_seq ?? 0)}`;
16256
16472
  const explicitCursor = this.explicitGroupCursorParams(params2);
16257
16473
  const cursorSuffix = Object.keys(explicitCursor).length > 0 ? `|cursor_params=${stableStringify(explicitCursor)}` : "";
16258
- return `group:${gid}|mode=${mode}|cursor=${cursor}${cursorSuffix}|force=${String(Boolean(params2.force))}|limit=${String(params2.limit)}`;
16474
+ const limit = mode === "forward" ? Number(params2.limit ?? 50) || 50 : params2.limit;
16475
+ return `group:${gid}|mode=${mode}|cursor=${cursor}${cursorSuffix}|force=${String(Boolean(params2.force))}|limit=${String(limit)}`;
16259
16476
  }
16260
16477
  if (method === "group.pull_events") {
16261
16478
  const gid = String(params2.group_id ?? params2.group_aid ?? "").trim();
@@ -16330,9 +16547,9 @@ var RpcPipeline = class {
16330
16547
  const index = key.indexOf("|");
16331
16548
  return index < 0 ? key : key.slice(0, index);
16332
16549
  }
16333
- bindActivePullCancellation(method, params2, request) {
16550
+ bindActivePullCancellation(method, params2, request, gateKey = "") {
16334
16551
  const cancel = request.cancel;
16335
- const key = this.pullGateKeyForCall(method, params2);
16552
+ const key = gateKey || this.pullGateKeyForCall(method, params2);
16336
16553
  if (typeof cancel !== "function" || !key) return request;
16337
16554
  const state = this.pullGateStates.get(this.pullGateName(key));
16338
16555
  const active = state?.active;
@@ -16714,10 +16931,10 @@ var RpcPipeline = class {
16714
16931
  else if (options?.trace !== void 0) request = client._transport.call(method, payload, timeout, options.trace);
16715
16932
  else if (timeout !== void 0) request = client._transport.call(method, payload, timeout);
16716
16933
  else request = client._transport.call(method, payload);
16717
- return this.bindActivePullCancellation(method, payload, request);
16934
+ return this.bindActivePullCancellation(method, payload, request, options?.pullGateKey ?? "");
16718
16935
  };
16719
16936
  const result = await this.transportCallWithIdentityRecovery(invokeTransport, method, payload);
16720
- this.throwIfPullInvalidated(this.pullScopeKey(this.pullGateKeyForCall(method, payload)));
16937
+ this.throwIfPullInvalidated(this.pullScopeKey(options?.pullGateKey || this.pullGateKeyForCall(method, payload)));
16721
16938
  return result;
16722
16939
  }
16723
16940
  async transportCallWithIdentityRecovery(operation, method, params2) {
@@ -18222,7 +18439,7 @@ async function verifyGroupIndex(body, signer) {
18222
18439
  return resultOk({ valid: false, reason: "etag mismatch" });
18223
18440
  }
18224
18441
  const verified = await signer.verify(groupIndexSigningPayload(parsed.meta, parsed.entries), signature);
18225
- if (!verified.ok) return resultErr(verified.error.code, verified.error.message || "group index verify failed", verified.error.cause);
18442
+ if (!verified.ok) return resultErr(verified.error.code, verified.error.message || "group index verify failed");
18226
18443
  if (!verified.data.valid) return resultOk({ valid: false, reason: "signature verification failed" });
18227
18444
  return resultOk({ valid: true, meta: parsed.meta, entries: canonicalEntries(parsed.entries) });
18228
18445
  } catch (exc) {
@@ -24956,7 +25173,16 @@ var V2E2EECoordinator = class {
24956
25173
  const limit = strictWindowLimit(params2.limit ?? V2_PULL_DEFAULT_PAGE_LIMIT);
24957
25174
  const ns = client._aid ? `p2p:${client._aid}` : "";
24958
25175
  if (ns) client._delivery.onPullStarted?.(ns);
24959
- const result = await client._callRawV2Rpc("message.v2.pull", { window_mode: "tail", after_seq: afterSeq, limit, _rpc_foreground: true });
25176
+ const pullGateKey = pullGateKeyForClient(client, "message.v2.pull", {
25177
+ window_mode: "tail",
25178
+ after_seq: afterSeq,
25179
+ limit
25180
+ }, `${ns}|tail|after=${afterSeq}|limit=${limit}`);
25181
+ const result = await client._callRawV2Rpc(
25182
+ "message.v2.pull",
25183
+ { window_mode: "tail", after_seq: afterSeq, limit, _rpc_foreground: true },
25184
+ pullGateKey
25185
+ );
24960
25186
  const page = validateTailPage(result, afterSeq, limit);
24961
25187
  if (ns) {
24962
25188
  client._seqTracker.commitTailWindow(ns, {
@@ -25065,7 +25291,7 @@ var V2E2EECoordinator = class {
25065
25291
  limit,
25066
25292
  ...opts?.force ? { force: true } : {},
25067
25293
  ...ackUpToSeq > 0 ? { ack_up_to_seq: ackUpToSeq } : {}
25068
- });
25294
+ }, pullGateKey);
25069
25295
  if (ackUpToSeq > 0) {
25070
25296
  const actualAckSeq = client._delivery?.resolveP2PPullAckSeq?.(result, ackUpToSeq) ?? 0;
25071
25297
  if (actualAckSeq >= ackUpToSeq) {
@@ -25423,18 +25649,27 @@ var V2E2EECoordinator = class {
25423
25649
  const afterSeq = strictWindowSeq(params2.after_seq ?? 0, "after_seq");
25424
25650
  const limit = strictWindowLimit(params2.limit ?? V2_PULL_DEFAULT_PAGE_LIMIT);
25425
25651
  const ns = `group:${groupId}`;
25426
- const cursorParams = isJsonObject(params2._group_cursor_params) ? params2._group_cursor_params : params2;
25652
+ const explicitCursorParams = isJsonObject(params2._group_cursor_params) ? params2._group_cursor_params : {};
25653
+ const cursorParams = Object.keys(explicitCursorParams).length > 0 ? explicitCursorParams : params2;
25427
25654
  const requestDeviceId = String(cursorParams.device_id ?? "").trim();
25428
25655
  const requestSlotId = String(cursorParams.slot_id ?? "").trim();
25429
25656
  const ownsCursor = (!requestDeviceId || requestDeviceId === String(client._deviceId ?? "")) && (!requestSlotId || requestSlotId === String(client._slotId ?? ""));
25430
25657
  if (ownsCursor) client._delivery.onPullStarted?.(ns);
25658
+ const pullGateKey = pullGateKeyForClient(client, "group.v2.pull", {
25659
+ group_id: groupId,
25660
+ window_mode: "tail",
25661
+ after_seq: afterSeq,
25662
+ limit,
25663
+ _group_cursor_params: explicitCursorParams
25664
+ }, `${ns}|tail|after=${afterSeq}|limit=${limit}`);
25431
25665
  const result = await client._callRawV2Rpc("group.v2.pull", withExplicitGroupAid({
25432
25666
  group_id: groupId,
25433
25667
  window_mode: "tail",
25434
25668
  after_seq: afterSeq,
25435
25669
  limit,
25670
+ _group_cursor_params: explicitCursorParams,
25436
25671
  _rpc_foreground: true
25437
- }, groupAid));
25672
+ }, groupAid), pullGateKey);
25438
25673
  const resultAid = String(result.group_aid ?? result.groupAid ?? "").trim();
25439
25674
  if (resultAid) groupAid = resultAid;
25440
25675
  const page = validateTailPage(result, afterSeq, limit);
@@ -25525,6 +25760,7 @@ var V2E2EECoordinator = class {
25525
25760
  }
25526
25761
  const result = await this.pullGroupV2TailInternal({
25527
25762
  ...opts?.cursorParams ?? {},
25763
+ _group_cursor_params: opts?.cursorParams,
25528
25764
  group_id: String(opts.wireGroupId ?? gid),
25529
25765
  group_aid: groupAid || void 0,
25530
25766
  window_mode: "tail",
@@ -25551,13 +25787,13 @@ var V2E2EECoordinator = class {
25551
25787
  const cursorParams = opts?.cursorParams ?? {};
25552
25788
  const ownsCursor = opts?.ownsCursor !== false;
25553
25789
  if (ownsCursor) client._delivery.onPullStarted?.(ns);
25554
- let pullGateKey = ownsCursor ? pullGateKeyForClient(client, "group.v2.pull", {
25790
+ let pullGateKey = pullGateKeyForClient(client, "group.v2.pull", {
25555
25791
  group_id: gid,
25556
25792
  after_seq: afterSeq,
25557
25793
  force: opts?.force === true,
25558
25794
  limit,
25559
25795
  _group_cursor_params: cursorParams
25560
- }, `${ns}|forward|after=${afterSeq}|force=${String(Boolean(opts?.force))}|limit=${limit}`) : "";
25796
+ }, `${ns}|forward|after=${afterSeq}|force=${String(Boolean(opts?.force))}|limit=${limit}`);
25561
25797
  let nextAfterSeq = opts?.explicitAfterSeq || opts?.force ? afterSeq : afterSeq || client._seqTracker.getContiguousSeq(ns);
25562
25798
  const deferredServerCursor = ownsCursor ? this.pendingForwardCursor(ns, client._seqTracker.getContiguousSeq(ns)) : 0;
25563
25799
  const deferredForwardAck = ownsCursor ? this.pendingForwardAck(ns, client._seqTracker.getContiguousSeq(ns)) : 0;
@@ -25576,7 +25812,7 @@ var V2E2EECoordinator = class {
25576
25812
  ...cursorParams,
25577
25813
  ...opts?.force ? { force: true } : {},
25578
25814
  ...ackUpToSeq > 0 ? { ack_up_to_seq: ackUpToSeq } : {}
25579
- }, groupAid));
25815
+ }, groupAid), pullGateKey);
25580
25816
  if (ackUpToSeq > 0) {
25581
25817
  const actualAckSeq = client._delivery?.resolveGroupPullAckSeq?.(result, ackUpToSeq) ?? 0;
25582
25818
  if (actualAckSeq >= ackUpToSeq) {
@@ -28380,104 +28616,6 @@ __publicField(_IndexedDBTokenStore, "_TRUST_CERT_PREFIX", "__trust_roots:cert:")
28380
28616
  __publicField(_IndexedDBTokenStore, "_TRUST_ISSUER_PREFIX", "__trust_roots:issuer:");
28381
28617
  var IndexedDBTokenStore = _IndexedDBTokenStore;
28382
28618
 
28383
- // src/logger.ts
28384
- var LEVEL_ORDER = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3 };
28385
- function formatMessage(template, args) {
28386
- if (args.length === 0) return template;
28387
- let i = 0;
28388
- let result = "";
28389
- let consumed = 0;
28390
- for (let p = 0; p < template.length; p++) {
28391
- const ch = template[p];
28392
- if (ch === "%" && template[p + 1] === "s" && i < args.length) {
28393
- result += String(args[i++]);
28394
- consumed++;
28395
- p++;
28396
- } else {
28397
- result += ch;
28398
- }
28399
- }
28400
- if (i < args.length) {
28401
- const tail = args.slice(i).map((a) => a instanceof Error ? a.message : String(a)).join(" ");
28402
- if (tail) result += " " + tail;
28403
- }
28404
- return result;
28405
- }
28406
- var AUNLogger = class {
28407
- constructor(opts) {
28408
- __publicField(this, "_debug");
28409
- __publicField(this, "_aunPath");
28410
- __publicField(this, "_deviceId", "-");
28411
- __publicField(this, "_aid", null);
28412
- __publicField(this, "_minLevel");
28413
- this._debug = opts.debug;
28414
- this._aunPath = String(opts.aunPath || "-");
28415
- this._minLevel = this._debug ? LEVEL_ORDER.DEBUG : LEVEL_ORDER.INFO;
28416
- }
28417
- for(module) {
28418
- return {
28419
- error: (msg, ...args) => this._emit("ERROR", module, msg, args),
28420
- warn: (msg, ...args) => this._emit("WARN", module, msg, args),
28421
- info: (msg, ...args) => this._emit("INFO", module, msg, args),
28422
- debug: (msg, ...args) => this._emit("DEBUG", module, msg, args),
28423
- isDebugEnabled: () => this.isDebugEnabled()
28424
- };
28425
- }
28426
- isDebugEnabled() {
28427
- return this._debug && this._minLevel <= LEVEL_ORDER.DEBUG;
28428
- }
28429
- bindAid(aid) {
28430
- this._aid = aid || null;
28431
- }
28432
- bindDeviceId(deviceId) {
28433
- this._deviceId = String(deviceId || "").trim() || "-";
28434
- }
28435
- close() {
28436
- }
28437
- _emit(level, module, msg, args) {
28438
- if (LEVEL_ORDER[level] < this._minLevel) return;
28439
- if (level === "DEBUG" && !this._debug) return;
28440
- const { date, time, ms } = this._now();
28441
- const head = `[${date} ${time}.${ms}][${level}][${module}][aun_path=${this._aunPath || "-"}][device_id=${this._deviceId || "-"}]`;
28442
- const aidPart = this._aid ? ` [${this._aid}]` : "";
28443
- const formatted = formatMessage(msg, args);
28444
- const line = `${head}${aidPart} ${formatted}`;
28445
- let errArg;
28446
- for (let i = args.length - 1; i >= 0; i--) {
28447
- if (args[i] instanceof Error) {
28448
- errArg = args[i];
28449
- break;
28450
- }
28451
- }
28452
- switch (level) {
28453
- case "ERROR":
28454
- if (errArg) {
28455
- console.error(line, errArg);
28456
- } else {
28457
- console.error(line);
28458
- }
28459
- break;
28460
- case "WARN":
28461
- console.warn(line);
28462
- break;
28463
- case "INFO":
28464
- console.info(line);
28465
- break;
28466
- case "DEBUG":
28467
- console.debug(line);
28468
- break;
28469
- }
28470
- }
28471
- _now() {
28472
- const d = /* @__PURE__ */ new Date();
28473
- const pad = (n, w = 2) => String(n).padStart(w, "0");
28474
- const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
28475
- const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
28476
- const ms = pad(d.getMilliseconds(), 3);
28477
- return { date, time, ms };
28478
- }
28479
- };
28480
-
28481
28619
  // src/agent-md.ts
28482
28620
  var DEFAULT_HTTP_TIMEOUT_MS = 3e4;
28483
28621
  function buildDefaultAgentMd(aid, options = {}) {
@@ -28486,6 +28624,7 @@ function buildDefaultAgentMd(aid, options = {}) {
28486
28624
  const name = String(options.name ?? "").trim() || target.split(".", 1)[0] || target;
28487
28625
  const normalized = String(options.description ?? "").trim().replace(/\s+/g, " ") || `AUN ${type} ${name}`;
28488
28626
  const description = Array.from(normalized).slice(0, 100).join("");
28627
+ const avatar = Array.from(String(options.avatar ?? "").trim()).slice(0, 256).join("");
28489
28628
  return [
28490
28629
  "---",
28491
28630
  `aid: ${JSON.stringify(target)}`,
@@ -28493,6 +28632,7 @@ function buildDefaultAgentMd(aid, options = {}) {
28493
28632
  `type: ${JSON.stringify(type)}`,
28494
28633
  'version: "1.0.0"',
28495
28634
  `description: ${JSON.stringify(description)}`,
28635
+ ...avatar ? [`avatar: ${JSON.stringify(avatar)}`] : [],
28496
28636
  "---",
28497
28637
  "",
28498
28638
  `# ${name}`,
@@ -29582,6 +29722,13 @@ function _v2ConcatBytes(...parts) {
29582
29722
  function formatCaughtError2(error) {
29583
29723
  return error instanceof Error ? error : String(error);
29584
29724
  }
29725
+ function publicError(error) {
29726
+ const record = error && typeof error === "object" ? error : null;
29727
+ const rawCode = record?.localCode ?? record?.stringCode ?? record?.code;
29728
+ const code = rawCode === void 0 || rawCode === null || rawCode === "" || rawCode === -1 ? "INTERNAL_ERROR" : typeof rawCode === "string" || typeof rawCode === "number" ? rawCode : "INTERNAL_ERROR";
29729
+ const message = String(record?.message ?? error ?? "internal error").trim() || "internal error";
29730
+ return { code, message };
29731
+ }
29585
29732
  var RELOGIN_REFRESH_ERRORS = /* @__PURE__ */ new Set([
29586
29733
  "missing refresh_token",
29587
29734
  "invalid_or_expired_refresh_token",
@@ -29844,6 +29991,7 @@ var _AUNClient = class _AUNClient {
29844
29991
  this._deviceId = inputAid?.deviceId || getDeviceId();
29845
29992
  this._logger = new AUNLogger({ debug: _debug, aunPath: this.configModel.aunPath });
29846
29993
  this._logger.bindDeviceId(this._deviceId);
29994
+ this._logger.bindAid(initAid ?? "");
29847
29995
  this._clientLog = this._logger.for("aun_core.client");
29848
29996
  this._logAuth = this._logger.for("aun_core.auth");
29849
29997
  this._logTransport = this._logger.for("aun_core.transport");
@@ -29891,10 +30039,10 @@ var _AUNClient = class _AUNClient {
29891
30039
  });
29892
30040
  this._transport = new RPCTransport({
29893
30041
  eventDispatcher: this._dispatcher,
29894
- timeout: DEFAULT_SESSION_OPTIONS.timeouts.call,
29895
- onDisconnect: (error, closeCode) => this._handleTransportDisconnect(error, closeCode)
30042
+ timeout: DEFAULT_SESSION_OPTIONS.timeouts.call
29896
30043
  });
29897
- this._transport.setMetaObserver(
30044
+ this._transport.setProtocolDisconnectCallback((error, closeCode) => this._handleTransportDisconnect(error, closeCode));
30045
+ this._transport.setProtocolMetaObserver(
29898
30046
  (meta) => this._observeRpcMeta(meta).catch((exc) => {
29899
30047
  this._clientLog.debug(`rpc meta observer skipped: ${String(exc)}`);
29900
30048
  })
@@ -29929,54 +30077,54 @@ var _AUNClient = class _AUNClient {
29929
30077
  if (typeof this._tokenStore.setLogger === "function") {
29930
30078
  this._tokenStore.setLogger(this._tokenStoreLog);
29931
30079
  }
29932
- this._dispatcher.subscribe("_raw.message.received", (data) => {
30080
+ this._dispatcher.subscribeProtocol("_raw.message.received", (data) => {
29933
30081
  this._onRawMessageReceived(data);
29934
30082
  });
29935
- this._dispatcher.subscribe("_raw.message.recalled", (data) => {
30083
+ this._dispatcher.subscribeProtocol("_raw.message.recalled", (data) => {
29936
30084
  this._safeAsync(this._onRawMessageRecalled(data));
29937
30085
  });
29938
- this._dispatcher.subscribe("_raw.group.message_created", (data) => {
30086
+ this._dispatcher.subscribeProtocol("_raw.group.message_created", (data) => {
29939
30087
  this._onRawGroupMessageCreated(data);
29940
30088
  });
29941
- this._dispatcher.subscribe("_raw.group.message_recalled", (data) => {
30089
+ this._dispatcher.subscribeProtocol("_raw.group.message_recalled", (data) => {
29942
30090
  this._safeAsync(this._onRawGroupMessageRecalled(data));
29943
30091
  });
29944
- this._dispatcher.subscribe("_raw.group.changed", (data) => {
30092
+ this._dispatcher.subscribeProtocol("_raw.group.changed", (data) => {
29945
30093
  this._onRawGroupChanged(data);
29946
30094
  });
29947
- this._dispatcher.subscribe("_raw.group.invite_created", (data) => {
30095
+ this._dispatcher.subscribeProtocol("_raw.group.invite_created", (data) => {
29948
30096
  this._safeAsync(this._onRawGroupInviteReceived(data, "push"));
29949
30097
  });
29950
- this._dispatcher.subscribe("_raw.group.invite_received", (data) => {
30098
+ this._dispatcher.subscribeProtocol("_raw.group.invite_received", (data) => {
29951
30099
  this._safeAsync(this._onRawGroupInviteReceived(data, "push"));
29952
30100
  });
29953
- this._dispatcher.subscribe("_raw.group.invite_finalized", (data) => {
30101
+ this._dispatcher.subscribeProtocol("_raw.group.invite_finalized", (data) => {
29954
30102
  this._safeAsync(this._onRawGroupInviteFinalized(data));
29955
30103
  });
29956
- this._dispatcher.subscribe("_raw.peer.v2.message_received", (data) => {
30104
+ this._dispatcher.subscribeProtocol("_raw.peer.v2.message_received", (data) => {
29957
30105
  this._safeAsync(this._onV2PushNotification(data));
29958
30106
  });
29959
- this._dispatcher.subscribe("_raw.group.v2.message_created", (data) => {
30107
+ this._dispatcher.subscribeProtocol("_raw.group.v2.message_created", (data) => {
29960
30108
  this._safeAsync(this._onRawGroupV2MessageCreated(data));
29961
30109
  });
29962
- this._dispatcher.subscribe("_raw.group.v2.state_proposed", (data) => {
30110
+ this._dispatcher.subscribeProtocol("_raw.group.v2.state_proposed", (data) => {
29963
30111
  this._safeAsync(this._onV2StateProposed(data));
29964
30112
  });
29965
- this._dispatcher.subscribe("_raw.group.v2.state_retry_needed", (data) => {
30113
+ this._dispatcher.subscribeProtocol("_raw.group.v2.state_retry_needed", (data) => {
29966
30114
  this._safeAsync(this._onV2StateRetryNeeded(data));
29967
30115
  });
29968
- this._dispatcher.subscribe("_raw.group.v2.state_confirmed", (data) => {
30116
+ this._dispatcher.subscribeProtocol("_raw.group.v2.state_confirmed", (data) => {
29969
30117
  this._safeAsync(this._onV2StateConfirmed(data));
29970
30118
  });
29971
- this._dispatcher.subscribe("_raw.group.state_committed", (data) => {
30119
+ this._dispatcher.subscribeProtocol("_raw.group.state_committed", (data) => {
29972
30120
  this._safeAsync(this._onGroupStateCommitted(data));
29973
30121
  });
29974
30122
  for (const evt of ["message.ack", "storage.object_changed", "stream/created", "stream/closed"]) {
29975
- this._dispatcher.subscribe(`_raw.${evt}`, (data) => {
30123
+ this._dispatcher.subscribeProtocol(`_raw.${evt}`, (data) => {
29976
30124
  this._dispatcher.enqueue(evt, data);
29977
30125
  });
29978
30126
  }
29979
- this._dispatcher.subscribe("_raw.gateway.disconnect", async (data) => {
30127
+ this._dispatcher.subscribeProtocol("_raw.gateway.disconnect", async (data) => {
29980
30128
  await this._onGatewayDisconnect(data);
29981
30129
  });
29982
30130
  }
@@ -30249,6 +30397,7 @@ var _AUNClient = class _AUNClient {
30249
30397
  this._slotId = aid.slotId || "default";
30250
30398
  this._logger = new AUNLogger({ debug: aid.debug, aunPath: nextConfig.aunPath });
30251
30399
  this._logger.bindDeviceId(this._deviceId);
30400
+ this._logger.bindAid(aid.aid);
30252
30401
  this._clientLog = this._logger.for("aun_core.client");
30253
30402
  this._logAuth = this._logger.for("aun_core.auth");
30254
30403
  this._logTransport = this._logger.for("aun_core.transport");
@@ -30290,10 +30439,10 @@ var _AUNClient = class _AUNClient {
30290
30439
  });
30291
30440
  this._transport = new RPCTransport({
30292
30441
  eventDispatcher: this._dispatcher,
30293
- timeout: DEFAULT_SESSION_OPTIONS.timeouts.call,
30294
- onDisconnect: (error, closeCode) => this._handleTransportDisconnect(error, closeCode)
30442
+ timeout: DEFAULT_SESSION_OPTIONS.timeouts.call
30295
30443
  });
30296
- this._transport.setMetaObserver(
30444
+ this._transport.setProtocolDisconnectCallback((error, closeCode) => this._handleTransportDisconnect(error, closeCode));
30445
+ this._transport.setProtocolMetaObserver(
30297
30446
  (meta) => this._observeRpcMeta(meta).catch((exc) => {
30298
30447
  this._clientLog.debug(`rpc meta observer skipped: ${String(exc)}`);
30299
30448
  })
@@ -30519,7 +30668,7 @@ var _AUNClient = class _AUNClient {
30519
30668
  throw new ValidationError("group.create response missing group.group_id");
30520
30669
  }
30521
30670
  const bindParams = { group_id: groupId };
30522
- for (const key of ["name", "description", "group_description", "group_agent_md", "groupAgentMd", "content"]) {
30671
+ for (const key of ["name", "description", "group_description", "avatar", "group_agent_md", "groupAgentMd", "content"]) {
30523
30672
  if (key in payload) bindParams[key] = payload[key];
30524
30673
  }
30525
30674
  const bound = await this._runGroupIdentityOperation(
@@ -30621,6 +30770,7 @@ var _AUNClient = class _AUNClient {
30621
30770
  const name = value("name", "group_name", "title") || groupAid;
30622
30771
  const normalizedDescription = (value("description", "group_description") || `AUN group ${name}`).split(/\s+/).filter(Boolean).join(" ");
30623
30772
  const description = Array.from(normalizedDescription).slice(0, 100).join("");
30773
+ const avatar = Array.from(value("avatar")).slice(0, 256).join("");
30624
30774
  return [
30625
30775
  "---\n",
30626
30776
  `aid: ${JSON.stringify(groupAid)}
@@ -30631,6 +30781,8 @@ var _AUNClient = class _AUNClient {
30631
30781
  'version: "1.0.0"\n',
30632
30782
  `description: ${JSON.stringify(description)}
30633
30783
  `,
30784
+ ...avatar ? [`avatar: ${JSON.stringify(avatar)}
30785
+ `] : [],
30634
30786
  "---\n\n",
30635
30787
  `# ${name}
30636
30788
  `
@@ -31053,7 +31205,7 @@ var _AUNClient = class _AUNClient {
31053
31205
  }
31054
31206
  await this._transport.notify(directMethod, payload);
31055
31207
  }
31056
- async _callRawV2Rpc(method, params2) {
31208
+ async _callRawV2Rpc(method, params2, pullGateKey = "") {
31057
31209
  const p = { ...params2 ?? {} };
31058
31210
  const forceForeground = Boolean(p._rpc_foreground);
31059
31211
  const rpcBackground = !forceForeground && (Boolean(p._rpc_background) || this._backgroundRpcDepth > 0);
@@ -31078,7 +31230,10 @@ var _AUNClient = class _AUNClient {
31078
31230
  if (method.startsWith("group.") && p.slot_id === void 0) {
31079
31231
  p.slot_id = this._slotId;
31080
31232
  }
31081
- return await this._rpcPipeline.rawCall(method, p, { background: rpcBackground });
31233
+ return await this._rpcPipeline.rawCall(method, p, {
31234
+ background: rpcBackground,
31235
+ ...pullGateKey ? { pullGateKey } : {}
31236
+ });
31082
31237
  }
31083
31238
  // ── 事件 ──────────────────────────────────────────
31084
31239
  /**
@@ -31672,6 +31827,7 @@ ${invitee}` : "";
31672
31827
  if (identity && isJsonObject(identity)) {
31673
31828
  this._identity = identity;
31674
31829
  this._aid = String(identity.aid ?? this._aid ?? "");
31830
+ this._logger.bindAid(this._aid);
31675
31831
  if (this._sessionParams) {
31676
31832
  this._sessionParams.access_token = String(auth.token ?? params2.access_token ?? "");
31677
31833
  }
@@ -31872,6 +32028,7 @@ ${invitee}` : "";
31872
32028
  identity.access_token = accessToken;
31873
32029
  this._identity = identity;
31874
32030
  this._aid = String(identity.aid ?? this._aid ?? "");
32031
+ this._logger.bindAid(this._aid);
31875
32032
  if (identity.aid) {
31876
32033
  const persistIdentity = this._auth._persistIdentity;
31877
32034
  if (typeof persistIdentity === "function") {
@@ -32091,7 +32248,7 @@ ${invitee}` : "";
32091
32248
  }
32092
32249
  this._clientLog.warn(`token refresh failed (${this._tokenRefreshFailures}/3), next retry: ${String(exc)}`);
32093
32250
  } else {
32094
- this._dispatcher.enqueue("connection.error", { error: formatCaughtError2(exc) });
32251
+ this._dispatcher.enqueue("connection.error", { error: publicError(exc) });
32095
32252
  }
32096
32253
  }
32097
32254
  scheduleRefresh();
@@ -32141,7 +32298,7 @@ ${invitee}` : "";
32141
32298
  }
32142
32299
  this._dispatcher.enqueue("state_change", {
32143
32300
  state: this._publicState(this._state),
32144
- error
32301
+ error: error ? publicError(error) : null
32145
32302
  });
32146
32303
  if (reconnectAbort.signal.aborted || this._reconnectAbort !== reconnectAbort || this._closing) {
32147
32304
  if (this._reconnectAbort === reconnectAbort) {
@@ -32165,7 +32322,7 @@ ${invitee}` : "";
32165
32322
  const disconnectInfo = this._lastDisconnectInfo ?? {};
32166
32323
  const eventPayload = {
32167
32324
  state: this._publicState(this._state),
32168
- error,
32325
+ error: error ? publicError(error) : null,
32169
32326
  reason
32170
32327
  };
32171
32328
  const detail = disconnectInfo.detail;
@@ -32368,7 +32525,7 @@ ${invitee}` : "";
32368
32525
  this._lastError = exc instanceof Error ? exc : new Error(String(exc));
32369
32526
  this._lastErrorCode = "reconnect_failed";
32370
32527
  if (!reconnectAbort || !await this._publishReconnectEvent(reconnectAbort, "connection.error", {
32371
- error: formatCaughtError2(exc),
32528
+ error: publicError(exc),
32372
32529
  attempt
32373
32530
  })) return;
32374
32531
  if (!this._shouldRetryReconnect(exc)) {
@@ -32376,7 +32533,7 @@ ${invitee}` : "";
32376
32533
  this._nextRetryAt = null;
32377
32534
  if (reconnectAbort) await this._publishReconnectEvent(reconnectAbort, "state_change", {
32378
32535
  state: this._publicState(this._state),
32379
- error: formatCaughtError2(exc),
32536
+ error: publicError(exc),
32380
32537
  attempt
32381
32538
  });
32382
32539
  return;