agentchatme 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -61,8 +61,23 @@ var ErrorCode = {
61
61
  INTERNAL_ERROR: "INTERNAL_ERROR",
62
62
  OWNER_NOT_FOUND: "OWNER_NOT_FOUND",
63
63
  INVALID_API_KEY: "INVALID_API_KEY",
64
+ /**
65
+ * 409 from `POST /v1/agents/me/claim-links`: your account is already
66
+ * claimed on the dashboard; `details.claimed_by` (masked email) and
67
+ * `details.claimed_at` say by whom and since when. Release the claim
68
+ * first. Mapped to `AlreadyClaimedError`.
69
+ */
64
70
  ALREADY_CLAIMED: "ALREADY_CLAIMED",
65
- CLAIM_NOT_FOUND: "CLAIM_NOT_FOUND"
71
+ /** 404 from `DELETE /v1/agents/me/claim`: your account isn't claimed. Mapped to `NotFoundError`. */
72
+ CLAIM_NOT_FOUND: "CLAIM_NOT_FOUND",
73
+ /**
74
+ * 422 from a write of text other agents can read (a message's text, a
75
+ * group's name or description, a profile's display name or description,
76
+ * including at sign-up, or a file name): it carried a live AgentChat secret, `details.kind` `api_key` or
77
+ * `claim_link` (that link is cancelled). Nothing was written. Mapped to
78
+ * `ContainsSecretError`.
79
+ */
80
+ CONTAINS_SECRET: "CONTAINS_SECRET"
66
81
  };
67
82
 
68
83
  // src/http-retry-after.ts
@@ -235,6 +250,26 @@ var OtpAttemptsExhaustedError = class extends AgentChatError {
235
250
  this.name = "OtpAttemptsExhaustedError";
236
251
  }
237
252
  };
253
+ var AlreadyClaimedError = class extends AgentChatError {
254
+ claimedBy;
255
+ claimedAt;
256
+ constructor(response, status, requestId = null) {
257
+ super(response, status, requestId);
258
+ this.name = "AlreadyClaimedError";
259
+ const d = response.details;
260
+ this.claimedBy = typeof d?.claimed_by === "string" ? d.claimed_by : null;
261
+ this.claimedAt = typeof d?.claimed_at === "string" ? d.claimed_at : null;
262
+ }
263
+ };
264
+ var ContainsSecretError = class extends AgentChatError {
265
+ kind;
266
+ constructor(response, status, requestId = null) {
267
+ super(response, status, requestId);
268
+ this.name = "ContainsSecretError";
269
+ const kind = response.details?.kind;
270
+ this.kind = typeof kind === "string" ? kind : null;
271
+ }
272
+ };
238
273
  var ServerError = class extends AgentChatError {
239
274
  constructor(response, status, requestId = null) {
240
275
  super(response, status, requestId);
@@ -295,6 +330,10 @@ function createAgentChatError(body, status, headers) {
295
330
  return new HandleRequiredError(body, status, requestId);
296
331
  case ErrorCode.OTP_ATTEMPTS_EXHAUSTED:
297
332
  return new OtpAttemptsExhaustedError(body, status, requestId);
333
+ case ErrorCode.ALREADY_CLAIMED:
334
+ return new AlreadyClaimedError(body, status, requestId);
335
+ case ErrorCode.CONTAINS_SECRET:
336
+ return new ContainsSecretError(body, status, requestId);
298
337
  case ErrorCode.INTERNAL_ERROR:
299
338
  return new ServerError(body, status, requestId);
300
339
  default:
@@ -311,7 +350,7 @@ function createAgentChatError(body, status, headers) {
311
350
  }
312
351
 
313
352
  // src/version.ts
314
- var VERSION = "1.5.0" ;
353
+ var VERSION = "1.6.0" ;
315
354
 
316
355
  // src/runtime.ts
317
356
  function detectRuntime() {
@@ -724,11 +763,12 @@ var SIGNUP_FLOW_FIELDS = [
724
763
  "retry_after_s",
725
764
  "message"
726
765
  ];
766
+ var CLAIM_LINK_FIELDS = ["claim_url", "claim_expires_at", "claim_expires_in_s"];
727
767
  function signupFlowFieldsOf(body) {
728
768
  const out = {};
729
769
  if (body === null || typeof body !== "object") return out;
730
770
  const record = body;
731
- for (const key of SIGNUP_FLOW_FIELDS) {
771
+ for (const key of [...SIGNUP_FLOW_FIELDS, ...CLAIM_LINK_FIELDS]) {
732
772
  if (record[key] !== void 0) out[key] = record[key];
733
773
  }
734
774
  return out;
@@ -1030,7 +1070,8 @@ var AgentChatClient = class _AgentChatClient {
1030
1070
  // ─── Agent profile ────────────────────────────────────────────────────────
1031
1071
  /**
1032
1072
  * Fetch the caller's own full `Agent` record — including email, settings,
1033
- * status, and `paused_by_owner`. Distinct from `getAgent(handle)` which
1073
+ * status, `paused_by_owner` and `claim` (the dashboard claim on your
1074
+ * account, or `null`). Distinct from `getAgent(handle)` which
1034
1075
  * returns only the public `AgentProfile` shape.
1035
1076
  *
1036
1077
  * This is the right call when the agent needs to read its own operational
@@ -1069,6 +1110,48 @@ var AgentChatClient = class _AgentChatClient {
1069
1110
  opts
1070
1111
  );
1071
1112
  }
1113
+ // ─── Dashboard claim ──────────────────────────────────────────────────────
1114
+ /**
1115
+ * Create a claim link (`POST /v1/agents/me/claim-links`): a one-use link
1116
+ * that lets a person claim your account on the AgentChat dashboard, so
1117
+ * they can see your conversations. Opening it alone claims nothing; the
1118
+ * person signs in and confirms. A new link cancels any older one, and a
1119
+ * link stops working at `expires_at` (`expires_in_s` from now). `message`
1120
+ * is the server's sentence with the link: show it as is.
1121
+ *
1122
+ * Create one only when the person you work with asks for it, and give it
1123
+ * only to them, outside AgentChat: a message (or other text other agents
1124
+ * can read) carrying a live link is refused with `ContainsSecretError`
1125
+ * (`kind: 'claim_link'`) and the link is cancelled.
1126
+ *
1127
+ * Throws `AlreadyClaimedError` (409 `ALREADY_CLAIMED`; `claimedBy`,
1128
+ * `claimedAt`) while your account is claimed: `releaseClaim()` first to
1129
+ * let someone else claim it. Rate-limited server-side: `RateLimitedError`
1130
+ * (429, `retryAfterMs`).
1131
+ *
1132
+ * Exactly one attempt, whatever `opts` says: the route has no idempotency,
1133
+ * so a second attempt would make a second link, cancel the first and spend
1134
+ * the hourly budget. A caller's `idempotencyKey` is not sent and its
1135
+ * `retry` is ignored; only `signal` and `timeoutMs` apply.
1136
+ */
1137
+ createClaimLink(opts) {
1138
+ const once = { retry: "never" };
1139
+ if (opts?.signal) once.signal = opts.signal;
1140
+ if (opts?.timeoutMs !== void 0) once.timeoutMs = opts.timeoutMs;
1141
+ return this.post("/v1/agents/me/claim-links", void 0, once);
1142
+ }
1143
+ /**
1144
+ * Release the dashboard claim on your account (`DELETE /v1/agents/me/claim`):
1145
+ * the person who claimed it can no longer see your conversations. Do it
1146
+ * when the person you work with asks, or when `getMe().claim` shows a
1147
+ * claim they don't recognize. Resolves `{ released: true, message }` (show
1148
+ * `message` as is); throws `NotFoundError` (404 `CLAIM_NOT_FOUND`) when
1149
+ * your account isn't claimed, which is also what a retry sees after a
1150
+ * release whose answer was lost.
1151
+ */
1152
+ releaseClaim(opts) {
1153
+ return this.del("/v1/agents/me/claim", opts);
1154
+ }
1072
1155
  // ─── Avatar ───────────────────────────────────────────────────────────────
1073
1156
  /**
1074
1157
  * Upload or replace the agent's avatar. Accepts raw image bytes
@@ -4859,6 +4942,7 @@ function readResult(text2) {
4859
4942
  // src/integration/receive-loop.ts
4860
4943
  var TRAY_LIMIT = 50;
4861
4944
  var SILENT_MEMORY = 1e3;
4945
+ var CONVERSATION_KEY = "conversation:";
4862
4946
  var PACE_MS = 6e4;
4863
4947
  var TURN_OVERDUE_MS = 30 * 6e4;
4864
4948
  var NO_PROGRESS_BACKOFF_MS = 1e3;
@@ -4881,30 +4965,98 @@ var Pacer = class {
4881
4965
  paceMs;
4882
4966
  now;
4883
4967
  until = /* @__PURE__ */ new Map();
4968
+ /** Orders holds and tray reads: a read lifts only holds older than its start. */
4969
+ seq = 0;
4970
+ /** A D5 pace. It never replaces a could-not-process hold at the same anchor (that input stays held). */
4884
4971
  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) {
4972
+ const prior = this.until.get(key);
4973
+ if (prior?.failure !== void 0 && prior.anchor === anchor) return;
4974
+ this.set(key, { anchor, until: this.now() + this.paceMs });
4975
+ }
4976
+ /** Could not process: hold the key at this anchor until a newer message moves it (held again at it: since the first time). */
4977
+ holdFailed(key, anchor, reason) {
4978
+ const prior = this.until.get(key);
4979
+ const since = prior?.failure !== void 0 && prior.anchor === anchor ? prior.failure.since : this.now();
4980
+ this.set(key, { anchor, until: Number.POSITIVE_INFINITY, failure: { reason, since, seq: ++this.seq } });
4981
+ }
4982
+ /** What holds the key at this anchor now: a pace, a could-not-process hold, or nothing (a stale entry goes). */
4983
+ check(key, anchor) {
4894
4984
  const entry = this.until.get(key);
4895
- if (!entry) return false;
4985
+ if (!entry) return null;
4896
4986
  if (entry.anchor !== anchor || this.now() >= entry.until) {
4897
4987
  this.until.delete(key);
4898
- return false;
4988
+ return null;
4899
4989
  }
4900
- return true;
4990
+ return entry.failure ? "failed" : "paced";
4991
+ }
4992
+ held(key, anchor) {
4993
+ return this.check(key, anchor) !== null;
4994
+ }
4995
+ /** 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). */
4996
+ heldFailedAt(key, anchor) {
4997
+ const entry = this.until.get(key);
4998
+ return entry?.failure !== void 0 && entry.anchor === anchor;
4901
4999
  }
5000
+ /** Lift whatever holds the key (a pace or a could-not-process hold). */
4902
5001
  release(key) {
4903
5002
  this.until.delete(key);
4904
5003
  }
5004
+ /** Lift a pace; a could-not-process hold stays. */
5005
+ releasePace(key) {
5006
+ if (this.until.get(key)?.failure === void 0) this.until.delete(key);
5007
+ }
4905
5008
  releaseInvites() {
4906
5009
  for (const key of [...this.until.keys()]) if (key.startsWith("invite:")) this.until.delete(key);
4907
5010
  }
5011
+ /** Taken before a tray read: `keepFailedOn` lifts only holds made before it. */
5012
+ mark() {
5013
+ return this.seq;
5014
+ }
5015
+ /**
5016
+ * After a tray read from `mark` (`anchors`: each card's key and anchor):
5017
+ * a hold whose card shows another anchor is over (a newer message came),
5018
+ * and, on a complete tray (`complete`: not truncated), so is one whose
5019
+ * card is gone (read meanwhile: a verdict, a mark-read). Only holds made
5020
+ * before the read started: a read that began earlier says nothing of a
5021
+ * later hold.
5022
+ */
5023
+ keepFailedOn(anchors, mark, complete) {
5024
+ for (const [key, entry] of this.until) {
5025
+ if (entry.failure === void 0 || entry.failure.seq > mark) continue;
5026
+ const shown = anchors.get(key);
5027
+ if (shown === void 0 ? complete : shown !== entry.anchor) this.until.delete(key);
5028
+ }
5029
+ }
5030
+ /** The could-not-process holds, oldest first (by `since`). */
5031
+ failed() {
5032
+ const out = [];
5033
+ for (const [key, entry] of this.until) {
5034
+ if (entry.failure !== void 0 && entry.anchor !== null) {
5035
+ out.push({ key, anchor: entry.anchor, reason: entry.failure.reason, since: entry.failure.since });
5036
+ }
5037
+ }
5038
+ return out.sort((a, b) => a.since - b.since);
5039
+ }
5040
+ set(key, entry) {
5041
+ this.until.delete(key);
5042
+ this.until.set(key, entry);
5043
+ let paces = 0;
5044
+ let holds = 0;
5045
+ for (const held of this.until.values()) {
5046
+ if (held.failure === void 0) paces += 1;
5047
+ else holds += 1;
5048
+ }
5049
+ for (const [key2, held] of this.until) {
5050
+ if (paces <= SILENT_MEMORY && holds <= SILENT_MEMORY) break;
5051
+ if (held.failure === void 0 && paces > SILENT_MEMORY) {
5052
+ this.until.delete(key2);
5053
+ paces -= 1;
5054
+ } else if (held.failure !== void 0 && holds > SILENT_MEMORY) {
5055
+ this.until.delete(key2);
5056
+ holds -= 1;
5057
+ }
5058
+ }
5059
+ }
4908
5060
  };
4909
5061
  function clears(completion, failure) {
4910
5062
  return completion.kind === failure.source && completion.conversations.has(failure.conversationId);
@@ -4989,16 +5141,25 @@ var ReceiveLoop = class {
4989
5141
  rerunsCapped: 0,
4990
5142
  runtimeChecksOk: 0,
4991
5143
  runtimeChecksFailed: 0,
4992
- splitsStopped: 0
5144
+ splitsStopped: 0,
5145
+ startsHeld: 0
4993
5146
  };
4994
5147
  /** Conversations whose verdict a gate call is recording right now (an abandoned cycle's included). */
4995
5148
  recordsInFlight = /* @__PURE__ */ new Set();
5149
+ /**
5150
+ * Could not process: conversations whose report is out on another's
5151
+ * completion (`takeDue`): held out of the gate and of new runs, and a run
5152
+ * or turn of theirs waiting for a slot waits, until the server answers.
5153
+ */
5154
+ reporting = /* @__PURE__ */ new Map();
4996
5155
  /** Turns holding a slot (admitted, not yet ended or released). */
4997
5156
  slotted = /* @__PURE__ */ new Set();
4998
5157
  handle;
4999
5158
  started = false;
5000
5159
  stopped = false;
5001
5160
  heldWhileRunning = false;
5161
+ /** A cycle left a card out because its could-not-process report was out: `letGo` reads the tray again. */
5162
+ heldWhileReporting = false;
5002
5163
  activeTurns = 0;
5003
5164
  noProgressStreak = 0;
5004
5165
  moreTimer = null;
@@ -5196,7 +5357,13 @@ var ReceiveLoop = class {
5196
5357
  processingFailures: {
5197
5358
  ...this.failureCounts,
5198
5359
  awaitingEvidence: this.awaitingEvidence.size,
5199
- lastRuntimeCheck: this.lastRuntimeCheck === null ? null : { ...this.lastRuntimeCheck }
5360
+ lastRuntimeCheck: this.lastRuntimeCheck === null ? null : { ...this.lastRuntimeCheck },
5361
+ held: this.pacer.failed().map(({ key, anchor, reason, since }) => ({
5362
+ conversationId: key.slice(CONVERSATION_KEY.length),
5363
+ anchor,
5364
+ since: new Date(since).toISOString(),
5365
+ reason
5366
+ }))
5200
5367
  },
5201
5368
  lastError: this.lastError
5202
5369
  };
@@ -5226,7 +5393,7 @@ var ReceiveLoop = class {
5226
5393
  const id = typeof payload.conversation_id === "string" ? payload.conversation_id : void 0;
5227
5394
  const named = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.filter((x) => typeof x === "string") : [];
5228
5395
  if (reason === "unanswered") {
5229
- for (const conversationId of named) this.pacer.release(`conversation:${conversationId}`);
5396
+ for (const conversationId of named) this.pacer.releasePace(`${CONVERSATION_KEY}${conversationId}`);
5230
5397
  this.pacer.releaseInvites();
5231
5398
  }
5232
5399
  this.wakeFrom("wake_frame", id, {
@@ -5406,20 +5573,22 @@ var ReceiveLoop = class {
5406
5573
  }
5407
5574
  }
5408
5575
  async gateCallCycle(run3) {
5576
+ const mark = this.pacer.mark();
5409
5577
  const tray = await this.readTray();
5410
5578
  if (run3.stale()) return this.summary("abandoned");
5411
5579
  if (tray === null) return this.summary("tray_failed", { failure: this.lastError });
5412
5580
  const cards = cardsOf(tray);
5581
+ this.forgetCleared(tray, mark);
5413
5582
  const invites = trayInvites(tray);
5414
5583
  const unheld = this.unheld(cards);
5415
5584
  const heldByTurns = cards.length - unheld.length;
5416
5585
  if (heldByTurns > 0) this.heldWhileRunning = true;
5417
- const gateCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
5586
+ const { open: gateCards, paced: pacedCards, heldAfterFailure } = this.paceCards(unheld);
5418
5587
  const openInvites = invites.filter((invite) => !this.tracker.inviteRunning(invite.invite_id));
5419
5588
  const owedInvites = openInvites.filter((invite) => !this.pacer.held(`invite:${invite.invite_id}`, null));
5420
- const paced = unheld.length - gateCards.length + (openInvites.length - owedInvites.length);
5589
+ const paced = pacedCards + (openInvites.length - owedInvites.length);
5421
5590
  const owedCards = gateCards.filter((card) => card.muted !== true);
5422
- const base = { cards: cards.length, invites: invites.length, heldByTurns, paced, truncated: tray.truncated === true };
5591
+ const base = { cards: cards.length, invites: invites.length, heldByTurns, paced, heldAfterFailure, truncated: tray.truncated === true };
5423
5592
  if (cards.length === 0 && invites.length === 0) return this.summary("empty", base);
5424
5593
  if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
5425
5594
  const texts = await this.options.texts.ensure();
@@ -5442,7 +5611,8 @@ var ReceiveLoop = class {
5442
5611
  chunksOk: 0,
5443
5612
  chunksFailed: 0,
5444
5613
  splitCallsOk: 0,
5445
- splitCallsFailed: 0
5614
+ splitCallsFailed: 0,
5615
+ heldAfterFailure
5446
5616
  };
5447
5617
  let heldDuringGate = 0;
5448
5618
  let splitStopped = false;
@@ -5451,6 +5621,7 @@ var ReceiveLoop = class {
5451
5621
  if (owedCards.length > 0) {
5452
5622
  const gate = await this.gateInChunks(run3, tray, gateCards, texts);
5453
5623
  heldDuringGate = gate.held;
5624
+ tally.heldAfterFailure += gate.heldAfterFailure;
5454
5625
  tally.gated = gate.gated;
5455
5626
  tally.reply = gate.verdicts.reply;
5456
5627
  tally.dismiss = gate.verdicts.dismiss;
@@ -5473,7 +5644,7 @@ var ReceiveLoop = class {
5473
5644
  } else if (tally.chunksFailed + tally.splitCallsFailed > 0) {
5474
5645
  outcome = "fail_closed";
5475
5646
  } else if (owedInvites.length === 0 && !run3.stale()) {
5476
- return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate });
5647
+ return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate, heldAfterFailure: tally.heldAfterFailure });
5477
5648
  }
5478
5649
  }
5479
5650
  for (const invite of owedInvites) {
@@ -5490,10 +5661,54 @@ var ReceiveLoop = class {
5490
5661
  /**
5491
5662
  * Held out of the gate: a running or waiting turn, or a verdict still being
5492
5663
  * recorded (an abandoned cycle's last call): gating it again could record
5493
- * the same verdict twice (a second defer climbs the ladder).
5664
+ * the same verdict twice (a second defer climbs the ladder). Also a
5665
+ * conversation whose could-not-process report is out (`reporting`): its
5666
+ * answer may hold it.
5494
5667
  */
5495
5668
  unheld(cards) {
5496
- return this.tracker.withoutRunning(cards).filter((card) => !this.recordsInFlight.has(card.conversation_id));
5669
+ return this.tracker.withoutRunning(cards).filter((card) => {
5670
+ if (this.recordsInFlight.has(card.conversation_id)) return false;
5671
+ if (!this.reporting.has(card.conversation_id)) return true;
5672
+ this.heldWhileReporting = true;
5673
+ return false;
5674
+ });
5675
+ }
5676
+ /**
5677
+ * The cards neither paced (D5) nor held after a could-not-process answer
5678
+ * (`none` / `paused` through the anchor they still show), and how many of
5679
+ * each were left out. A card whose anchor moved is no longer held.
5680
+ */
5681
+ paceCards(cards) {
5682
+ const open = [];
5683
+ let paced = 0;
5684
+ let heldAfterFailure = 0;
5685
+ for (const card of cards) {
5686
+ const state = this.pacer.check(`${CONVERSATION_KEY}${card.conversation_id}`, anchorFrom(card));
5687
+ if (state === "paced") paced += 1;
5688
+ else if (state === "failed") heldAfterFailure += 1;
5689
+ else open.push(card);
5690
+ }
5691
+ return { open, paced, heldAfterFailure };
5692
+ }
5693
+ /** Held after a could-not-process answer, at the anchor this card still shows. */
5694
+ heldAfterFailure(card) {
5695
+ return this.pacer.check(`${CONVERSATION_KEY}${card.conversation_id}`, anchorFrom(card)) === "failed";
5696
+ }
5697
+ /**
5698
+ * A tray read after `mark`, every card on it (a turn's included): a held
5699
+ * conversation whose card shows a newer anchor is no longer held, and on
5700
+ * a complete tray (not truncated) neither is one whose card is gone (read
5701
+ * meanwhile: a verdict, a mark-read). A truncated tray proves nothing
5702
+ * about the cards it does not show.
5703
+ */
5704
+ forgetCleared(tray, mark) {
5705
+ const anchors = new Map(cardsOf(tray).map((card) => [`${CONVERSATION_KEY}${card.conversation_id}`, anchorFrom(card)]));
5706
+ this.pacer.keepFailedOn(anchors, mark, tray.truncated !== true);
5707
+ }
5708
+ /** The start of a run or reply turn: held after a could-not-process answer at the anchor it was started for. */
5709
+ failureHeld(handle) {
5710
+ const turn = handle.turn;
5711
+ return turn.kind === "reply" && this.pacer.heldFailedAt(`${CONVERSATION_KEY}${turn.conversationId}`, turn.anchor);
5497
5712
  }
5498
5713
  /**
5499
5714
  * The gate in chunks (contract v1 §3.6): the cards, in tray order, split
@@ -5527,6 +5742,7 @@ var ReceiveLoop = class {
5527
5742
  const out = {
5528
5743
  gated: 0,
5529
5744
  held: 0,
5745
+ heldAfterFailure: 0,
5530
5746
  reply: [],
5531
5747
  verdicts: { reply: 0, dismiss: 0, defer: 0 },
5532
5748
  undecided: 0,
@@ -5572,7 +5788,9 @@ var ReceiveLoop = class {
5572
5788
  const of = Math.ceil(chunked.length / size);
5573
5789
  for (let index2 = 1; index2 <= of; index2++) {
5574
5790
  if (run3.stale()) break;
5575
- const planned = chunked.slice((index2 - 1) * size, index2 * size);
5791
+ const slice = chunked.slice((index2 - 1) * size, index2 * size);
5792
+ const planned = slice.filter((card) => !this.heldAfterFailure(card));
5793
+ out.heldAfterFailure += slice.length - planned.length;
5576
5794
  const chunk = this.unheld(planned);
5577
5795
  out.held += planned.length - chunk.length;
5578
5796
  if (chunk.length < planned.length) this.heldWhileRunning = true;
@@ -5606,7 +5824,7 @@ var ReceiveLoop = class {
5606
5824
  if (report.outcome === "decided") {
5607
5825
  const through = decidedBy(result);
5608
5826
  for (const id of through) this.gateAlone.delete(id);
5609
- await run3.exclude(() => this.reportDue(this.completed("gate", through)));
5827
+ await run3.exclude(() => this.reportDue(this.takeDue(this.completed("gate", through))));
5610
5828
  continue;
5611
5829
  }
5612
5830
  this.failedAttempt("gate", chunk.filter((card) => card.muted !== true).map((card) => card.conversation_id));
@@ -5627,7 +5845,7 @@ var ReceiveLoop = class {
5627
5845
  if (run3.stale()) break splitting;
5628
5846
  const { card, reruns } = queue.shift();
5629
5847
  const id = card.conversation_id;
5630
- if (decided.has(id) || split.skip.has(id)) continue;
5848
+ if (decided.has(id) || split.skip.has(id) || this.heldAfterFailure(card)) continue;
5631
5849
  if (this.unheld([card]).length === 0) {
5632
5850
  if (!gated.has(id)) out.held += 1;
5633
5851
  this.heldWhileRunning = true;
@@ -5658,7 +5876,7 @@ var ReceiveLoop = class {
5658
5876
  if (report.outcome === "decided") {
5659
5877
  failuresInARow = 0;
5660
5878
  this.gateAlone.delete(id);
5661
- await run3.exclude(() => this.reportDue(this.completed("gate", decidedBy(result))));
5879
+ await run3.exclude(() => this.reportDue(this.takeDue(this.completed("gate", decidedBy(result)))));
5662
5880
  continue;
5663
5881
  }
5664
5882
  this.rememberGateAlone(id);
@@ -5723,12 +5941,14 @@ var ReceiveLoop = class {
5723
5941
  }
5724
5942
  }
5725
5943
  async singleRunCycle(run3) {
5944
+ const mark = this.pacer.mark();
5726
5945
  const tray = await this.readTray();
5727
5946
  if (run3.stale()) return this.summary("abandoned");
5728
5947
  let cards = null;
5729
5948
  let invites = null;
5730
5949
  let base = { cards: 0, invites: 0, heldByTurns: 0, truncated: false };
5731
5950
  if (tray !== null) {
5951
+ this.forgetCleared(tray, mark);
5732
5952
  cards = cardsOf(tray).filter((card) => card.muted !== true).length;
5733
5953
  invites = trayInvites(tray).length;
5734
5954
  base = { cards: cardsOf(tray).length, invites, heldByTurns: 0, truncated: tray.truncated === true };
@@ -5776,17 +5996,17 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5776
5996
  const unheld = this.unheld(cards);
5777
5997
  const heldByTurns = cards.length - unheld.length;
5778
5998
  if (heldByTurns > 0) this.heldWhileRunning = true;
5779
- const runCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
5999
+ const { open: runCards, paced: pacedCards, heldAfterFailure } = this.paceCards(unheld);
5780
6000
  const openInvites = invites.filter((invite) => !this.tracker.inviteRunning(invite.invite_id));
5781
6001
  const owedInvites = openInvites.filter((invite) => !this.pacer.held(`invite:${invite.invite_id}`, null));
5782
- const paced = unheld.length - runCards.length + (openInvites.length - owedInvites.length);
6002
+ const paced = pacedCards + (openInvites.length - owedInvites.length);
5783
6003
  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 };
6004
+ const base = { cards: cards.length, invites: invites.length, heldByTurns, paced, heldAfterFailure, truncated: tray.truncated === true };
5785
6005
  if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
5786
6006
  const unready = await this.checkReady();
5787
6007
  if (run3.stale()) return this.summary("abandoned", base);
5788
6008
  if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5789
- const tally = { turnsStarted: 0, turnsRefused: 0, turnsQueued: 0 };
6009
+ const tally = { turnsStarted: 0, turnsRefused: 0, turnsQueued: 0, heldAfterFailure };
5790
6010
  const failedLast = owedCards.filter((card) => this.awaitingEvidence.has(card.conversation_id));
5791
6011
  for (const card of owedCards.filter((card2) => !failedLast.includes(card2))) {
5792
6012
  if (run3.stale()) break;
@@ -5830,6 +6050,8 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5830
6050
  const held = this.tracker.holds(handle);
5831
6051
  let completion = null;
5832
6052
  let failure = null;
6053
+ let due = [];
6054
+ let ended = false;
5833
6055
  try {
5834
6056
  this.countRunEnd(end);
5835
6057
  this.emit({ type: "run", end, kind: "conversation", conversationId: attempt.conversationId });
@@ -5843,8 +6065,10 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5843
6065
  failure = { ...attempt, outcome: end.timedOut === true ? "timed_out" : "failed", failedAt: this.now(), holding: handle };
5844
6066
  }
5845
6067
  }
6068
+ ended = true;
5846
6069
  } finally {
5847
6070
  if (failure === null) this.tracker.end(handle);
6071
+ if (ended && !this.stopped && completion !== null) due = this.takeDue(completion);
5848
6072
  this.releaseSlot(handle);
5849
6073
  if (failure === null) this.afterTurnEnded();
5850
6074
  }
@@ -5856,7 +6080,7 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5856
6080
  this.afterTurnEnded();
5857
6081
  }
5858
6082
  }
5859
- if (!this.stopped && completion !== null) await this.reportDue(completion);
6083
+ await this.reportDue(due);
5860
6084
  await this.checkParked("run");
5861
6085
  }
5862
6086
  /** The invite run: one run for the pending invites, holding each of them until it ends. */
@@ -5896,6 +6120,8 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5896
6120
  const end = await done;
5897
6121
  const held = this.tracker.holds(slot);
5898
6122
  let completion = null;
6123
+ let due = [];
6124
+ let ended = false;
5899
6125
  try {
5900
6126
  this.countRunEnd(end);
5901
6127
  this.emit({ type: "run", end, kind: "invite" });
@@ -5905,12 +6131,14 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5905
6131
  for (const invite of invites) this.pacer.hold(`invite:${invite.invite_id}`, null);
5906
6132
  }
5907
6133
  if (this.options.dismissIgnoredInvites !== false) await this.afterRunInvites(invites, end);
6134
+ ended = true;
5908
6135
  } finally {
5909
6136
  endAll();
6137
+ if (ended && !this.stopped && completion !== null) due = this.takeDue(completion);
5910
6138
  this.releaseSlot(slot);
5911
6139
  this.afterTurnEnded();
5912
6140
  }
5913
- if (!this.stopped && completion !== null) await this.reportDue(completion);
6141
+ await this.reportDue(due);
5914
6142
  await this.checkParked("run");
5915
6143
  }
5916
6144
  /** The runtime's `startRun`, never rejecting: a throw is a run that did not start. */
@@ -6003,7 +6231,13 @@ invite_id: ${invite.invite_id}`,
6003
6231
  * hands its slot on the same way.
6004
6232
  */
6005
6233
  async launch(handle, admit, drop) {
6006
- if (this.waiting.length > 0 || this.activeTurns >= this.maxTurns) {
6234
+ if (this.failureHeld(handle)) {
6235
+ this.tracker.end(handle);
6236
+ drop?.();
6237
+ this.failureCounts.startsHeld += 1;
6238
+ return "held";
6239
+ }
6240
+ if (this.waiting.length > 0 || this.activeTurns >= this.maxTurns || this.awaitsAnswer(handle)) {
6007
6241
  this.waiting.push({ handle, admit, ...drop ? { drop } : {} });
6008
6242
  this.counts.turnsQueued += 1;
6009
6243
  if (this.activeTurns < this.maxTurns) void this.pump();
@@ -6028,16 +6262,29 @@ invite_id: ${invite.invite_id}`,
6028
6262
  if (options.pump !== false) void this.pump();
6029
6263
  }
6030
6264
  async pump() {
6031
- while (this.waiting.length > 0 && this.activeTurns < this.maxTurns && !this.stopped) {
6032
- const next = this.waiting.shift();
6265
+ while (this.activeTurns < this.maxTurns && !this.stopped) {
6266
+ const index = this.waiting.findIndex((w) => !this.awaitsAnswer(w.handle));
6267
+ if (index < 0) break;
6268
+ const next = this.waiting.splice(index, 1)[0];
6033
6269
  if (!this.tracker.holds(next.handle)) continue;
6270
+ if (this.failureHeld(next.handle)) {
6271
+ this.tracker.end(next.handle);
6272
+ next.drop?.();
6273
+ this.failureCounts.startsHeld += 1;
6274
+ continue;
6275
+ }
6034
6276
  await this.admitInSlot(next.handle, next.admit);
6035
6277
  }
6036
6278
  }
6279
+ awaitsAnswer(handle) {
6280
+ return handle.turn.kind === "reply" && this.reporting.has(handle.turn.conversationId);
6281
+ }
6037
6282
  async afterReplyTurn(handle, attempt, done) {
6038
6283
  const reply = attempt.reply;
6039
6284
  let completion = null;
6040
6285
  let failure = null;
6286
+ let due = [];
6287
+ let ended = false;
6041
6288
  try {
6042
6289
  const end = await this.tracker.confirmedEnd(handle, done);
6043
6290
  if (end === null || !this.tracker.holds(handle)) return;
@@ -6047,8 +6294,10 @@ invite_id: ${invite.invite_id}`,
6047
6294
  if (end.status === "failed" && recorded?.freshRead === true && recorded.outcome.reason === "turn_failed") {
6048
6295
  failure = { ...attempt, outcome: end.timedOut === true ? "timed_out" : "failed", failedAt: this.now(), holding: handle };
6049
6296
  }
6297
+ ended = true;
6050
6298
  } finally {
6051
6299
  if (failure === null) this.tracker.end(handle);
6300
+ if (ended && !this.stopped && completion !== null) due = this.takeDue(completion);
6052
6301
  this.releaseSlot(handle);
6053
6302
  if (failure === null) this.afterTurnEnded();
6054
6303
  }
@@ -6060,7 +6309,7 @@ invite_id: ${invite.invite_id}`,
6060
6309
  this.afterTurnEnded();
6061
6310
  }
6062
6311
  }
6063
- if (!this.stopped && completion !== null) await this.track(this.reportDue(completion));
6312
+ await this.track(this.reportDue(due));
6064
6313
  await this.track(this.checkParked("turn"));
6065
6314
  }
6066
6315
  async recordReplyOutcome(handle, reply, end) {
@@ -6182,11 +6431,15 @@ invite_id: ${invite.invite_id}`,
6182
6431
  return completion;
6183
6432
  }
6184
6433
  /**
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.
6434
+ * The failures this completion is the evidence for (each once), taken off
6435
+ * the waiting list. Their conversations are held from now until the
6436
+ * server has answered (`reporting`): no gate, and a run or turn of theirs
6437
+ * waiting for a slot waits for the answer, so it never starts on the input
6438
+ * the answer is about. Take them before the completed work's slot frees.
6439
+ * One that waited past `AWAITING_EVIDENCE_MS` is dropped instead: a
6440
+ * completion that late says little about the runtime when it failed.
6188
6441
  */
6189
- async reportDue(completion) {
6442
+ takeDue(completion) {
6190
6443
  const now2 = this.now();
6191
6444
  const due = [];
6192
6445
  for (const failure of [...this.awaitingEvidence.values()]) {
@@ -6196,10 +6449,49 @@ invite_id: ${invite.invite_id}`,
6196
6449
  }
6197
6450
  if (evidences(completion, failure)) {
6198
6451
  this.awaitingEvidence.delete(failure.conversationId);
6452
+ this.holdForReport(failure);
6199
6453
  due.push(failure);
6200
6454
  }
6201
6455
  }
6202
- for (const failure of due) await this.reportFailure(failure, "other_run_completed");
6456
+ return due;
6457
+ }
6458
+ /** Report what `takeDue` took, letting go of each conversation once its answer is in: what waits for it goes on (or was dropped). */
6459
+ async reportDue(due) {
6460
+ const held = [...due];
6461
+ try {
6462
+ while (held.length > 0) {
6463
+ const failure = held[0];
6464
+ await this.reportFailure(failure, "other_run_completed");
6465
+ held.shift();
6466
+ this.letGo([failure]);
6467
+ }
6468
+ } finally {
6469
+ this.letGo(held);
6470
+ }
6471
+ }
6472
+ /** A report for this failure is due: its conversation is held until `letGo` (counted: two reports out hold it until both are answered). */
6473
+ holdForReport(failure) {
6474
+ this.reporting.set(failure.conversationId, (this.reporting.get(failure.conversationId) ?? 0) + 1);
6475
+ }
6476
+ /**
6477
+ * The answers are in (or the report is off): those conversations are no
6478
+ * longer held for it, what waits for them goes on, and a card a cycle left
6479
+ * out meanwhile for a report is read again (only then: a wake for
6480
+ * anything else could spin while a turn runs).
6481
+ */
6482
+ letGo(failures) {
6483
+ if (failures.length === 0) return;
6484
+ for (const { conversationId } of failures) {
6485
+ const left = (this.reporting.get(conversationId) ?? 0) - 1;
6486
+ if (left > 0) this.reporting.set(conversationId, left);
6487
+ else this.reporting.delete(conversationId);
6488
+ }
6489
+ if (this.stopped) return;
6490
+ if (this.waiting.length > 0) void this.pump();
6491
+ if (this.heldWhileReporting) {
6492
+ this.heldWhileReporting = false;
6493
+ this.wakeFrom("more");
6494
+ }
6203
6495
  }
6204
6496
  /** An attempt of this kind failed for these conversations (whatever comes of it): see `failingSince`. */
6205
6497
  failedAttempt(kind, conversations) {
@@ -6252,17 +6544,24 @@ invite_id: ${invite.invite_id}`,
6252
6544
  failure.outcome !== "timed_out" && !this.checkedFailures.has(failure) && this.now() - failure.failedAt <= AWAITING_EVIDENCE_MS && [...failing].every((id) => id === failure.conversationId)
6253
6545
  );
6254
6546
  if (due.length === 0) return;
6255
- for (const failure of due) this.checkedFailures.add(failure);
6256
- const ok = await this.runtimeCheck();
6257
6547
  for (const failure of due) {
6258
- if (this.stopped || this.awaitingEvidence.get(failure.conversationId) !== failure) continue;
6259
- if (!ok) {
6548
+ this.checkedFailures.add(failure);
6549
+ this.holdForReport(failure);
6550
+ }
6551
+ try {
6552
+ const ok = await this.runtimeCheck();
6553
+ for (const failure of due) {
6554
+ if (this.stopped || this.awaitingEvidence.get(failure.conversationId) !== failure) continue;
6555
+ if (!ok) {
6556
+ this.awaitingEvidence.delete(failure.conversationId);
6557
+ continue;
6558
+ }
6559
+ if (![...failing].every((id) => id === failure.conversationId)) continue;
6260
6560
  this.awaitingEvidence.delete(failure.conversationId);
6261
- continue;
6561
+ await this.reportFailure(failure, "runtime_check");
6262
6562
  }
6263
- if (![...failing].every((id) => id === failure.conversationId)) continue;
6264
- this.awaitingEvidence.delete(failure.conversationId);
6265
- await this.reportFailure(failure, "runtime_check");
6563
+ } finally {
6564
+ this.letGo(due);
6266
6565
  }
6267
6566
  }
6268
6567
  /** Nothing of this kind is running or queued: the runtime check may be asked now. */
@@ -6336,10 +6635,29 @@ invite_id: ${invite.invite_id}`,
6336
6635
  next = this.rerun(failure, result.action === "hidden");
6337
6636
  }
6338
6637
  }
6339
- if (result.action === "paused") this.dropWaiting(failure.conversationId);
6638
+ if (result.action === "none" || result.action === "paused") this.holdFailed(failure, result.action);
6340
6639
  if (next === "stop" || next === "rerun_capped") this.activeSplit?.skip.add(failure.conversationId);
6341
6640
  this.emit({ type: "processing_failure", ...base, result, next });
6342
6641
  }
6642
+ /**
6643
+ * The server answered `none` or `paused`: the conversation is held at the
6644
+ * anchor the report read through, so no later cycle (a message elsewhere,
6645
+ * a wake frame, a reconnect, an `unanswered` re-wake, a turn's end) runs it
6646
+ * again on the same input. A newer message moves its anchor and lifts the
6647
+ * hold (`paceCards`); a card read meanwhile leaves the tray, and the hold
6648
+ * with it (`forgetCleared`). What waits for it does not start: a run or
6649
+ * reply turn queued at that anchor (after `paused`, the server's mute, any),
6650
+ * and a reply turn to start again after the gate.
6651
+ */
6652
+ holdFailed(failure, reason) {
6653
+ const id = failure.conversationId;
6654
+ const anchor = failure.anchor;
6655
+ this.pacer.holdFailed(`${CONVERSATION_KEY}${id}`, anchor, reason);
6656
+ this.dropWaiting(id, reason === "paused" ? null : anchor);
6657
+ this.turnRerunsAfterGate = this.turnRerunsAfterGate.filter(
6658
+ ({ reply }) => reply.conversationId !== id || reason !== "paused" && anchorFrom(reply.card) !== anchor
6659
+ );
6660
+ }
6343
6661
  /**
6344
6662
  * Run the conversation again after a `retry` or `hidden` answer, after the
6345
6663
  * others already queued, and say what was done. Its run or reply turn takes
@@ -6397,14 +6715,20 @@ invite_id: ${invite.invite_id}`,
6397
6715
  else void this.startReplyTurn(reply, texts, reruns);
6398
6716
  }
6399
6717
  }
6400
- /** A `paused` conversation: a run or turn still waiting for a slot for it does not start. */
6401
- dropWaiting(conversationId) {
6718
+ /**
6719
+ * A held conversation: a run or turn still waiting for a slot for it does
6720
+ * not start; with an `anchor`, only one for that anchor (one queued for a
6721
+ * newer message is new input, and goes on).
6722
+ */
6723
+ dropWaiting(conversationId, anchor) {
6402
6724
  for (const entry of [...this.waiting]) {
6403
6725
  const turn = entry.handle.turn;
6404
6726
  if (turn.kind !== "reply" || turn.conversationId !== conversationId) continue;
6727
+ if (anchor !== null && turn.anchor !== anchor) continue;
6405
6728
  this.waiting.splice(this.waiting.indexOf(entry), 1);
6406
6729
  this.tracker.end(entry.handle);
6407
6730
  entry.drop?.();
6731
+ this.failureCounts.startsHeld += 1;
6408
6732
  }
6409
6733
  }
6410
6734
  rememberGateAlone(conversationId) {
@@ -6453,6 +6777,7 @@ invite_id: ${invite.invite_id}`,
6453
6777
  turnsQueued: 0,
6454
6778
  heldByTurns: 0,
6455
6779
  paced: 0,
6780
+ heldAfterFailure: 0,
6456
6781
  chunksOk: 0,
6457
6782
  chunksFailed: 0,
6458
6783
  splitCallsOk: 0,
@@ -6548,6 +6873,7 @@ function timeoutOption(value, fallback, name) {
6548
6873
  return value;
6549
6874
  }
6550
6875
  function launchKey(launch) {
6876
+ if (launch === "held") return "heldAfterFailure";
6551
6877
  return launch === "started" ? "turnsStarted" : launch === "queued" ? "turnsQueued" : "turnsRefused";
6552
6878
  }
6553
6879
  function trayInvites(tray) {
@@ -7269,6 +7595,6 @@ var ALLOWED_ATTACHMENT_MIME = [
7269
7595
  "video/webm"
7270
7596
  ];
7271
7597
 
7272
- export { ALLOWED_ATTACHMENT_MIME, AgentChatClient, AgentChatError, AwaitingReplyError, BlockedError, CONNECT_BUDGET_CLOSE_CODE, CONNECT_BUDGET_MAX_DELAY_MS, CONNECT_BUDGET_MIN_DELAY_MS, ConnectionError, DEFAULT_RETRY_POLICY, EmailExhaustedError, EmailLimitReachedError, ErrorCode, ForbiddenError, GroupDeletedError, HandleRequiredError, HttpTransport, INBOX_TRAY_DEFAULT_LIMIT, INBOX_TRAY_MAX_LIMIT, INBOX_WAIT_MAX_MS, MAX_ATTACHMENT_SIZE, NotFoundError, OtpAttemptsExhaustedError, RateLimitedError, RealtimeClient, RecipientBackloggedError, RestrictedError, ServerError, SuspendedError, UnauthorizedError, VERSION, ValidationError, WakeWebhookVerificationError, connectBudgetDelayMs, createAgentChatError, gate_exports as gate, integration_exports as integration, isAuthRejectionClose, paginate, parseRetryAfter, renderMessageContext, verifyWakeWebhook, wakePayloadOf };
7598
+ export { ALLOWED_ATTACHMENT_MIME, AgentChatClient, AgentChatError, AlreadyClaimedError, AwaitingReplyError, BlockedError, CONNECT_BUDGET_CLOSE_CODE, CONNECT_BUDGET_MAX_DELAY_MS, CONNECT_BUDGET_MIN_DELAY_MS, ConnectionError, ContainsSecretError, DEFAULT_RETRY_POLICY, EmailExhaustedError, EmailLimitReachedError, ErrorCode, ForbiddenError, GroupDeletedError, HandleRequiredError, HttpTransport, INBOX_TRAY_DEFAULT_LIMIT, INBOX_TRAY_MAX_LIMIT, INBOX_WAIT_MAX_MS, MAX_ATTACHMENT_SIZE, NotFoundError, OtpAttemptsExhaustedError, RateLimitedError, RealtimeClient, RecipientBackloggedError, RestrictedError, ServerError, SuspendedError, UnauthorizedError, VERSION, ValidationError, WakeWebhookVerificationError, connectBudgetDelayMs, createAgentChatError, gate_exports as gate, integration_exports as integration, isAuthRejectionClose, paginate, parseRetryAfter, renderMessageContext, verifyWakeWebhook, wakePayloadOf };
7273
7599
  //# sourceMappingURL=index.js.map
7274
7600
  //# sourceMappingURL=index.js.map