@sjawhar/claude-envoy 4.19.2 → 4.20.1

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.
@@ -2,5 +2,5 @@
2
2
  "name": "claude-envoy",
3
3
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
4
4
  "mcpServers": "./.mcp.json",
5
- "version": "4.19.2"
5
+ "version": "4.20.1"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "4.19.2",
3
+ "version": "4.20.1",
4
4
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
5
5
  "mcpServers": {}
6
6
  }
@@ -29490,6 +29490,24 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
29490
29490
  }
29491
29491
  return new LoggableError(`${source} is broker, but the trade for the session's token failed: ${tradeFailureReason(error)}`);
29492
29492
  };
29493
+ const expiresAt = () => held?.token.expiresAt ?? new Date(0);
29494
+ const needsReconnect = () => presented !== undefined && held !== undefined && presented !== held.token.accessToken;
29495
+ const drop = () => {
29496
+ const dropped = held;
29497
+ held = undefined;
29498
+ if (dropped !== undefined)
29499
+ dropTradedToken(env, dropped);
29500
+ };
29501
+ const tokenGeneration = () => generation;
29502
+ const tokenSession = () => held?.session;
29503
+ const refusals = brokerTokenRefusals({
29504
+ expiresAt,
29505
+ needsReconnect,
29506
+ drop,
29507
+ tokenGeneration,
29508
+ tokenSession
29509
+ });
29510
+ let admissions = { count: 0, dialedAt: undefined };
29493
29511
  return {
29494
29512
  ready: async (options = {}) => {
29495
29513
  if (live())
@@ -29528,16 +29546,16 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
29528
29546
  presented = accessToken;
29529
29547
  return { auth_token: accessToken, sig };
29530
29548
  },
29531
- expiresAt: () => held?.token.expiresAt ?? new Date(0),
29532
- needsReconnect: () => presented !== undefined && held !== undefined && presented !== held.token.accessToken,
29533
- drop: () => {
29534
- const dropped = held;
29535
- held = undefined;
29536
- if (dropped !== undefined)
29537
- dropTradedToken(env, dropped);
29549
+ expiresAt,
29550
+ needsReconnect,
29551
+ tokenGeneration,
29552
+ tokenSession,
29553
+ refused: refusals.refused,
29554
+ admitted: (dialedAt) => {
29555
+ admissions = { count: admissions.count + 1, dialedAt };
29556
+ refusals.reset();
29538
29557
  },
29539
- tokenGeneration: () => generation,
29540
- tokenSession: () => held?.session
29558
+ admissions: () => admissions
29541
29559
  };
29542
29560
  }
29543
29561
  var RENEW_FLOOR_MS = 1000;
@@ -29551,6 +29569,36 @@ var REFUSED_CODES = new Set([
29551
29569
  ]);
29552
29570
  var ERRORED = "error";
29553
29571
  var RECONNECTED = "reconnect";
29572
+ function brokerTokenRefusals(token) {
29573
+ let refusals = 0;
29574
+ let counting = token.tokenGeneration();
29575
+ const droppedFor = new Set;
29576
+ return {
29577
+ refused: (code) => {
29578
+ const live = token.expiresAt().getTime() > Date.now();
29579
+ if (!REFUSED_CODES.has(code) || !live || token.needsReconnect())
29580
+ return;
29581
+ const generation = token.tokenGeneration();
29582
+ if (generation !== counting) {
29583
+ counting = generation;
29584
+ refusals = 0;
29585
+ }
29586
+ refusals += 1;
29587
+ const session = token.tokenSession();
29588
+ const droppedBefore = session !== undefined && droppedFor.has(session);
29589
+ if (refusals !== REFUSALS_BEFORE_DROP || session === undefined || droppedBefore) {
29590
+ return { droppedBefore, dropped: false };
29591
+ }
29592
+ droppedFor.add(session);
29593
+ token.drop();
29594
+ return { droppedBefore, dropped: true };
29595
+ },
29596
+ reset: () => {
29597
+ refusals = 0;
29598
+ droppedFor.clear();
29599
+ }
29600
+ };
29601
+ }
29554
29602
  function warnedEvery(warn) {
29555
29603
  let warnedAt;
29556
29604
  return {
@@ -29646,38 +29694,23 @@ function keepNatsCredential(connection, credential, warn) {
29646
29694
  else
29647
29695
  schedule(0);
29648
29696
  };
29649
- const live = () => credential.expiresAt().getTime() > Date.now();
29650
29697
  (async () => {
29651
- let refusals = 0;
29652
- let counting = credential.tokenGeneration();
29653
- const droppedFor = new Set;
29654
29698
  for await (const status of statuses) {
29655
29699
  if (stopped)
29656
29700
  return;
29657
29701
  if (status.type === RECONNECTED) {
29658
- refusals = 0;
29659
- droppedFor.clear();
29702
+ credential.admitted();
29660
29703
  refusal.reset();
29661
29704
  continue;
29662
29705
  }
29663
29706
  if (status.type !== ERRORED || typeof status.data !== "string")
29664
29707
  continue;
29665
- if (!REFUSED_CODES.has(status.data) || !live() || credential.needsReconnect())
29708
+ const counted = credential.refused(status.data);
29709
+ if (counted === undefined)
29666
29710
  continue;
29667
- const token = credential.tokenGeneration();
29668
- if (token !== counting) {
29669
- counting = token;
29670
- refusals = 0;
29671
- }
29672
- refusals += 1;
29673
- const session = credential.tokenSession();
29674
- const dropped = session !== undefined && droppedFor.has(session);
29675
- refusal.warn(`the NATS server refused the connection's live broker token (${status.data}): the auth service is away, or the token was revoked; the connection keeps redialling, and ${dropped ? "this session's token was dropped and another traded once already, so none is dropped again until the connection is back" : "at the second refusal the token is dropped and another traded"}`);
29676
- if (refusals !== REFUSALS_BEFORE_DROP || session === undefined || dropped)
29677
- continue;
29678
- droppedFor.add(session);
29679
- credential.drop();
29680
- renewNow();
29711
+ refusal.warn(`the NATS server refused the connection's live broker token (${status.data}): the auth service is away, or the token was revoked; the connection keeps redialling, and ${counted.droppedBefore ? "this session's token was dropped and another traded once already, so none is dropped again until the connection is back" : "at the second refusal the token is dropped and another traded"}`);
29712
+ if (counted.dropped)
29713
+ renewNow();
29681
29714
  }
29682
29715
  })().catch((error) => {
29683
29716
  if (!stopped)
package/dist/dispatch.js CHANGED
@@ -30741,6 +30741,24 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
30741
30741
  }
30742
30742
  return new LoggableError(`${source} is broker, but the trade for the session's token failed: ${tradeFailureReason(error)}`);
30743
30743
  };
30744
+ const expiresAt = () => held?.token.expiresAt ?? new Date(0);
30745
+ const needsReconnect = () => presented !== undefined && held !== undefined && presented !== held.token.accessToken;
30746
+ const drop = () => {
30747
+ const dropped = held;
30748
+ held = undefined;
30749
+ if (dropped !== undefined)
30750
+ dropTradedToken(env, dropped);
30751
+ };
30752
+ const tokenGeneration = () => generation;
30753
+ const tokenSession = () => held?.session;
30754
+ const refusals = brokerTokenRefusals({
30755
+ expiresAt,
30756
+ needsReconnect,
30757
+ drop,
30758
+ tokenGeneration,
30759
+ tokenSession
30760
+ });
30761
+ let admissions = { count: 0, dialedAt: undefined };
30744
30762
  return {
30745
30763
  ready: async (options = {}) => {
30746
30764
  if (live())
@@ -30779,16 +30797,16 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
30779
30797
  presented = accessToken;
30780
30798
  return { auth_token: accessToken, sig };
30781
30799
  },
30782
- expiresAt: () => held?.token.expiresAt ?? new Date(0),
30783
- needsReconnect: () => presented !== undefined && held !== undefined && presented !== held.token.accessToken,
30784
- drop: () => {
30785
- const dropped = held;
30786
- held = undefined;
30787
- if (dropped !== undefined)
30788
- dropTradedToken(env, dropped);
30800
+ expiresAt,
30801
+ needsReconnect,
30802
+ tokenGeneration,
30803
+ tokenSession,
30804
+ refused: refusals.refused,
30805
+ admitted: (dialedAt) => {
30806
+ admissions = { count: admissions.count + 1, dialedAt };
30807
+ refusals.reset();
30789
30808
  },
30790
- tokenGeneration: () => generation,
30791
- tokenSession: () => held?.session
30809
+ admissions: () => admissions
30792
30810
  };
30793
30811
  }
30794
30812
  var RENEW_FLOOR_MS = 1000;
@@ -30802,6 +30820,36 @@ var REFUSED_CODES = new Set([
30802
30820
  ]);
30803
30821
  var ERRORED = "error";
30804
30822
  var RECONNECTED = "reconnect";
30823
+ function brokerTokenRefusals(token) {
30824
+ let refusals = 0;
30825
+ let counting = token.tokenGeneration();
30826
+ const droppedFor = new Set;
30827
+ return {
30828
+ refused: (code) => {
30829
+ const live = token.expiresAt().getTime() > Date.now();
30830
+ if (!REFUSED_CODES.has(code) || !live || token.needsReconnect())
30831
+ return;
30832
+ const generation = token.tokenGeneration();
30833
+ if (generation !== counting) {
30834
+ counting = generation;
30835
+ refusals = 0;
30836
+ }
30837
+ refusals += 1;
30838
+ const session = token.tokenSession();
30839
+ const droppedBefore = session !== undefined && droppedFor.has(session);
30840
+ if (refusals !== REFUSALS_BEFORE_DROP || session === undefined || droppedBefore) {
30841
+ return { droppedBefore, dropped: false };
30842
+ }
30843
+ droppedFor.add(session);
30844
+ token.drop();
30845
+ return { droppedBefore, dropped: true };
30846
+ },
30847
+ reset: () => {
30848
+ refusals = 0;
30849
+ droppedFor.clear();
30850
+ }
30851
+ };
30852
+ }
30805
30853
  function warnedEvery(warn) {
30806
30854
  let warnedAt;
30807
30855
  return {
@@ -30897,38 +30945,23 @@ function keepNatsCredential(connection, credential, warn) {
30897
30945
  else
30898
30946
  schedule(0);
30899
30947
  };
30900
- const live = () => credential.expiresAt().getTime() > Date.now();
30901
30948
  (async () => {
30902
- let refusals = 0;
30903
- let counting = credential.tokenGeneration();
30904
- const droppedFor = new Set;
30905
30949
  for await (const status of statuses) {
30906
30950
  if (stopped)
30907
30951
  return;
30908
30952
  if (status.type === RECONNECTED) {
30909
- refusals = 0;
30910
- droppedFor.clear();
30953
+ credential.admitted();
30911
30954
  refusal.reset();
30912
30955
  continue;
30913
30956
  }
30914
30957
  if (status.type !== ERRORED || typeof status.data !== "string")
30915
30958
  continue;
30916
- if (!REFUSED_CODES.has(status.data) || !live() || credential.needsReconnect())
30959
+ const counted = credential.refused(status.data);
30960
+ if (counted === undefined)
30917
30961
  continue;
30918
- const token = credential.tokenGeneration();
30919
- if (token !== counting) {
30920
- counting = token;
30921
- refusals = 0;
30922
- }
30923
- refusals += 1;
30924
- const session = credential.tokenSession();
30925
- const dropped = session !== undefined && droppedFor.has(session);
30926
- refusal.warn(`the NATS server refused the connection's live broker token (${status.data}): the auth service is away, or the token was revoked; the connection keeps redialling, and ${dropped ? "this session's token was dropped and another traded once already, so none is dropped again until the connection is back" : "at the second refusal the token is dropped and another traded"}`);
30927
- if (refusals !== REFUSALS_BEFORE_DROP || session === undefined || dropped)
30928
- continue;
30929
- droppedFor.add(session);
30930
- credential.drop();
30931
- renewNow();
30962
+ refusal.warn(`the NATS server refused the connection's live broker token (${status.data}): the auth service is away, or the token was revoked; the connection keeps redialling, and ${counted.droppedBefore ? "this session's token was dropped and another traded once already, so none is dropped again until the connection is back" : "at the second refusal the token is dropped and another traded"}`);
30963
+ if (counted.dropped)
30964
+ renewNow();
30932
30965
  }
30933
30966
  })().catch((error) => {
30934
30967
  if (!stopped)
@@ -52650,6 +52650,24 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
52650
52650
  }
52651
52651
  return new LoggableError(`${source} is broker, but the trade for the session's token failed: ${tradeFailureReason(error)}`);
52652
52652
  };
52653
+ const expiresAt = () => held?.token.expiresAt ?? new Date(0);
52654
+ const needsReconnect = () => presented !== undefined && held !== undefined && presented !== held.token.accessToken;
52655
+ const drop = () => {
52656
+ const dropped = held;
52657
+ held = undefined;
52658
+ if (dropped !== undefined)
52659
+ dropTradedToken(env, dropped);
52660
+ };
52661
+ const tokenGeneration = () => generation;
52662
+ const tokenSession = () => held?.session;
52663
+ const refusals = brokerTokenRefusals({
52664
+ expiresAt,
52665
+ needsReconnect,
52666
+ drop,
52667
+ tokenGeneration,
52668
+ tokenSession
52669
+ });
52670
+ let admissions = { count: 0, dialedAt: undefined };
52653
52671
  return {
52654
52672
  ready: async (options = {}) => {
52655
52673
  if (live())
@@ -52688,16 +52706,16 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
52688
52706
  presented = accessToken;
52689
52707
  return { auth_token: accessToken, sig };
52690
52708
  },
52691
- expiresAt: () => held?.token.expiresAt ?? new Date(0),
52692
- needsReconnect: () => presented !== undefined && held !== undefined && presented !== held.token.accessToken,
52693
- drop: () => {
52694
- const dropped = held;
52695
- held = undefined;
52696
- if (dropped !== undefined)
52697
- dropTradedToken(env, dropped);
52709
+ expiresAt,
52710
+ needsReconnect,
52711
+ tokenGeneration,
52712
+ tokenSession,
52713
+ refused: refusals.refused,
52714
+ admitted: (dialedAt) => {
52715
+ admissions = { count: admissions.count + 1, dialedAt };
52716
+ refusals.reset();
52698
52717
  },
52699
- tokenGeneration: () => generation,
52700
- tokenSession: () => held?.session
52718
+ admissions: () => admissions
52701
52719
  };
52702
52720
  }
52703
52721
  var RENEW_FLOOR_MS = 1000;
@@ -52711,6 +52729,36 @@ var REFUSED_CODES = new Set([
52711
52729
  ]);
52712
52730
  var ERRORED = "error";
52713
52731
  var RECONNECTED = "reconnect";
52732
+ function brokerTokenRefusals(token) {
52733
+ let refusals = 0;
52734
+ let counting = token.tokenGeneration();
52735
+ const droppedFor = new Set;
52736
+ return {
52737
+ refused: (code) => {
52738
+ const live = token.expiresAt().getTime() > Date.now();
52739
+ if (!REFUSED_CODES.has(code) || !live || token.needsReconnect())
52740
+ return;
52741
+ const generation = token.tokenGeneration();
52742
+ if (generation !== counting) {
52743
+ counting = generation;
52744
+ refusals = 0;
52745
+ }
52746
+ refusals += 1;
52747
+ const session = token.tokenSession();
52748
+ const droppedBefore = session !== undefined && droppedFor.has(session);
52749
+ if (refusals !== REFUSALS_BEFORE_DROP || session === undefined || droppedBefore) {
52750
+ return { droppedBefore, dropped: false };
52751
+ }
52752
+ droppedFor.add(session);
52753
+ token.drop();
52754
+ return { droppedBefore, dropped: true };
52755
+ },
52756
+ reset: () => {
52757
+ refusals = 0;
52758
+ droppedFor.clear();
52759
+ }
52760
+ };
52761
+ }
52714
52762
  function warnedEvery(warn) {
52715
52763
  let warnedAt;
52716
52764
  return {
@@ -52806,38 +52854,23 @@ function keepNatsCredential(connection, credential, warn) {
52806
52854
  else
52807
52855
  schedule(0);
52808
52856
  };
52809
- const live = () => credential.expiresAt().getTime() > Date.now();
52810
52857
  (async () => {
52811
- let refusals = 0;
52812
- let counting = credential.tokenGeneration();
52813
- const droppedFor = new Set;
52814
52858
  for await (const status of statuses) {
52815
52859
  if (stopped)
52816
52860
  return;
52817
52861
  if (status.type === RECONNECTED) {
52818
- refusals = 0;
52819
- droppedFor.clear();
52862
+ credential.admitted();
52820
52863
  refusal.reset();
52821
52864
  continue;
52822
52865
  }
52823
52866
  if (status.type !== ERRORED || typeof status.data !== "string")
52824
52867
  continue;
52825
- if (!REFUSED_CODES.has(status.data) || !live() || credential.needsReconnect())
52868
+ const counted = credential.refused(status.data);
52869
+ if (counted === undefined)
52826
52870
  continue;
52827
- const token = credential.tokenGeneration();
52828
- if (token !== counting) {
52829
- counting = token;
52830
- refusals = 0;
52831
- }
52832
- refusals += 1;
52833
- const session = credential.tokenSession();
52834
- const dropped = session !== undefined && droppedFor.has(session);
52835
- refusal.warn(`the NATS server refused the connection's live broker token (${status.data}): the auth service is away, or the token was revoked; the connection keeps redialling, and ${dropped ? "this session's token was dropped and another traded once already, so none is dropped again until the connection is back" : "at the second refusal the token is dropped and another traded"}`);
52836
- if (refusals !== REFUSALS_BEFORE_DROP || session === undefined || dropped)
52837
- continue;
52838
- droppedFor.add(session);
52839
- credential.drop();
52840
- renewNow();
52871
+ refusal.warn(`the NATS server refused the connection's live broker token (${status.data}): the auth service is away, or the token was revoked; the connection keeps redialling, and ${counted.droppedBefore ? "this session's token was dropped and another traded once already, so none is dropped again until the connection is back" : "at the second refusal the token is dropped and another traded"}`);
52872
+ if (counted.dropped)
52873
+ renewNow();
52841
52874
  }
52842
52875
  })().catch((error) => {
52843
52876
  if (!stopped)
@@ -56136,10 +56169,72 @@ function natsConnectionOptions(input) {
56136
56169
  timeout: NATS_DIAL_TIMEOUT_MS,
56137
56170
  reconnect: true,
56138
56171
  maxReconnectAttempts: -1,
56139
- reconnectTimeWait: 2000,
56140
56172
  pingInterval: NATS_PING_INTERVAL_MS,
56141
56173
  maxPingOut: NATS_MAX_PINGS_OUT,
56142
- ...input.credential.kind === "broker" ? { ignoreAuthErrorAbort: true } : {}
56174
+ ...input.credential.kind === "broker" ? {
56175
+ ignoreAuthErrorAbort: true,
56176
+ reconnectDelayHandler: brokerRedialDelays(input.credential.broker)
56177
+ } : { reconnectTimeWait: 2000 }
56178
+ };
56179
+ }
56180
+ var BROKER_REDIAL_FIRST_MS = 4000;
56181
+ var BROKER_REDIAL_CAP_MS = 20000;
56182
+ var BROKER_REDIAL_OUTAGE_GAP_MS = 60000;
56183
+ var BROKER_REDIAL_POLL_MS = 1000;
56184
+ var DUE_SLACK_MS = 50;
56185
+ function brokerRedialWaitBounds(wait) {
56186
+ const highestMs = Math.min(BROKER_REDIAL_CAP_MS, BROKER_REDIAL_FIRST_MS * 2 ** Math.min(wait - 1, 30));
56187
+ return { lowestMs: highestMs / 2, highestMs };
56188
+ }
56189
+ function brokerRedialWaitMs(wait, random) {
56190
+ const { lowestMs, highestMs } = brokerRedialWaitBounds(wait);
56191
+ return Math.round(lowestMs + random() * (highestMs - lowestMs));
56192
+ }
56193
+ function brokerRedialDelays(credential, random = Math.random, now = Date.now, pollMs = BROKER_REDIAL_POLL_MS) {
56194
+ let lastCall = Number.NEGATIVE_INFINITY;
56195
+ let dialedAt = 0;
56196
+ let dueAt = Number.NEGATIVE_INFINITY;
56197
+ let waits = 0;
56198
+ let rushed;
56199
+ let dialedSession;
56200
+ let rushedInWait = false;
56201
+ let admissions = credential.admissions().count;
56202
+ return () => {
56203
+ const at = now();
56204
+ if (at - lastCall > BROKER_REDIAL_OUTAGE_GAP_MS) {
56205
+ dueAt = Number.NEGATIVE_INFINITY;
56206
+ waits = 0;
56207
+ }
56208
+ lastCall = at;
56209
+ const admitted = credential.admissions();
56210
+ if (admitted.count !== admissions) {
56211
+ admissions = admitted.count;
56212
+ rushedInWait = false;
56213
+ if (admitted.dialedAt !== undefined && admitted.dialedAt > dialedAt) {
56214
+ dialedAt = admitted.dialedAt;
56215
+ }
56216
+ }
56217
+ const unpresented = credential.needsReconnect() ? credential.tokenGeneration() : undefined;
56218
+ const session = credential.tokenSession();
56219
+ if (at < dueAt - DUE_SLACK_MS) {
56220
+ const renewal = session === dialedSession;
56221
+ if (unpresented === undefined || unpresented === rushed || rushedInWait && renewal) {
56222
+ return Math.min(dueAt, at + pollMs) - dialedAt;
56223
+ }
56224
+ rushed = unpresented;
56225
+ rushedInWait = true;
56226
+ dialedSession = session;
56227
+ dialedAt = at;
56228
+ return 0;
56229
+ }
56230
+ if (unpresented !== undefined)
56231
+ rushed = unpresented;
56232
+ dialedSession = session;
56233
+ rushedInWait = false;
56234
+ waits += 1;
56235
+ dialedAt = at;
56236
+ dueAt = at + brokerRedialWaitMs(waits, random);
56237
+ return 0;
56143
56238
  };
56144
56239
  }
56145
56240
  function natsServersForLog(setting, count) {
@@ -56154,6 +56249,7 @@ var NATS_DIAL_PLAN = {
56154
56249
  maxDelayMs: 4000,
56155
56250
  budgetMs: 25000
56156
56251
  };
56252
+ var NATS_DIAL_TOKEN_DROPPED = "the hub refused the session's broker token twice, so the token was dropped and another trade started";
56157
56253
  var NATS_MIN_REDIAL_BOUND_MS = 500;
56158
56254
 
56159
56255
  class NatsDialBoundError extends LoggableError {
@@ -56175,18 +56271,41 @@ var NEVER_CURED = {
56175
56271
  function redialCures(error, options) {
56176
56272
  if (error instanceof NatsDialBoundError)
56177
56273
  return true;
56178
- if (!(error instanceof Error) || !("code" in error) || typeof error.code !== "string")
56274
+ const code = errorCode(error);
56275
+ if (code === undefined)
56179
56276
  return false;
56180
- const { code } = error;
56181
56277
  if (AUTHORIZATION_REFUSALS[code] === true)
56182
56278
  return options.ignoreAuthErrorAbort === true;
56183
56279
  return NEVER_CURED[code] !== true && !code.startsWith("ERR_");
56184
56280
  }
56281
+ function errorCode(error) {
56282
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
56283
+ }
56284
+ function brokerDialRefusals(credential, random) {
56285
+ if (credential?.kind !== "broker")
56286
+ return;
56287
+ const { broker } = credential;
56288
+ let refusals = 0;
56289
+ return {
56290
+ refused: (code) => {
56291
+ if (code === undefined || AUTHORIZATION_REFUSALS[code] !== true)
56292
+ return;
56293
+ refusals += 1;
56294
+ const dropped = broker.refused(code)?.dropped === true;
56295
+ if (dropped)
56296
+ broker.renew(AbortSignal.timeout(TRADE_DEADLINE_MS)).catch(() => {});
56297
+ return { waitMs: brokerRedialWaitMs(refusals, random), dropped };
56298
+ },
56299
+ admitted: (dialedAt) => broker.admitted(dialedAt)
56300
+ };
56301
+ }
56185
56302
  async function connectNats(connect, options, plan, hooks = {}) {
56186
56303
  const started = performance.now();
56187
56304
  const elapsed = () => performance.now() - started;
56188
56305
  const timeout = options.timeout ?? NATS_DIAL_TIMEOUT_MS;
56189
56306
  const servers = Array.isArray(options.servers) ? Math.max(1, options.servers.length) : 1;
56307
+ const brokerRefusals = brokerDialRefusals(hooks.credential, hooks.random ?? Math.random);
56308
+ const wait = hooks.delay ?? delay;
56190
56309
  let delayMs = plan.firstDelayMs;
56191
56310
  let failed;
56192
56311
  for (let attempt = 1;; attempt += 1) {
@@ -56194,24 +56313,30 @@ async function connectNats(connect, options, plan, hooks = {}) {
56194
56313
  throw failed ?? new LoggableError("the NATS dial was stopped before it began");
56195
56314
  }
56196
56315
  const bound = Math.max(1, Math.round(Math.min(timeout, attempt === 1 ? hooks.firstBoundMs ?? timeout : plan.budgetMs - elapsed())));
56316
+ const dialedAt = Date.now();
56197
56317
  try {
56198
56318
  const nc = await boundedDial(connect, {
56199
56319
  ...options,
56200
56320
  timeout: Math.min(bound, Math.max(NATS_MIN_REDIAL_BOUND_MS, Math.floor(bound / servers)))
56201
56321
  }, bound);
56202
56322
  keepWholeTimeout(nc, timeout);
56323
+ brokerRefusals?.admitted(dialedAt);
56203
56324
  return nc;
56204
56325
  } catch (error) {
56205
56326
  failed = error;
56206
- const waitEnds = elapsed() + delayMs;
56207
- if (!redialCures(error, options) || waitEnds + NATS_MIN_REDIAL_BOUND_MS > plan.budgetMs || hooks.stopped?.() === true) {
56327
+ const refusal = brokerRefusals?.refused(errorCode(error));
56328
+ if (refusal?.dropped === true)
56329
+ hooks.onTokenDropped?.(error, attempt);
56330
+ const waitMs = refusal?.waitMs ?? delayMs;
56331
+ if (!redialCures(error, options) || elapsed() + waitMs + NATS_MIN_REDIAL_BOUND_MS > plan.budgetMs || hooks.stopped?.() === true) {
56208
56332
  throw error;
56209
56333
  }
56210
- hooks.onRetry?.(error, delayMs, attempt);
56211
- await delay(delayMs);
56334
+ hooks.onRetry?.(error, waitMs, attempt);
56335
+ await wait(waitMs);
56212
56336
  if (plan.budgetMs - elapsed() < NATS_MIN_REDIAL_BOUND_MS)
56213
56337
  throw error;
56214
- delayMs = Math.min(delayMs * 2, plan.maxDelayMs);
56338
+ if (refusal === undefined)
56339
+ delayMs = Math.min(delayMs * 2, plan.maxDelayMs);
56215
56340
  }
56216
56341
  }
56217
56342
  }
@@ -56286,7 +56411,7 @@ var CHANNEL_DIAL_PLAN = {
56286
56411
  ...NATS_DIAL_PLAN,
56287
56412
  budgetMs: Number.POSITIVE_INFINITY
56288
56413
  };
56289
- async function dialChannelNats(inbound, name, warn, dial = import_nats4.connect, signal, plan = CHANNEL_DIAL_PLAN) {
56414
+ async function dialChannelNats(inbound, name, warn, dial = import_nats4.connect, signal, plan = CHANNEL_DIAL_PLAN, waits = {}) {
56290
56415
  const stopped = Promise.withResolvers();
56291
56416
  const onAbort = () => stopped.resolve("stopping");
56292
56417
  if (signal?.aborted === true)
@@ -56309,7 +56434,10 @@ async function dialChannelNats(inbound, name, warn, dial = import_nats4.connect,
56309
56434
  const broker = natsCredential.kind === "broker" ? natsCredential.broker : undefined;
56310
56435
  await unlessStopped(broker?.ready({ life: signal ?? new AbortController().signal }) ?? Promise.resolve());
56311
56436
  const dialing = connectNats(dial, natsConnectionOptions({ servers: inbound.natsUrls, name, credential: natsCredential }), plan, {
56437
+ ...waits,
56312
56438
  stopped: () => signal?.aborted === true,
56439
+ credential: natsCredential,
56440
+ onTokenDropped: (error, attempt) => warn(`${NATS_DIAL_TOKEN_DROPPED} (dial ${attempt})`, error),
56313
56441
  onRetry: (error, delayMs) => warn(`${failed(error)}; dialing again in ${delayMs} ms`, error)
56314
56442
  });
56315
56443
  let connection;
@@ -57836,7 +57964,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
57836
57964
 
57837
57965
  // package.json
57838
57966
  var name2 = "@sjawhar/claude-envoy";
57839
- var version2 = "4.19.2";
57967
+ var version2 = "4.20.1";
57840
57968
  var legion = {
57841
57969
  daemonApiVersion: 202
57842
57970
  };
@@ -29516,6 +29516,24 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
29516
29516
  }
29517
29517
  return new LoggableError(`${source} is broker, but the trade for the session's token failed: ${tradeFailureReason(error)}`);
29518
29518
  };
29519
+ const expiresAt = () => held?.token.expiresAt ?? new Date(0);
29520
+ const needsReconnect = () => presented !== undefined && held !== undefined && presented !== held.token.accessToken;
29521
+ const drop = () => {
29522
+ const dropped = held;
29523
+ held = undefined;
29524
+ if (dropped !== undefined)
29525
+ dropTradedToken(env, dropped);
29526
+ };
29527
+ const tokenGeneration = () => generation;
29528
+ const tokenSession = () => held?.session;
29529
+ const refusals = brokerTokenRefusals({
29530
+ expiresAt,
29531
+ needsReconnect,
29532
+ drop,
29533
+ tokenGeneration,
29534
+ tokenSession
29535
+ });
29536
+ let admissions = { count: 0, dialedAt: undefined };
29519
29537
  return {
29520
29538
  ready: async (options = {}) => {
29521
29539
  if (live())
@@ -29554,16 +29572,16 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
29554
29572
  presented = accessToken;
29555
29573
  return { auth_token: accessToken, sig };
29556
29574
  },
29557
- expiresAt: () => held?.token.expiresAt ?? new Date(0),
29558
- needsReconnect: () => presented !== undefined && held !== undefined && presented !== held.token.accessToken,
29559
- drop: () => {
29560
- const dropped = held;
29561
- held = undefined;
29562
- if (dropped !== undefined)
29563
- dropTradedToken(env, dropped);
29575
+ expiresAt,
29576
+ needsReconnect,
29577
+ tokenGeneration,
29578
+ tokenSession,
29579
+ refused: refusals.refused,
29580
+ admitted: (dialedAt) => {
29581
+ admissions = { count: admissions.count + 1, dialedAt };
29582
+ refusals.reset();
29564
29583
  },
29565
- tokenGeneration: () => generation,
29566
- tokenSession: () => held?.session
29584
+ admissions: () => admissions
29567
29585
  };
29568
29586
  }
29569
29587
  var RENEW_FLOOR_MS = 1000;
@@ -29577,6 +29595,36 @@ var REFUSED_CODES = new Set([
29577
29595
  ]);
29578
29596
  var ERRORED = "error";
29579
29597
  var RECONNECTED = "reconnect";
29598
+ function brokerTokenRefusals(token) {
29599
+ let refusals = 0;
29600
+ let counting = token.tokenGeneration();
29601
+ const droppedFor = new Set;
29602
+ return {
29603
+ refused: (code) => {
29604
+ const live = token.expiresAt().getTime() > Date.now();
29605
+ if (!REFUSED_CODES.has(code) || !live || token.needsReconnect())
29606
+ return;
29607
+ const generation = token.tokenGeneration();
29608
+ if (generation !== counting) {
29609
+ counting = generation;
29610
+ refusals = 0;
29611
+ }
29612
+ refusals += 1;
29613
+ const session = token.tokenSession();
29614
+ const droppedBefore = session !== undefined && droppedFor.has(session);
29615
+ if (refusals !== REFUSALS_BEFORE_DROP || session === undefined || droppedBefore) {
29616
+ return { droppedBefore, dropped: false };
29617
+ }
29618
+ droppedFor.add(session);
29619
+ token.drop();
29620
+ return { droppedBefore, dropped: true };
29621
+ },
29622
+ reset: () => {
29623
+ refusals = 0;
29624
+ droppedFor.clear();
29625
+ }
29626
+ };
29627
+ }
29580
29628
  function warnedEvery(warn) {
29581
29629
  let warnedAt;
29582
29630
  return {
@@ -29672,38 +29720,23 @@ function keepNatsCredential(connection, credential, warn) {
29672
29720
  else
29673
29721
  schedule(0);
29674
29722
  };
29675
- const live = () => credential.expiresAt().getTime() > Date.now();
29676
29723
  (async () => {
29677
- let refusals = 0;
29678
- let counting = credential.tokenGeneration();
29679
- const droppedFor = new Set;
29680
29724
  for await (const status of statuses) {
29681
29725
  if (stopped)
29682
29726
  return;
29683
29727
  if (status.type === RECONNECTED) {
29684
- refusals = 0;
29685
- droppedFor.clear();
29728
+ credential.admitted();
29686
29729
  refusal.reset();
29687
29730
  continue;
29688
29731
  }
29689
29732
  if (status.type !== ERRORED || typeof status.data !== "string")
29690
29733
  continue;
29691
- if (!REFUSED_CODES.has(status.data) || !live() || credential.needsReconnect())
29734
+ const counted = credential.refused(status.data);
29735
+ if (counted === undefined)
29692
29736
  continue;
29693
- const token = credential.tokenGeneration();
29694
- if (token !== counting) {
29695
- counting = token;
29696
- refusals = 0;
29697
- }
29698
- refusals += 1;
29699
- const session = credential.tokenSession();
29700
- const dropped = session !== undefined && droppedFor.has(session);
29701
- refusal.warn(`the NATS server refused the connection's live broker token (${status.data}): the auth service is away, or the token was revoked; the connection keeps redialling, and ${dropped ? "this session's token was dropped and another traded once already, so none is dropped again until the connection is back" : "at the second refusal the token is dropped and another traded"}`);
29702
- if (refusals !== REFUSALS_BEFORE_DROP || session === undefined || dropped)
29703
- continue;
29704
- droppedFor.add(session);
29705
- credential.drop();
29706
- renewNow();
29737
+ refusal.warn(`the NATS server refused the connection's live broker token (${status.data}): the auth service is away, or the token was revoked; the connection keeps redialling, and ${counted.droppedBefore ? "this session's token was dropped and another traded once already, so none is dropped again until the connection is back" : "at the second refusal the token is dropped and another traded"}`);
29738
+ if (counted.dropped)
29739
+ renewNow();
29707
29740
  }
29708
29741
  })().catch((error) => {
29709
29742
  if (!stopped)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "4.19.2",
3
+ "version": "4.20.1",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -8,6 +8,8 @@ import { LoggableError } from "@legion/envoy-client/errors"
8
8
  import {
9
9
  connectNats,
10
10
  NATS_DIAL_PLAN,
11
+ NATS_DIAL_TOKEN_DROPPED,
12
+ type NatsDialHooks,
11
13
  type NatsDialPlan,
12
14
  natsConnectionOptions,
13
15
  natsDialFailure,
@@ -124,16 +126,19 @@ export interface ChannelNatsSettings {
124
126
  * signed into the CONNECT itself, so a live one is taken before the dial; and the connection is
125
127
  * then kept on a token the auth service admits (`keepNatsCredential`, warnings through `warn`,
126
128
  * with no dial error, which tells them from a redial's), until `stop` or the connection closing.
127
- * A dial that fails is dialed again as `plan` says, which by default is for the server's life;
129
+ * A dial that fails is dialed again as `plan` says, which by default is for the server's life, and
130
+ * a hub's refusal of the session's broker token on the broker-token backoff (`connectNats`);
128
131
  * each redial is warned of, naming the servers by their setting and the credential it presented
129
132
  * beside why it failed, as a log may print both
130
133
  * (`natsDialFailure`: no part of a server's text, and the reason nats.js's code or the server's
131
134
  * fixed refusal, never text derived from what the servers were set to or what the client sent),
132
- * and `warn` is handed the failed dial's error with its line. A dial that fails for good (an
133
- * authorization refusal, or the end of a finite `plan`) throws the same line, as a
134
- * `LoggableError`; the error keeps no cause: nats.js's own error still carries them. A token that
135
- * cannot be taken fails with the credential's own line (`BrokerNatsCredential.ready`). `dial` is
136
- * nats.js's `connect`, or a test's.
135
+ * and `warn` is handed the failed dial's error with its line; a dial whose refusal dropped the
136
+ * session's broker token is warned of at the drop (`NATS_DIAL_TOKEN_DROPPED`). A dial that fails
137
+ * for good (an authorization refusal of a seed or of no credential, or the end of a finite `plan`)
138
+ * throws the same line, as a `LoggableError`; the error keeps no cause: nats.js's own error still
139
+ * carries them. A token that cannot be taken fails with the credential's own line
140
+ * (`BrokerNatsCredential.ready`). `dial` is nats.js's `connect`, or a test's, and `waits` how the
141
+ * dials wait between them, a test's where it sets one.
137
142
  *
138
143
  * `signal` aborting (the process is stopping) ends the wait for the token and for the dial at once,
139
144
  * with `START_STOPPING`, and starts no further dial; the token trade itself goes on, since it is
@@ -147,6 +152,7 @@ export async function dialChannelNats(
147
152
  dial: (options: ConnectionOptions) => Promise<NatsConnection> = connect,
148
153
  signal?: AbortSignal,
149
154
  plan: NatsDialPlan = CHANNEL_DIAL_PLAN,
155
+ waits: Pick<NatsDialHooks, "delay" | "random"> = {},
150
156
  ): Promise<ChannelNats> {
151
157
  const stopped = Promise.withResolvers<"stopping">()
152
158
  const onAbort = (): void => stopped.resolve("stopping")
@@ -186,13 +192,19 @@ export async function dialChannelNats(
186
192
  // A dial that fails is dialed again for the server's life, as the token wait above is:
187
193
  // Claude Code starts no channel server again once one ended, and a hub closes a dial whose
188
194
  // CONNECT came after its 2 s authentication timeout, then answers the next one. Each dial has
189
- // its own bound (`connectNats`); a stop ends the redials.
195
+ // its own bound (`connectNats`); a stop ends the redials. A hub's refusal of the session's
196
+ // broker token waits on the broker-token backoff, 2-4 s doubling to 10-20 s, and a token it
197
+ // refuses twice is dropped and another trade started at once.
190
198
  const dialing = connectNats(
191
199
  dial,
192
200
  natsConnectionOptions({ servers: inbound.natsUrls, name, credential: natsCredential }),
193
201
  plan,
194
202
  {
203
+ ...waits,
195
204
  stopped: () => signal?.aborted === true,
205
+ credential: natsCredential,
206
+ onTokenDropped: (error, attempt) =>
207
+ warn(`${NATS_DIAL_TOKEN_DROPPED} (dial ${attempt})`, error),
196
208
  onRetry: (error, delayMs) =>
197
209
  warn(`${failed(error)}; dialing again in ${delayMs} ms`, error),
198
210
  },