@agentunion/fastaun-browser 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -254,13 +254,8 @@ function agentMdHttpScheme(gatewayUrl) {
254
254
  const raw = String(gatewayUrl ?? '').trim().toLowerCase();
255
255
  return raw.startsWith('ws://') ? 'http' : 'https';
256
256
  }
257
- function agentMdAuthority(aid, discoveryPort) {
258
- const host = String(aid ?? '').trim();
259
- if (!host)
260
- return '';
261
- if (discoveryPort && !host.includes(':'))
262
- return `${host}:${discoveryPort}`;
263
- return host;
257
+ function agentMdAuthority(aid) {
258
+ return String(aid ?? '').trim();
264
259
  }
265
260
  async function fetchWithTimeout(input, init, timeoutMs = AGENT_MD_HTTP_TIMEOUT_MS) {
266
261
  const controller = new AbortController();
@@ -752,23 +747,16 @@ export class AUNClient {
752
747
  _logKeystore;
753
748
  _logDiscovery;
754
749
  _logEvents;
755
- constructor(first, second) {
756
- if (typeof first === 'string') {
750
+ constructor(aid) {
751
+ const inputAid = aid instanceof AID ? aid : null;
752
+ if (typeof aid === 'string') {
757
753
  throw new ValidationError('AUNClient aid must be an AID object, not a string');
758
754
  }
759
- if (typeof second === 'boolean') {
760
- throw new ValidationError('AUNClient debug must be passed as options.debug');
761
- }
762
- const inputAid = first instanceof AID ? first : null;
763
- if (!inputAid && second !== undefined) {
764
- throw new ValidationError('AUNClient options-only construction accepts a single options object');
765
- }
766
- const options = inputAid ? (second ?? {}) : (first ?? {});
767
- assertClientOptions(options, 'AUNClient options');
755
+ const options = {};
768
756
  const rawConfig = clientOptionsConfig(options);
769
757
  if (inputAid)
770
758
  rawConfig.aun_path = inputAid.aunPath;
771
- const _debug = !!options?.debug;
759
+ const _debug = false;
772
760
  this.configModel = createConfig(rawConfig);
773
761
  const initAid = inputAid ? inputAid.aid : null;
774
762
  this.config = {
@@ -908,7 +896,7 @@ export class AUNClient {
908
896
  gatewayUrl = '';
909
897
  }
910
898
  }
911
- const authority = agentMdAuthority(target, this.configModel.discoveryPort);
899
+ const authority = agentMdAuthority(target);
912
900
  return `${agentMdHttpScheme(gatewayUrl)}://${authority}/agent.md`;
913
901
  }
914
902
  async _ensureAgentMdUploadToken(aid, gatewayUrl) {
@@ -1682,7 +1670,7 @@ export class AUNClient {
1682
1670
  throw new StateError('authenticate requires a loaded AID with a valid private key');
1683
1671
  }
1684
1672
  const publicState = this.state;
1685
- if (publicState !== ConnectionState.STANDBY && publicState !== ConnectionState.AUTHENTICATED) {
1673
+ if (publicState !== ConnectionState.STANDBY) {
1686
1674
  throw new StateError(`authenticate not allowed in state ${publicState}`);
1687
1675
  }
1688
1676
  if ('aid' in options || 'access_token' in options || 'token' in options || 'kite_token' in options) {
@@ -1705,15 +1693,27 @@ export class AUNClient {
1705
1693
  }
1706
1694
  }
1707
1695
  /** 连接到 Gateway;身份来自构造函数或 loadIdentity(aid),认证由 SDK 内部自动完成。 */
1708
- async connect(options = {}) {
1696
+ async connect(opts) {
1709
1697
  const tStart = Date.now();
1710
- this._clientLog.debug(`connect enter: state=${this._state} aid=${this._aid ?? '-'}`);
1711
- if (arguments.length > 1) {
1712
- throw new ValidationError('connect accepts a single options object');
1698
+ const options = {};
1699
+ if (opts?.auto_reconnect !== undefined)
1700
+ options.auto_reconnect = opts.auto_reconnect;
1701
+ if (opts?.heartbeat_interval !== undefined)
1702
+ options.heartbeat_interval = opts.heartbeat_interval;
1703
+ if (opts?.connect_timeout !== undefined || opts?.call_timeout !== undefined) {
1704
+ options.timeouts = {
1705
+ ...(opts.connect_timeout !== undefined ? { connect: opts.connect_timeout } : {}),
1706
+ ...(opts.call_timeout !== undefined ? { call: opts.call_timeout } : {}),
1707
+ };
1713
1708
  }
1714
- if ('aid' in options || 'access_token' in options || 'token' in options || 'kite_token' in options) {
1715
- throw new ValidationError('connect options must not include aid or token fields; load an AID object first');
1709
+ if (opts?.retry_initial_delay !== undefined || opts?.retry_max_delay !== undefined || opts?.retry_max_attempts !== undefined) {
1710
+ options.retry = {
1711
+ initial_delay: opts.retry_initial_delay ?? 1,
1712
+ max_delay: opts.retry_max_delay ?? 64,
1713
+ max_attempts: opts.retry_max_attempts ?? 0,
1714
+ };
1716
1715
  }
1716
+ this._clientLog.debug(`connect enter: state=${this._state} aid=${this._aid ?? '-'}`);
1717
1717
  const target = this._currentAid?.aid ?? this._aid ?? '';
1718
1718
  if (!target || !this._currentAid?.isPrivateKeyValid()) {
1719
1719
  throw new StateError('connect requires a loaded AID with a valid private key');
@@ -1729,8 +1729,12 @@ export class AUNClient {
1729
1729
  this._clientLog.debug(`connect exit (error): elapsed=${Date.now() - tStart}ms err=invalid_state state=${this._state}`);
1730
1730
  throw new StateError(`connect not allowed in state ${publicState}`);
1731
1731
  }
1732
+ // gateway 来自 authenticate() 缓存的 this._gatewayUrl;未认证则自动 authenticate()
1733
+ if (!this._gatewayUrl) {
1734
+ await this.authenticate();
1735
+ }
1732
1736
  this._state = 'connecting';
1733
- const gateway = String(options.gateway ?? this._gatewayUrl ?? await this._resolveGatewayForAid(target)).trim();
1737
+ const gateway = String(this._gatewayUrl ?? '').trim();
1734
1738
  const params = { ...options, gateway };
1735
1739
  const normalized = this._normalizeConnectParams(params);
1736
1740
  this._sessionParams = normalized;
@@ -1779,7 +1783,7 @@ export class AUNClient {
1779
1783
  }
1780
1784
  await this._transport.close();
1781
1785
  this._state = 'disconnected';
1782
- await this._dispatcher.publish('connection.state', { state: this._publicState(this._state) });
1786
+ await this._dispatcher.publish('state_change', { state: this._publicState(this._state) });
1783
1787
  this._clientLog.debug(`disconnect exit: elapsed=${Date.now() - tStart}ms`);
1784
1788
  }
1785
1789
  /** 关闭连接 */
@@ -1810,7 +1814,7 @@ export class AUNClient {
1810
1814
  }
1811
1815
  await this._transport.close();
1812
1816
  this._state = 'closed';
1813
- await this._dispatcher.publish('connection.state', { state: this._publicState(this._state) });
1817
+ await this._dispatcher.publish('state_change', { state: this._publicState(this._state) });
1814
1818
  this._resetSeqTrackingState();
1815
1819
  this._clientLog.debug(`close exit: elapsed=${Date.now() - tStart}ms`);
1816
1820
  }
@@ -3696,7 +3700,7 @@ export class AUNClient {
3696
3700
  }
3697
3701
  this._state = 'connected';
3698
3702
  this._connectedAt = Date.now();
3699
- await this._dispatcher.publish('connection.state', {
3703
+ await this._dispatcher.publish('state_change', {
3700
3704
  state: this._publicState(this._state),
3701
3705
  gateway: gatewayUrl,
3702
3706
  });
@@ -3750,7 +3754,7 @@ export class AUNClient {
3750
3754
  }
3751
3755
  const dotIdx = target.indexOf('.');
3752
3756
  const issuerDomain = dotIdx >= 0 ? target.slice(dotIdx + 1) : target;
3753
- const portSuffix = this.configModel.discoveryPort ? `:${this.configModel.discoveryPort}` : '';
3757
+ const portSuffix = '';
3754
3758
  const candidates = [
3755
3759
  `https://${target}${portSuffix}/.well-known/aun-gateway`,
3756
3760
  `https://gateway.${issuerDomain}${portSuffix}/.well-known/aun-gateway`,
@@ -4196,7 +4200,7 @@ export class AUNClient {
4196
4200
  this._state = 'disconnected';
4197
4201
  // 先停止后台任务,避免心跳/token刷新在重连期间继续触发
4198
4202
  this._stopBackgroundTasks();
4199
- await this._dispatcher.publish('connection.state', {
4203
+ await this._dispatcher.publish('state_change', {
4200
4204
  state: this._publicState(this._state),
4201
4205
  error,
4202
4206
  });
@@ -4221,7 +4225,7 @@ export class AUNClient {
4221
4225
  if (disconnectInfo.code !== undefined && disconnectInfo.code !== null) {
4222
4226
  eventPayload.code = disconnectInfo.code;
4223
4227
  }
4224
- await this._dispatcher.publish('connection.state', eventPayload);
4228
+ await this._dispatcher.publish('state_change', eventPayload);
4225
4229
  return;
4226
4230
  }
4227
4231
  // 1000 = 正常关闭, 1006 = 网络异常断开(无 close frame),其他 code = 服务端主动关闭
@@ -4248,7 +4252,7 @@ export class AUNClient {
4248
4252
  this._nextRetryAt = null;
4249
4253
  this._reconnectActive = false;
4250
4254
  this._reconnectAbort = null;
4251
- await this._dispatcher.publish('connection.state', {
4255
+ await this._dispatcher.publish('state_change', {
4252
4256
  state: this._publicState(this._state),
4253
4257
  attempt: attempt - 1,
4254
4258
  reason: 'max_attempts_exhausted',
@@ -4260,7 +4264,7 @@ export class AUNClient {
4260
4264
  const sleepMs = reconnectSleepDelaySeconds(delay, maxBaseDelay) * 1000;
4261
4265
  this._nextRetryAt = new Date(Date.now() + sleepMs);
4262
4266
  this._state = 'retry_backoff';
4263
- await this._dispatcher.publish('connection.state', {
4267
+ await this._dispatcher.publish('state_change', {
4264
4268
  state: this._publicState(this._state),
4265
4269
  attempt,
4266
4270
  next_retry_at: this._nextRetryAt.getTime() / 1000,
@@ -4274,7 +4278,7 @@ export class AUNClient {
4274
4278
  }
4275
4279
  // 退避结束,进入 reconnecting 状态
4276
4280
  this._state = 'reconnecting';
4277
- await this._dispatcher.publish('connection.state', {
4281
+ await this._dispatcher.publish('state_change', {
4278
4282
  state: this._publicState(this._state),
4279
4283
  attempt,
4280
4284
  });
@@ -4312,7 +4316,7 @@ export class AUNClient {
4312
4316
  this._nextRetryAt = null;
4313
4317
  this._reconnectActive = false;
4314
4318
  this._reconnectAbort = null;
4315
- await this._dispatcher.publish('connection.state', {
4319
+ await this._dispatcher.publish('state_change', {
4316
4320
  state: this._publicState(this._state),
4317
4321
  error: formatCaughtError(exc),
4318
4322
  attempt,