@sjawhar/claude-envoy 4.21.1 → 4.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,5 +2,5 @@
2
2
  "name": "claude-envoy",
3
3
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
4
4
  "mcpServers": "./.mcp.json",
5
- "version": "4.21.1"
5
+ "version": "4.21.2"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "4.21.1",
3
+ "version": "4.21.2",
4
4
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
5
5
  "mcpServers": {}
6
6
  }
@@ -13848,6 +13848,7 @@ var IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
13848
13848
  var IDEMPOTENCY_REPLAYED_HEADER = "Idempotency-Replayed";
13849
13849
  var IDEMPOTENCY_KEY_MAX = 128;
13850
13850
  var IDEMPOTENCY_KEY_PATTERN = new RegExp(`^[A-Za-z0-9._:-]{1,${IDEMPOTENCY_KEY_MAX}}$`);
13851
+ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
13851
13852
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
13852
13853
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
13853
13854
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
@@ -19674,7 +19675,7 @@ class DispatchWriteUnsettledError extends Error {
19674
19675
  attempts;
19675
19676
  key;
19676
19677
  name = "DispatchWriteUnsettledError";
19677
- constructor(last, attempts, key, unanswered, keyed = false) {
19678
+ constructor(last, attempts, key, unanswered) {
19678
19679
  let answer;
19679
19680
  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";
19680
19681
  if (last instanceof DispatchGatewayError) {
@@ -19689,10 +19690,7 @@ class DispatchWriteUnsettledError extends Error {
19689
19690
  why = "an attempt of the write may have reached Dispatch";
19690
19691
  }
19691
19692
  const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
19692
- const next = keyed ? ". Dispatch finishes an attempt it received whatever this command does, so read the " + "write back before you send it again: a new command sends it under a new key." : ": check whether it did before retrying it.";
19693
- super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect${next}`, {
19694
- cause: last
19695
- });
19693
+ super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect. Dispatch ` + "finishes an attempt it received whatever this command does, so read the write back " + "before you send it again: a new command sends it under a new key.", { cause: last });
19696
19694
  this.last = last;
19697
19695
  this.attempts = attempts;
19698
19696
  this.key = key;
@@ -19781,43 +19779,6 @@ function retryAfterMs(response) {
19781
19779
  const at = Date.parse(value);
19782
19780
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
19783
19781
  }
19784
- var KEYED_LAYER_MEMORY_MS = 5 * 60000;
19785
- var KEYED_LAYER_SEEN = new Map;
19786
- var KEYED_LAYER_PROBES = new Map;
19787
- var KEY_LAYER_PROBE_MS = 5000;
19788
- function keyedLayerMemory() {
19789
- const wall = Date.now();
19790
- const now = performance.now();
19791
- const kept = {};
19792
- for (const [origin, seen] of KEYED_LAYER_SEEN) {
19793
- const age = now - seen;
19794
- if (age >= 0 && age < KEYED_LAYER_MEMORY_MS) {
19795
- kept[origin] = new Date(wall - age).toISOString();
19796
- }
19797
- }
19798
- return kept;
19799
- }
19800
- function rememberKeyedLayer(saved) {
19801
- if (typeof saved !== "object" || saved === null)
19802
- return;
19803
- const wall = Date.now();
19804
- const now = performance.now();
19805
- for (const [origin, at] of Object.entries(saved)) {
19806
- if (typeof at !== "string")
19807
- continue;
19808
- const age = wall - Date.parse(at);
19809
- if (!(age >= 0 && age < KEYED_LAYER_MEMORY_MS))
19810
- continue;
19811
- const seen = now - age;
19812
- const known = KEYED_LAYER_SEEN.get(origin);
19813
- if (known === undefined || known < seen)
19814
- KEYED_LAYER_SEEN.set(origin, seen);
19815
- }
19816
- }
19817
- function keyEchoed(response, key) {
19818
- const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
19819
- return echoed.replace(/^"(.*)"$/, "$1") === key;
19820
- }
19821
19782
  var STREAMED_BODY_MIN = 1 << 20;
19822
19783
  var STREAMED_BODY_CHUNK = 64 << 10;
19823
19784
  function attemptBody(body, headers, progress) {
@@ -19856,17 +19817,18 @@ function parsedJson(response, text) {
19856
19817
  }
19857
19818
  }
19858
19819
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
19859
- async function writeAnswer(response, echoed) {
19820
+ async function writeAnswer(response) {
19860
19821
  if (NULL_BODY_STATUSES.has(response.status)) {
19861
19822
  return {
19862
19823
  response,
19863
- echoed,
19864
19824
  malformed: false,
19865
19825
  notJson: false,
19866
19826
  text: "",
19867
19827
  json: undefined,
19868
19828
  code: undefined,
19869
- error: undefined
19829
+ error: undefined,
19830
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
19831
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
19870
19832
  };
19871
19833
  }
19872
19834
  const text = await response.text();
@@ -19876,23 +19838,27 @@ async function writeAnswer(response, echoed) {
19876
19838
  const own = typeof shape.error === "string";
19877
19839
  return {
19878
19840
  response,
19879
- echoed,
19880
19841
  malformed: text !== "" && typed && json === undefined,
19881
19842
  notJson: text === "" || !typed,
19882
19843
  text,
19883
19844
  json,
19884
19845
  code: own ? shape.code : undefined,
19885
- error: own ? shape.error : undefined
19846
+ error: own ? shape.error : undefined,
19847
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
19848
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
19886
19849
  };
19887
19850
  }
19888
- function answerEvent(answer, canTellDeadToken, layerKnown) {
19851
+ function isStoredKeyStatus(status) {
19852
+ return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
19853
+ }
19854
+ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
19889
19855
  const { status } = answer.response;
19890
19856
  if (status >= 200 && status < 300) {
19891
19857
  if (answer.notJson)
19892
19858
  return "foreign-2xx";
19893
19859
  if (answer.malformed)
19894
19860
  return "body-malformed";
19895
- return !answer.echoed && layerKnown ? "foreign-2xx" : "applied";
19861
+ return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
19896
19862
  }
19897
19863
  if (status >= 300 && status < 400)
19898
19864
  return "redirect";
@@ -19907,7 +19873,13 @@ function answerEvent(answer, canTellDeadToken, layerKnown) {
19907
19873
  return "in-flight";
19908
19874
  return status >= 500 ? "server-error" : "try-later";
19909
19875
  }
19910
- return answer.echoed ? "judged" : "unjudged";
19876
+ if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
19877
+ return "judged";
19878
+ if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
19879
+ return "unjudged";
19880
+ if (answer.code === IDEMPOTENCY_KEY_REUSED)
19881
+ return "judged";
19882
+ return answer.code === IDEMPOTENCY_KEY_IN_FLIGHT ? "unjudged" : "judged";
19911
19883
  }
19912
19884
  function credentialEvent(error) {
19913
19885
  return error instanceof TradeRetryingError ? "no-credential" : "no-credential-final";
@@ -20493,7 +20465,7 @@ class DispatchClient {
20493
20465
  key: key ?? crypto.randomUUID(),
20494
20466
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
20495
20467
  writes,
20496
- progress: { sent: 0, running: false, sawKeyedLayer: false }
20468
+ progress: { sent: 0, running: false, keyEchoed: false }
20497
20469
  };
20498
20470
  }
20499
20471
  async#upload(path, input, key) {
@@ -20511,12 +20483,12 @@ class DispatchClient {
20511
20483
  form.set("file", input.file, input.name);
20512
20484
  return this.#form("POST", path, form, key);
20513
20485
  }
20514
- async#form(method, path, form, key) {
20486
+ async#form(method, path, form, callerKey) {
20515
20487
  const url = this.#url(path);
20516
20488
  const encoded = new Response(form);
20517
20489
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
20518
20490
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
20519
- const write = this.#writeCall(method, url, key);
20491
+ const write = this.#writeCall(method, url, callerKey);
20520
20492
  if (write !== undefined) {
20521
20493
  const answer = await this.#write(method, url, body, "application/json", undefined, write);
20522
20494
  return this.#payloadOf(method, url, answer);
@@ -20601,14 +20573,12 @@ class DispatchClient {
20601
20573
  sent
20602
20574
  };
20603
20575
  }
20604
- const echoed = keyEchoed(response, key);
20605
- const heard = { echoed, retryAfterMs: retryAfterMs(response) };
20606
- if (echoed)
20607
- KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
20608
- progress.sawKeyedLayer ||= echoed;
20576
+ const heard = { retryAfterMs: retryAfterMs(response) };
20577
+ if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
20578
+ progress.keyEchoed = true;
20609
20579
  let answer;
20610
20580
  try {
20611
- answer = await writeAnswer(response, echoed);
20581
+ answer = await writeAnswer(response);
20612
20582
  } catch (error) {
20613
20583
  const stop = stoppedEvent(limit, true, error);
20614
20584
  return {
@@ -20620,7 +20590,7 @@ class DispatchClient {
20620
20590
  };
20621
20591
  }
20622
20592
  return {
20623
- event: answerEvent(answer, this.#credential.stale !== undefined && !deadTokenTold, progress.sawKeyedLayer || this.#remembersKeyedLayer()),
20593
+ event: answerEvent(answer, write.key, progress.keyEchoed, this.#credential.stale !== undefined && !deadTokenTold),
20624
20594
  answer,
20625
20595
  presented,
20626
20596
  sent,
@@ -20685,16 +20655,7 @@ class DispatchClient {
20685
20655
  const scheduled = progress.running ? Math.min(pausesMs[paced - 1] ?? inFlightPauseMs, inFlightPauseMs) : pausesMs[paced - 1];
20686
20656
  const wait = Math.max(scheduled ?? 0, last.heard?.retryAfterMs ?? 0);
20687
20657
  const latest = Math.min(started + (progress.running ? inFlightWithinMs : withinMs), lastAsk);
20688
- let again = scheduled !== undefined && this.#now() + wait <= latest;
20689
- const { answer } = last;
20690
- const unjudged = answer !== undefined && !answer.echoed && answer.error !== undefined;
20691
- if (again && state === "may-have-landed") {
20692
- again = (last.heard?.echoed ?? false) || await this.#runsKeyedLayer(unjudged);
20693
- progress.sawKeyedLayer ||= again;
20694
- again &&= this.#now() + wait <= latest;
20695
- } else if (unjudged && state === "nothing-sent") {
20696
- KEYED_LAYER_SEEN.delete(this.#baseUrl);
20697
- }
20658
+ const again = scheduled !== undefined && this.#now() + wait <= latest;
20698
20659
  if (!again) {
20699
20660
  event = "exhausted";
20700
20661
  continue;
@@ -20718,10 +20679,6 @@ class DispatchClient {
20718
20679
  }
20719
20680
  }
20720
20681
  }
20721
- #remembersKeyedLayer() {
20722
- const seen = KEYED_LAYER_SEEN.get(this.#baseUrl);
20723
- return seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS;
20724
- }
20725
20682
  #credentialSignal(limit) {
20726
20683
  return credentialDeadline(limit, Math.max(1, this.#deadlineAt - performance.now()));
20727
20684
  }
@@ -20759,7 +20716,7 @@ class DispatchClient {
20759
20716
  let own = failure;
20760
20717
  if (answer?.response.ok === true) {
20761
20718
  const { status } = answer.response;
20762
- 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 this 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`);
20719
+ 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`);
20763
20720
  } else if (answer !== undefined) {
20764
20721
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
20765
20722
  }
@@ -20791,39 +20748,7 @@ class DispatchClient {
20791
20748
  unanswered = `${request} failed on its last attempt (${last.message})`;
20792
20749
  }
20793
20750
  }
20794
- return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered, progress.sawKeyedLayer);
20795
- }
20796
- async#runsKeyedLayer(unjudged) {
20797
- const origin = this.#baseUrl;
20798
- if (unjudged)
20799
- KEYED_LAYER_SEEN.delete(origin);
20800
- const seen = KEYED_LAYER_SEEN.get(origin);
20801
- if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
20802
- return true;
20803
- let probe = KEYED_LAYER_PROBES.get(origin);
20804
- if (probe === undefined) {
20805
- probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
20806
- KEYED_LAYER_PROBES.set(origin, probe);
20807
- }
20808
- const runs = await probe;
20809
- if (runs)
20810
- KEYED_LAYER_SEEN.set(origin, this.#now());
20811
- return runs;
20812
- }
20813
- async#probeKeyedLayer() {
20814
- try {
20815
- const response = await this.#fetch(`${this.#baseUrl}/healthz`, {
20816
- method: "GET",
20817
- headers: { Accept: "application/json" },
20818
- signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
20819
- });
20820
- if (!isJson(response))
20821
- return false;
20822
- const health = await response.json();
20823
- return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
20824
- } catch {
20825
- return false;
20826
- }
20751
+ return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered);
20827
20752
  }
20828
20753
  #url(path, query) {
20829
20754
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
package/dist/dispatch.js CHANGED
@@ -15145,6 +15145,7 @@ var IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
15145
15145
  var IDEMPOTENCY_REPLAYED_HEADER = "Idempotency-Replayed";
15146
15146
  var IDEMPOTENCY_KEY_MAX = 128;
15147
15147
  var IDEMPOTENCY_KEY_PATTERN = new RegExp(`^[A-Za-z0-9._:-]{1,${IDEMPOTENCY_KEY_MAX}}$`);
15148
+ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
15148
15149
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
15149
15150
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
15150
15151
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
@@ -19952,7 +19953,7 @@ class DispatchWriteUnsettledError extends Error {
19952
19953
  attempts;
19953
19954
  key;
19954
19955
  name = "DispatchWriteUnsettledError";
19955
- constructor(last, attempts, key, unanswered, keyed = false) {
19956
+ constructor(last, attempts, key, unanswered) {
19956
19957
  let answer;
19957
19958
  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";
19958
19959
  if (last instanceof DispatchGatewayError) {
@@ -19967,10 +19968,7 @@ class DispatchWriteUnsettledError extends Error {
19967
19968
  why = "an attempt of the write may have reached Dispatch";
19968
19969
  }
19969
19970
  const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
19970
- const next = keyed ? ". Dispatch finishes an attempt it received whatever this command does, so read the " + "write back before you send it again: a new command sends it under a new key." : ": check whether it did before retrying it.";
19971
- super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect${next}`, {
19972
- cause: last
19973
- });
19971
+ super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect. Dispatch ` + "finishes an attempt it received whatever this command does, so read the write back " + "before you send it again: a new command sends it under a new key.", { cause: last });
19974
19972
  this.last = last;
19975
19973
  this.attempts = attempts;
19976
19974
  this.key = key;
@@ -20059,43 +20057,6 @@ function retryAfterMs(response) {
20059
20057
  const at = Date.parse(value);
20060
20058
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
20061
20059
  }
20062
- var KEYED_LAYER_MEMORY_MS = 5 * 60000;
20063
- var KEYED_LAYER_SEEN = new Map;
20064
- var KEYED_LAYER_PROBES = new Map;
20065
- var KEY_LAYER_PROBE_MS = 5000;
20066
- function keyedLayerMemory() {
20067
- const wall = Date.now();
20068
- const now = performance.now();
20069
- const kept = {};
20070
- for (const [origin, seen] of KEYED_LAYER_SEEN) {
20071
- const age = now - seen;
20072
- if (age >= 0 && age < KEYED_LAYER_MEMORY_MS) {
20073
- kept[origin] = new Date(wall - age).toISOString();
20074
- }
20075
- }
20076
- return kept;
20077
- }
20078
- function rememberKeyedLayer(saved) {
20079
- if (typeof saved !== "object" || saved === null)
20080
- return;
20081
- const wall = Date.now();
20082
- const now = performance.now();
20083
- for (const [origin, at] of Object.entries(saved)) {
20084
- if (typeof at !== "string")
20085
- continue;
20086
- const age = wall - Date.parse(at);
20087
- if (!(age >= 0 && age < KEYED_LAYER_MEMORY_MS))
20088
- continue;
20089
- const seen = now - age;
20090
- const known = KEYED_LAYER_SEEN.get(origin);
20091
- if (known === undefined || known < seen)
20092
- KEYED_LAYER_SEEN.set(origin, seen);
20093
- }
20094
- }
20095
- function keyEchoed(response, key) {
20096
- const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
20097
- return echoed.replace(/^"(.*)"$/, "$1") === key;
20098
- }
20099
20060
  var STREAMED_BODY_MIN = 1 << 20;
20100
20061
  var STREAMED_BODY_CHUNK = 64 << 10;
20101
20062
  function attemptBody(body, headers, progress) {
@@ -20134,17 +20095,18 @@ function parsedJson(response, text) {
20134
20095
  }
20135
20096
  }
20136
20097
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
20137
- async function writeAnswer(response, echoed) {
20098
+ async function writeAnswer(response) {
20138
20099
  if (NULL_BODY_STATUSES.has(response.status)) {
20139
20100
  return {
20140
20101
  response,
20141
- echoed,
20142
20102
  malformed: false,
20143
20103
  notJson: false,
20144
20104
  text: "",
20145
20105
  json: undefined,
20146
20106
  code: undefined,
20147
- error: undefined
20107
+ error: undefined,
20108
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
20109
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
20148
20110
  };
20149
20111
  }
20150
20112
  const text = await response.text();
@@ -20154,23 +20116,27 @@ async function writeAnswer(response, echoed) {
20154
20116
  const own = typeof shape.error === "string";
20155
20117
  return {
20156
20118
  response,
20157
- echoed,
20158
20119
  malformed: text !== "" && typed && json === undefined,
20159
20120
  notJson: text === "" || !typed,
20160
20121
  text,
20161
20122
  json,
20162
20123
  code: own ? shape.code : undefined,
20163
- error: own ? shape.error : undefined
20124
+ error: own ? shape.error : undefined,
20125
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
20126
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
20164
20127
  };
20165
20128
  }
20166
- function answerEvent(answer, canTellDeadToken, layerKnown) {
20129
+ function isStoredKeyStatus(status) {
20130
+ return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
20131
+ }
20132
+ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
20167
20133
  const { status } = answer.response;
20168
20134
  if (status >= 200 && status < 300) {
20169
20135
  if (answer.notJson)
20170
20136
  return "foreign-2xx";
20171
20137
  if (answer.malformed)
20172
20138
  return "body-malformed";
20173
- return !answer.echoed && layerKnown ? "foreign-2xx" : "applied";
20139
+ return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
20174
20140
  }
20175
20141
  if (status >= 300 && status < 400)
20176
20142
  return "redirect";
@@ -20185,7 +20151,13 @@ function answerEvent(answer, canTellDeadToken, layerKnown) {
20185
20151
  return "in-flight";
20186
20152
  return status >= 500 ? "server-error" : "try-later";
20187
20153
  }
20188
- return answer.echoed ? "judged" : "unjudged";
20154
+ if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
20155
+ return "judged";
20156
+ if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
20157
+ return "unjudged";
20158
+ if (answer.code === IDEMPOTENCY_KEY_REUSED)
20159
+ return "judged";
20160
+ return answer.code === IDEMPOTENCY_KEY_IN_FLIGHT ? "unjudged" : "judged";
20189
20161
  }
20190
20162
  function credentialEvent(error) {
20191
20163
  return error instanceof TradeRetryingError ? "no-credential" : "no-credential-final";
@@ -20771,7 +20743,7 @@ class DispatchClient {
20771
20743
  key: key ?? crypto.randomUUID(),
20772
20744
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
20773
20745
  writes,
20774
- progress: { sent: 0, running: false, sawKeyedLayer: false }
20746
+ progress: { sent: 0, running: false, keyEchoed: false }
20775
20747
  };
20776
20748
  }
20777
20749
  async#upload(path, input, key) {
@@ -20789,12 +20761,12 @@ class DispatchClient {
20789
20761
  form.set("file", input.file, input.name);
20790
20762
  return this.#form("POST", path, form, key);
20791
20763
  }
20792
- async#form(method, path, form, key) {
20764
+ async#form(method, path, form, callerKey) {
20793
20765
  const url = this.#url(path);
20794
20766
  const encoded = new Response(form);
20795
20767
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
20796
20768
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
20797
- const write = this.#writeCall(method, url, key);
20769
+ const write = this.#writeCall(method, url, callerKey);
20798
20770
  if (write !== undefined) {
20799
20771
  const answer = await this.#write(method, url, body, "application/json", undefined, write);
20800
20772
  return this.#payloadOf(method, url, answer);
@@ -20879,14 +20851,12 @@ class DispatchClient {
20879
20851
  sent
20880
20852
  };
20881
20853
  }
20882
- const echoed = keyEchoed(response, key);
20883
- const heard = { echoed, retryAfterMs: retryAfterMs(response) };
20884
- if (echoed)
20885
- KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
20886
- progress.sawKeyedLayer ||= echoed;
20854
+ const heard = { retryAfterMs: retryAfterMs(response) };
20855
+ if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
20856
+ progress.keyEchoed = true;
20887
20857
  let answer;
20888
20858
  try {
20889
- answer = await writeAnswer(response, echoed);
20859
+ answer = await writeAnswer(response);
20890
20860
  } catch (error) {
20891
20861
  const stop = stoppedEvent(limit, true, error);
20892
20862
  return {
@@ -20898,7 +20868,7 @@ class DispatchClient {
20898
20868
  };
20899
20869
  }
20900
20870
  return {
20901
- event: answerEvent(answer, this.#credential.stale !== undefined && !deadTokenTold, progress.sawKeyedLayer || this.#remembersKeyedLayer()),
20871
+ event: answerEvent(answer, write.key, progress.keyEchoed, this.#credential.stale !== undefined && !deadTokenTold),
20902
20872
  answer,
20903
20873
  presented,
20904
20874
  sent,
@@ -20963,16 +20933,7 @@ class DispatchClient {
20963
20933
  const scheduled = progress.running ? Math.min(pausesMs[paced - 1] ?? inFlightPauseMs, inFlightPauseMs) : pausesMs[paced - 1];
20964
20934
  const wait = Math.max(scheduled ?? 0, last.heard?.retryAfterMs ?? 0);
20965
20935
  const latest = Math.min(started + (progress.running ? inFlightWithinMs : withinMs), lastAsk);
20966
- let again = scheduled !== undefined && this.#now() + wait <= latest;
20967
- const { answer } = last;
20968
- const unjudged = answer !== undefined && !answer.echoed && answer.error !== undefined;
20969
- if (again && state === "may-have-landed") {
20970
- again = (last.heard?.echoed ?? false) || await this.#runsKeyedLayer(unjudged);
20971
- progress.sawKeyedLayer ||= again;
20972
- again &&= this.#now() + wait <= latest;
20973
- } else if (unjudged && state === "nothing-sent") {
20974
- KEYED_LAYER_SEEN.delete(this.#baseUrl);
20975
- }
20936
+ const again = scheduled !== undefined && this.#now() + wait <= latest;
20976
20937
  if (!again) {
20977
20938
  event = "exhausted";
20978
20939
  continue;
@@ -20996,10 +20957,6 @@ class DispatchClient {
20996
20957
  }
20997
20958
  }
20998
20959
  }
20999
- #remembersKeyedLayer() {
21000
- const seen = KEYED_LAYER_SEEN.get(this.#baseUrl);
21001
- return seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS;
21002
- }
21003
20960
  #credentialSignal(limit) {
21004
20961
  return credentialDeadline(limit, Math.max(1, this.#deadlineAt - performance.now()));
21005
20962
  }
@@ -21037,7 +20994,7 @@ class DispatchClient {
21037
20994
  let own = failure;
21038
20995
  if (answer?.response.ok === true) {
21039
20996
  const { status } = answer.response;
21040
- 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 this 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`);
20997
+ 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`);
21041
20998
  } else if (answer !== undefined) {
21042
20999
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
21043
21000
  }
@@ -21069,39 +21026,7 @@ class DispatchClient {
21069
21026
  unanswered = `${request} failed on its last attempt (${last.message})`;
21070
21027
  }
21071
21028
  }
21072
- return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered, progress.sawKeyedLayer);
21073
- }
21074
- async#runsKeyedLayer(unjudged) {
21075
- const origin = this.#baseUrl;
21076
- if (unjudged)
21077
- KEYED_LAYER_SEEN.delete(origin);
21078
- const seen = KEYED_LAYER_SEEN.get(origin);
21079
- if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
21080
- return true;
21081
- let probe = KEYED_LAYER_PROBES.get(origin);
21082
- if (probe === undefined) {
21083
- probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
21084
- KEYED_LAYER_PROBES.set(origin, probe);
21085
- }
21086
- const runs = await probe;
21087
- if (runs)
21088
- KEYED_LAYER_SEEN.set(origin, this.#now());
21089
- return runs;
21090
- }
21091
- async#probeKeyedLayer() {
21092
- try {
21093
- const response = await this.#fetch(`${this.#baseUrl}/healthz`, {
21094
- method: "GET",
21095
- headers: { Accept: "application/json" },
21096
- signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
21097
- });
21098
- if (!isJson(response))
21099
- return false;
21100
- const health = await response.json();
21101
- return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
21102
- } catch {
21103
- return false;
21104
- }
21029
+ return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered);
21105
21030
  }
21106
21031
  #url(path, query) {
21107
21032
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
@@ -28092,15 +28017,13 @@ function loadSessionMemory(dir, sessionId) {
28092
28017
  const pictures = shownPictures(sessionId);
28093
28018
  for (const address of stringList(state.pictures))
28094
28019
  pictures.add(address);
28095
- rememberKeyedLayer(state.keyedLayer);
28096
28020
  return new Set(stringList(state.follows));
28097
28021
  }
28098
28022
  function writeMemory(dir, sessionId, follows) {
28099
28023
  const state = {
28100
28024
  advice: [...adviceMemory()],
28101
28025
  pictures: [...shownPictures(sessionId)],
28102
- follows: [...follows],
28103
- keyedLayer: keyedLayerMemory()
28026
+ follows: [...follows]
28104
28027
  };
28105
28028
  writeAtomically(join6(dir, "state.json"), `${JSON.stringify(state)}
28106
28029
  `);
@@ -36648,6 +36648,7 @@ var IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
36648
36648
  var IDEMPOTENCY_REPLAYED_HEADER = "Idempotency-Replayed";
36649
36649
  var IDEMPOTENCY_KEY_MAX = 128;
36650
36650
  var IDEMPOTENCY_KEY_PATTERN = new RegExp(`^[A-Za-z0-9._:-]{1,${IDEMPOTENCY_KEY_MAX}}$`);
36651
+ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
36651
36652
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
36652
36653
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
36653
36654
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
@@ -43536,7 +43537,7 @@ class DispatchWriteUnsettledError extends Error {
43536
43537
  attempts;
43537
43538
  key;
43538
43539
  name = "DispatchWriteUnsettledError";
43539
- constructor(last, attempts, key, unanswered, keyed = false) {
43540
+ constructor(last, attempts, key, unanswered) {
43540
43541
  let answer;
43541
43542
  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";
43542
43543
  if (last instanceof DispatchGatewayError) {
@@ -43551,10 +43552,7 @@ class DispatchWriteUnsettledError extends Error {
43551
43552
  why = "an attempt of the write may have reached Dispatch";
43552
43553
  }
43553
43554
  const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
43554
- const next = keyed ? ". Dispatch finishes an attempt it received whatever this command does, so read the " + "write back before you send it again: a new command sends it under a new key." : ": check whether it did before retrying it.";
43555
- super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect${next}`, {
43556
- cause: last
43557
- });
43555
+ super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect. Dispatch ` + "finishes an attempt it received whatever this command does, so read the write back " + "before you send it again: a new command sends it under a new key.", { cause: last });
43558
43556
  this.last = last;
43559
43557
  this.attempts = attempts;
43560
43558
  this.key = key;
@@ -43643,43 +43641,6 @@ function retryAfterMs(response) {
43643
43641
  const at = Date.parse(value);
43644
43642
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
43645
43643
  }
43646
- var KEYED_LAYER_MEMORY_MS = 5 * 60000;
43647
- var KEYED_LAYER_SEEN = new Map;
43648
- var KEYED_LAYER_PROBES = new Map;
43649
- var KEY_LAYER_PROBE_MS = 5000;
43650
- function keyedLayerMemory() {
43651
- const wall = Date.now();
43652
- const now = performance.now();
43653
- const kept = {};
43654
- for (const [origin, seen] of KEYED_LAYER_SEEN) {
43655
- const age = now - seen;
43656
- if (age >= 0 && age < KEYED_LAYER_MEMORY_MS) {
43657
- kept[origin] = new Date(wall - age).toISOString();
43658
- }
43659
- }
43660
- return kept;
43661
- }
43662
- function rememberKeyedLayer(saved) {
43663
- if (typeof saved !== "object" || saved === null)
43664
- return;
43665
- const wall = Date.now();
43666
- const now = performance.now();
43667
- for (const [origin, at] of Object.entries(saved)) {
43668
- if (typeof at !== "string")
43669
- continue;
43670
- const age = wall - Date.parse(at);
43671
- if (!(age >= 0 && age < KEYED_LAYER_MEMORY_MS))
43672
- continue;
43673
- const seen = now - age;
43674
- const known = KEYED_LAYER_SEEN.get(origin);
43675
- if (known === undefined || known < seen)
43676
- KEYED_LAYER_SEEN.set(origin, seen);
43677
- }
43678
- }
43679
- function keyEchoed(response, key) {
43680
- const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
43681
- return echoed.replace(/^"(.*)"$/, "$1") === key;
43682
- }
43683
43644
  var STREAMED_BODY_MIN = 1 << 20;
43684
43645
  var STREAMED_BODY_CHUNK = 64 << 10;
43685
43646
  function attemptBody(body, headers, progress) {
@@ -43718,17 +43679,18 @@ function parsedJson(response, text) {
43718
43679
  }
43719
43680
  }
43720
43681
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
43721
- async function writeAnswer(response, echoed) {
43682
+ async function writeAnswer(response) {
43722
43683
  if (NULL_BODY_STATUSES.has(response.status)) {
43723
43684
  return {
43724
43685
  response,
43725
- echoed,
43726
43686
  malformed: false,
43727
43687
  notJson: false,
43728
43688
  text: "",
43729
43689
  json: undefined,
43730
43690
  code: undefined,
43731
- error: undefined
43691
+ error: undefined,
43692
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
43693
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
43732
43694
  };
43733
43695
  }
43734
43696
  const text = await response.text();
@@ -43738,23 +43700,27 @@ async function writeAnswer(response, echoed) {
43738
43700
  const own = typeof shape.error === "string";
43739
43701
  return {
43740
43702
  response,
43741
- echoed,
43742
43703
  malformed: text !== "" && typed && json === undefined,
43743
43704
  notJson: text === "" || !typed,
43744
43705
  text,
43745
43706
  json,
43746
43707
  code: own ? shape.code : undefined,
43747
- error: own ? shape.error : undefined
43708
+ error: own ? shape.error : undefined,
43709
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
43710
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
43748
43711
  };
43749
43712
  }
43750
- function answerEvent(answer, canTellDeadToken, layerKnown) {
43713
+ function isStoredKeyStatus(status) {
43714
+ return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
43715
+ }
43716
+ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
43751
43717
  const { status } = answer.response;
43752
43718
  if (status >= 200 && status < 300) {
43753
43719
  if (answer.notJson)
43754
43720
  return "foreign-2xx";
43755
43721
  if (answer.malformed)
43756
43722
  return "body-malformed";
43757
- return !answer.echoed && layerKnown ? "foreign-2xx" : "applied";
43723
+ return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
43758
43724
  }
43759
43725
  if (status >= 300 && status < 400)
43760
43726
  return "redirect";
@@ -43769,7 +43735,13 @@ function answerEvent(answer, canTellDeadToken, layerKnown) {
43769
43735
  return "in-flight";
43770
43736
  return status >= 500 ? "server-error" : "try-later";
43771
43737
  }
43772
- return answer.echoed ? "judged" : "unjudged";
43738
+ if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
43739
+ return "judged";
43740
+ if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
43741
+ return "unjudged";
43742
+ if (answer.code === IDEMPOTENCY_KEY_REUSED)
43743
+ return "judged";
43744
+ return answer.code === IDEMPOTENCY_KEY_IN_FLIGHT ? "unjudged" : "judged";
43773
43745
  }
43774
43746
  function credentialEvent(error) {
43775
43747
  return error instanceof TradeRetryingError ? "no-credential" : "no-credential-final";
@@ -44355,7 +44327,7 @@ class DispatchClient {
44355
44327
  key: key ?? crypto.randomUUID(),
44356
44328
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
44357
44329
  writes,
44358
- progress: { sent: 0, running: false, sawKeyedLayer: false }
44330
+ progress: { sent: 0, running: false, keyEchoed: false }
44359
44331
  };
44360
44332
  }
44361
44333
  async#upload(path, input, key) {
@@ -44373,12 +44345,12 @@ class DispatchClient {
44373
44345
  form.set("file", input.file, input.name);
44374
44346
  return this.#form("POST", path, form, key);
44375
44347
  }
44376
- async#form(method, path, form, key) {
44348
+ async#form(method, path, form, callerKey) {
44377
44349
  const url = this.#url(path);
44378
44350
  const encoded = new Response(form);
44379
44351
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
44380
44352
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
44381
- const write = this.#writeCall(method, url, key);
44353
+ const write = this.#writeCall(method, url, callerKey);
44382
44354
  if (write !== undefined) {
44383
44355
  const answer = await this.#write(method, url, body, "application/json", undefined, write);
44384
44356
  return this.#payloadOf(method, url, answer);
@@ -44463,14 +44435,12 @@ class DispatchClient {
44463
44435
  sent
44464
44436
  };
44465
44437
  }
44466
- const echoed = keyEchoed(response, key);
44467
- const heard = { echoed, retryAfterMs: retryAfterMs(response) };
44468
- if (echoed)
44469
- KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
44470
- progress.sawKeyedLayer ||= echoed;
44438
+ const heard = { retryAfterMs: retryAfterMs(response) };
44439
+ if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
44440
+ progress.keyEchoed = true;
44471
44441
  let answer;
44472
44442
  try {
44473
- answer = await writeAnswer(response, echoed);
44443
+ answer = await writeAnswer(response);
44474
44444
  } catch (error) {
44475
44445
  const stop = stoppedEvent(limit, true, error);
44476
44446
  return {
@@ -44482,7 +44452,7 @@ class DispatchClient {
44482
44452
  };
44483
44453
  }
44484
44454
  return {
44485
- event: answerEvent(answer, this.#credential.stale !== undefined && !deadTokenTold, progress.sawKeyedLayer || this.#remembersKeyedLayer()),
44455
+ event: answerEvent(answer, write.key, progress.keyEchoed, this.#credential.stale !== undefined && !deadTokenTold),
44486
44456
  answer,
44487
44457
  presented,
44488
44458
  sent,
@@ -44547,16 +44517,7 @@ class DispatchClient {
44547
44517
  const scheduled = progress.running ? Math.min(pausesMs[paced - 1] ?? inFlightPauseMs, inFlightPauseMs) : pausesMs[paced - 1];
44548
44518
  const wait = Math.max(scheduled ?? 0, last.heard?.retryAfterMs ?? 0);
44549
44519
  const latest = Math.min(started + (progress.running ? inFlightWithinMs : withinMs), lastAsk);
44550
- let again = scheduled !== undefined && this.#now() + wait <= latest;
44551
- const { answer } = last;
44552
- const unjudged = answer !== undefined && !answer.echoed && answer.error !== undefined;
44553
- if (again && state === "may-have-landed") {
44554
- again = (last.heard?.echoed ?? false) || await this.#runsKeyedLayer(unjudged);
44555
- progress.sawKeyedLayer ||= again;
44556
- again &&= this.#now() + wait <= latest;
44557
- } else if (unjudged && state === "nothing-sent") {
44558
- KEYED_LAYER_SEEN.delete(this.#baseUrl);
44559
- }
44520
+ const again = scheduled !== undefined && this.#now() + wait <= latest;
44560
44521
  if (!again) {
44561
44522
  event = "exhausted";
44562
44523
  continue;
@@ -44580,10 +44541,6 @@ class DispatchClient {
44580
44541
  }
44581
44542
  }
44582
44543
  }
44583
- #remembersKeyedLayer() {
44584
- const seen = KEYED_LAYER_SEEN.get(this.#baseUrl);
44585
- return seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS;
44586
- }
44587
44544
  #credentialSignal(limit) {
44588
44545
  return credentialDeadline(limit, Math.max(1, this.#deadlineAt - performance.now()));
44589
44546
  }
@@ -44621,7 +44578,7 @@ class DispatchClient {
44621
44578
  let own = failure;
44622
44579
  if (answer?.response.ok === true) {
44623
44580
  const { status } = answer.response;
44624
- 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 this 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`);
44581
+ 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`);
44625
44582
  } else if (answer !== undefined) {
44626
44583
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
44627
44584
  }
@@ -44653,39 +44610,7 @@ class DispatchClient {
44653
44610
  unanswered = `${request} failed on its last attempt (${last.message})`;
44654
44611
  }
44655
44612
  }
44656
- return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered, progress.sawKeyedLayer);
44657
- }
44658
- async#runsKeyedLayer(unjudged) {
44659
- const origin = this.#baseUrl;
44660
- if (unjudged)
44661
- KEYED_LAYER_SEEN.delete(origin);
44662
- const seen = KEYED_LAYER_SEEN.get(origin);
44663
- if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
44664
- return true;
44665
- let probe = KEYED_LAYER_PROBES.get(origin);
44666
- if (probe === undefined) {
44667
- probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
44668
- KEYED_LAYER_PROBES.set(origin, probe);
44669
- }
44670
- const runs = await probe;
44671
- if (runs)
44672
- KEYED_LAYER_SEEN.set(origin, this.#now());
44673
- return runs;
44674
- }
44675
- async#probeKeyedLayer() {
44676
- try {
44677
- const response = await this.#fetch(`${this.#baseUrl}/healthz`, {
44678
- method: "GET",
44679
- headers: { Accept: "application/json" },
44680
- signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
44681
- });
44682
- if (!isJson(response))
44683
- return false;
44684
- const health = await response.json();
44685
- return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
44686
- } catch {
44687
- return false;
44688
- }
44613
+ return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered);
44689
44614
  }
44690
44615
  #url(path, query) {
44691
44616
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
@@ -52524,15 +52449,13 @@ function loadSessionMemory(dir, sessionId) {
52524
52449
  const pictures = shownPictures(sessionId);
52525
52450
  for (const address of stringList(state.pictures))
52526
52451
  pictures.add(address);
52527
- rememberKeyedLayer(state.keyedLayer);
52528
52452
  return new Set(stringList(state.follows));
52529
52453
  }
52530
52454
  function writeMemory(dir, sessionId, follows) {
52531
52455
  const state = {
52532
52456
  advice: [...adviceMemory()],
52533
52457
  pictures: [...shownPictures(sessionId)],
52534
- follows: [...follows],
52535
- keyedLayer: keyedLayerMemory()
52458
+ follows: [...follows]
52536
52459
  };
52537
52460
  writeAtomically(join6(dir, "state.json"), `${JSON.stringify(state)}
52538
52461
  `);
@@ -58025,7 +57948,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
58025
57948
 
58026
57949
  // package.json
58027
57950
  var name2 = "@sjawhar/claude-envoy";
58028
- var version2 = "4.21.1";
57951
+ var version2 = "4.21.2";
58029
57952
  var legion = {
58030
57953
  daemonApiVersion: 202
58031
57954
  };
@@ -14052,6 +14052,7 @@ var IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
14052
14052
  var IDEMPOTENCY_REPLAYED_HEADER = "Idempotency-Replayed";
14053
14053
  var IDEMPOTENCY_KEY_MAX = 128;
14054
14054
  var IDEMPOTENCY_KEY_PATTERN = new RegExp(`^[A-Za-z0-9._:-]{1,${IDEMPOTENCY_KEY_MAX}}$`);
14055
+ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
14055
14056
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
14056
14057
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
14057
14058
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
@@ -19675,7 +19676,7 @@ class DispatchWriteUnsettledError extends Error {
19675
19676
  attempts;
19676
19677
  key;
19677
19678
  name = "DispatchWriteUnsettledError";
19678
- constructor(last, attempts, key, unanswered, keyed = false) {
19679
+ constructor(last, attempts, key, unanswered) {
19679
19680
  let answer;
19680
19681
  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";
19681
19682
  if (last instanceof DispatchGatewayError) {
@@ -19690,10 +19691,7 @@ class DispatchWriteUnsettledError extends Error {
19690
19691
  why = "an attempt of the write may have reached Dispatch";
19691
19692
  }
19692
19693
  const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
19693
- const next = keyed ? ". Dispatch finishes an attempt it received whatever this command does, so read the " + "write back before you send it again: a new command sends it under a new key." : ": check whether it did before retrying it.";
19694
- super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect${next}`, {
19695
- cause: last
19696
- });
19694
+ super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect. Dispatch ` + "finishes an attempt it received whatever this command does, so read the write back " + "before you send it again: a new command sends it under a new key.", { cause: last });
19697
19695
  this.last = last;
19698
19696
  this.attempts = attempts;
19699
19697
  this.key = key;
@@ -19782,43 +19780,6 @@ function retryAfterMs(response) {
19782
19780
  const at = Date.parse(value);
19783
19781
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
19784
19782
  }
19785
- var KEYED_LAYER_MEMORY_MS = 5 * 60000;
19786
- var KEYED_LAYER_SEEN = new Map;
19787
- var KEYED_LAYER_PROBES = new Map;
19788
- var KEY_LAYER_PROBE_MS = 5000;
19789
- function keyedLayerMemory() {
19790
- const wall = Date.now();
19791
- const now = performance.now();
19792
- const kept = {};
19793
- for (const [origin, seen] of KEYED_LAYER_SEEN) {
19794
- const age = now - seen;
19795
- if (age >= 0 && age < KEYED_LAYER_MEMORY_MS) {
19796
- kept[origin] = new Date(wall - age).toISOString();
19797
- }
19798
- }
19799
- return kept;
19800
- }
19801
- function rememberKeyedLayer(saved) {
19802
- if (typeof saved !== "object" || saved === null)
19803
- return;
19804
- const wall = Date.now();
19805
- const now = performance.now();
19806
- for (const [origin, at] of Object.entries(saved)) {
19807
- if (typeof at !== "string")
19808
- continue;
19809
- const age = wall - Date.parse(at);
19810
- if (!(age >= 0 && age < KEYED_LAYER_MEMORY_MS))
19811
- continue;
19812
- const seen = now - age;
19813
- const known = KEYED_LAYER_SEEN.get(origin);
19814
- if (known === undefined || known < seen)
19815
- KEYED_LAYER_SEEN.set(origin, seen);
19816
- }
19817
- }
19818
- function keyEchoed(response, key) {
19819
- const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
19820
- return echoed.replace(/^"(.*)"$/, "$1") === key;
19821
- }
19822
19783
  var STREAMED_BODY_MIN = 1 << 20;
19823
19784
  var STREAMED_BODY_CHUNK = 64 << 10;
19824
19785
  function attemptBody(body, headers, progress) {
@@ -19857,17 +19818,18 @@ function parsedJson(response, text) {
19857
19818
  }
19858
19819
  }
19859
19820
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
19860
- async function writeAnswer(response, echoed) {
19821
+ async function writeAnswer(response) {
19861
19822
  if (NULL_BODY_STATUSES.has(response.status)) {
19862
19823
  return {
19863
19824
  response,
19864
- echoed,
19865
19825
  malformed: false,
19866
19826
  notJson: false,
19867
19827
  text: "",
19868
19828
  json: undefined,
19869
19829
  code: undefined,
19870
- error: undefined
19830
+ error: undefined,
19831
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
19832
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
19871
19833
  };
19872
19834
  }
19873
19835
  const text = await response.text();
@@ -19877,23 +19839,27 @@ async function writeAnswer(response, echoed) {
19877
19839
  const own = typeof shape.error === "string";
19878
19840
  return {
19879
19841
  response,
19880
- echoed,
19881
19842
  malformed: text !== "" && typed && json === undefined,
19882
19843
  notJson: text === "" || !typed,
19883
19844
  text,
19884
19845
  json,
19885
19846
  code: own ? shape.code : undefined,
19886
- error: own ? shape.error : undefined
19847
+ error: own ? shape.error : undefined,
19848
+ replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
19849
+ keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
19887
19850
  };
19888
19851
  }
19889
- function answerEvent(answer, canTellDeadToken, layerKnown) {
19852
+ function isStoredKeyStatus(status) {
19853
+ return status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429;
19854
+ }
19855
+ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
19890
19856
  const { status } = answer.response;
19891
19857
  if (status >= 200 && status < 300) {
19892
19858
  if (answer.notJson)
19893
19859
  return "foreign-2xx";
19894
19860
  if (answer.malformed)
19895
19861
  return "body-malformed";
19896
- return !answer.echoed && layerKnown ? "foreign-2xx" : "applied";
19862
+ return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
19897
19863
  }
19898
19864
  if (status >= 300 && status < 400)
19899
19865
  return "redirect";
@@ -19908,7 +19874,13 @@ function answerEvent(answer, canTellDeadToken, layerKnown) {
19908
19874
  return "in-flight";
19909
19875
  return status >= 500 ? "server-error" : "try-later";
19910
19876
  }
19911
- return answer.echoed ? "judged" : "unjudged";
19877
+ if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
19878
+ return "judged";
19879
+ if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
19880
+ return "unjudged";
19881
+ if (answer.code === IDEMPOTENCY_KEY_REUSED)
19882
+ return "judged";
19883
+ return answer.code === IDEMPOTENCY_KEY_IN_FLIGHT ? "unjudged" : "judged";
19912
19884
  }
19913
19885
  function credentialEvent(error) {
19914
19886
  return error instanceof TradeRetryingError ? "no-credential" : "no-credential-final";
@@ -20494,7 +20466,7 @@ class DispatchClient {
20494
20466
  key: key ?? crypto.randomUUID(),
20495
20467
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
20496
20468
  writes,
20497
- progress: { sent: 0, running: false, sawKeyedLayer: false }
20469
+ progress: { sent: 0, running: false, keyEchoed: false }
20498
20470
  };
20499
20471
  }
20500
20472
  async#upload(path, input, key) {
@@ -20512,12 +20484,12 @@ class DispatchClient {
20512
20484
  form.set("file", input.file, input.name);
20513
20485
  return this.#form("POST", path, form, key);
20514
20486
  }
20515
- async#form(method, path, form, key) {
20487
+ async#form(method, path, form, callerKey) {
20516
20488
  const url = this.#url(path);
20517
20489
  const encoded = new Response(form);
20518
20490
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
20519
20491
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
20520
- const write = this.#writeCall(method, url, key);
20492
+ const write = this.#writeCall(method, url, callerKey);
20521
20493
  if (write !== undefined) {
20522
20494
  const answer = await this.#write(method, url, body, "application/json", undefined, write);
20523
20495
  return this.#payloadOf(method, url, answer);
@@ -20602,14 +20574,12 @@ class DispatchClient {
20602
20574
  sent
20603
20575
  };
20604
20576
  }
20605
- const echoed = keyEchoed(response, key);
20606
- const heard = { echoed, retryAfterMs: retryAfterMs(response) };
20607
- if (echoed)
20608
- KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
20609
- progress.sawKeyedLayer ||= echoed;
20577
+ const heard = { retryAfterMs: retryAfterMs(response) };
20578
+ if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
20579
+ progress.keyEchoed = true;
20610
20580
  let answer;
20611
20581
  try {
20612
- answer = await writeAnswer(response, echoed);
20582
+ answer = await writeAnswer(response);
20613
20583
  } catch (error) {
20614
20584
  const stop = stoppedEvent(limit, true, error);
20615
20585
  return {
@@ -20621,7 +20591,7 @@ class DispatchClient {
20621
20591
  };
20622
20592
  }
20623
20593
  return {
20624
- event: answerEvent(answer, this.#credential.stale !== undefined && !deadTokenTold, progress.sawKeyedLayer || this.#remembersKeyedLayer()),
20594
+ event: answerEvent(answer, write.key, progress.keyEchoed, this.#credential.stale !== undefined && !deadTokenTold),
20625
20595
  answer,
20626
20596
  presented,
20627
20597
  sent,
@@ -20686,16 +20656,7 @@ class DispatchClient {
20686
20656
  const scheduled = progress.running ? Math.min(pausesMs[paced - 1] ?? inFlightPauseMs, inFlightPauseMs) : pausesMs[paced - 1];
20687
20657
  const wait = Math.max(scheduled ?? 0, last.heard?.retryAfterMs ?? 0);
20688
20658
  const latest = Math.min(started + (progress.running ? inFlightWithinMs : withinMs), lastAsk);
20689
- let again = scheduled !== undefined && this.#now() + wait <= latest;
20690
- const { answer } = last;
20691
- const unjudged = answer !== undefined && !answer.echoed && answer.error !== undefined;
20692
- if (again && state === "may-have-landed") {
20693
- again = (last.heard?.echoed ?? false) || await this.#runsKeyedLayer(unjudged);
20694
- progress.sawKeyedLayer ||= again;
20695
- again &&= this.#now() + wait <= latest;
20696
- } else if (unjudged && state === "nothing-sent") {
20697
- KEYED_LAYER_SEEN.delete(this.#baseUrl);
20698
- }
20659
+ const again = scheduled !== undefined && this.#now() + wait <= latest;
20699
20660
  if (!again) {
20700
20661
  event = "exhausted";
20701
20662
  continue;
@@ -20719,10 +20680,6 @@ class DispatchClient {
20719
20680
  }
20720
20681
  }
20721
20682
  }
20722
- #remembersKeyedLayer() {
20723
- const seen = KEYED_LAYER_SEEN.get(this.#baseUrl);
20724
- return seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS;
20725
- }
20726
20683
  #credentialSignal(limit) {
20727
20684
  return credentialDeadline(limit, Math.max(1, this.#deadlineAt - performance.now()));
20728
20685
  }
@@ -20760,7 +20717,7 @@ class DispatchClient {
20760
20717
  let own = failure;
20761
20718
  if (answer?.response.ok === true) {
20762
20719
  const { status } = answer.response;
20763
- 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 this 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`);
20720
+ 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`);
20764
20721
  } else if (answer !== undefined) {
20765
20722
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
20766
20723
  }
@@ -20792,39 +20749,7 @@ class DispatchClient {
20792
20749
  unanswered = `${request} failed on its last attempt (${last.message})`;
20793
20750
  }
20794
20751
  }
20795
- return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered, progress.sawKeyedLayer);
20796
- }
20797
- async#runsKeyedLayer(unjudged) {
20798
- const origin = this.#baseUrl;
20799
- if (unjudged)
20800
- KEYED_LAYER_SEEN.delete(origin);
20801
- const seen = KEYED_LAYER_SEEN.get(origin);
20802
- if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
20803
- return true;
20804
- let probe = KEYED_LAYER_PROBES.get(origin);
20805
- if (probe === undefined) {
20806
- probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
20807
- KEYED_LAYER_PROBES.set(origin, probe);
20808
- }
20809
- const runs = await probe;
20810
- if (runs)
20811
- KEYED_LAYER_SEEN.set(origin, this.#now());
20812
- return runs;
20813
- }
20814
- async#probeKeyedLayer() {
20815
- try {
20816
- const response = await this.#fetch(`${this.#baseUrl}/healthz`, {
20817
- method: "GET",
20818
- headers: { Accept: "application/json" },
20819
- signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
20820
- });
20821
- if (!isJson(response))
20822
- return false;
20823
- const health = await response.json();
20824
- return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
20825
- } catch {
20826
- return false;
20827
- }
20752
+ return new DispatchWriteUnsettledError(last, progress.sent, write.key, unanswered);
20828
20753
  }
20829
20754
  #url(path, query) {
20830
20755
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "4.21.1",
3
+ "version": "4.21.2",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",