@sjawhar/claude-envoy 6.3.1 → 6.4.0

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.
@@ -37743,7 +37743,7 @@ var dispatchToolSpecs = [
37743
37743
  {
37744
37744
  name: "dispatch_review",
37745
37745
  example: { issue: "DSP-1", version: 2, verdict: "approved" },
37746
- description: "Approve one version of an issue's document, or request changes on it, as the person your " + "token names: what the document header's Approve and Request changes record. A review " + "records an approval or a changes request in the person's name at that version, so it " + "works only with a token that names a person who holds approve; Dispatch refuses it to " + "any other token, with 403 OAUTH_SCOPE_REQUIRED or 403 SIGN_IN_REQUIRED. --version is the " + "version you read, sent in the review route's path, and it must be the version the review " + "would record: the document's latest settled version, or, while an approval request is " + "open on it, the version that request names for it. Any other is refused 409 " + "REVIEW_VERSION_MOVED, which names the version to read, and nothing is recorded. A " + "Dispatch build without the versioned review route answers no route and records nothing; " + "the command then says so and names /healthz, which names the commit of the build that " + "answers it when that build was stamped with one. With a request open the review answers " + "it, and records the same verdict on every document the " + "request names, each at the version the request names. A later version makes an approval " + "stale. A review is the one browser action this command takes for a person; every other " + "browser action is dispatch://INFRA-910's. " + ISSUE_REFERENCE,
37746
+ description: "Approve one version of an issue's document, or request changes on it, as the person your " + "token names: what the document header's Approve and Request changes record. A review " + "records an approval or a changes request in the person's name at that version, so it " + "works only with a token that names a person who holds approve; Dispatch refuses it to " + "any other token, with 403 OAUTH_SCOPE_REQUIRED or 403 SIGN_IN_REQUIRED. On a box where " + "the person signed in with agent-secrets login, the review goes through Cipher's proxy " + "instead, with the approve placeholder the session trades that sign-in for; a secrets " + "broker that serves no approve capability refuses that trade 400 invalid_request, with a " + "reason that says so, and nothing is sent to Dispatch. --version is the " + "version you read, sent in the review route's path, and it must be the version the review " + "would record: the document's latest settled version, or, while an approval request is " + "open on it, the version that request names for it. Any other is refused 409 " + "REVIEW_VERSION_MOVED, which names the version to read, and nothing is recorded. A " + "Dispatch build without the versioned review route answers no route and records nothing; " + "the command then says so and names /healthz, which names the commit of the build that " + "answers it when that build was stamped with one. With a request open the review answers " + "it, and records the same verdict on every document the " + "request names, each at the version the request names. A later version makes an approval " + "stale. A review is the one browser action this command takes for a person; every other " + "browser action is dispatch://INFRA-910's. " + ISSUE_REFERENCE,
37747
37747
  arguments: (z) => ({
37748
37748
  issue: z.string().describe(ISSUE_REFERENCE),
37749
37749
  artifact: z.string().describe("Document artifact id, slug, or filename; the issue's spec by default.").optional(),
@@ -44138,6 +44138,11 @@ var SUBJECT_TOKEN_TYPE_GITHUB = "urn:envoy:params:oauth:token-type:github-workfl
44138
44138
  var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
44139
44139
  var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
44140
44140
  var TOKEN_TYPE_DPOP = "DPoP";
44141
+ var FORM_REQUESTED_TOKEN_TYPE = "requested_token_type";
44142
+ var TOKEN_TYPE_PROXY_PLACEHOLDER = "urn:envoy:params:oauth:token-type:proxy-placeholder";
44143
+ var TOKEN_TYPE_NOT_APPLICABLE = "N_A";
44144
+ var PLACEHOLDER_PREFIX = "agent-secrets-placeholder-";
44145
+ var PROXY_APPROVE_NAME = "DISPATCH_APPROVE_TOKEN";
44141
44146
  var SUBJECT_TYPE_ACCESS = "urn:ietf:params:oauth:token-type:access_token";
44142
44147
  var DEVICE_AUTHORIZATION_PATH = "/v1/oauth/device_authorization";
44143
44148
  var GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code";
@@ -44259,6 +44264,8 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
44259
44264
  `Refused: this pod's registration for session '${SESSION_SLOT}' was released; a pod trades only under a registration its registrar has not released\\.`,
44260
44265
  `The session name '${SESSION_SLOT}' belongs to another daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
44261
44266
  `The session name '${SESSION_SLOT}' is bound to no daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
44267
+ "Only a person's sign-in is traded for the approve capability's proxy placeholder, on a broker that serves it\\.",
44268
+ "A trade for the approve capability's proxy placeholder asks for the scope read, and a trade narrowed to reading approves nothing: trade for the placeholder without the scope, a cut or a DPoP-Holder proof\\.",
44262
44269
  `${PERSON_SLOT}'s credentials are held by Dispatch; they work again when \\k<person> signs in to Dispatch, or when Dispatch can confirm \\k<person> with Google again`,
44263
44270
  "The 'as_of' parameter names a cut, and only a trade that asks for the scope read may name one\\.",
44264
44271
  "The 'as_of' parameter is not an RFC 3339 time with at most six fractional digits\\.",
@@ -44983,8 +44990,25 @@ class BrokerTokenClient {
44983
44990
  return await this.#exchange(await source.read(signal), signal);
44984
44991
  }
44985
44992
  async#exchange(subject, signal) {
44993
+ const { endpoint, answered, raw } = await this.#grant(subject, signal, {});
44994
+ return this.#read(endpoint, answered, raw);
44995
+ }
44996
+ async proxyPlaceholder(signal) {
44997
+ const trade = async (subject) => {
44998
+ const { endpoint, answered, raw } = await this.#grant(subject, signal, {
44999
+ [FORM_REQUESTED_TOKEN_TYPE]: TOKEN_TYPE_PROXY_PLACEHOLDER
45000
+ });
45001
+ return this.#readPlaceholder(endpoint, answered, raw);
45002
+ };
45003
+ const source = this.#subject;
45004
+ if (source.spend !== undefined)
45005
+ return await source.spend(trade, signal);
45006
+ return await trade(await source.read(signal));
45007
+ }
45008
+ async#grant(subject, signal, asked) {
44986
45009
  holdSecret(subject.token, heldUntil(subject.token));
44987
45010
  const form = {
45011
+ ...asked,
44988
45012
  subject_token: subject.token,
44989
45013
  subject_token_type: subject.tokenType
44990
45014
  };
@@ -45025,7 +45049,7 @@ class BrokerTokenClient {
45025
45049
  ...this.#session === "" ? {} : { session: this.#session }
45026
45050
  });
45027
45051
  }
45028
- return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
45052
+ return { endpoint: urlForText(endpoint, BROKER_URL_SETTING), answered, raw: raw.body };
45029
45053
  }
45030
45054
  async#send(url, options, signal, raw) {
45031
45055
  const answer = await sendWithProof({ key: this.#key, holderKey: this.#holderKey, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
@@ -45063,6 +45087,56 @@ class BrokerTokenClient {
45063
45087
  credentialExpiresAt
45064
45088
  };
45065
45089
  }
45090
+ #readPlaceholder(endpoint, answered, raw) {
45091
+ const refused = (what) => new BrokerTradeFailedError(`the broker at ${endpoint} answered a proxy placeholder trade with ${what}`);
45092
+ const body = typeof raw === "object" && raw !== null ? raw : {};
45093
+ if (answered["issued_token_type"] !== TOKEN_TYPE_PROXY_PLACEHOLDER) {
45094
+ throw refused("an issued_token_type that is not the proxy placeholder's");
45095
+ }
45096
+ if (body["token_type"] !== TOKEN_TYPE_NOT_APPLICABLE) {
45097
+ throw refused(`a token_type other than ${TOKEN_TYPE_NOT_APPLICABLE}`);
45098
+ }
45099
+ if (answered.refresh_token !== undefined && answered.refresh_token !== "") {
45100
+ throw refused("a refresh token, which this grant never issues");
45101
+ }
45102
+ const seconds = answered.expires_in ?? 0;
45103
+ if (!(seconds > 0))
45104
+ throw refused("no usable expires_in (a positive number of seconds)");
45105
+ const placeholder = answered.access_token;
45106
+ if (!placeholder.startsWith(PLACEHOLDER_PREFIX) || placeholder.length <= PLACEHOLDER_PREFIX.length) {
45107
+ throw refused("an access_token that is no placeholder");
45108
+ }
45109
+ holdSecret(placeholder, Date.now() + seconds * 1000);
45110
+ if (typeof body["grant_id"] !== "string" || body["grant_id"] === "")
45111
+ throw refused("no grant_id");
45112
+ const release = body["proxy"];
45113
+ if (typeof release !== "object" || release === null)
45114
+ throw refused("no proxy release");
45115
+ const {
45116
+ proxy_url: proxyUrl,
45117
+ ca_certificate: caCertificate,
45118
+ proxy_password: password,
45119
+ names
45120
+ } = release;
45121
+ if (typeof proxyUrl !== "string" || !isHttpUrl(proxyUrl))
45122
+ throw refused("a proxy_url that is no http URL");
45123
+ if (typeof caCertificate !== "string" || caCertificate.trim() === "")
45124
+ throw refused("no ca_certificate");
45125
+ if (password !== placeholder)
45126
+ throw refused("a proxy_password other than the placeholder");
45127
+ if (typeof names !== "object" || names === null || Object.keys(names).length === 0) {
45128
+ throw refused("no name behind the proxy");
45129
+ }
45130
+ const read = {};
45131
+ for (const [name, entry] of Object.entries(names)) {
45132
+ const { value, hosts } = typeof entry === "object" && entry !== null ? entry : {};
45133
+ if (value !== placeholder || !Array.isArray(hosts) || hosts.length === 0 || !hosts.every((host) => typeof host === "string" && host !== "")) {
45134
+ throw refused("a name holding no host, or a value other than the placeholder");
45135
+ }
45136
+ read[name] = { hosts };
45137
+ }
45138
+ return { placeholder, proxyUrl, caCertificate, names: read };
45139
+ }
45066
45140
  }
45067
45141
  function heldUntil(token) {
45068
45142
  const now = Date.now();
@@ -47513,6 +47587,22 @@ function brokerCredential(env, session, read) {
47513
47587
  const told = headers === undefined ? undefined : presentedAs.get(headers);
47514
47588
  dropHeld(told?.key ?? keyOf(env, own(acting), read), told?.token);
47515
47589
  },
47590
+ async approveRoute(signal) {
47591
+ const { made } = await untilAborted(clientFor(env, own(undefined), read), signal);
47592
+ if (made.client === undefined || made.signIn === "")
47593
+ return;
47594
+ const held = await made.client.proxyPlaceholder(signal);
47595
+ const approve = held.names[PROXY_APPROVE_NAME];
47596
+ if (approve === undefined) {
47597
+ throw new LoggableError(`the secrets broker answered a placeholder of Cipher's proxy that holds no ${PROXY_APPROVE_NAME}, so no review was sent`);
47598
+ }
47599
+ return {
47600
+ placeholder: held.placeholder,
47601
+ proxyUrl: held.proxyUrl,
47602
+ caCertificate: held.caCertificate,
47603
+ hosts: approve.hosts
47604
+ };
47605
+ },
47516
47606
  secret: () => presented
47517
47607
  };
47518
47608
  }
@@ -47974,7 +48064,10 @@ var WRITE_TRANSITIONS = {
47974
48064
  deadline: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
47975
48065
  "cancelled-in-flight": { "nothing-sent": landed("end"), "may-have-landed": landed("end") },
47976
48066
  cancelled: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
47977
- exhausted: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") }
48067
+ exhausted: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
48068
+ "proxy-refused": { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
48069
+ "proxy-failed": { "nothing-sent": nothing("retry"), "may-have-landed": landed("retry") },
48070
+ "proxy-unsettled": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") }
47978
48071
  };
47979
48072
  function writeStep(state, event, writes) {
47980
48073
  const step = WRITE_TRANSITIONS[event][state];
@@ -48024,6 +48117,32 @@ class DispatchGatewayError extends DispatchServiceError {
48024
48117
  this.mayHaveReachedDispatch = reachesDispatch(status);
48025
48118
  }
48026
48119
  }
48120
+ var PROXY_CODE_HEADER = "Cipher-Proxy-Code";
48121
+ var PROXY_FORWARDED_HEADER = "Cipher-Proxy-Forwarded";
48122
+
48123
+ class DispatchProxyRefusalError extends DispatchServiceError {
48124
+ fromDispatch = false;
48125
+ }
48126
+ var PROXY_CODE_FORM = /^[A-Z][A-Z0-9_]{0,63}$/;
48127
+ function proxyTunnelAnswer(error) {
48128
+ if (typeof error !== "object" || error === null)
48129
+ return;
48130
+ const { code, status, headers } = error;
48131
+ if (code !== "ERR_PROXY_TUNNEL" || typeof status !== "number" || !(headers instanceof Headers)) {
48132
+ return;
48133
+ }
48134
+ const proxyCode = headers.get(PROXY_CODE_HEADER) ?? "";
48135
+ if (status < 400 || status > 599 || !PROXY_CODE_FORM.test(proxyCode))
48136
+ return;
48137
+ const forwarded = headers.get(PROXY_FORWARDED_HEADER);
48138
+ return new Response(null, {
48139
+ status,
48140
+ headers: {
48141
+ [PROXY_CODE_HEADER]: proxyCode,
48142
+ ...forwarded === null ? {} : { [PROXY_FORWARDED_HEADER]: forwarded }
48143
+ }
48144
+ });
48145
+ }
48027
48146
  var CREDENTIAL_ECHOED = "CREDENTIAL_ECHOED";
48028
48147
 
48029
48148
  class DispatchCredentialEchoError extends DispatchServiceError {
@@ -48040,7 +48159,7 @@ class DispatchWriteUnsettledError extends Error {
48040
48159
  name = "DispatchWriteUnsettledError";
48041
48160
  constructor(last, attempts, key, unanswered) {
48042
48161
  let answer;
48043
- let why = last instanceof DispatchServiceError && last.status >= 500 ? "an attempt of the write may have reached Dispatch" : "an earlier attempt of the write may have reached Dispatch";
48162
+ 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";
48044
48163
  if (last instanceof DispatchGatewayError) {
48045
48164
  answer = last.answer;
48046
48165
  } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
@@ -48130,9 +48249,11 @@ class DispatchNoRouteError extends DispatchServiceError {
48130
48249
 
48131
48250
  class DispatchUnreachableError extends Error {
48132
48251
  reachedNothing;
48133
- constructor(message, reachedNothing) {
48252
+ failure;
48253
+ constructor(message, reachedNothing, failure) {
48134
48254
  super(message);
48135
48255
  this.reachedNothing = reachedNothing;
48256
+ this.failure = failure;
48136
48257
  }
48137
48258
  }
48138
48259
  function reviewNoRouteRefusal(baseUrl, route, version) {
@@ -48211,6 +48332,10 @@ class WriteAttemptSilent extends Error {
48211
48332
  super(`made no progress for ${silenceMs / 1000} s, so it was cut off`);
48212
48333
  }
48213
48334
  }
48335
+ function originOf(url) {
48336
+ const parsed = new URL(url);
48337
+ return `${parsed.protocol}//${parsed.host}`;
48338
+ }
48214
48339
  function parsedJson(response, text) {
48215
48340
  if (text === "" || !isJson(response))
48216
48341
  return;
@@ -48269,8 +48394,13 @@ async function writeAnswer(response) {
48269
48394
  function isStoredKeyStatus(status) {
48270
48395
  return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
48271
48396
  }
48272
- function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
48397
+ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
48273
48398
  const { status } = answer.response;
48399
+ if (proxied && answer.response.headers.get(PROXY_CODE_HEADER) !== null) {
48400
+ if (answer.response.headers.get(PROXY_FORWARDED_HEADER) !== "false")
48401
+ return "proxy-unsettled";
48402
+ return status >= 500 ? "proxy-failed" : "proxy-refused";
48403
+ }
48274
48404
  if (status >= 200 && status < 300) {
48275
48405
  if (answer.notJson)
48276
48406
  return "foreign-2xx";
@@ -48391,7 +48521,7 @@ class DispatchClient {
48391
48521
  return await fetchImpl(input, { ...init, redirect: "manual" });
48392
48522
  } catch (error) {
48393
48523
  if (error instanceof TypeError) {
48394
- throw new DispatchUnreachableError(`Dispatch at ${shown} is unreachable: ${errorClass(error)}. If the Dispatch URL changed, restart this agent process so it picks up the new configuration.`, reachedNothing(error));
48524
+ throw new DispatchUnreachableError(`Dispatch at ${shown} is unreachable: ${errorClass(error)}. If the Dispatch URL changed, restart this agent process so it picks up the new configuration.`, reachedNothing(error), errorClass(error));
48395
48525
  }
48396
48526
  throw error;
48397
48527
  }
@@ -48658,11 +48788,31 @@ class DispatchClient {
48658
48788
  const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
48659
48789
  const body = { state: input.state, reason: input.reason };
48660
48790
  try {
48791
+ const route = await this.#credential.approveRoute?.(this.#credentialSignal(this.#signal));
48792
+ if (route !== undefined) {
48793
+ const via = this.#throughProxy(route, this.#url(path));
48794
+ return (await this.#jsonAnswer("POST", path, body, { via })).payload;
48795
+ }
48661
48796
  return await this.#json("POST", path, body);
48662
48797
  } catch (error) {
48663
48798
  throw this.#refusalOfNoRoute(error, path, (route) => reviewNoRouteRefusal(this.#baseUrl, route, version));
48664
48799
  }
48665
48800
  }
48801
+ #throughProxy(route, url) {
48802
+ const target = new URL(url);
48803
+ if (target.protocol !== "https:" || target.port !== "" || !route.hosts.includes(target.hostname)) {
48804
+ throw new LoggableError(`a person's review goes through Cipher's proxy, which reaches https://${route.hosts.join(" and https://")} alone, and the Dispatch URL is ${urlForText(this.#baseUrl, DISPATCH_URL_SETTING)}, so no review was sent`);
48805
+ }
48806
+ const proxy = new URL(route.proxyUrl);
48807
+ proxy.username = "agent";
48808
+ proxy.password = route.placeholder;
48809
+ const credential = {
48810
+ scheme: "DPoP",
48811
+ headers: () => ({ Authorization: `DPoP ${route.placeholder}` }),
48812
+ secret: () => route.placeholder
48813
+ };
48814
+ return { credential, init: { proxy: proxy.toString(), tls: { ca: route.caCertificate } } };
48815
+ }
48666
48816
  async recordResult(issue, input) {
48667
48817
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
48668
48818
  }
@@ -48894,12 +49044,12 @@ class DispatchClient {
48894
49044
  return (await this.#jsonAnswer(method, path, body, { query, signal, key })).payload;
48895
49045
  }
48896
49046
  async#jsonAnswer(method, path, body, options = {}) {
48897
- const { query, signal, key, writes = true } = options;
49047
+ const { query, signal, key, writes = true, via } = options;
48898
49048
  const url = this.#url(path, query);
48899
49049
  const encoded = body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" };
48900
49050
  const write = this.#writeCall(method, url, key, writes);
48901
49051
  if (write !== undefined) {
48902
- const answer = await this.#write(method, url, encoded, "application/json", signal, write);
49052
+ const answer = await this.#write(method, url, encoded, "application/json", signal, write, via);
48903
49053
  return { status: answer.response.status, payload: this.#payloadOf(method, url, answer) };
48904
49054
  }
48905
49055
  return this.#noRoute(async () => {
@@ -49040,9 +49190,10 @@ class DispatchClient {
49040
49190
  });
49041
49191
  return { answer, presented };
49042
49192
  }
49043
- async#write(method, url, body, accept, signal, write) {
49193
+ async#write(method, url, body, accept, signal, write, via) {
49044
49194
  const limit = signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]);
49045
49195
  const { key, progress } = write;
49196
+ const credential = via?.credential ?? this.#credential;
49046
49197
  const headers = { Accept: accept, [IDEMPOTENCY_KEY_HEADER]: key };
49047
49198
  if (body !== undefined)
49048
49199
  headers["Content-Type"] = body.type;
@@ -49062,7 +49213,7 @@ class DispatchClient {
49062
49213
  let presented;
49063
49214
  try {
49064
49215
  limit.throwIfAborted();
49065
- presented = await this.#credential.headers(method, url, undefined, this.#credentialSignal(limit));
49216
+ presented = await credential.headers(method, url, undefined, this.#credentialSignal(limit));
49066
49217
  this.#sent.note(presented);
49067
49218
  limit.throwIfAborted();
49068
49219
  } catch (error) {
@@ -49073,7 +49224,7 @@ class DispatchClient {
49073
49224
  ...error === limit.reason ? {} : { credentialFailure: error }
49074
49225
  };
49075
49226
  }
49076
- const identity = this.#credential.identity?.(presented);
49227
+ const identity = credential.identity?.(presented);
49077
49228
  if (state === "may-have-landed" && identity !== login) {
49078
49229
  return {
49079
49230
  event: "no-credential-final",
@@ -49085,7 +49236,7 @@ class DispatchClient {
49085
49236
  progress.sent += 1;
49086
49237
  let response;
49087
49238
  try {
49088
- response = await this.#attempt(url, method, { ...headers, ...presented }, body, silenceMs, limit);
49239
+ response = await this.#attempt(url, method, { ...headers, ...presented }, body, silenceMs, limit, via?.init);
49089
49240
  } catch (error) {
49090
49241
  return {
49091
49242
  event: stoppedEvent(limit, true, error) ?? (error instanceof WriteAttemptSilent ? "silence" : error instanceof DispatchUnreachableError && error.reachedNothing ? "unreached" : "reset"),
@@ -49111,7 +49262,7 @@ class DispatchClient {
49111
49262
  };
49112
49263
  }
49113
49264
  return {
49114
- event: answerEvent(answer, write.key, progress.keyEchoed, this.#credential.stale !== undefined && !deadTokenTold),
49265
+ event: answerEvent(answer, write.key, progress.keyEchoed, credential.stale !== undefined && !deadTokenTold, via !== undefined),
49115
49266
  answer,
49116
49267
  presented,
49117
49268
  sent,
@@ -49146,10 +49297,10 @@ class DispatchClient {
49146
49297
  }
49147
49298
  return last.answer;
49148
49299
  case "end":
49149
- throw await this.#endWrite(method, url, state, event === "exhausted" ? last.event : event, last.answer, state === "nothing-sent" && credentialFailure !== undefined && (event === "deadline" || event === "cancelled") ? credentialFailure : last.failure, write, event === "exhausted" && last.event === "no-route" && this.#retryNoRoute);
49300
+ throw await this.#endWrite(method, url, state, event === "exhausted" ? last.event : event, last.answer, state === "nothing-sent" && credentialFailure !== undefined && (event === "deadline" || event === "cancelled") ? credentialFailure : last.failure, write, event === "exhausted" && last.event === "no-route" && this.#retryNoRoute, via);
49150
49301
  case "retry-at-once":
49151
49302
  deadTokenTold = true;
49152
- this.#credential.stale?.(undefined, last.sent?.with);
49303
+ credential.stale?.(undefined, last.sent?.with);
49153
49304
  last = await next();
49154
49305
  event = last.event;
49155
49306
  continue;
@@ -49206,7 +49357,7 @@ class DispatchClient {
49206
49357
  #now() {
49207
49358
  return this.writeRetry.now?.() ?? performance.now();
49208
49359
  }
49209
- async#attempt(url, method, headers, body, silenceMs, limit) {
49360
+ async#attempt(url, method, headers, body, silenceMs, limit, transport) {
49210
49361
  const cut = new AbortController;
49211
49362
  const silent = () => cut.abort(new WriteAttemptSilent(silenceMs));
49212
49363
  let timer = setTimeout(silent, silenceMs);
@@ -49221,21 +49372,30 @@ class DispatchClient {
49221
49372
  return await this.#fetch(url, {
49222
49373
  method,
49223
49374
  signal: AbortSignal.any([limit, cut.signal]),
49375
+ ...transport,
49224
49376
  ...body === undefined ? { headers } : attemptBody(body, headers, progress)
49225
49377
  });
49226
49378
  } catch (error) {
49227
49379
  if (cut.signal.aborted && !limit.aborted)
49228
49380
  throw cut.signal.reason;
49381
+ const refused = transport === undefined ? undefined : proxyTunnelAnswer(error);
49382
+ if (refused !== undefined)
49383
+ return refused;
49229
49384
  throw error;
49230
49385
  } finally {
49231
49386
  answered = true;
49232
49387
  clearTimeout(timer);
49233
49388
  }
49234
49389
  }
49235
- async#endWrite(method, url, state, event, answer, failure, write, routeSpent) {
49390
+ async#endWrite(method, url, state, event, answer, failure, write, routeSpent, via) {
49236
49391
  const { request, progress } = write;
49237
49392
  let own = failure;
49238
- if (answer?.response.ok === true) {
49393
+ const proxyCode = via === undefined ? null : answer?.response.headers.get(PROXY_CODE_HEADER);
49394
+ if (via !== undefined && answer !== undefined && typeof proxyCode === "string") {
49395
+ own = this.#proxyRefusal(request, via, answer, proxyCode, state, event);
49396
+ } else if (via !== undefined && failure instanceof DispatchUnreachableError) {
49397
+ own = this.#proxyUnreachable(via, failure, state);
49398
+ } else if (answer?.response.ok === true) {
49239
49399
  const { status } = answer.response;
49240
49400
  own = new Error(answer.notJson ? `${request} answered ${status} with ${bodyForText(answer.text, this.#sent.with(this.token), "JSON")}, though every Dispatch write answers JSON, so something in Dispatch's place answered` : event === "foreign-2xx" ? `${request} answered ${status} without carrying back its ${IDEMPOTENCY_KEY_HEADER}, though an earlier answer of this write carried it and Dispatch answers every keyed write with it, so something in Dispatch's place answered` : `${request} answered ${status} with a body that is not the JSON its Content-Type says`);
49241
49401
  } else if (answer !== undefined) {
@@ -49271,6 +49431,17 @@ class DispatchClient {
49271
49431
  }
49272
49432
  return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered);
49273
49433
  }
49434
+ #proxyUnreachable(via, failure, state) {
49435
+ const again = state === "nothing-sent" ? " The review can be sent again once the broker answers." : "";
49436
+ return new DispatchUnreachableError(`Dispatch at ${urlForText(this.#baseUrl, DISPATCH_URL_SETTING)}, through Cipher's proxy at ${originOf(via.init.proxy)}, is unreachable: ${failure.failure}. The proxy is the secrets broker's.${again}`, failure.reachedNothing, failure.failure);
49437
+ }
49438
+ #proxyRefusal(request, via, answer, code, state, event) {
49439
+ const { status } = answer.response;
49440
+ const said = excerpt(answer.text, this.#sent.with(this.token));
49441
+ const by = `${request} was answered ${status} ${code} by Cipher's proxy at ${originOf(via.init.proxy)}${said === "" ? "" : ` (${JSON.stringify(said)})`}`;
49442
+ const message = state !== "nothing-sent" ? event === "proxy-unsettled" ? `${by}, after this attempt may have reached Dispatch` : `${by} before this attempt left the proxy, after an earlier attempt of the review may have reached Dispatch` : event === "proxy-failed" ? `${by} before any of it left the proxy, so nothing reached Dispatch. The proxy is the secrets broker's, and a new \`dispatch review\` trades a new grant once the broker answers.` : `${by} before any of it left the proxy, so nothing reached Dispatch, and a new \`dispatch review\` trades a new grant.`;
49443
+ return new DispatchProxyRefusalError(code, status, message);
49444
+ }
49274
49445
  #url(path, query) {
49275
49446
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
49276
49447
  if (query) {
@@ -66255,7 +66426,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
66255
66426
 
66256
66427
  // package.json
66257
66428
  var name2 = "@sjawhar/claude-envoy";
66258
- var version2 = "6.3.1";
66429
+ var version2 = "6.4.0";
66259
66430
  var package_default = {
66260
66431
  name: name2,
66261
66432
  version: version2,