@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.
@@ -2960,6 +2960,11 @@ var SUBJECT_TOKEN_TYPE_GITHUB = "urn:envoy:params:oauth:token-type:github-workfl
2960
2960
  var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
2961
2961
  var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
2962
2962
  var TOKEN_TYPE_DPOP = "DPoP";
2963
+ var FORM_REQUESTED_TOKEN_TYPE = "requested_token_type";
2964
+ var TOKEN_TYPE_PROXY_PLACEHOLDER = "urn:envoy:params:oauth:token-type:proxy-placeholder";
2965
+ var TOKEN_TYPE_NOT_APPLICABLE = "N_A";
2966
+ var PLACEHOLDER_PREFIX = "agent-secrets-placeholder-";
2967
+ var PROXY_APPROVE_NAME = "DISPATCH_APPROVE_TOKEN";
2963
2968
  var SUBJECT_TYPE_ACCESS = "urn:ietf:params:oauth:token-type:access_token";
2964
2969
  var DEVICE_AUTHORIZATION_PATH = "/v1/oauth/device_authorization";
2965
2970
  var GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code";
@@ -3081,6 +3086,8 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
3081
3086
  `Refused: this pod's registration for session '${SESSION_SLOT}' was released; a pod trades only under a registration its registrar has not released\\.`,
3082
3087
  `The session name '${SESSION_SLOT}' belongs to another daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
3083
3088
  `The session name '${SESSION_SLOT}' is bound to no daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
3089
+ "Only a person's sign-in is traded for the approve capability's proxy placeholder, on a broker that serves it\\.",
3090
+ "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\\.",
3084
3091
  `${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`,
3085
3092
  "The 'as_of' parameter names a cut, and only a trade that asks for the scope read may name one\\.",
3086
3093
  "The 'as_of' parameter is not an RFC 3339 time with at most six fractional digits\\.",
@@ -3761,8 +3768,25 @@ class BrokerTokenClient {
3761
3768
  return await this.#exchange(await source.read(signal), signal);
3762
3769
  }
3763
3770
  async#exchange(subject, signal) {
3771
+ const { endpoint, answered, raw } = await this.#grant(subject, signal, {});
3772
+ return this.#read(endpoint, answered, raw);
3773
+ }
3774
+ async proxyPlaceholder(signal) {
3775
+ const trade = async (subject) => {
3776
+ const { endpoint, answered, raw } = await this.#grant(subject, signal, {
3777
+ [FORM_REQUESTED_TOKEN_TYPE]: TOKEN_TYPE_PROXY_PLACEHOLDER
3778
+ });
3779
+ return this.#readPlaceholder(endpoint, answered, raw);
3780
+ };
3781
+ const source = this.#subject;
3782
+ if (source.spend !== undefined)
3783
+ return await source.spend(trade, signal);
3784
+ return await trade(await source.read(signal));
3785
+ }
3786
+ async#grant(subject, signal, asked) {
3764
3787
  holdSecret(subject.token, heldUntil(subject.token));
3765
3788
  const form = {
3789
+ ...asked,
3766
3790
  subject_token: subject.token,
3767
3791
  subject_token_type: subject.tokenType
3768
3792
  };
@@ -3803,7 +3827,7 @@ class BrokerTokenClient {
3803
3827
  ...this.#session === "" ? {} : { session: this.#session }
3804
3828
  });
3805
3829
  }
3806
- return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
3830
+ return { endpoint: urlForText(endpoint, BROKER_URL_SETTING), answered, raw: raw.body };
3807
3831
  }
3808
3832
  async#send(url, options, signal, raw) {
3809
3833
  const answer = await sendWithProof({ key: this.#key, holderKey: this.#holderKey, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
@@ -3841,6 +3865,56 @@ class BrokerTokenClient {
3841
3865
  credentialExpiresAt
3842
3866
  };
3843
3867
  }
3868
+ #readPlaceholder(endpoint, answered, raw) {
3869
+ const refused = (what) => new BrokerTradeFailedError(`the broker at ${endpoint} answered a proxy placeholder trade with ${what}`);
3870
+ const body = typeof raw === "object" && raw !== null ? raw : {};
3871
+ if (answered["issued_token_type"] !== TOKEN_TYPE_PROXY_PLACEHOLDER) {
3872
+ throw refused("an issued_token_type that is not the proxy placeholder's");
3873
+ }
3874
+ if (body["token_type"] !== TOKEN_TYPE_NOT_APPLICABLE) {
3875
+ throw refused(`a token_type other than ${TOKEN_TYPE_NOT_APPLICABLE}`);
3876
+ }
3877
+ if (answered.refresh_token !== undefined && answered.refresh_token !== "") {
3878
+ throw refused("a refresh token, which this grant never issues");
3879
+ }
3880
+ const seconds = answered.expires_in ?? 0;
3881
+ if (!(seconds > 0))
3882
+ throw refused("no usable expires_in (a positive number of seconds)");
3883
+ const placeholder = answered.access_token;
3884
+ if (!placeholder.startsWith(PLACEHOLDER_PREFIX) || placeholder.length <= PLACEHOLDER_PREFIX.length) {
3885
+ throw refused("an access_token that is no placeholder");
3886
+ }
3887
+ holdSecret(placeholder, Date.now() + seconds * 1000);
3888
+ if (typeof body["grant_id"] !== "string" || body["grant_id"] === "")
3889
+ throw refused("no grant_id");
3890
+ const release = body["proxy"];
3891
+ if (typeof release !== "object" || release === null)
3892
+ throw refused("no proxy release");
3893
+ const {
3894
+ proxy_url: proxyUrl,
3895
+ ca_certificate: caCertificate,
3896
+ proxy_password: password,
3897
+ names
3898
+ } = release;
3899
+ if (typeof proxyUrl !== "string" || !isHttpUrl(proxyUrl))
3900
+ throw refused("a proxy_url that is no http URL");
3901
+ if (typeof caCertificate !== "string" || caCertificate.trim() === "")
3902
+ throw refused("no ca_certificate");
3903
+ if (password !== placeholder)
3904
+ throw refused("a proxy_password other than the placeholder");
3905
+ if (typeof names !== "object" || names === null || Object.keys(names).length === 0) {
3906
+ throw refused("no name behind the proxy");
3907
+ }
3908
+ const read = {};
3909
+ for (const [name, entry] of Object.entries(names)) {
3910
+ const { value, hosts } = typeof entry === "object" && entry !== null ? entry : {};
3911
+ if (value !== placeholder || !Array.isArray(hosts) || hosts.length === 0 || !hosts.every((host) => typeof host === "string" && host !== "")) {
3912
+ throw refused("a name holding no host, or a value other than the placeholder");
3913
+ }
3914
+ read[name] = { hosts };
3915
+ }
3916
+ return { placeholder, proxyUrl, caCertificate, names: read };
3917
+ }
3844
3918
  }
3845
3919
  function heldUntil(token) {
3846
3920
  const now = Date.now();
@@ -18468,7 +18542,7 @@ var dispatchToolSpecs = [
18468
18542
  {
18469
18543
  name: "dispatch_review",
18470
18544
  example: { issue: "DSP-1", version: 2, verdict: "approved" },
18471
- 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,
18545
+ 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,
18472
18546
  arguments: (z) => ({
18473
18547
  issue: z.string().describe(ISSUE_REFERENCE),
18474
18548
  artifact: z.string().describe("Document artifact id, slug, or filename; the issue's spec by default.").optional(),
@@ -26203,7 +26277,10 @@ var WRITE_TRANSITIONS = {
26203
26277
  deadline: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
26204
26278
  "cancelled-in-flight": { "nothing-sent": landed("end"), "may-have-landed": landed("end") },
26205
26279
  cancelled: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
26206
- exhausted: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") }
26280
+ exhausted: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
26281
+ "proxy-refused": { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
26282
+ "proxy-failed": { "nothing-sent": nothing("retry"), "may-have-landed": landed("retry") },
26283
+ "proxy-unsettled": { "nothing-sent": landed("retry"), "may-have-landed": landed("retry") }
26207
26284
  };
26208
26285
  function writeStep(state, event, writes) {
26209
26286
  const step = WRITE_TRANSITIONS[event][state];
@@ -26253,6 +26330,32 @@ class DispatchGatewayError extends DispatchServiceError {
26253
26330
  this.mayHaveReachedDispatch = reachesDispatch(status);
26254
26331
  }
26255
26332
  }
26333
+ var PROXY_CODE_HEADER = "Cipher-Proxy-Code";
26334
+ var PROXY_FORWARDED_HEADER = "Cipher-Proxy-Forwarded";
26335
+
26336
+ class DispatchProxyRefusalError extends DispatchServiceError {
26337
+ fromDispatch = false;
26338
+ }
26339
+ var PROXY_CODE_FORM = /^[A-Z][A-Z0-9_]{0,63}$/;
26340
+ function proxyTunnelAnswer(error) {
26341
+ if (typeof error !== "object" || error === null)
26342
+ return;
26343
+ const { code, status, headers } = error;
26344
+ if (code !== "ERR_PROXY_TUNNEL" || typeof status !== "number" || !(headers instanceof Headers)) {
26345
+ return;
26346
+ }
26347
+ const proxyCode = headers.get(PROXY_CODE_HEADER) ?? "";
26348
+ if (status < 400 || status > 599 || !PROXY_CODE_FORM.test(proxyCode))
26349
+ return;
26350
+ const forwarded = headers.get(PROXY_FORWARDED_HEADER);
26351
+ return new Response(null, {
26352
+ status,
26353
+ headers: {
26354
+ [PROXY_CODE_HEADER]: proxyCode,
26355
+ ...forwarded === null ? {} : { [PROXY_FORWARDED_HEADER]: forwarded }
26356
+ }
26357
+ });
26358
+ }
26256
26359
  var CREDENTIAL_ECHOED = "CREDENTIAL_ECHOED";
26257
26360
 
26258
26361
  class DispatchCredentialEchoError extends DispatchServiceError {
@@ -26269,7 +26372,7 @@ class DispatchWriteUnsettledError extends Error {
26269
26372
  name = "DispatchWriteUnsettledError";
26270
26373
  constructor(last, attempts, key, unanswered) {
26271
26374
  let answer;
26272
- 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";
26375
+ 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";
26273
26376
  if (last instanceof DispatchGatewayError) {
26274
26377
  answer = last.answer;
26275
26378
  } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
@@ -26359,9 +26462,11 @@ class DispatchNoRouteError extends DispatchServiceError {
26359
26462
 
26360
26463
  class DispatchUnreachableError extends Error {
26361
26464
  reachedNothing;
26362
- constructor(message, reachedNothing) {
26465
+ failure;
26466
+ constructor(message, reachedNothing, failure) {
26363
26467
  super(message);
26364
26468
  this.reachedNothing = reachedNothing;
26469
+ this.failure = failure;
26365
26470
  }
26366
26471
  }
26367
26472
  function reviewNoRouteRefusal(baseUrl, route, version) {
@@ -26440,6 +26545,10 @@ class WriteAttemptSilent extends Error {
26440
26545
  super(`made no progress for ${silenceMs / 1000} s, so it was cut off`);
26441
26546
  }
26442
26547
  }
26548
+ function originOf(url) {
26549
+ const parsed = new URL(url);
26550
+ return `${parsed.protocol}//${parsed.host}`;
26551
+ }
26443
26552
  function parsedJson(response, text) {
26444
26553
  if (text === "" || !isJson(response))
26445
26554
  return;
@@ -26498,8 +26607,13 @@ async function writeAnswer(response) {
26498
26607
  function isStoredKeyStatus(status) {
26499
26608
  return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
26500
26609
  }
26501
- function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
26610
+ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
26502
26611
  const { status } = answer.response;
26612
+ if (proxied && answer.response.headers.get(PROXY_CODE_HEADER) !== null) {
26613
+ if (answer.response.headers.get(PROXY_FORWARDED_HEADER) !== "false")
26614
+ return "proxy-unsettled";
26615
+ return status >= 500 ? "proxy-failed" : "proxy-refused";
26616
+ }
26503
26617
  if (status >= 200 && status < 300) {
26504
26618
  if (answer.notJson)
26505
26619
  return "foreign-2xx";
@@ -26620,7 +26734,7 @@ class DispatchClient {
26620
26734
  return await fetchImpl(input, { ...init, redirect: "manual" });
26621
26735
  } catch (error) {
26622
26736
  if (error instanceof TypeError) {
26623
- 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));
26737
+ 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));
26624
26738
  }
26625
26739
  throw error;
26626
26740
  }
@@ -26887,11 +27001,31 @@ class DispatchClient {
26887
27001
  const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
26888
27002
  const body = { state: input.state, reason: input.reason };
26889
27003
  try {
27004
+ const route = await this.#credential.approveRoute?.(this.#credentialSignal(this.#signal));
27005
+ if (route !== undefined) {
27006
+ const via = this.#throughProxy(route, this.#url(path));
27007
+ return (await this.#jsonAnswer("POST", path, body, { via })).payload;
27008
+ }
26890
27009
  return await this.#json("POST", path, body);
26891
27010
  } catch (error) {
26892
27011
  throw this.#refusalOfNoRoute(error, path, (route) => reviewNoRouteRefusal(this.#baseUrl, route, version));
26893
27012
  }
26894
27013
  }
27014
+ #throughProxy(route, url) {
27015
+ const target = new URL(url);
27016
+ if (target.protocol !== "https:" || target.port !== "" || !route.hosts.includes(target.hostname)) {
27017
+ 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`);
27018
+ }
27019
+ const proxy = new URL(route.proxyUrl);
27020
+ proxy.username = "agent";
27021
+ proxy.password = route.placeholder;
27022
+ const credential = {
27023
+ scheme: "DPoP",
27024
+ headers: () => ({ Authorization: `DPoP ${route.placeholder}` }),
27025
+ secret: () => route.placeholder
27026
+ };
27027
+ return { credential, init: { proxy: proxy.toString(), tls: { ca: route.caCertificate } } };
27028
+ }
26895
27029
  async recordResult(issue, input) {
26896
27030
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
26897
27031
  }
@@ -27123,12 +27257,12 @@ class DispatchClient {
27123
27257
  return (await this.#jsonAnswer(method, path, body, { query, signal, key })).payload;
27124
27258
  }
27125
27259
  async#jsonAnswer(method, path, body, options = {}) {
27126
- const { query, signal, key, writes = true } = options;
27260
+ const { query, signal, key, writes = true, via } = options;
27127
27261
  const url = this.#url(path, query);
27128
27262
  const encoded = body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" };
27129
27263
  const write = this.#writeCall(method, url, key, writes);
27130
27264
  if (write !== undefined) {
27131
- const answer = await this.#write(method, url, encoded, "application/json", signal, write);
27265
+ const answer = await this.#write(method, url, encoded, "application/json", signal, write, via);
27132
27266
  return { status: answer.response.status, payload: this.#payloadOf(method, url, answer) };
27133
27267
  }
27134
27268
  return this.#noRoute(async () => {
@@ -27269,9 +27403,10 @@ class DispatchClient {
27269
27403
  });
27270
27404
  return { answer, presented };
27271
27405
  }
27272
- async#write(method, url, body, accept, signal, write) {
27406
+ async#write(method, url, body, accept, signal, write, via) {
27273
27407
  const limit = signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]);
27274
27408
  const { key, progress } = write;
27409
+ const credential = via?.credential ?? this.#credential;
27275
27410
  const headers = { Accept: accept, [IDEMPOTENCY_KEY_HEADER]: key };
27276
27411
  if (body !== undefined)
27277
27412
  headers["Content-Type"] = body.type;
@@ -27291,7 +27426,7 @@ class DispatchClient {
27291
27426
  let presented;
27292
27427
  try {
27293
27428
  limit.throwIfAborted();
27294
- presented = await this.#credential.headers(method, url, undefined, this.#credentialSignal(limit));
27429
+ presented = await credential.headers(method, url, undefined, this.#credentialSignal(limit));
27295
27430
  this.#sent.note(presented);
27296
27431
  limit.throwIfAborted();
27297
27432
  } catch (error) {
@@ -27302,7 +27437,7 @@ class DispatchClient {
27302
27437
  ...error === limit.reason ? {} : { credentialFailure: error }
27303
27438
  };
27304
27439
  }
27305
- const identity = this.#credential.identity?.(presented);
27440
+ const identity = credential.identity?.(presented);
27306
27441
  if (state === "may-have-landed" && identity !== login) {
27307
27442
  return {
27308
27443
  event: "no-credential-final",
@@ -27314,7 +27449,7 @@ class DispatchClient {
27314
27449
  progress.sent += 1;
27315
27450
  let response;
27316
27451
  try {
27317
- response = await this.#attempt(url, method, { ...headers, ...presented }, body, silenceMs, limit);
27452
+ response = await this.#attempt(url, method, { ...headers, ...presented }, body, silenceMs, limit, via?.init);
27318
27453
  } catch (error) {
27319
27454
  return {
27320
27455
  event: stoppedEvent(limit, true, error) ?? (error instanceof WriteAttemptSilent ? "silence" : error instanceof DispatchUnreachableError && error.reachedNothing ? "unreached" : "reset"),
@@ -27340,7 +27475,7 @@ class DispatchClient {
27340
27475
  };
27341
27476
  }
27342
27477
  return {
27343
- event: answerEvent(answer, write.key, progress.keyEchoed, this.#credential.stale !== undefined && !deadTokenTold),
27478
+ event: answerEvent(answer, write.key, progress.keyEchoed, credential.stale !== undefined && !deadTokenTold, via !== undefined),
27344
27479
  answer,
27345
27480
  presented,
27346
27481
  sent,
@@ -27375,10 +27510,10 @@ class DispatchClient {
27375
27510
  }
27376
27511
  return last.answer;
27377
27512
  case "end":
27378
- 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);
27513
+ 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);
27379
27514
  case "retry-at-once":
27380
27515
  deadTokenTold = true;
27381
- this.#credential.stale?.(undefined, last.sent?.with);
27516
+ credential.stale?.(undefined, last.sent?.with);
27382
27517
  last = await next();
27383
27518
  event = last.event;
27384
27519
  continue;
@@ -27435,7 +27570,7 @@ class DispatchClient {
27435
27570
  #now() {
27436
27571
  return this.writeRetry.now?.() ?? performance.now();
27437
27572
  }
27438
- async#attempt(url, method, headers, body, silenceMs, limit) {
27573
+ async#attempt(url, method, headers, body, silenceMs, limit, transport) {
27439
27574
  const cut = new AbortController;
27440
27575
  const silent = () => cut.abort(new WriteAttemptSilent(silenceMs));
27441
27576
  let timer = setTimeout(silent, silenceMs);
@@ -27450,21 +27585,30 @@ class DispatchClient {
27450
27585
  return await this.#fetch(url, {
27451
27586
  method,
27452
27587
  signal: AbortSignal.any([limit, cut.signal]),
27588
+ ...transport,
27453
27589
  ...body === undefined ? { headers } : attemptBody(body, headers, progress)
27454
27590
  });
27455
27591
  } catch (error) {
27456
27592
  if (cut.signal.aborted && !limit.aborted)
27457
27593
  throw cut.signal.reason;
27594
+ const refused = transport === undefined ? undefined : proxyTunnelAnswer(error);
27595
+ if (refused !== undefined)
27596
+ return refused;
27458
27597
  throw error;
27459
27598
  } finally {
27460
27599
  answered = true;
27461
27600
  clearTimeout(timer);
27462
27601
  }
27463
27602
  }
27464
- async#endWrite(method, url, state, event, answer, failure, write, routeSpent) {
27603
+ async#endWrite(method, url, state, event, answer, failure, write, routeSpent, via) {
27465
27604
  const { request, progress } = write;
27466
27605
  let own = failure;
27467
- if (answer?.response.ok === true) {
27606
+ const proxyCode = via === undefined ? null : answer?.response.headers.get(PROXY_CODE_HEADER);
27607
+ if (via !== undefined && answer !== undefined && typeof proxyCode === "string") {
27608
+ own = this.#proxyRefusal(request, via, answer, proxyCode, state, event);
27609
+ } else if (via !== undefined && failure instanceof DispatchUnreachableError) {
27610
+ own = this.#proxyUnreachable(via, failure, state);
27611
+ } else if (answer?.response.ok === true) {
27468
27612
  const { status } = answer.response;
27469
27613
  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`);
27470
27614
  } else if (answer !== undefined) {
@@ -27500,6 +27644,17 @@ class DispatchClient {
27500
27644
  }
27501
27645
  return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered);
27502
27646
  }
27647
+ #proxyUnreachable(via, failure, state) {
27648
+ const again = state === "nothing-sent" ? " The review can be sent again once the broker answers." : "";
27649
+ 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);
27650
+ }
27651
+ #proxyRefusal(request, via, answer, code, state, event) {
27652
+ const { status } = answer.response;
27653
+ const said = excerpt(answer.text, this.#sent.with(this.token));
27654
+ const by = `${request} was answered ${status} ${code} by Cipher's proxy at ${originOf(via.init.proxy)}${said === "" ? "" : ` (${JSON.stringify(said)})`}`;
27655
+ 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.`;
27656
+ return new DispatchProxyRefusalError(code, status, message);
27657
+ }
27503
27658
  #url(path, query) {
27504
27659
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
27505
27660
  if (query) {
@@ -36890,6 +37045,22 @@ function brokerCredential(env, session, read) {
36890
37045
  const told = headers === undefined ? undefined : presentedAs.get(headers);
36891
37046
  dropHeld(told?.key ?? keyOf(env, own(acting), read), told?.token);
36892
37047
  },
37048
+ async approveRoute(signal) {
37049
+ const { made } = await untilAborted(clientFor(env, own(undefined), read), signal);
37050
+ if (made.client === undefined || made.signIn === "")
37051
+ return;
37052
+ const held = await made.client.proxyPlaceholder(signal);
37053
+ const approve = held.names[PROXY_APPROVE_NAME];
37054
+ if (approve === undefined) {
37055
+ throw new LoggableError(`the secrets broker answered a placeholder of Cipher's proxy that holds no ${PROXY_APPROVE_NAME}, so no review was sent`);
37056
+ }
37057
+ return {
37058
+ placeholder: held.placeholder,
37059
+ proxyUrl: held.proxyUrl,
37060
+ caCertificate: held.caCertificate,
37061
+ hosts: approve.hosts
37062
+ };
37063
+ },
36893
37064
  secret: () => presented
36894
37065
  };
36895
37066
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "6.3.1",
3
+ "version": "6.4.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",