agentchatme 1.5.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -313,7 +313,7 @@ function createAgentChatError(body, status, headers) {
313
313
  }
314
314
 
315
315
  // src/version.ts
316
- var VERSION = "1.5.0" ;
316
+ var VERSION = "1.5.1" ;
317
317
 
318
318
  // src/runtime.ts
319
319
  function detectRuntime() {
@@ -4861,6 +4861,7 @@ function readResult(text2) {
4861
4861
  // src/integration/receive-loop.ts
4862
4862
  var TRAY_LIMIT = 50;
4863
4863
  var SILENT_MEMORY = 1e3;
4864
+ var CONVERSATION_KEY = "conversation:";
4864
4865
  var PACE_MS = 6e4;
4865
4866
  var TURN_OVERDUE_MS = 30 * 6e4;
4866
4867
  var NO_PROGRESS_BACKOFF_MS = 1e3;
@@ -4883,30 +4884,98 @@ var Pacer = class {
4883
4884
  paceMs;
4884
4885
  now;
4885
4886
  until = /* @__PURE__ */ new Map();
4887
+ /** Orders holds and tray reads: a read lifts only holds older than its start. */
4888
+ seq = 0;
4889
+ /** A D5 pace. It never replaces a could-not-process hold at the same anchor (that input stays held). */
4886
4890
  hold(key, anchor) {
4887
- this.until.delete(key);
4888
- this.until.set(key, { anchor, until: this.now() + this.paceMs });
4889
- while (this.until.size > SILENT_MEMORY) {
4890
- const oldest = this.until.keys().next().value;
4891
- if (oldest === void 0) break;
4892
- this.until.delete(oldest);
4893
- }
4894
- }
4895
- held(key, anchor) {
4891
+ const prior = this.until.get(key);
4892
+ if (prior?.failure !== void 0 && prior.anchor === anchor) return;
4893
+ this.set(key, { anchor, until: this.now() + this.paceMs });
4894
+ }
4895
+ /** Could not process: hold the key at this anchor until a newer message moves it (held again at it: since the first time). */
4896
+ holdFailed(key, anchor, reason) {
4897
+ const prior = this.until.get(key);
4898
+ const since = prior?.failure !== void 0 && prior.anchor === anchor ? prior.failure.since : this.now();
4899
+ this.set(key, { anchor, until: Number.POSITIVE_INFINITY, failure: { reason, since, seq: ++this.seq } });
4900
+ }
4901
+ /** What holds the key at this anchor now: a pace, a could-not-process hold, or nothing (a stale entry goes). */
4902
+ check(key, anchor) {
4896
4903
  const entry = this.until.get(key);
4897
- if (!entry) return false;
4904
+ if (!entry) return null;
4898
4905
  if (entry.anchor !== anchor || this.now() >= entry.until) {
4899
4906
  this.until.delete(key);
4900
- return false;
4907
+ return null;
4901
4908
  }
4902
- return true;
4909
+ return entry.failure ? "failed" : "paced";
4903
4910
  }
4911
+ held(key, anchor) {
4912
+ return this.check(key, anchor) !== null;
4913
+ }
4914
+ /** A could-not-process hold on the key at exactly this anchor; changes nothing (a queued run's anchor may be older than the card's). */
4915
+ heldFailedAt(key, anchor) {
4916
+ const entry = this.until.get(key);
4917
+ return entry?.failure !== void 0 && entry.anchor === anchor;
4918
+ }
4919
+ /** Lift whatever holds the key (a pace or a could-not-process hold). */
4904
4920
  release(key) {
4905
4921
  this.until.delete(key);
4906
4922
  }
4923
+ /** Lift a pace; a could-not-process hold stays. */
4924
+ releasePace(key) {
4925
+ if (this.until.get(key)?.failure === void 0) this.until.delete(key);
4926
+ }
4907
4927
  releaseInvites() {
4908
4928
  for (const key of [...this.until.keys()]) if (key.startsWith("invite:")) this.until.delete(key);
4909
4929
  }
4930
+ /** Taken before a tray read: `keepFailedOn` lifts only holds made before it. */
4931
+ mark() {
4932
+ return this.seq;
4933
+ }
4934
+ /**
4935
+ * After a tray read from `mark` (`anchors`: each card's key and anchor):
4936
+ * a hold whose card shows another anchor is over (a newer message came),
4937
+ * and, on a complete tray (`complete`: not truncated), so is one whose
4938
+ * card is gone (read meanwhile: a verdict, a mark-read). Only holds made
4939
+ * before the read started: a read that began earlier says nothing of a
4940
+ * later hold.
4941
+ */
4942
+ keepFailedOn(anchors, mark, complete) {
4943
+ for (const [key, entry] of this.until) {
4944
+ if (entry.failure === void 0 || entry.failure.seq > mark) continue;
4945
+ const shown = anchors.get(key);
4946
+ if (shown === void 0 ? complete : shown !== entry.anchor) this.until.delete(key);
4947
+ }
4948
+ }
4949
+ /** The could-not-process holds, oldest first (by `since`). */
4950
+ failed() {
4951
+ const out = [];
4952
+ for (const [key, entry] of this.until) {
4953
+ if (entry.failure !== void 0 && entry.anchor !== null) {
4954
+ out.push({ key, anchor: entry.anchor, reason: entry.failure.reason, since: entry.failure.since });
4955
+ }
4956
+ }
4957
+ return out.sort((a, b) => a.since - b.since);
4958
+ }
4959
+ set(key, entry) {
4960
+ this.until.delete(key);
4961
+ this.until.set(key, entry);
4962
+ let paces = 0;
4963
+ let holds = 0;
4964
+ for (const held of this.until.values()) {
4965
+ if (held.failure === void 0) paces += 1;
4966
+ else holds += 1;
4967
+ }
4968
+ for (const [key2, held] of this.until) {
4969
+ if (paces <= SILENT_MEMORY && holds <= SILENT_MEMORY) break;
4970
+ if (held.failure === void 0 && paces > SILENT_MEMORY) {
4971
+ this.until.delete(key2);
4972
+ paces -= 1;
4973
+ } else if (held.failure !== void 0 && holds > SILENT_MEMORY) {
4974
+ this.until.delete(key2);
4975
+ holds -= 1;
4976
+ }
4977
+ }
4978
+ }
4910
4979
  };
4911
4980
  function clears(completion, failure) {
4912
4981
  return completion.kind === failure.source && completion.conversations.has(failure.conversationId);
@@ -4991,16 +5060,25 @@ var ReceiveLoop = class {
4991
5060
  rerunsCapped: 0,
4992
5061
  runtimeChecksOk: 0,
4993
5062
  runtimeChecksFailed: 0,
4994
- splitsStopped: 0
5063
+ splitsStopped: 0,
5064
+ startsHeld: 0
4995
5065
  };
4996
5066
  /** Conversations whose verdict a gate call is recording right now (an abandoned cycle's included). */
4997
5067
  recordsInFlight = /* @__PURE__ */ new Set();
5068
+ /**
5069
+ * Could not process: conversations whose report is out on another's
5070
+ * completion (`takeDue`): held out of the gate and of new runs, and a run
5071
+ * or turn of theirs waiting for a slot waits, until the server answers.
5072
+ */
5073
+ reporting = /* @__PURE__ */ new Map();
4998
5074
  /** Turns holding a slot (admitted, not yet ended or released). */
4999
5075
  slotted = /* @__PURE__ */ new Set();
5000
5076
  handle;
5001
5077
  started = false;
5002
5078
  stopped = false;
5003
5079
  heldWhileRunning = false;
5080
+ /** A cycle left a card out because its could-not-process report was out: `letGo` reads the tray again. */
5081
+ heldWhileReporting = false;
5004
5082
  activeTurns = 0;
5005
5083
  noProgressStreak = 0;
5006
5084
  moreTimer = null;
@@ -5198,7 +5276,13 @@ var ReceiveLoop = class {
5198
5276
  processingFailures: {
5199
5277
  ...this.failureCounts,
5200
5278
  awaitingEvidence: this.awaitingEvidence.size,
5201
- lastRuntimeCheck: this.lastRuntimeCheck === null ? null : { ...this.lastRuntimeCheck }
5279
+ lastRuntimeCheck: this.lastRuntimeCheck === null ? null : { ...this.lastRuntimeCheck },
5280
+ held: this.pacer.failed().map(({ key, anchor, reason, since }) => ({
5281
+ conversationId: key.slice(CONVERSATION_KEY.length),
5282
+ anchor,
5283
+ since: new Date(since).toISOString(),
5284
+ reason
5285
+ }))
5202
5286
  },
5203
5287
  lastError: this.lastError
5204
5288
  };
@@ -5228,7 +5312,7 @@ var ReceiveLoop = class {
5228
5312
  const id = typeof payload.conversation_id === "string" ? payload.conversation_id : void 0;
5229
5313
  const named = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.filter((x) => typeof x === "string") : [];
5230
5314
  if (reason === "unanswered") {
5231
- for (const conversationId of named) this.pacer.release(`conversation:${conversationId}`);
5315
+ for (const conversationId of named) this.pacer.releasePace(`${CONVERSATION_KEY}${conversationId}`);
5232
5316
  this.pacer.releaseInvites();
5233
5317
  }
5234
5318
  this.wakeFrom("wake_frame", id, {
@@ -5408,20 +5492,22 @@ var ReceiveLoop = class {
5408
5492
  }
5409
5493
  }
5410
5494
  async gateCallCycle(run3) {
5495
+ const mark = this.pacer.mark();
5411
5496
  const tray = await this.readTray();
5412
5497
  if (run3.stale()) return this.summary("abandoned");
5413
5498
  if (tray === null) return this.summary("tray_failed", { failure: this.lastError });
5414
5499
  const cards = cardsOf(tray);
5500
+ this.forgetCleared(tray, mark);
5415
5501
  const invites = trayInvites(tray);
5416
5502
  const unheld = this.unheld(cards);
5417
5503
  const heldByTurns = cards.length - unheld.length;
5418
5504
  if (heldByTurns > 0) this.heldWhileRunning = true;
5419
- const gateCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
5505
+ const { open: gateCards, paced: pacedCards, heldAfterFailure } = this.paceCards(unheld);
5420
5506
  const openInvites = invites.filter((invite) => !this.tracker.inviteRunning(invite.invite_id));
5421
5507
  const owedInvites = openInvites.filter((invite) => !this.pacer.held(`invite:${invite.invite_id}`, null));
5422
- const paced = unheld.length - gateCards.length + (openInvites.length - owedInvites.length);
5508
+ const paced = pacedCards + (openInvites.length - owedInvites.length);
5423
5509
  const owedCards = gateCards.filter((card) => card.muted !== true);
5424
- const base = { cards: cards.length, invites: invites.length, heldByTurns, paced, truncated: tray.truncated === true };
5510
+ const base = { cards: cards.length, invites: invites.length, heldByTurns, paced, heldAfterFailure, truncated: tray.truncated === true };
5425
5511
  if (cards.length === 0 && invites.length === 0) return this.summary("empty", base);
5426
5512
  if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
5427
5513
  const texts = await this.options.texts.ensure();
@@ -5444,7 +5530,8 @@ var ReceiveLoop = class {
5444
5530
  chunksOk: 0,
5445
5531
  chunksFailed: 0,
5446
5532
  splitCallsOk: 0,
5447
- splitCallsFailed: 0
5533
+ splitCallsFailed: 0,
5534
+ heldAfterFailure
5448
5535
  };
5449
5536
  let heldDuringGate = 0;
5450
5537
  let splitStopped = false;
@@ -5453,6 +5540,7 @@ var ReceiveLoop = class {
5453
5540
  if (owedCards.length > 0) {
5454
5541
  const gate = await this.gateInChunks(run3, tray, gateCards, texts);
5455
5542
  heldDuringGate = gate.held;
5543
+ tally.heldAfterFailure += gate.heldAfterFailure;
5456
5544
  tally.gated = gate.gated;
5457
5545
  tally.reply = gate.verdicts.reply;
5458
5546
  tally.dismiss = gate.verdicts.dismiss;
@@ -5475,7 +5563,7 @@ var ReceiveLoop = class {
5475
5563
  } else if (tally.chunksFailed + tally.splitCallsFailed > 0) {
5476
5564
  outcome = "fail_closed";
5477
5565
  } else if (owedInvites.length === 0 && !run3.stale()) {
5478
- return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate });
5566
+ return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate, heldAfterFailure: tally.heldAfterFailure });
5479
5567
  }
5480
5568
  }
5481
5569
  for (const invite of owedInvites) {
@@ -5492,10 +5580,54 @@ var ReceiveLoop = class {
5492
5580
  /**
5493
5581
  * Held out of the gate: a running or waiting turn, or a verdict still being
5494
5582
  * recorded (an abandoned cycle's last call): gating it again could record
5495
- * the same verdict twice (a second defer climbs the ladder).
5583
+ * the same verdict twice (a second defer climbs the ladder). Also a
5584
+ * conversation whose could-not-process report is out (`reporting`): its
5585
+ * answer may hold it.
5496
5586
  */
5497
5587
  unheld(cards) {
5498
- return this.tracker.withoutRunning(cards).filter((card) => !this.recordsInFlight.has(card.conversation_id));
5588
+ return this.tracker.withoutRunning(cards).filter((card) => {
5589
+ if (this.recordsInFlight.has(card.conversation_id)) return false;
5590
+ if (!this.reporting.has(card.conversation_id)) return true;
5591
+ this.heldWhileReporting = true;
5592
+ return false;
5593
+ });
5594
+ }
5595
+ /**
5596
+ * The cards neither paced (D5) nor held after a could-not-process answer
5597
+ * (`none` / `paused` through the anchor they still show), and how many of
5598
+ * each were left out. A card whose anchor moved is no longer held.
5599
+ */
5600
+ paceCards(cards) {
5601
+ const open = [];
5602
+ let paced = 0;
5603
+ let heldAfterFailure = 0;
5604
+ for (const card of cards) {
5605
+ const state = this.pacer.check(`${CONVERSATION_KEY}${card.conversation_id}`, anchorFrom(card));
5606
+ if (state === "paced") paced += 1;
5607
+ else if (state === "failed") heldAfterFailure += 1;
5608
+ else open.push(card);
5609
+ }
5610
+ return { open, paced, heldAfterFailure };
5611
+ }
5612
+ /** Held after a could-not-process answer, at the anchor this card still shows. */
5613
+ heldAfterFailure(card) {
5614
+ return this.pacer.check(`${CONVERSATION_KEY}${card.conversation_id}`, anchorFrom(card)) === "failed";
5615
+ }
5616
+ /**
5617
+ * A tray read after `mark`, every card on it (a turn's included): a held
5618
+ * conversation whose card shows a newer anchor is no longer held, and on
5619
+ * a complete tray (not truncated) neither is one whose card is gone (read
5620
+ * meanwhile: a verdict, a mark-read). A truncated tray proves nothing
5621
+ * about the cards it does not show.
5622
+ */
5623
+ forgetCleared(tray, mark) {
5624
+ const anchors = new Map(cardsOf(tray).map((card) => [`${CONVERSATION_KEY}${card.conversation_id}`, anchorFrom(card)]));
5625
+ this.pacer.keepFailedOn(anchors, mark, tray.truncated !== true);
5626
+ }
5627
+ /** The start of a run or reply turn: held after a could-not-process answer at the anchor it was started for. */
5628
+ failureHeld(handle) {
5629
+ const turn = handle.turn;
5630
+ return turn.kind === "reply" && this.pacer.heldFailedAt(`${CONVERSATION_KEY}${turn.conversationId}`, turn.anchor);
5499
5631
  }
5500
5632
  /**
5501
5633
  * The gate in chunks (contract v1 §3.6): the cards, in tray order, split
@@ -5529,6 +5661,7 @@ var ReceiveLoop = class {
5529
5661
  const out = {
5530
5662
  gated: 0,
5531
5663
  held: 0,
5664
+ heldAfterFailure: 0,
5532
5665
  reply: [],
5533
5666
  verdicts: { reply: 0, dismiss: 0, defer: 0 },
5534
5667
  undecided: 0,
@@ -5574,7 +5707,9 @@ var ReceiveLoop = class {
5574
5707
  const of = Math.ceil(chunked.length / size);
5575
5708
  for (let index2 = 1; index2 <= of; index2++) {
5576
5709
  if (run3.stale()) break;
5577
- const planned = chunked.slice((index2 - 1) * size, index2 * size);
5710
+ const slice = chunked.slice((index2 - 1) * size, index2 * size);
5711
+ const planned = slice.filter((card) => !this.heldAfterFailure(card));
5712
+ out.heldAfterFailure += slice.length - planned.length;
5578
5713
  const chunk = this.unheld(planned);
5579
5714
  out.held += planned.length - chunk.length;
5580
5715
  if (chunk.length < planned.length) this.heldWhileRunning = true;
@@ -5608,7 +5743,7 @@ var ReceiveLoop = class {
5608
5743
  if (report.outcome === "decided") {
5609
5744
  const through = decidedBy(result);
5610
5745
  for (const id of through) this.gateAlone.delete(id);
5611
- await run3.exclude(() => this.reportDue(this.completed("gate", through)));
5746
+ await run3.exclude(() => this.reportDue(this.takeDue(this.completed("gate", through))));
5612
5747
  continue;
5613
5748
  }
5614
5749
  this.failedAttempt("gate", chunk.filter((card) => card.muted !== true).map((card) => card.conversation_id));
@@ -5629,7 +5764,7 @@ var ReceiveLoop = class {
5629
5764
  if (run3.stale()) break splitting;
5630
5765
  const { card, reruns } = queue.shift();
5631
5766
  const id = card.conversation_id;
5632
- if (decided.has(id) || split.skip.has(id)) continue;
5767
+ if (decided.has(id) || split.skip.has(id) || this.heldAfterFailure(card)) continue;
5633
5768
  if (this.unheld([card]).length === 0) {
5634
5769
  if (!gated.has(id)) out.held += 1;
5635
5770
  this.heldWhileRunning = true;
@@ -5660,7 +5795,7 @@ var ReceiveLoop = class {
5660
5795
  if (report.outcome === "decided") {
5661
5796
  failuresInARow = 0;
5662
5797
  this.gateAlone.delete(id);
5663
- await run3.exclude(() => this.reportDue(this.completed("gate", decidedBy(result))));
5798
+ await run3.exclude(() => this.reportDue(this.takeDue(this.completed("gate", decidedBy(result)))));
5664
5799
  continue;
5665
5800
  }
5666
5801
  this.rememberGateAlone(id);
@@ -5725,12 +5860,14 @@ var ReceiveLoop = class {
5725
5860
  }
5726
5861
  }
5727
5862
  async singleRunCycle(run3) {
5863
+ const mark = this.pacer.mark();
5728
5864
  const tray = await this.readTray();
5729
5865
  if (run3.stale()) return this.summary("abandoned");
5730
5866
  let cards = null;
5731
5867
  let invites = null;
5732
5868
  let base = { cards: 0, invites: 0, heldByTurns: 0, truncated: false };
5733
5869
  if (tray !== null) {
5870
+ this.forgetCleared(tray, mark);
5734
5871
  cards = cardsOf(tray).filter((card) => card.muted !== true).length;
5735
5872
  invites = trayInvites(tray).length;
5736
5873
  base = { cards: cardsOf(tray).length, invites, heldByTurns: 0, truncated: tray.truncated === true };
@@ -5778,17 +5915,17 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5778
5915
  const unheld = this.unheld(cards);
5779
5916
  const heldByTurns = cards.length - unheld.length;
5780
5917
  if (heldByTurns > 0) this.heldWhileRunning = true;
5781
- const runCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
5918
+ const { open: runCards, paced: pacedCards, heldAfterFailure } = this.paceCards(unheld);
5782
5919
  const openInvites = invites.filter((invite) => !this.tracker.inviteRunning(invite.invite_id));
5783
5920
  const owedInvites = openInvites.filter((invite) => !this.pacer.held(`invite:${invite.invite_id}`, null));
5784
- const paced = unheld.length - runCards.length + (openInvites.length - owedInvites.length);
5921
+ const paced = pacedCards + (openInvites.length - owedInvites.length);
5785
5922
  const owedCards = runCards.filter((card) => card.muted !== true && card.preview != null);
5786
- const base = { cards: cards.length, invites: invites.length, heldByTurns, paced, truncated: tray.truncated === true };
5923
+ const base = { cards: cards.length, invites: invites.length, heldByTurns, paced, heldAfterFailure, truncated: tray.truncated === true };
5787
5924
  if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
5788
5925
  const unready = await this.checkReady();
5789
5926
  if (run3.stale()) return this.summary("abandoned", base);
5790
5927
  if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5791
- const tally = { turnsStarted: 0, turnsRefused: 0, turnsQueued: 0 };
5928
+ const tally = { turnsStarted: 0, turnsRefused: 0, turnsQueued: 0, heldAfterFailure };
5792
5929
  const failedLast = owedCards.filter((card) => this.awaitingEvidence.has(card.conversation_id));
5793
5930
  for (const card of owedCards.filter((card2) => !failedLast.includes(card2))) {
5794
5931
  if (run3.stale()) break;
@@ -5832,6 +5969,8 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5832
5969
  const held = this.tracker.holds(handle);
5833
5970
  let completion = null;
5834
5971
  let failure = null;
5972
+ let due = [];
5973
+ let ended = false;
5835
5974
  try {
5836
5975
  this.countRunEnd(end);
5837
5976
  this.emit({ type: "run", end, kind: "conversation", conversationId: attempt.conversationId });
@@ -5845,8 +5984,10 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5845
5984
  failure = { ...attempt, outcome: end.timedOut === true ? "timed_out" : "failed", failedAt: this.now(), holding: handle };
5846
5985
  }
5847
5986
  }
5987
+ ended = true;
5848
5988
  } finally {
5849
5989
  if (failure === null) this.tracker.end(handle);
5990
+ if (ended && !this.stopped && completion !== null) due = this.takeDue(completion);
5850
5991
  this.releaseSlot(handle);
5851
5992
  if (failure === null) this.afterTurnEnded();
5852
5993
  }
@@ -5858,7 +5999,7 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5858
5999
  this.afterTurnEnded();
5859
6000
  }
5860
6001
  }
5861
- if (!this.stopped && completion !== null) await this.reportDue(completion);
6002
+ await this.reportDue(due);
5862
6003
  await this.checkParked("run");
5863
6004
  }
5864
6005
  /** The invite run: one run for the pending invites, holding each of them until it ends. */
@@ -5898,6 +6039,8 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5898
6039
  const end = await done;
5899
6040
  const held = this.tracker.holds(slot);
5900
6041
  let completion = null;
6042
+ let due = [];
6043
+ let ended = false;
5901
6044
  try {
5902
6045
  this.countRunEnd(end);
5903
6046
  this.emit({ type: "run", end, kind: "invite" });
@@ -5907,12 +6050,14 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5907
6050
  for (const invite of invites) this.pacer.hold(`invite:${invite.invite_id}`, null);
5908
6051
  }
5909
6052
  if (this.options.dismissIgnoredInvites !== false) await this.afterRunInvites(invites, end);
6053
+ ended = true;
5910
6054
  } finally {
5911
6055
  endAll();
6056
+ if (ended && !this.stopped && completion !== null) due = this.takeDue(completion);
5912
6057
  this.releaseSlot(slot);
5913
6058
  this.afterTurnEnded();
5914
6059
  }
5915
- if (!this.stopped && completion !== null) await this.reportDue(completion);
6060
+ await this.reportDue(due);
5916
6061
  await this.checkParked("run");
5917
6062
  }
5918
6063
  /** The runtime's `startRun`, never rejecting: a throw is a run that did not start. */
@@ -6005,7 +6150,13 @@ invite_id: ${invite.invite_id}`,
6005
6150
  * hands its slot on the same way.
6006
6151
  */
6007
6152
  async launch(handle, admit, drop) {
6008
- if (this.waiting.length > 0 || this.activeTurns >= this.maxTurns) {
6153
+ if (this.failureHeld(handle)) {
6154
+ this.tracker.end(handle);
6155
+ drop?.();
6156
+ this.failureCounts.startsHeld += 1;
6157
+ return "held";
6158
+ }
6159
+ if (this.waiting.length > 0 || this.activeTurns >= this.maxTurns || this.awaitsAnswer(handle)) {
6009
6160
  this.waiting.push({ handle, admit, ...drop ? { drop } : {} });
6010
6161
  this.counts.turnsQueued += 1;
6011
6162
  if (this.activeTurns < this.maxTurns) void this.pump();
@@ -6030,16 +6181,29 @@ invite_id: ${invite.invite_id}`,
6030
6181
  if (options.pump !== false) void this.pump();
6031
6182
  }
6032
6183
  async pump() {
6033
- while (this.waiting.length > 0 && this.activeTurns < this.maxTurns && !this.stopped) {
6034
- const next = this.waiting.shift();
6184
+ while (this.activeTurns < this.maxTurns && !this.stopped) {
6185
+ const index = this.waiting.findIndex((w) => !this.awaitsAnswer(w.handle));
6186
+ if (index < 0) break;
6187
+ const next = this.waiting.splice(index, 1)[0];
6035
6188
  if (!this.tracker.holds(next.handle)) continue;
6189
+ if (this.failureHeld(next.handle)) {
6190
+ this.tracker.end(next.handle);
6191
+ next.drop?.();
6192
+ this.failureCounts.startsHeld += 1;
6193
+ continue;
6194
+ }
6036
6195
  await this.admitInSlot(next.handle, next.admit);
6037
6196
  }
6038
6197
  }
6198
+ awaitsAnswer(handle) {
6199
+ return handle.turn.kind === "reply" && this.reporting.has(handle.turn.conversationId);
6200
+ }
6039
6201
  async afterReplyTurn(handle, attempt, done) {
6040
6202
  const reply = attempt.reply;
6041
6203
  let completion = null;
6042
6204
  let failure = null;
6205
+ let due = [];
6206
+ let ended = false;
6043
6207
  try {
6044
6208
  const end = await this.tracker.confirmedEnd(handle, done);
6045
6209
  if (end === null || !this.tracker.holds(handle)) return;
@@ -6049,8 +6213,10 @@ invite_id: ${invite.invite_id}`,
6049
6213
  if (end.status === "failed" && recorded?.freshRead === true && recorded.outcome.reason === "turn_failed") {
6050
6214
  failure = { ...attempt, outcome: end.timedOut === true ? "timed_out" : "failed", failedAt: this.now(), holding: handle };
6051
6215
  }
6216
+ ended = true;
6052
6217
  } finally {
6053
6218
  if (failure === null) this.tracker.end(handle);
6219
+ if (ended && !this.stopped && completion !== null) due = this.takeDue(completion);
6054
6220
  this.releaseSlot(handle);
6055
6221
  if (failure === null) this.afterTurnEnded();
6056
6222
  }
@@ -6062,7 +6228,7 @@ invite_id: ${invite.invite_id}`,
6062
6228
  this.afterTurnEnded();
6063
6229
  }
6064
6230
  }
6065
- if (!this.stopped && completion !== null) await this.track(this.reportDue(completion));
6231
+ await this.track(this.reportDue(due));
6066
6232
  await this.track(this.checkParked("turn"));
6067
6233
  }
6068
6234
  async recordReplyOutcome(handle, reply, end) {
@@ -6184,11 +6350,15 @@ invite_id: ${invite.invite_id}`,
6184
6350
  return completion;
6185
6351
  }
6186
6352
  /**
6187
- * Report the failures this completion is the evidence for (each once). One
6188
- * that waited past `AWAITING_EVIDENCE_MS` is dropped instead: a completion
6189
- * that late says little about the runtime when it failed.
6353
+ * The failures this completion is the evidence for (each once), taken off
6354
+ * the waiting list. Their conversations are held from now until the
6355
+ * server has answered (`reporting`): no gate, and a run or turn of theirs
6356
+ * waiting for a slot waits for the answer, so it never starts on the input
6357
+ * the answer is about. Take them before the completed work's slot frees.
6358
+ * One that waited past `AWAITING_EVIDENCE_MS` is dropped instead: a
6359
+ * completion that late says little about the runtime when it failed.
6190
6360
  */
6191
- async reportDue(completion) {
6361
+ takeDue(completion) {
6192
6362
  const now2 = this.now();
6193
6363
  const due = [];
6194
6364
  for (const failure of [...this.awaitingEvidence.values()]) {
@@ -6198,10 +6368,49 @@ invite_id: ${invite.invite_id}`,
6198
6368
  }
6199
6369
  if (evidences(completion, failure)) {
6200
6370
  this.awaitingEvidence.delete(failure.conversationId);
6371
+ this.holdForReport(failure);
6201
6372
  due.push(failure);
6202
6373
  }
6203
6374
  }
6204
- for (const failure of due) await this.reportFailure(failure, "other_run_completed");
6375
+ return due;
6376
+ }
6377
+ /** Report what `takeDue` took, letting go of each conversation once its answer is in: what waits for it goes on (or was dropped). */
6378
+ async reportDue(due) {
6379
+ const held = [...due];
6380
+ try {
6381
+ while (held.length > 0) {
6382
+ const failure = held[0];
6383
+ await this.reportFailure(failure, "other_run_completed");
6384
+ held.shift();
6385
+ this.letGo([failure]);
6386
+ }
6387
+ } finally {
6388
+ this.letGo(held);
6389
+ }
6390
+ }
6391
+ /** A report for this failure is due: its conversation is held until `letGo` (counted: two reports out hold it until both are answered). */
6392
+ holdForReport(failure) {
6393
+ this.reporting.set(failure.conversationId, (this.reporting.get(failure.conversationId) ?? 0) + 1);
6394
+ }
6395
+ /**
6396
+ * The answers are in (or the report is off): those conversations are no
6397
+ * longer held for it, what waits for them goes on, and a card a cycle left
6398
+ * out meanwhile for a report is read again (only then: a wake for
6399
+ * anything else could spin while a turn runs).
6400
+ */
6401
+ letGo(failures) {
6402
+ if (failures.length === 0) return;
6403
+ for (const { conversationId } of failures) {
6404
+ const left = (this.reporting.get(conversationId) ?? 0) - 1;
6405
+ if (left > 0) this.reporting.set(conversationId, left);
6406
+ else this.reporting.delete(conversationId);
6407
+ }
6408
+ if (this.stopped) return;
6409
+ if (this.waiting.length > 0) void this.pump();
6410
+ if (this.heldWhileReporting) {
6411
+ this.heldWhileReporting = false;
6412
+ this.wakeFrom("more");
6413
+ }
6205
6414
  }
6206
6415
  /** An attempt of this kind failed for these conversations (whatever comes of it): see `failingSince`. */
6207
6416
  failedAttempt(kind, conversations) {
@@ -6254,17 +6463,24 @@ invite_id: ${invite.invite_id}`,
6254
6463
  failure.outcome !== "timed_out" && !this.checkedFailures.has(failure) && this.now() - failure.failedAt <= AWAITING_EVIDENCE_MS && [...failing].every((id) => id === failure.conversationId)
6255
6464
  );
6256
6465
  if (due.length === 0) return;
6257
- for (const failure of due) this.checkedFailures.add(failure);
6258
- const ok = await this.runtimeCheck();
6259
6466
  for (const failure of due) {
6260
- if (this.stopped || this.awaitingEvidence.get(failure.conversationId) !== failure) continue;
6261
- if (!ok) {
6467
+ this.checkedFailures.add(failure);
6468
+ this.holdForReport(failure);
6469
+ }
6470
+ try {
6471
+ const ok = await this.runtimeCheck();
6472
+ for (const failure of due) {
6473
+ if (this.stopped || this.awaitingEvidence.get(failure.conversationId) !== failure) continue;
6474
+ if (!ok) {
6475
+ this.awaitingEvidence.delete(failure.conversationId);
6476
+ continue;
6477
+ }
6478
+ if (![...failing].every((id) => id === failure.conversationId)) continue;
6262
6479
  this.awaitingEvidence.delete(failure.conversationId);
6263
- continue;
6480
+ await this.reportFailure(failure, "runtime_check");
6264
6481
  }
6265
- if (![...failing].every((id) => id === failure.conversationId)) continue;
6266
- this.awaitingEvidence.delete(failure.conversationId);
6267
- await this.reportFailure(failure, "runtime_check");
6482
+ } finally {
6483
+ this.letGo(due);
6268
6484
  }
6269
6485
  }
6270
6486
  /** Nothing of this kind is running or queued: the runtime check may be asked now. */
@@ -6338,10 +6554,29 @@ invite_id: ${invite.invite_id}`,
6338
6554
  next = this.rerun(failure, result.action === "hidden");
6339
6555
  }
6340
6556
  }
6341
- if (result.action === "paused") this.dropWaiting(failure.conversationId);
6557
+ if (result.action === "none" || result.action === "paused") this.holdFailed(failure, result.action);
6342
6558
  if (next === "stop" || next === "rerun_capped") this.activeSplit?.skip.add(failure.conversationId);
6343
6559
  this.emit({ type: "processing_failure", ...base, result, next });
6344
6560
  }
6561
+ /**
6562
+ * The server answered `none` or `paused`: the conversation is held at the
6563
+ * anchor the report read through, so no later cycle (a message elsewhere,
6564
+ * a wake frame, a reconnect, an `unanswered` re-wake, a turn's end) runs it
6565
+ * again on the same input. A newer message moves its anchor and lifts the
6566
+ * hold (`paceCards`); a card read meanwhile leaves the tray, and the hold
6567
+ * with it (`forgetCleared`). What waits for it does not start: a run or
6568
+ * reply turn queued at that anchor (after `paused`, the server's mute, any),
6569
+ * and a reply turn to start again after the gate.
6570
+ */
6571
+ holdFailed(failure, reason) {
6572
+ const id = failure.conversationId;
6573
+ const anchor = failure.anchor;
6574
+ this.pacer.holdFailed(`${CONVERSATION_KEY}${id}`, anchor, reason);
6575
+ this.dropWaiting(id, reason === "paused" ? null : anchor);
6576
+ this.turnRerunsAfterGate = this.turnRerunsAfterGate.filter(
6577
+ ({ reply }) => reply.conversationId !== id || reason !== "paused" && anchorFrom(reply.card) !== anchor
6578
+ );
6579
+ }
6345
6580
  /**
6346
6581
  * Run the conversation again after a `retry` or `hidden` answer, after the
6347
6582
  * others already queued, and say what was done. Its run or reply turn takes
@@ -6399,14 +6634,20 @@ invite_id: ${invite.invite_id}`,
6399
6634
  else void this.startReplyTurn(reply, texts, reruns);
6400
6635
  }
6401
6636
  }
6402
- /** A `paused` conversation: a run or turn still waiting for a slot for it does not start. */
6403
- dropWaiting(conversationId) {
6637
+ /**
6638
+ * A held conversation: a run or turn still waiting for a slot for it does
6639
+ * not start; with an `anchor`, only one for that anchor (one queued for a
6640
+ * newer message is new input, and goes on).
6641
+ */
6642
+ dropWaiting(conversationId, anchor) {
6404
6643
  for (const entry of [...this.waiting]) {
6405
6644
  const turn = entry.handle.turn;
6406
6645
  if (turn.kind !== "reply" || turn.conversationId !== conversationId) continue;
6646
+ if (anchor !== null && turn.anchor !== anchor) continue;
6407
6647
  this.waiting.splice(this.waiting.indexOf(entry), 1);
6408
6648
  this.tracker.end(entry.handle);
6409
6649
  entry.drop?.();
6650
+ this.failureCounts.startsHeld += 1;
6410
6651
  }
6411
6652
  }
6412
6653
  rememberGateAlone(conversationId) {
@@ -6455,6 +6696,7 @@ invite_id: ${invite.invite_id}`,
6455
6696
  turnsQueued: 0,
6456
6697
  heldByTurns: 0,
6457
6698
  paced: 0,
6699
+ heldAfterFailure: 0,
6458
6700
  chunksOk: 0,
6459
6701
  chunksFailed: 0,
6460
6702
  splitCallsOk: 0,
@@ -6550,6 +6792,7 @@ function timeoutOption(value, fallback, name) {
6550
6792
  return value;
6551
6793
  }
6552
6794
  function launchKey(launch) {
6795
+ if (launch === "held") return "heldAfterFailure";
6553
6796
  return launch === "started" ? "turnsStarted" : launch === "queued" ? "turnsQueued" : "turnsRefused";
6554
6797
  }
6555
6798
  function trayInvites(tray) {