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