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