@sjawhar/claude-envoy 6.12.1 → 6.12.3

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.
@@ -36661,6 +36661,21 @@ var ProjectAccessChangedEventPayloadSchema = strictObject({
36661
36661
  ])
36662
36662
  }).readonly();
36663
36663
 
36664
+ // ../contracts/src/http-status.ts
36665
+ function outage(status) {
36666
+ return status >= 500 || status === 408 || status === 429;
36667
+ }
36668
+ function mayHaveReachedServer(status) {
36669
+ return status >= 500 || status === 408;
36670
+ }
36671
+ function retryAfterMs(headers, now = Date.now()) {
36672
+ const value = headers.get("Retry-After")?.trim() ?? "";
36673
+ if (/^\d+$/.test(value))
36674
+ return Number(value) * 1000;
36675
+ const at = Date.parse(value);
36676
+ return Number.isNaN(at) ? 0 : Math.max(0, at - now);
36677
+ }
36678
+
36664
36679
  // ../contracts/src/dispatch-api-limits.ts
36665
36680
  var MAX_ISSUE_BLOCKERS = 20;
36666
36681
  var MAX_ISSUE_ADVANCES = 20;
@@ -36693,7 +36708,7 @@ var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
36693
36708
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
36694
36709
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
36695
36710
  function retriesUnderKey(status, code) {
36696
- return status >= 500 || status === 408 || status === 429 || status === 409 && code === IDEMPOTENCY_KEY_IN_FLIGHT;
36711
+ return outage(status) || status === 409 && code === IDEMPOTENCY_KEY_IN_FLIGHT;
36697
36712
  }
36698
36713
  function answerNotKept(status, replayed, body) {
36699
36714
  return replayed && status >= 200 && status < 300 && typeof body === "object" && body !== null && Reflect.get(body, "code") === IDEMPOTENCY_ANSWER_NOT_KEPT;
@@ -44228,23 +44243,6 @@ async function genericGrantRequest(config, grantType, parameters, options) {
44228
44243
  return result;
44229
44244
  }
44230
44245
 
44231
- // ../cipher-client/src/oauth-refusal.ts
44232
- var INVALID_GRANT = "invalid_grant";
44233
- var REQUEST_TIMEOUT = 408;
44234
- var TOO_MANY_REQUESTS = 429;
44235
- function outage(status) {
44236
- return status >= 500 || status === REQUEST_TIMEOUT || status === TOO_MANY_REQUESTS;
44237
- }
44238
- function refusalCode(error) {
44239
- if (!(error instanceof ResponseBodyError))
44240
- return "";
44241
- const refuses = error.status >= 400 && error.status < 500 && !outage(error.status);
44242
- return refuses ? error.error : "";
44243
- }
44244
- function endsGrant(error) {
44245
- return error instanceof ResponseBodyError && error.error === INVALID_GRANT && (error.status === 400 || error.status === 401);
44246
- }
44247
-
44248
44246
  // ../cipher-client/src/wire.ts
44249
44247
  var TOKEN_PATH = "/v1/oauth/token";
44250
44248
  var GRANT_TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
@@ -44622,7 +44620,7 @@ async function signInFlow(env) {
44622
44620
  // ../cipher-client/src/token-errors.ts
44623
44621
  var INVALID_DPOP_PROOF = "invalid_dpop_proof";
44624
44622
  var USE_DPOP_NONCE = "use_dpop_nonce";
44625
- var INVALID_GRANT2 = "invalid_grant";
44623
+ var INVALID_GRANT = "invalid_grant";
44626
44624
  var MEMBERSHIP_HELD = "membership_held";
44627
44625
  var TOKEN_NOT_VALID = "Token is not valid or has expired.";
44628
44626
  var MACHINE_LOGIN_ENDED = "The machine login the subject token belongs to has ended.";
@@ -44643,8 +44641,8 @@ class BrokerRefusedError extends Error {
44643
44641
  this.code = KNOWN_OAUTH_ERROR_CODES.has(code) ? code : "";
44644
44642
  this.shownCode = shownCode;
44645
44643
  this.said = said;
44646
- this.podSessionUnregistered = code === INVALID_GRANT2 && description.startsWith(`${POD_SESSION_NOT_REGISTERED}:`);
44647
- this.subjectNotHonoured = status === 400 && (code === "invalid_request" && description.endsWith(TOKEN_NOT_VALID) || code === INVALID_GRANT2 && description.endsWith(MACHINE_LOGIN_ENDED));
44644
+ this.podSessionUnregistered = code === INVALID_GRANT && description.startsWith(`${POD_SESSION_NOT_REGISTERED}:`);
44645
+ this.subjectNotHonoured = status === 400 && (code === "invalid_request" && description.endsWith(TOKEN_NOT_VALID) || code === INVALID_GRANT && description.endsWith(MACHINE_LOGIN_ENDED));
44648
44646
  }
44649
44647
  get permanent() {
44650
44648
  return !outage(this.status) && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE && this.code !== MEMBERSHIP_HELD && !this.podSessionUnregistered;
@@ -46073,6 +46071,18 @@ async function importDpopKey(pkcs8Pem, name) {
46073
46071
  // ../cipher-client/src/loopback.ts
46074
46072
  var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
46075
46073
 
46074
+ // ../cipher-client/src/oauth-refusal.ts
46075
+ var INVALID_GRANT2 = "invalid_grant";
46076
+ function refusalCode(error) {
46077
+ if (!(error instanceof ResponseBodyError))
46078
+ return "";
46079
+ const refuses = error.status >= 400 && error.status < 500 && !outage(error.status);
46080
+ return refuses ? error.error : "";
46081
+ }
46082
+ function endsGrant(error) {
46083
+ return error instanceof ResponseBodyError && error.error === INVALID_GRANT2 && (error.status === 400 || error.status === 401);
46084
+ }
46085
+
46076
46086
  // ../cipher-client/src/device-login.ts
46077
46087
  var BROKER_SETTING = "AGENT_SECRETS_URL";
46078
46088
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
@@ -46205,7 +46215,7 @@ async function startDeviceLogin(options) {
46205
46215
  key: privateKey
46206
46216
  };
46207
46217
  }
46208
- function retryAfterMs(error) {
46218
+ function retryAfterMs2(error) {
46209
46219
  const value = responseOf(error)?.headers.get("retry-after")?.trim() ?? "";
46210
46220
  if (/^\d+$/.test(value))
46211
46221
  return Number(value) * 1000;
@@ -46268,7 +46278,7 @@ async function finishDeviceLogin(started, options) {
46268
46278
  const refusal = brokerRefusal("poll the code of", "this machine's device login", endpoint, error);
46269
46279
  throw new Error(`${refusal.message}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
46270
46280
  }
46271
- const asked = unanswered ? retryAfterMs(error) : 0;
46281
+ const asked = unanswered ? retryAfterMs2(error) : 0;
46272
46282
  waitMs = Math.max(waitMillisecondsOf(interval), asked);
46273
46283
  continue;
46274
46284
  }
@@ -48172,7 +48182,7 @@ var WRITE_TRANSITIONS = {
48172
48182
  "foreign-2xx": { "nothing-sent": landed("end"), "may-have-landed": landed("end") },
48173
48183
  "body-broken": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
48174
48184
  "body-malformed": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
48175
- "server-error": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
48185
+ "may-have-run": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
48176
48186
  "in-flight": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
48177
48187
  "try-later": { "nothing-sent": nothing("retry"), "may-have-landed": landed("retry") },
48178
48188
  silence: { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
@@ -48239,7 +48249,7 @@ class DispatchGatewayError extends DispatchServiceError {
48239
48249
  this.answer = answer;
48240
48250
  this.advice = advice;
48241
48251
  this.transient = gatewayClears(status);
48242
- this.mayHaveReachedDispatch = reachesDispatch(status);
48252
+ this.mayHaveReachedDispatch = mayHaveReachedServer(status);
48243
48253
  }
48244
48254
  }
48245
48255
  var PROXY_CODE_HEADER = "Cipher-Proxy-Code";
@@ -48284,7 +48294,7 @@ class DispatchWriteUnsettledError extends Error {
48284
48294
  name = "DispatchWriteUnsettledError";
48285
48295
  constructor(last, attempts, key, unanswered) {
48286
48296
  let answer;
48287
- let why = last instanceof DispatchServiceError && last.status >= 500 || last instanceof DispatchProxyRefusalError ? "an attempt of the write may have reached Dispatch" : "an earlier attempt of the write may have reached Dispatch";
48297
+ let why = last instanceof DispatchServiceError && mayHaveReachedServer(last.status) || last instanceof DispatchProxyRefusalError ? "an attempt of the write may have reached Dispatch" : "an earlier attempt of the write may have reached Dispatch";
48288
48298
  if (last instanceof DispatchGatewayError) {
48289
48299
  answer = last.answer;
48290
48300
  } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
@@ -48422,13 +48432,6 @@ function pauseFor(ms, signal) {
48422
48432
  signal.addEventListener("abort", stop, { once: true });
48423
48433
  return promise;
48424
48434
  }
48425
- function retryAfterMs2(response) {
48426
- const value = response.headers.get("Retry-After")?.trim() ?? "";
48427
- if (/^\d+$/.test(value))
48428
- return Number(value) * 1000;
48429
- const at = Date.parse(value);
48430
- return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
48431
- }
48432
48435
  var STREAMED_BODY_MIN = 1 << 20;
48433
48436
  var STREAMED_BODY_CHUNK = 64 << 10;
48434
48437
  function attemptBody(body, headers, progress) {
@@ -48517,14 +48520,14 @@ async function writeAnswer(response) {
48517
48520
  };
48518
48521
  }
48519
48522
  function isStoredKeyStatus(status) {
48520
- return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
48523
+ return status >= 400 && status < 500 && status !== 401 && !outage(status);
48521
48524
  }
48522
48525
  function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
48523
48526
  const { status } = answer.response;
48524
48527
  if (proxied && answer.response.headers.get(PROXY_CODE_HEADER) !== null) {
48525
48528
  if (answer.response.headers.get(PROXY_FORWARDED_HEADER) !== "false")
48526
48529
  return "proxy-unsettled";
48527
- return status >= 500 ? "proxy-failed" : "proxy-refused";
48530
+ return outage(status) ? "proxy-failed" : "proxy-refused";
48528
48531
  }
48529
48532
  if (status >= 200 && status < 300) {
48530
48533
  if (answer.notJson)
@@ -48545,7 +48548,7 @@ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
48545
48548
  if (!textRefusal && retriesUnderKey(status, answer.code)) {
48546
48549
  if (status === 409)
48547
48550
  return "in-flight";
48548
- return status >= 500 ? "server-error" : "try-later";
48551
+ return mayHaveReachedServer(status) ? "may-have-run" : "try-later";
48549
48552
  }
48550
48553
  if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
48551
48554
  return "judged";
@@ -48611,16 +48614,10 @@ function gatewayAdvice(method, status) {
48611
48614
  }
48612
48615
  if (method === "GET" || status >= 200 && status < 300)
48613
48616
  return "a retry may succeed";
48614
- return reachesDispatch(status) ? "the write may or may not have reached Dispatch: check whether it took effect before retrying it" : "the write did not reach Dispatch, and a retry may succeed";
48617
+ return mayHaveReachedServer(status) ? "the write may or may not have reached Dispatch: check whether it took effect before retrying it" : "the write did not reach Dispatch, and a retry may succeed";
48615
48618
  }
48616
48619
  function gatewayClears(status) {
48617
- return transientStatus(status) || status >= 200 && status < 300;
48618
- }
48619
- function transientStatus(status) {
48620
- return status >= 500 || status === 408 || status === 429;
48621
- }
48622
- function reachesDispatch(status) {
48623
- return status >= 500;
48620
+ return outage(status) || status >= 200 && status < 300;
48624
48621
  }
48625
48622
 
48626
48623
  class DispatchClient {
@@ -49376,7 +49373,7 @@ class DispatchClient {
49376
49373
  sent
49377
49374
  };
49378
49375
  }
49379
- const heard = { retryAfterMs: retryAfterMs2(response) };
49376
+ const heard = { retryAfterMs: retryAfterMs(response.headers) };
49380
49377
  if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
49381
49378
  progress.keyEchoed = true;
49382
49379
  let answer;
@@ -53991,7 +53988,7 @@ async function textWithPictures(text, pictures, owner, upload, actor) {
53991
53988
  } catch (error) {
53992
53989
  const earlier = addresses.length === 0 ? "" : `; the pictures before it are uploaded (${addresses.join(", ")})`;
53993
53990
  const landed = error instanceof DispatchWriteLandedError || error instanceof Error && error.cause instanceof DispatchWriteLandedError;
53994
- const refused = error instanceof DispatchGatewayError ? !error.mayHaveReachedDispatch : error instanceof DispatchServiceError && error.status < 500;
53991
+ const refused = error instanceof DispatchGatewayError ? !error.mayHaveReachedDispatch : error instanceof DispatchServiceError && !mayHaveReachedServer(error.status);
53995
53992
  const outcome = landed ? "was uploaded" : refused ? "was not uploaded" : "may or may not have been uploaded";
53996
53993
  throw new Error(`images: ${picture.path} ${outcome}: ${messageFor(error).replace(/\.$/, "")}. Nothing ` + `was posted${earlier}.`);
53997
53994
  }
@@ -55167,7 +55164,7 @@ function refuseMissingPost(error, post) {
55167
55164
  function writeMayHaveLanded(error) {
55168
55165
  if (error instanceof DispatchGatewayError)
55169
55166
  return error.mayHaveReachedDispatch;
55170
- return !(error instanceof DispatchServiceError) || error.status >= 500;
55167
+ return !(error instanceof DispatchServiceError) || mayHaveReachedServer(error.status);
55171
55168
  }
55172
55169
  function closeAccount(error, closingNote) {
55173
55170
  const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
@@ -61575,7 +61572,7 @@ class EnvoyApiError extends Error {
61575
61572
  } catch {}
61576
61573
  const redirected = shown.redirectTo === undefined ? "" : ` (a redirect to ${shown.redirectTo}, which this client does not follow)`;
61577
61574
  const notSentAnswer = details.status === 503 && parsed?.error.startsWith(`${MESSAGE_NOT_SENT_PREFIX}: `) === true;
61578
- const earlier = notSentAnswer && shown.afterUnanswered === true ? " An earlier attempt got no answer or a 5xx, so that attempt may have stored the message." : "";
61575
+ const earlier = notSentAnswer && shown.afterUnanswered === true ? " An earlier attempt got no answer, a 5xx or a 408, so that attempt may have stored the message." : "";
61579
61576
  super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}${redirected}: ${bodyForText(details.responseBody, shown.tokens ?? "", "the listener's error JSON")}` : `${parsed.error}${parsed.reason === undefined ? "" : ` (reason: ${parsed.reason})`}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}${earlier}`);
61580
61577
  this.details = details;
61581
61578
  this.expected = parsed?.expected;
@@ -61716,7 +61713,7 @@ function createEnvoyClient(config) {
61716
61713
  redirectTo: redirectOrigin(response, url, redacted),
61717
61714
  afterUnanswered: unanswered
61718
61715
  });
61719
- if (response.status >= 500) {
61716
+ if (mayHaveReachedServer(response.status)) {
61720
61717
  if (!error.notSent) {
61721
61718
  unanswered = true;
61722
61719
  options.onUnanswered?.();
@@ -66848,7 +66845,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
66848
66845
 
66849
66846
  // package.json
66850
66847
  var name2 = "@sjawhar/claude-envoy";
66851
- var version2 = "6.12.1";
66848
+ var version2 = "6.12.3";
66852
66849
  var package_default = {
66853
66850
  name: name2,
66854
66851
  version: version2,
@@ -69502,13 +69499,17 @@ class LegionDaemonApiError extends Error {
69502
69499
  status;
69503
69500
  code;
69504
69501
  detail;
69505
- constructor(method, path, status, code, detail) {
69502
+ refusalShape;
69503
+ retryAfterMs;
69504
+ constructor(method, path, status, code, detail, refusalShape, retryAfterMs) {
69506
69505
  super(`${method} ${path} failed with ${status}${code === undefined ? "" : ` ${code}`}: ${detail}`);
69507
69506
  this.method = method;
69508
69507
  this.path = path;
69509
69508
  this.status = status;
69510
69509
  this.code = code;
69511
69510
  this.detail = detail;
69511
+ this.refusalShape = refusalShape;
69512
+ this.retryAfterMs = retryAfterMs;
69512
69513
  this.name = "LegionDaemonApiError";
69513
69514
  }
69514
69515
  }
@@ -69548,6 +69549,7 @@ class LegionDaemonContractError extends Error {
69548
69549
  }
69549
69550
  var READY_RETRY_ATTEMPTS = 3;
69550
69551
  var READY_RETRY_DELAY_MS = 1000;
69552
+ var READY_RETRY_AFTER_MAX_MS = 30000;
69551
69553
  function isNetworkOrTimeoutError(error) {
69552
69554
  if (!(error instanceof Error))
69553
69555
  return false;
@@ -69556,23 +69558,27 @@ function isNetworkOrTimeoutError(error) {
69556
69558
  const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
69557
69559
  return code === "ConnectionRefused" || code === "ConnectionTimeout" || code === "EAI_AGAIN" || code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EHOSTUNREACH" || code === "ENETUNREACH" || code === "ENOTFOUND" || code === "ETIMEDOUT" || error instanceof TypeError && (error.message === "Failed to fetch" || error.message === "fetch failed");
69558
69560
  }
69559
- async function callReadyWithRetry(label, call) {
69561
+ async function callReadyWithRetry(label, call, sleep = (ms) => {
69562
+ const waited = Promise.withResolvers();
69563
+ setTimeout(waited.resolve, ms);
69564
+ return waited.promise;
69565
+ }) {
69560
69566
  for (let attempt = 1;; attempt++) {
69561
69567
  try {
69562
69568
  await call();
69563
69569
  return;
69564
69570
  } catch (error) {
69565
- const retryable = error instanceof LegionDaemonApiError ? error.status >= 500 && error.status < 600 : isNetworkOrTimeoutError(error);
69571
+ const retryable = error instanceof LegionDaemonApiError ? outage(error.status) : isNetworkOrTimeoutError(error);
69566
69572
  if (!retryable)
69567
69573
  throw error;
69568
69574
  if (attempt === READY_RETRY_ATTEMPTS) {
69569
69575
  console.error(`[legion] ${label} failed after ${attempt} attempts: ${messageFor(error)}`);
69570
69576
  throw error;
69571
69577
  }
69572
- console.error(`[legion] ${label} failed (attempt ${attempt}/${READY_RETRY_ATTEMPTS}), retrying: ${messageFor(error)}`);
69573
- const retryDelay = Promise.withResolvers();
69574
- setTimeout(retryDelay.resolve, READY_RETRY_DELAY_MS);
69575
- await retryDelay.promise;
69578
+ const asked = error instanceof LegionDaemonApiError ? error.retryAfterMs : 0;
69579
+ const wait = Math.min(Math.max(READY_RETRY_DELAY_MS, asked), READY_RETRY_AFTER_MAX_MS);
69580
+ console.error(`[legion] ${label} failed (attempt ${attempt}/${READY_RETRY_ATTEMPTS}), retrying in ${wait / 1000} s: ${messageFor(error)}`);
69581
+ await sleep(wait);
69576
69582
  }
69577
69583
  }
69578
69584
  }
@@ -69581,7 +69587,9 @@ var DAEMON_RESTART_FIRST_DELAY_MS = 500;
69581
69587
  var DAEMON_RESTART_MAX_DELAY_MS = 30000;
69582
69588
  function daemonUnreachable(error) {
69583
69589
  if (error instanceof LegionDaemonApiError) {
69584
- return (error.status === 502 || error.status === 503) && error.code === undefined ? "dropped" : undefined;
69590
+ if (error.refusalShape || !outage(error.status))
69591
+ return;
69592
+ return mayHaveReachedServer(error.status) ? "dropped" : "refused";
69585
69593
  }
69586
69594
  if (!(error instanceof Error))
69587
69595
  return;
@@ -69682,11 +69690,12 @@ function createLegionDaemonClient(baseUrl, options) {
69682
69690
  const daemonContract = statedContract(response.headers);
69683
69691
  if (response.ok)
69684
69692
  return { status: response.status, text, daemonContract };
69693
+ const asked = retryAfterMs(response.headers);
69685
69694
  const refusal = parseBody(LegionErrorResponse, text);
69686
69695
  if ("value" in refusal) {
69687
- throw new LegionDaemonApiError(method, path, response.status, refusal.value.code, refusal.value.error);
69696
+ throw new LegionDaemonApiError(method, path, response.status, refusal.value.code, refusal.value.error, true, asked);
69688
69697
  }
69689
- throw new LegionDaemonApiError(method, path, response.status, undefined, `${unreadableBody(text)} is not the daemon's refusal shape (${refusal.problem}). ${contractStanding(pluginContract, daemonContract)}`);
69698
+ throw new LegionDaemonApiError(method, path, response.status, undefined, `${unreadableBody(text)} is not the daemon's refusal shape (${refusal.problem}). ${contractStanding(pluginContract, daemonContract)}`, false, asked);
69690
69699
  };
69691
69700
  const read = async (method, path, schema, body, signal) => {
69692
69701
  const { status, text, daemonContract } = await call(method, path, body, signal);
@@ -69764,7 +69773,7 @@ async function bootLegionClaim(host) {
69764
69773
  if (!(error instanceof LegionDaemonApiError))
69765
69774
  throw error;
69766
69775
  host.log(`claims/register registration failed (${error.status}): ${error.detail}`);
69767
- if (error.status < 400 || error.status >= 500)
69776
+ if (error.status < 400 || outage(error.status))
69768
69777
  throw error;
69769
69778
  host.stop();
69770
69779
  return { claimed: Promise.resolve() };
@@ -72176,7 +72185,7 @@ function acceptLanded(messageId, error) {
72176
72185
  return `Dispatch recorded this session's accept of message ${messageId} and gave no copy of its answer (${error.message}), so no turn follows; it arrives as a card`;
72177
72186
  }
72178
72187
  function mayHaveBeenPosted(error) {
72179
- return error instanceof DispatchWriteUnsettledError || error instanceof DispatchServiceError && error.status >= 500;
72188
+ return error instanceof DispatchWriteUnsettledError || error instanceof DispatchServiceError && mayHaveReachedServer(error.status);
72180
72189
  }
72181
72190
  function replyWarning(messageId, error) {
72182
72191
  if (error instanceof DispatchWriteLandedError) {
@@ -2925,21 +2925,19 @@ async function genericGrantRequest(config, grantType, parameters, options) {
2925
2925
  return result;
2926
2926
  }
2927
2927
 
2928
- // ../cipher-client/src/oauth-refusal.ts
2929
- var INVALID_GRANT = "invalid_grant";
2930
- var REQUEST_TIMEOUT = 408;
2931
- var TOO_MANY_REQUESTS = 429;
2928
+ // ../contracts/src/http-status.ts
2932
2929
  function outage(status) {
2933
- return status >= 500 || status === REQUEST_TIMEOUT || status === TOO_MANY_REQUESTS;
2930
+ return status >= 500 || status === 408 || status === 429;
2934
2931
  }
2935
- function refusalCode(error) {
2936
- if (!(error instanceof ResponseBodyError))
2937
- return "";
2938
- const refuses = error.status >= 400 && error.status < 500 && !outage(error.status);
2939
- return refuses ? error.error : "";
2932
+ function mayHaveReachedServer(status) {
2933
+ return status >= 500 || status === 408;
2940
2934
  }
2941
- function endsGrant(error) {
2942
- return error instanceof ResponseBodyError && error.error === INVALID_GRANT && (error.status === 400 || error.status === 401);
2935
+ function retryAfterMs(headers, now = Date.now()) {
2936
+ const value = headers.get("Retry-After")?.trim() ?? "";
2937
+ if (/^\d+$/.test(value))
2938
+ return Number(value) * 1000;
2939
+ const at = Date.parse(value);
2940
+ return Number.isNaN(at) ? 0 : Math.max(0, at - now);
2943
2941
  }
2944
2942
 
2945
2943
  // ../cipher-client/src/wire.ts
@@ -3307,7 +3305,7 @@ async function signInFlow(env) {
3307
3305
  // ../cipher-client/src/token-errors.ts
3308
3306
  var INVALID_DPOP_PROOF = "invalid_dpop_proof";
3309
3307
  var USE_DPOP_NONCE = "use_dpop_nonce";
3310
- var INVALID_GRANT2 = "invalid_grant";
3308
+ var INVALID_GRANT = "invalid_grant";
3311
3309
  var MEMBERSHIP_HELD = "membership_held";
3312
3310
  var TOKEN_NOT_VALID = "Token is not valid or has expired.";
3313
3311
  var MACHINE_LOGIN_ENDED = "The machine login the subject token belongs to has ended.";
@@ -3328,8 +3326,8 @@ class BrokerRefusedError extends Error {
3328
3326
  this.code = KNOWN_OAUTH_ERROR_CODES.has(code) ? code : "";
3329
3327
  this.shownCode = shownCode;
3330
3328
  this.said = said;
3331
- this.podSessionUnregistered = code === INVALID_GRANT2 && description.startsWith(`${POD_SESSION_NOT_REGISTERED}:`);
3332
- this.subjectNotHonoured = status === 400 && (code === "invalid_request" && description.endsWith(TOKEN_NOT_VALID) || code === INVALID_GRANT2 && description.endsWith(MACHINE_LOGIN_ENDED));
3329
+ this.podSessionUnregistered = code === INVALID_GRANT && description.startsWith(`${POD_SESSION_NOT_REGISTERED}:`);
3330
+ this.subjectNotHonoured = status === 400 && (code === "invalid_request" && description.endsWith(TOKEN_NOT_VALID) || code === INVALID_GRANT && description.endsWith(MACHINE_LOGIN_ENDED));
3333
3331
  }
3334
3332
  get permanent() {
3335
3333
  return !outage(this.status) && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE && this.code !== MEMBERSHIP_HELD && !this.podSessionUnregistered;
@@ -17497,7 +17495,7 @@ var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
17497
17495
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
17498
17496
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
17499
17497
  function retriesUnderKey(status, code) {
17500
- return status >= 500 || status === 408 || status === 429 || status === 409 && code === IDEMPOTENCY_KEY_IN_FLIGHT;
17498
+ return outage(status) || status === 409 && code === IDEMPOTENCY_KEY_IN_FLIGHT;
17501
17499
  }
17502
17500
  function answerNotKept(status, replayed, body) {
17503
17501
  return replayed && status >= 200 && status < 300 && typeof body === "object" && body !== null && Reflect.get(body, "code") === IDEMPOTENCY_ANSWER_NOT_KEPT;
@@ -26573,7 +26571,7 @@ var WRITE_TRANSITIONS = {
26573
26571
  "foreign-2xx": { "nothing-sent": landed("end"), "may-have-landed": landed("end") },
26574
26572
  "body-broken": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
26575
26573
  "body-malformed": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
26576
- "server-error": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
26574
+ "may-have-run": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
26577
26575
  "in-flight": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
26578
26576
  "try-later": { "nothing-sent": nothing("retry"), "may-have-landed": landed("retry") },
26579
26577
  silence: { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") },
@@ -26640,7 +26638,7 @@ class DispatchGatewayError extends DispatchServiceError {
26640
26638
  this.answer = answer;
26641
26639
  this.advice = advice;
26642
26640
  this.transient = gatewayClears(status);
26643
- this.mayHaveReachedDispatch = reachesDispatch(status);
26641
+ this.mayHaveReachedDispatch = mayHaveReachedServer(status);
26644
26642
  }
26645
26643
  }
26646
26644
  var PROXY_CODE_HEADER = "Cipher-Proxy-Code";
@@ -26685,7 +26683,7 @@ class DispatchWriteUnsettledError extends Error {
26685
26683
  name = "DispatchWriteUnsettledError";
26686
26684
  constructor(last, attempts, key, unanswered) {
26687
26685
  let answer;
26688
- let why = last instanceof DispatchServiceError && last.status >= 500 || last instanceof DispatchProxyRefusalError ? "an attempt of the write may have reached Dispatch" : "an earlier attempt of the write may have reached Dispatch";
26686
+ let why = last instanceof DispatchServiceError && mayHaveReachedServer(last.status) || last instanceof DispatchProxyRefusalError ? "an attempt of the write may have reached Dispatch" : "an earlier attempt of the write may have reached Dispatch";
26689
26687
  if (last instanceof DispatchGatewayError) {
26690
26688
  answer = last.answer;
26691
26689
  } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
@@ -26823,13 +26821,6 @@ function pauseFor(ms, signal) {
26823
26821
  signal.addEventListener("abort", stop, { once: true });
26824
26822
  return promise;
26825
26823
  }
26826
- function retryAfterMs(response) {
26827
- const value = response.headers.get("Retry-After")?.trim() ?? "";
26828
- if (/^\d+$/.test(value))
26829
- return Number(value) * 1000;
26830
- const at = Date.parse(value);
26831
- return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
26832
- }
26833
26824
  var STREAMED_BODY_MIN = 1 << 20;
26834
26825
  var STREAMED_BODY_CHUNK = 64 << 10;
26835
26826
  function attemptBody(body, headers, progress) {
@@ -26918,14 +26909,14 @@ async function writeAnswer(response) {
26918
26909
  };
26919
26910
  }
26920
26911
  function isStoredKeyStatus(status) {
26921
- return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
26912
+ return status >= 400 && status < 500 && status !== 401 && !outage(status);
26922
26913
  }
26923
26914
  function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
26924
26915
  const { status } = answer.response;
26925
26916
  if (proxied && answer.response.headers.get(PROXY_CODE_HEADER) !== null) {
26926
26917
  if (answer.response.headers.get(PROXY_FORWARDED_HEADER) !== "false")
26927
26918
  return "proxy-unsettled";
26928
- return status >= 500 ? "proxy-failed" : "proxy-refused";
26919
+ return outage(status) ? "proxy-failed" : "proxy-refused";
26929
26920
  }
26930
26921
  if (status >= 200 && status < 300) {
26931
26922
  if (answer.notJson)
@@ -26946,7 +26937,7 @@ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
26946
26937
  if (!textRefusal && retriesUnderKey(status, answer.code)) {
26947
26938
  if (status === 409)
26948
26939
  return "in-flight";
26949
- return status >= 500 ? "server-error" : "try-later";
26940
+ return mayHaveReachedServer(status) ? "may-have-run" : "try-later";
26950
26941
  }
26951
26942
  if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
26952
26943
  return "judged";
@@ -27012,16 +27003,10 @@ function gatewayAdvice(method, status) {
27012
27003
  }
27013
27004
  if (method === "GET" || status >= 200 && status < 300)
27014
27005
  return "a retry may succeed";
27015
- return reachesDispatch(status) ? "the write may or may not have reached Dispatch: check whether it took effect before retrying it" : "the write did not reach Dispatch, and a retry may succeed";
27006
+ return mayHaveReachedServer(status) ? "the write may or may not have reached Dispatch: check whether it took effect before retrying it" : "the write did not reach Dispatch, and a retry may succeed";
27016
27007
  }
27017
27008
  function gatewayClears(status) {
27018
- return transientStatus(status) || status >= 200 && status < 300;
27019
- }
27020
- function transientStatus(status) {
27021
- return status >= 500 || status === 408 || status === 429;
27022
- }
27023
- function reachesDispatch(status) {
27024
- return status >= 500;
27009
+ return outage(status) || status >= 200 && status < 300;
27025
27010
  }
27026
27011
 
27027
27012
  class DispatchClient {
@@ -27777,7 +27762,7 @@ class DispatchClient {
27777
27762
  sent
27778
27763
  };
27779
27764
  }
27780
- const heard = { retryAfterMs: retryAfterMs(response) };
27765
+ const heard = { retryAfterMs: retryAfterMs(response.headers) };
27781
27766
  if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
27782
27767
  progress.keyEchoed = true;
27783
27768
  let answer;
@@ -29145,7 +29130,7 @@ async function textWithPictures(text, pictures, owner, upload, actor) {
29145
29130
  } catch (error) {
29146
29131
  const earlier = addresses.length === 0 ? "" : `; the pictures before it are uploaded (${addresses.join(", ")})`;
29147
29132
  const landed = error instanceof DispatchWriteLandedError || error instanceof Error && error.cause instanceof DispatchWriteLandedError;
29148
- const refused = error instanceof DispatchGatewayError ? !error.mayHaveReachedDispatch : error instanceof DispatchServiceError && error.status < 500;
29133
+ const refused = error instanceof DispatchGatewayError ? !error.mayHaveReachedDispatch : error instanceof DispatchServiceError && !mayHaveReachedServer(error.status);
29149
29134
  const outcome = landed ? "was uploaded" : refused ? "was not uploaded" : "may or may not have been uploaded";
29150
29135
  throw new Error(`images: ${picture.path} ${outcome}: ${messageFor(error).replace(/\.$/, "")}. Nothing ` + `was posted${earlier}.`);
29151
29136
  }
@@ -30321,7 +30306,7 @@ function refuseMissingPost(error, post) {
30321
30306
  function writeMayHaveLanded(error) {
30322
30307
  if (error instanceof DispatchGatewayError)
30323
30308
  return error.mayHaveReachedDispatch;
30324
- return !(error instanceof DispatchServiceError) || error.status >= 500;
30309
+ return !(error instanceof DispatchServiceError) || mayHaveReachedServer(error.status);
30325
30310
  }
30326
30311
  function closeAccount(error, closingNote) {
30327
30312
  const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
@@ -36458,6 +36443,18 @@ async function importDpopKey(pkcs8Pem, name) {
36458
36443
  // ../cipher-client/src/loopback.ts
36459
36444
  var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
36460
36445
 
36446
+ // ../cipher-client/src/oauth-refusal.ts
36447
+ var INVALID_GRANT2 = "invalid_grant";
36448
+ function refusalCode(error) {
36449
+ if (!(error instanceof ResponseBodyError))
36450
+ return "";
36451
+ const refuses = error.status >= 400 && error.status < 500 && !outage(error.status);
36452
+ return refuses ? error.error : "";
36453
+ }
36454
+ function endsGrant(error) {
36455
+ return error instanceof ResponseBodyError && error.error === INVALID_GRANT2 && (error.status === 400 || error.status === 401);
36456
+ }
36457
+
36461
36458
  // ../cipher-client/src/device-login.ts
36462
36459
  var BROKER_SETTING = "AGENT_SECRETS_URL";
36463
36460
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "6.12.1",
3
+ "version": "6.12.3",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -77,9 +77,10 @@ function recorded(credential: RequestCredential): {
77
77
  * `envoy-send` command keeps every rule a session's own send keeps:
78
78
  * - one idempotency key for the message, on every attempt, so the listener stores it at most
79
79
  * once however many attempts reach it;
80
- * - an attempt that got no answer or a 5xx is sent again under that key, after 250 ms;
80
+ * - an attempt that got no answer, a 408 or a 5xx is sent again under that key, after 250 ms;
81
81
  * - a send that may have arrived is told so (`EnvoySendUnconfirmedError`), naming the key that
82
- * resends it safely, never "failed";
82
+ * resends it safely, never "failed": one an attempt of which got no answer, a 5xx or a 408, which
83
+ * a hop in front of the listener can send after it forwarded the send;
83
84
  * - each attempt's credential waits the attempt less the request's reserve
84
85
  * (`credentialDeadline`), and a credential that could not be minted lets the request go
85
86
  * without it, which a listener that asks for no credential answers. A listener that wants one
@@ -17,6 +17,7 @@
17
17
  // is Dispatch recording that this session accepted that very attempt, and what it injects is
18
18
  // the body Dispatch answers with, never the frame's own text.
19
19
  import { comparableLines } from "@legion/contracts"
20
+ import { mayHaveReachedServer } from "@legion/contracts/http-status"
20
21
  import type { DispatchDelivery, RenderInboundResult } from "@legion/envoy-client/delivery"
21
22
  import {
22
23
  type DispatchClient,
@@ -106,22 +107,26 @@ export function acceptLanded(messageId: string, error: DispatchWriteLandedError)
106
107
 
107
108
  /** Whether a post that ended in `error` may or may not have been posted: it ended with no
108
109
  * definitive answer while an attempt of it may have reached Dispatch
109
- * (`DispatchWriteUnsettledError`: an earlier attempt got a 5xx or failed in transport, or the last
110
- * was cut off for silence or by the deadline), or on a 5xx (a `DispatchServiceError` of 500 or
111
- * more, a gateway's included), which can follow a write Dispatch committed. Dispatch's own 4xx,
112
- * and an error raised before anything was sent, say it was not posted. */
110
+ * (`DispatchWriteUnsettledError`: an earlier attempt got a 5xx or a 408 or failed in transport,
111
+ * or the last was cut off for silence or by the deadline), or on a status after which the request
112
+ * may have reached Dispatch (`mayHaveReachedServer`: a 5xx or a 408, a gateway's included), which
113
+ * can follow a write Dispatch committed. The Dispatch client's keyed POST, which every host's
114
+ * reply goes through, already ends a 5xx or a 408 as `DispatchWriteUnsettledError`
115
+ * (`answerEvent`'s `may-have-run`), so the second test holds for such an error that reaches here
116
+ * unclassified. Dispatch's other 4xx, and an error raised before anything was sent, say it was
117
+ * not posted. */
113
118
  function mayHaveBeenPosted(error: unknown): boolean {
114
119
  return (
115
120
  error instanceof DispatchWriteUnsettledError ||
116
- (error instanceof DispatchServiceError && error.status >= 500)
121
+ (error instanceof DispatchServiceError && mayHaveReachedServer(error.status))
117
122
  )
118
123
  }
119
124
 
120
125
  /** What stderr says of a reply to message `messageId` whose post ended in `error`. One Dispatch
121
126
  * made and gave no copy of its answer for (`DispatchWriteLandedError`) is posted, and the
122
127
  * error's message says what was made; one that may have landed (`mayHaveBeenPosted`: a
123
- * `DispatchWriteUnsettledError`, or a 5xx) may or may not have been posted, and the line says
124
- * so; any other was not posted, whether Dispatch refused it (a `DispatchServiceError` under 500,
128
+ * `DispatchWriteUnsettledError`, a 5xx or a 408) may or may not have been posted, and the line
129
+ * says so; any other was not posted, whether Dispatch refused it (another `DispatchServiceError`,
125
130
  * such as a 409) or it never reached Dispatch, and the error's message says which. Every host of
126
131
  * this package says it in these words (`./codex/codex-user-turns`). */
127
132
  export function replyWarning(messageId: string, error: unknown): string {
@@ -137,8 +142,8 @@ export function replyWarning(messageId: string, error: unknown): string {
137
142
  /** What stderr says of a BTW answer to message `messageId` whose post ended in `error`. One
138
143
  * Dispatch made and gave no copy of its answer for (`DispatchWriteLandedError`) answered the
139
144
  * attempt, so no error reply follows it; one that may have landed (`mayHaveBeenPosted`: a
140
- * `DispatchWriteUnsettledError`, or a 5xx) may or may not have been posted, and the line says
141
- * so; any other was not posted, whether Dispatch refused it or it never reached Dispatch, and
145
+ * `DispatchWriteUnsettledError`, a 5xx or a 408) may or may not have been posted, and the line
146
+ * says so; any other was not posted, whether Dispatch refused it or it never reached Dispatch, and
142
147
  * the error's message says which. */
143
148
  export function btwAnswerWarning(messageId: string, error: unknown): string {
144
149
  if (error instanceof DispatchWriteLandedError) {
@@ -419,12 +424,11 @@ export function createUserTurnRouter(options: UserTurnRouterOptions): UserTurnRo
419
424
  await reply(delivery, { ...result, followUp })
420
425
  }
421
426
 
422
- /** Posts one reply to a delivery, naming on stderr a reply that was not posted, which Dispatch
423
- * refused or never received; one that may or may not have been posted, which ended with no
424
- * definitive answer after an attempt may have reached Dispatch (`DispatchWriteUnsettledError`)
425
- * or on a 5xx; and one Dispatch made and gave no copy of its answer for
426
- * (`DispatchWriteLandedError`), which is posted: the error's message says what was made
427
- * (`replyWarning`). */
427
+ /** Posts one reply to a delivery, naming on stderr how it ended (`replyWarning`): posted, where
428
+ * Dispatch made it and gave no copy of its answer (`DispatchWriteLandedError`), and the error's
429
+ * message says what was made; may or may not have been posted, where `mayHaveBeenPosted` says
430
+ * an attempt may have reached Dispatch; and not posted otherwise, which Dispatch refused or
431
+ * never received. */
428
432
  const answer = async (delivery: DispatchDelivery, body: string | undefined): Promise<void> => {
429
433
  if (body === undefined) return
430
434
  await post(delivery, { body }).catch((error: unknown) => {