agentchatme 1.3.2 → 1.5.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
@@ -37,10 +37,21 @@ var ErrorCode = {
37
37
  * lists the candidates; re-run `recover()` with one of them.
38
38
  */
39
39
  HANDLE_REQUIRED: "HANDLE_REQUIRED",
40
+ /**
41
+ * 429 from a sign-up verify call: the code's attempts are used up and the
42
+ * pending id is gone. Repeating never succeeds; request a new code.
43
+ * Mapped to `OtpAttemptsExhaustedError` (not `RateLimitedError`).
44
+ */
45
+ OTP_ATTEMPTS_EXHAUSTED: "OTP_ATTEMPTS_EXHAUSTED",
40
46
  SUSPENDED: "SUSPENDED",
41
47
  RESTRICTED: "RESTRICTED",
42
48
  CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND",
43
49
  MESSAGE_NOT_FOUND: "MESSAGE_NOT_FOUND",
50
+ /**
51
+ * 410 when you download the attachment of a message hidden from you
52
+ * because your machine could not process it (`Message.could_not_process`).
53
+ */
54
+ COULD_NOT_PROCESS: "COULD_NOT_PROCESS",
44
55
  GROUP_DELETED: "GROUP_DELETED",
45
56
  RATE_LIMITED: "RATE_LIMITED",
46
57
  RECIPIENT_BACKLOGGED: "RECIPIENT_BACKLOGGED",
@@ -72,6 +83,12 @@ function parseRetryAfter(raw, now2 = Date.now()) {
72
83
  }
73
84
 
74
85
  // src/errors.ts
86
+ function wholeSeconds(value) {
87
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
88
+ }
89
+ function retryAfterSecondsOf(response) {
90
+ return wholeSeconds(response.retry_after_s) ?? wholeSeconds(response.details?.retry_after_s);
91
+ }
75
92
  var AgentChatError = class extends Error {
76
93
  code;
77
94
  status;
@@ -82,6 +99,13 @@ var AgentChatError = class extends Error {
82
99
  * server-side trace in seconds.
83
100
  */
84
101
  requestId;
102
+ /**
103
+ * The body's `retry_after_s` in seconds (top level, else
104
+ * `details.retry_after_s`), or null. The sign-up 429s carry it; so does
105
+ * the per-IP rate limit. `RateLimitedError.retryAfterMs` prefers the
106
+ * `Retry-After` header.
107
+ */
108
+ retryAfterS;
85
109
  constructor(response, status, requestId = null) {
86
110
  super(response.message);
87
111
  this.name = "AgentChatError";
@@ -89,6 +113,7 @@ var AgentChatError = class extends Error {
89
113
  this.status = status;
90
114
  this.details = response.details;
91
115
  this.requestId = requestId;
116
+ this.retryAfterS = retryAfterSecondsOf(response);
92
117
  Object.setPrototypeOf(this, new.target.prototype);
93
118
  }
94
119
  };
@@ -206,6 +231,12 @@ var HandleRequiredError = class extends AgentChatError {
206
231
  this.handles = Array.isArray(raw) ? raw.filter((h) => typeof h === "string") : [];
207
232
  }
208
233
  };
234
+ var OtpAttemptsExhaustedError = class extends AgentChatError {
235
+ constructor(response, status, requestId = null) {
236
+ super(response, status, requestId);
237
+ this.name = "OtpAttemptsExhaustedError";
238
+ }
239
+ };
209
240
  var ServerError = class extends AgentChatError {
210
241
  constructor(response, status, requestId = null) {
211
242
  super(response, status, requestId);
@@ -218,13 +249,17 @@ var ConnectionError = class extends Error {
218
249
  this.name = "ConnectionError";
219
250
  }
220
251
  };
252
+ function retryAfterMsOf(body) {
253
+ const seconds = retryAfterSecondsOf(body);
254
+ return seconds === null ? null : seconds * 1e3;
255
+ }
221
256
  function createAgentChatError(body, status, headers) {
222
257
  const requestId = headers?.get("x-request-id") ?? null;
223
258
  switch (body.code) {
224
259
  case ErrorCode.RATE_LIMITED: {
225
260
  const fromHeader = headers ? parseRetryAfter(headers.get("retry-after")) : null;
226
261
  const fromBody = typeof body.details?.retry_after_ms === "number" ? body.details.retry_after_ms : null;
227
- return new RateLimitedError(body, status, fromHeader ?? fromBody, requestId);
262
+ return new RateLimitedError(body, status, fromHeader ?? fromBody ?? retryAfterMsOf(body), requestId);
228
263
  }
229
264
  case ErrorCode.SUSPENDED:
230
265
  case ErrorCode.AGENT_SUSPENDED:
@@ -260,6 +295,8 @@ function createAgentChatError(body, status, headers) {
260
295
  return new EmailExhaustedError(body, status, requestId);
261
296
  case ErrorCode.HANDLE_REQUIRED:
262
297
  return new HandleRequiredError(body, status, requestId);
298
+ case ErrorCode.OTP_ATTEMPTS_EXHAUSTED:
299
+ return new OtpAttemptsExhaustedError(body, status, requestId);
263
300
  case ErrorCode.INTERNAL_ERROR:
264
301
  return new ServerError(body, status, requestId);
265
302
  default:
@@ -268,7 +305,7 @@ function createAgentChatError(body, status, headers) {
268
305
  if (status === 404) return new NotFoundError(body, status, requestId);
269
306
  if (status === 429) {
270
307
  const fromHeader = headers ? parseRetryAfter(headers.get("retry-after")) : null;
271
- return new RateLimitedError(body, status, fromHeader, requestId);
308
+ return new RateLimitedError(body, status, fromHeader ?? retryAfterMsOf(body), requestId);
272
309
  }
273
310
  if (status >= 500) return new ServerError(body, status, requestId);
274
311
  return new AgentChatError(body, status, requestId);
@@ -276,7 +313,7 @@ function createAgentChatError(body, status, headers) {
276
313
  }
277
314
 
278
315
  // src/version.ts
279
- var VERSION = "1.3.2" ;
316
+ var VERSION = "1.5.0" ;
280
317
 
281
318
  // src/runtime.ts
282
319
  function detectRuntime() {
@@ -410,8 +447,10 @@ var HttpTransport = class {
410
447
  }
411
448
  const errBody = await parseErrorBody(res);
412
449
  const error = createAgentChatError(errBody, res.status, res.headers);
413
- const isTerminal429 = error instanceof RecipientBackloggedError || error instanceof AwaitingReplyError;
414
- const retriable = canRetry && attempt < maxAttempts && RETRIABLE_STATUSES.has(res.status) && !isTerminal429;
450
+ const isTerminal429 = error instanceof RecipientBackloggedError || error instanceof AwaitingReplyError || error instanceof OtpAttemptsExhaustedError;
451
+ const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
452
+ const waitsTooLong = res.status === 429 && retryAfter !== null && retryAfter > policy.maxDelayMs;
453
+ const retriable = canRetry && attempt < maxAttempts && RETRIABLE_STATUSES.has(res.status) && !isTerminal429 && !waitsTooLong;
415
454
  await safeInvoke(this.hooks.onError, {
416
455
  ...requestInfo,
417
456
  status: res.status,
@@ -419,7 +458,6 @@ var HttpTransport = class {
419
458
  error
420
459
  });
421
460
  if (retriable) {
422
- const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
423
461
  const delayMs = computeDelay(policy, attempt, retryAfter);
424
462
  await safeInvoke(this.hooks.onRetry, {
425
463
  ...requestInfo,
@@ -527,23 +565,23 @@ function toConnectionError(err, userSignal) {
527
565
  }
528
566
  async function parseJsonOrVoid(res) {
529
567
  if (res.status === 204) return void 0;
530
- const text = await res.text();
531
- if (!text) return void 0;
568
+ const text2 = await res.text();
569
+ if (!text2) return void 0;
532
570
  try {
533
- return JSON.parse(text);
571
+ return JSON.parse(text2);
534
572
  } catch {
535
573
  throw new ConnectionError(
536
- `AgentChat SDK: expected JSON response but got: ${text.slice(0, 200)}`
574
+ `AgentChat SDK: expected JSON response but got: ${text2.slice(0, 200)}`
537
575
  );
538
576
  }
539
577
  }
540
578
  async function parseErrorBody(res) {
541
579
  try {
542
- const text = await res.text();
543
- if (!text) {
580
+ const text2 = await res.text();
581
+ if (!text2) {
544
582
  return { code: statusToCode(res.status), message: res.statusText || "Request failed" };
545
583
  }
546
- const body = JSON.parse(text);
584
+ const body = JSON.parse(text2);
547
585
  if (body && typeof body === "object" && typeof body.code === "string" && typeof body.message === "string") {
548
586
  return body;
549
587
  }
@@ -641,6 +679,7 @@ function parseBacklogWarning(header2) {
641
679
  if (!Number.isFinite(undeliveredCount) || !Number.isInteger(undeliveredCount)) return null;
642
680
  return { recipientHandle, undeliveredCount };
643
681
  }
682
+ var PROCESSING_FAILURE_ACTIONS = /* @__PURE__ */ new Set(["retry", "hidden", "paused", "none"]);
644
683
  function intHeader(headers, name) {
645
684
  const raw = headers?.get?.(name);
646
685
  if (typeof raw !== "string" || !/^\d+$/.test(raw.trim())) return null;
@@ -672,6 +711,30 @@ function generateClientMsgId() {
672
711
  }
673
712
  return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
674
713
  }
714
+ var SIGNUP_FLOW_FIELDS = [
715
+ "version",
716
+ "flow",
717
+ "next_step",
718
+ "status",
719
+ "param",
720
+ "expires_at",
721
+ "expires_in_s",
722
+ "code_length",
723
+ "attempts",
724
+ "max_attempts",
725
+ "resend_after_s",
726
+ "retry_after_s",
727
+ "message"
728
+ ];
729
+ function signupFlowFieldsOf(body) {
730
+ const out = {};
731
+ if (body === null || typeof body !== "object") return out;
732
+ const record = body;
733
+ for (const key of SIGNUP_FLOW_FIELDS) {
734
+ if (record[key] !== void 0) out[key] = record[key];
735
+ }
736
+ return out;
737
+ }
675
738
  var INBOX_WAIT_TIMEOUT_GRACE_MS = 1e4;
676
739
  var AgentChatClient = class _AgentChatClient {
677
740
  http;
@@ -708,7 +771,8 @@ var AgentChatClient = class _AgentChatClient {
708
771
  record: (conversationId, opts) => this.recordDecision(conversationId, opts)
709
772
  };
710
773
  this.conversations = {
711
- markRead: (conversationId, throughMessageId, opts) => this.markConversationRead(conversationId, throughMessageId, opts)
774
+ markRead: (conversationId, throughMessageId, opts) => this.markConversationRead(conversationId, throughMessageId, opts),
775
+ reportProcessingFailure: (conversationId, opts) => this.reportProcessingFailure(conversationId, opts)
712
776
  };
713
777
  this.texts = {
714
778
  get: (opts) => this.getTexts(opts)
@@ -780,6 +844,36 @@ var AgentChatClient = class _AgentChatClient {
780
844
  options
781
845
  );
782
846
  }
847
+ async reportProcessingFailure(conversationId, options) {
848
+ const body = {
849
+ through_message_id: options.throughMessageId,
850
+ outcome: options.outcome,
851
+ evidence: options.evidence
852
+ };
853
+ let res;
854
+ try {
855
+ res = await this.post(
856
+ `/v1/conversations/${encodeURIComponent(conversationId)}/processing-failures`,
857
+ body,
858
+ // One report, one count: a retried request carries the same key.
859
+ { ...options, idempotencyKey: options.idempotencyKey ?? generateClientMsgId() }
860
+ );
861
+ } catch (err) {
862
+ if (err instanceof AgentChatError && err.status === 404 && err.code !== "CONVERSATION_NOT_FOUND" && err.code !== "MESSAGE_NOT_FOUND") {
863
+ return { action: "none", attempts: 0, hidden_message_ids: [], paused_until: null };
864
+ }
865
+ throw err;
866
+ }
867
+ const r = res !== null && typeof res === "object" ? res : {};
868
+ const action = PROCESSING_FAILURE_ACTIONS.has(r.action) ? r.action : "none";
869
+ return {
870
+ action,
871
+ attempts: typeof r.attempts === "number" && Number.isFinite(r.attempts) ? r.attempts : 0,
872
+ hidden_message_ids: Array.isArray(r.hidden_message_ids) ? r.hidden_message_ids.filter((id) => typeof id === "string") : [],
873
+ ...typeof r.hidden_count === "number" && Number.isFinite(r.hidden_count) ? { hidden_count: r.hidden_count } : {},
874
+ paused_until: typeof r.paused_until === "string" ? r.paused_until : null
875
+ };
876
+ }
783
877
  getTexts(options) {
784
878
  const params = new URLSearchParams({ runtime: options.runtime });
785
879
  return this.get(`/v1/texts?${params.toString()}`, options);
@@ -882,7 +976,7 @@ var AgentChatClient = class _AgentChatClient {
882
976
  clientIdentity: options?.clientIdentity,
883
977
  ...options?.fetch ? { fetch: options.fetch } : {}
884
978
  });
885
- return { agent: res.data.agent, apiKey: res.data.api_key, client };
979
+ return { ...signupFlowFieldsOf(res.data), agent: res.data.agent, apiKey: res.data.api_key, client };
886
980
  }
887
981
  /**
888
982
  * Start account recovery for a lost API key. The server emails a 6-digit
@@ -933,7 +1027,7 @@ var AgentChatClient = class _AgentChatClient {
933
1027
  clientIdentity: options?.clientIdentity,
934
1028
  ...options?.fetch ? { fetch: options.fetch } : {}
935
1029
  });
936
- return { handle: res.data.handle, apiKey: res.data.api_key, client };
1030
+ return { ...signupFlowFieldsOf(res.data), handle: res.data.handle, apiKey: res.data.api_key, client };
937
1031
  }
938
1032
  // ─── Agent profile ────────────────────────────────────────────────────────
939
1033
  /**
@@ -1044,24 +1138,48 @@ var AgentChatClient = class _AgentChatClient {
1044
1138
  * most one:
1045
1139
  * - `beforeSeq` — backwards scrollback (rows with seq < N, newest first)
1046
1140
  * - `afterSeq` — forwards gap-fill (rows with seq > N, oldest first)
1141
+ * - `afterMessageId` — forwards from a message you hold (instead of `afterSeq`)
1047
1142
  * - `aroundMessageId` — backwards window ending at that exact message
1048
1143
  *
1049
1144
  * `afterSeq` is the path `RealtimeClient` uses for in-order recovery
1050
1145
  * when a per-conversation seq gap is detected. Application code usually
1051
1146
  * only needs `beforeSeq` for normal pagination.
1147
+ *
1148
+ * With `waitMs` > 0 (and `afterSeq` or `afterMessageId`) this is the
1149
+ * scoped wait: the server holds the request until a message from someone
1150
+ * else arrives after the cursor, or answers `[]` after `waitMs`. One
1151
+ * conversation only, no sync ack. `getMessagesPage` also returns how long
1152
+ * the server held it.
1052
1153
  */
1053
- getMessages(conversationId, options) {
1154
+ async getMessages(conversationId, options) {
1155
+ return (await this.getMessagesPage(conversationId, options)).messages;
1156
+ }
1157
+ /** `getMessages()` with the response facts a waiter needs: how long the server held a scoped wait (`waitedMs`). */
1158
+ async getMessagesPage(conversationId, options) {
1054
1159
  const params = new URLSearchParams();
1055
1160
  params.set("limit", String(options?.limit ?? 50));
1056
1161
  if (options?.beforeSeq !== void 0) params.set("before_seq", String(options.beforeSeq));
1057
1162
  if (options?.afterSeq !== void 0) params.set("after_seq", String(options.afterSeq));
1163
+ if (options?.afterMessageId !== void 0) params.set("after_message_id", options.afterMessageId);
1058
1164
  if (options?.aroundMessageId !== void 0) {
1059
1165
  params.set("around_message_id", options.aroundMessageId);
1060
1166
  }
1061
- return this.get(
1167
+ const waitMs = Math.floor(options?.waitMs ?? 0);
1168
+ if (waitMs > 0) params.set("wait_ms", String(waitMs));
1169
+ const timeoutMs = options?.timeoutMs !== void 0 ? options.timeoutMs : waitMs > 0 ? waitMs + INBOX_WAIT_TIMEOUT_GRACE_MS : void 0;
1170
+ const res = await this.http.request(
1171
+ "GET",
1062
1172
  `/v1/messages/${encodeURIComponent(conversationId)}?${params.toString()}`,
1063
- options
1173
+ this.toRequestOpts({ ...options, timeoutMs })
1064
1174
  );
1175
+ const waitedMs = intHeader(res.headers, "x-agentchat-waited-ms");
1176
+ return {
1177
+ messages: res.data,
1178
+ waitedMs,
1179
+ scopedWaitSupported: waitMs > 0 ? waitedMs !== null : null,
1180
+ requestId: res.requestId,
1181
+ headers: res.headers
1182
+ };
1065
1183
  }
1066
1184
  /**
1067
1185
  * Hide a message from your own view (hide-for-me). Either side of the
@@ -1353,11 +1471,13 @@ var AgentChatClient = class _AgentChatClient {
1353
1471
  }
1354
1472
  // ─── Mutes ────────────────────────────────────────────────────────────────
1355
1473
  //
1356
- // Mute suppresses real-time WebSocket push from a specific agent or
1357
- // conversation without blocking/leaving. Envelopes still land in
1358
- // `/v1/messages/sync` and the unread counter still bumps — the muter
1359
- // catches up on their own schedule. The sender sees a normal "delivered"
1360
- // receipt; no mute signal leaks across the wire.
1474
+ // Mute stops the wake for a specific agent or conversation without
1475
+ // blocking or leaving: no real-time WebSocket push and no wake webhook.
1476
+ // Nothing is hidden — the conversation stays on the inbox tray
1477
+ // (`muted: true`), envelopes still land in `/v1/messages/sync`, and the
1478
+ // unread counter still bumps. A muted message reaches the machine at its
1479
+ // next sync (every reconnect) or when the agent opens the conversation;
1480
+ // until then the sender sees it as `stored`, not `delivered`.
1361
1481
  //
1362
1482
  // All mute APIs are idempotent:
1363
1483
  // - Re-muting with a different `mutedUntil` refreshes the expiry.
@@ -2789,12 +2909,12 @@ var RealtimeClient = class {
2789
2909
  * `inFlightAdoptMs` at most — a handler that never finishes must not stop
2790
2910
  * its conversation for good (it keeps running; the next message goes on).
2791
2911
  */
2792
- heldAtMost(run2) {
2912
+ heldAtMost(run3) {
2793
2913
  const ms = this.options.inFlightAdoptMs;
2794
2914
  return new Promise((resolve) => {
2795
2915
  const timer = setTimeout(resolve, ms);
2796
2916
  unref(timer);
2797
- run2.then(
2917
+ run3.then(
2798
2918
  () => {
2799
2919
  clearTimeout(timer);
2800
2920
  resolve();
@@ -2926,16 +3046,16 @@ var RealtimeClient = class {
2926
3046
  return "payload is not an object";
2927
3047
  }
2928
3048
  const p = payload;
2929
- const text = (key) => typeof p[key] !== "string" || p[key] === "" ? `${key} is not a non-empty string` : null;
3049
+ const text2 = (key) => typeof p[key] !== "string" || p[key] === "" ? `${key} is not a non-empty string` : null;
2930
3050
  const integerStep = typeof p.step === "number" && Number.isInteger(p.step);
2931
3051
  if (!this.negotiated.has("rewake")) {
2932
- return text("reason") ?? text("conversation_id") ?? text("anchor_message_id") ?? text("at") ?? (integerStep ? null : "step is not an integer");
3052
+ return text2("reason") ?? text2("conversation_id") ?? text2("anchor_message_id") ?? text2("at") ?? (integerStep ? null : "step is not an integer");
2933
3053
  }
2934
- const reasonProblem = text("reason") ?? text("at");
3054
+ const reasonProblem = text2("reason") ?? text2("at");
2935
3055
  if (reasonProblem !== null) return reasonProblem;
2936
3056
  switch (p.reason) {
2937
3057
  case "reminder":
2938
- return text("conversation_id") ?? text("anchor_message_id") ?? (integerStep ? null : "step is not an integer");
3058
+ return text2("conversation_id") ?? text2("anchor_message_id") ?? (integerStep ? null : "step is not an integer");
2939
3059
  case "unanswered": {
2940
3060
  const ids = p.conversation_ids;
2941
3061
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) {
@@ -3315,8 +3435,8 @@ ${canonicalJson(card)}`);
3315
3435
  function servedText(value) {
3316
3436
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
3317
3437
  }
3318
- function parseVerdicts(text, tray) {
3319
- const raw = extractJson(text);
3438
+ function parseVerdicts(text2, tray) {
3439
+ const raw = extractJson(text2);
3320
3440
  if (raw === null) return null;
3321
3441
  let parsed;
3322
3442
  try {
@@ -3353,18 +3473,18 @@ function parseVerdicts(text, tray) {
3353
3473
  }
3354
3474
  return out;
3355
3475
  }
3356
- function extractJson(text) {
3357
- if (typeof text !== "string" || text.trim().length === 0) return null;
3358
- let s = text.trim();
3476
+ function extractJson(text2) {
3477
+ if (typeof text2 !== "string" || text2.trim().length === 0) return null;
3478
+ let s = text2.trim();
3359
3479
  const fence = FENCE_RE.exec(s);
3360
3480
  if (fence?.[1]) s = fence[1].trim();
3361
3481
  const starts = [s.indexOf("{"), s.indexOf("[")].filter((i) => i !== -1);
3362
3482
  if (starts.length === 0) return null;
3363
- const start = Math.min(...starts);
3364
- const closer = s[start] === "{" ? "}" : "]";
3483
+ const start2 = Math.min(...starts);
3484
+ const closer = s[start2] === "{" ? "}" : "]";
3365
3485
  const end = s.lastIndexOf(closer);
3366
- if (end <= start) return null;
3367
- return s.slice(start, end + 1);
3486
+ if (end <= start2) return null;
3487
+ return s.slice(start2, end + 1);
3368
3488
  }
3369
3489
  function normalizeDecision(value) {
3370
3490
  if (typeof value !== "string") return null;
@@ -3384,7 +3504,7 @@ async function run(options) {
3384
3504
  const ids = cards.map((card) => card.conversation_id);
3385
3505
  if (ids.length === 0) return emptyResult("empty", [], null);
3386
3506
  let prompt;
3387
- let text;
3507
+ let text2;
3388
3508
  try {
3389
3509
  prompt = buildPrompt(options.tray, { texts: options.texts, toolNamer: options.toolNamer });
3390
3510
  } catch (err) {
@@ -3392,12 +3512,12 @@ async function run(options) {
3392
3512
  }
3393
3513
  if (options.signal?.aborted) return emptyResult("fail_closed", ids, "the gate was stopped");
3394
3514
  try {
3395
- text = options.signal ? await options.callModel(prompt, { signal: options.signal }) : await options.callModel(prompt);
3515
+ text2 = options.signal ? await options.callModel(prompt, { signal: options.signal }) : await options.callModel(prompt);
3396
3516
  } catch (err) {
3397
3517
  return emptyResult("fail_closed", ids, `model call failed: ${describe(err)}`);
3398
3518
  }
3399
3519
  if (options.signal?.aborted) return emptyResult("fail_closed", ids, "the gate was stopped");
3400
- const verdicts = parseVerdicts(text, options.tray);
3520
+ const verdicts = parseVerdicts(text2, options.tray);
3401
3521
  if (verdicts === null || verdicts.length === 0) {
3402
3522
  return emptyResult("fail_closed", ids, "no usable verdicts in the answer");
3403
3523
  }
@@ -3501,9 +3621,11 @@ __export(integration_exports, {
3501
3621
  TextsCache: () => TextsCache,
3502
3622
  TurnTracker: () => TurnTracker,
3503
3623
  WakeCoalescer: () => WakeCoalescer,
3624
+ account: () => account_exports,
3504
3625
  anchor: () => anchor_exports,
3505
3626
  applyInviteOutcome: () => applyInviteOutcome,
3506
3627
  applyOutcome: () => applyOutcome,
3628
+ conversationRunPrompt: () => conversationRunPrompt,
3507
3629
  hostedMcpUrl: () => hostedMcpUrl,
3508
3630
  inviteOutcome: () => inviteOutcome,
3509
3631
  isTexts: () => isTexts,
@@ -3803,11 +3925,11 @@ function render(texts, handle) {
3803
3925
  }
3804
3926
  return [START_MARKER, handleLine(bare), line, END_MARKER].join("\n");
3805
3927
  }
3806
- function find(text, options = {}) {
3807
- const spans = blocksOf(text);
3928
+ function find(text2, options = {}) {
3929
+ const spans = blocksOf(text2);
3808
3930
  const span = spans.find((s) => !s.legacy) ?? spans[0];
3809
3931
  if (!span) return null;
3810
- const inner = text.slice(span.innerStart, span.innerEnd).replace(/\r\n/g, "\n");
3932
+ const inner = text2.slice(span.innerStart, span.innerEnd).replace(/\r\n/g, "\n");
3811
3933
  let handle = null;
3812
3934
  let marked = false;
3813
3935
  const kept = [];
@@ -3824,39 +3946,39 @@ function find(text, options = {}) {
3824
3946
  if (handle === null) handle = handleFromWording(body, options.template ?? null);
3825
3947
  return { start: span.start, end: span.end, handle, marked, legacy: span.legacy, body };
3826
3948
  }
3827
- function replace(text, block) {
3828
- const spans = blocksOf(text);
3949
+ function replace(text2, block) {
3950
+ const spans = blocksOf(text2);
3829
3951
  if (spans.length === 0) {
3830
- const trimmed = text.replace(/\n+$/, "");
3952
+ const trimmed = text2.replace(/\n+$/, "");
3831
3953
  return trimmed.length === 0 ? `${block}
3832
3954
  ` : `${trimmed}
3833
3955
 
3834
3956
  ${block}
3835
3957
  `;
3836
3958
  }
3837
- return rebuild(text, spans, block);
3959
+ return rebuild(text2, spans, block);
3838
3960
  }
3839
- function remove(text) {
3840
- const spans = blocksOf(text);
3841
- if (spans.length === 0) return text;
3842
- return rebuild(text, spans, null);
3961
+ function remove(text2) {
3962
+ const spans = blocksOf(text2);
3963
+ if (spans.length === 0) return text2;
3964
+ return rebuild(text2, spans, null);
3843
3965
  }
3844
- function linesOf(text) {
3966
+ function linesOf(text2) {
3845
3967
  const lines = [];
3846
3968
  let at = 0;
3847
- while (at <= text.length) {
3848
- const nl = text.indexOf("\n", at);
3849
- const end = nl === -1 ? text.length : nl;
3850
- lines.push({ start: at, end, next: nl === -1 ? text.length + 1 : nl + 1, trimmed: text.slice(at, end).trim() });
3969
+ while (at <= text2.length) {
3970
+ const nl = text2.indexOf("\n", at);
3971
+ const end = nl === -1 ? text2.length : nl;
3972
+ lines.push({ start: at, end, next: nl === -1 ? text2.length + 1 : nl + 1, trimmed: text2.slice(at, end).trim() });
3851
3973
  if (nl === -1) break;
3852
3974
  at = nl + 1;
3853
3975
  }
3854
3976
  return lines;
3855
3977
  }
3856
- function blocksOf(text) {
3978
+ function blocksOf(text2) {
3857
3979
  const spans = [];
3858
3980
  let open = null;
3859
- for (const line of linesOf(text)) {
3981
+ for (const line of linesOf(text2)) {
3860
3982
  if (line.trimmed === START_MARKER || line.trimmed === LEGACY_START_MARKER) {
3861
3983
  open = { line, legacy: line.trimmed === LEGACY_START_MARKER };
3862
3984
  continue;
@@ -3875,20 +3997,20 @@ function blocksOf(text) {
3875
3997
  }
3876
3998
  return spans;
3877
3999
  }
3878
- function rebuild(text, spans, replacement) {
4000
+ function rebuild(text2, spans, replacement) {
3879
4001
  const parts = [];
3880
4002
  const first = spans[0];
3881
4003
  const last = spans[spans.length - 1];
3882
- if (!first || !last) return text;
3883
- parts.push(text.slice(0, first.start).replace(/\n+$/, ""));
4004
+ if (!first || !last) return text2;
4005
+ parts.push(text2.slice(0, first.start).replace(/\n+$/, ""));
3884
4006
  if (replacement !== null) parts.push(replacement);
3885
4007
  for (let i = 1; i < spans.length; i++) {
3886
4008
  const previous = spans[i - 1];
3887
4009
  const current = spans[i];
3888
4010
  if (!previous || !current) continue;
3889
- parts.push(text.slice(previous.end, current.start).replace(/^\n+/, "").replace(/\n+$/, ""));
4011
+ parts.push(text2.slice(previous.end, current.start).replace(/^\n+/, "").replace(/\n+$/, ""));
3890
4012
  }
3891
- parts.push(text.slice(last.end).replace(/^\n+/, ""));
4013
+ parts.push(text2.slice(last.end).replace(/^\n+/, ""));
3892
4014
  const kept = parts.filter((part) => part.length > 0);
3893
4015
  if (kept.length === 0) return "";
3894
4016
  const out = kept.join("\n\n");
@@ -4327,13 +4449,13 @@ var MANUAL_FETCH_TIMEOUT_MS = 1e4;
4327
4449
  var MANUAL_MAX_REDIRECTS = 3;
4328
4450
  var MANUAL_SKILL_NAME = "agentchat";
4329
4451
  function manualFrontMatter(raw) {
4330
- const text = (raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw).replace(/\r\n/g, "\n");
4331
- if (!text.startsWith("---\n")) return null;
4332
- let close = text.indexOf("\n---", 3);
4333
- while (close >= 0 && text.charAt(close + 4) !== "\n" && close + 4 !== text.length) close = text.indexOf("\n---", close + 1);
4452
+ const text2 = (raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw).replace(/\r\n/g, "\n");
4453
+ if (!text2.startsWith("---\n")) return null;
4454
+ let close = text2.indexOf("\n---", 3);
4455
+ while (close >= 0 && text2.charAt(close + 4) !== "\n" && close + 4 !== text2.length) close = text2.indexOf("\n---", close + 1);
4334
4456
  if (close < 0) return null;
4335
4457
  const fields = /* @__PURE__ */ new Map();
4336
- for (const line of text.slice(4, close).split("\n")) {
4458
+ for (const line of text2.slice(4, close).split("\n")) {
4337
4459
  const match = /^([A-Za-z0-9_-]+):[ \t]*(.*?)[ \t]*$/.exec(line);
4338
4460
  if (match === null) continue;
4339
4461
  const value = match[2] ?? "";
@@ -4341,8 +4463,8 @@ function manualFrontMatter(raw) {
4341
4463
  }
4342
4464
  return fields;
4343
4465
  }
4344
- function manualVersion(text) {
4345
- const version = manualFrontMatter(text)?.get("version");
4466
+ function manualVersion(text2) {
4467
+ const version = manualFrontMatter(text2)?.get("version");
4346
4468
  return version !== void 0 && version.length > 0 ? version : null;
4347
4469
  }
4348
4470
  async function syncManual(options) {
@@ -4582,13 +4704,13 @@ async function downloadManual(served, hash, origin, options) {
4582
4704
  if (timeout.aborted) throw new Error(`no answer from ${served.url} within ${timeoutMs} ms`);
4583
4705
  throw err;
4584
4706
  }
4585
- let text;
4707
+ let text2;
4586
4708
  try {
4587
- text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
4709
+ text2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
4588
4710
  } catch {
4589
4711
  throw new Error("the body is not UTF-8 text");
4590
4712
  }
4591
- checkManualText(text, served.version);
4713
+ checkManualText(text2, served.version);
4592
4714
  if (hash !== null) {
4593
4715
  const got = await sha256(bytes);
4594
4716
  if (got !== hash) throw new Error(`the body's sha256 is ${got}, the server announced ${hash}`);
@@ -4618,12 +4740,12 @@ async function readCapped(response, maxBytes) {
4618
4740
  }
4619
4741
  return out;
4620
4742
  }
4621
- function checkManualText(text, announced) {
4622
- if (text.includes("\0")) throw new Error("the body is not text");
4623
- const fields = manualFrontMatter(text);
4743
+ function checkManualText(text2, announced) {
4744
+ if (text2.includes("\0")) throw new Error("the body is not text");
4745
+ const fields = manualFrontMatter(text2);
4624
4746
  if (fields === null) throw new Error("the body has no front matter \u2014 not the manual");
4625
4747
  if (fields.get("name") !== MANUAL_SKILL_NAME) throw new Error(`the front matter names "${fields.get("name") ?? ""}", not the ${MANUAL_SKILL_NAME} skill`);
4626
- const version = manualVersion(text);
4748
+ const version = manualVersion(text2);
4627
4749
  if (version !== announced) throw new Error(`the body is version ${version ?? "(none)"}, the server announced ${announced}`);
4628
4750
  }
4629
4751
  function anySignal(a, b) {
@@ -4661,18 +4783,18 @@ async function probeHostedTools(options) {
4661
4783
  accept: "application/json, text/event-stream",
4662
4784
  ...clientIdentityHeaders(options.clientIdentity)
4663
4785
  };
4664
- const call = async (id, method, params, extra = {}) => {
4786
+ const call2 = async (id, method, params, extra = {}) => {
4665
4787
  const res = await fetchImpl(hostedMcpUrl(options.apiBase), {
4666
4788
  method: "POST",
4667
4789
  headers: { ...headers, ...extra },
4668
4790
  body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
4669
4791
  signal: controller.signal
4670
4792
  });
4671
- const text = await res.text();
4672
- return { res, result: readResult(text) };
4793
+ const text2 = await res.text();
4794
+ return { res, result: readResult(text2) };
4673
4795
  };
4674
4796
  try {
4675
- const init = await call(1, "initialize", {
4797
+ const init = await call2(1, "initialize", {
4676
4798
  protocolVersion: MCP_PROTOCOL_VERSION,
4677
4799
  capabilities: {},
4678
4800
  clientInfo: { name: options.clientIdentity?.name ?? "typescript_sdk", version: options.clientIdentity?.version ?? "0" }
@@ -4693,7 +4815,7 @@ async function probeHostedTools(options) {
4693
4815
  ...typeof serverInfo.version === "string" ? { serverVersion: serverInfo.version } : {},
4694
4816
  protocolVersion
4695
4817
  };
4696
- const list = await call(2, "tools/list", {}, {
4818
+ const list = await call2(2, "tools/list", {}, {
4697
4819
  "mcp-protocol-version": protocolVersion,
4698
4820
  ...session ? { "mcp-session-id": session } : {}
4699
4821
  });
@@ -4718,11 +4840,11 @@ async function probeHostedTools(options) {
4718
4840
  clearTimeout(timer);
4719
4841
  }
4720
4842
  }
4721
- function readResult(text) {
4843
+ function readResult(text2) {
4722
4844
  const candidates = [];
4723
- const trimmed = text.trim();
4845
+ const trimmed = text2.trim();
4724
4846
  if (trimmed.startsWith("{")) candidates.push(trimmed);
4725
- for (const line of text.split(/\r?\n/)) {
4847
+ for (const line of text2.split(/\r?\n/)) {
4726
4848
  if (line.startsWith("data:")) candidates.push(line.slice(5).trim());
4727
4849
  }
4728
4850
  for (const candidate of candidates) {
@@ -4748,6 +4870,11 @@ var CYCLE_TIMEOUT_MS = 10 * 6e4;
4748
4870
  var GATE_CHUNK_SIZE = 10;
4749
4871
  var REPLY_TURN_PLACEHOLDER = "<conversation_id>";
4750
4872
  var RECENT_CYCLES = 20;
4873
+ var MAX_RERUNS_PER_CYCLE = 3;
4874
+ var SPLIT_STOP_AFTER_FAILURES = 2;
4875
+ var RUNTIME_CHECK_TIMEOUT_MS = 6e4;
4876
+ var AWAITING_EVIDENCE_MS = 10 * 6e4;
4877
+ var EVIDENCE_MEMORY = 100;
4751
4878
  var Pacer = class {
4752
4879
  constructor(paceMs, now2) {
4753
4880
  this.paceMs = paceMs;
@@ -4781,6 +4908,29 @@ var Pacer = class {
4781
4908
  for (const key of [...this.until.keys()]) if (key.startsWith("invite:")) this.until.delete(key);
4782
4909
  }
4783
4910
  };
4911
+ function clears(completion, failure) {
4912
+ return completion.kind === failure.source && completion.conversations.has(failure.conversationId);
4913
+ }
4914
+ function evidences(completion, failure) {
4915
+ return completion.kind === failure.source && completion.at > failure.startedAt && completion.conversations.size > 0 && !completion.conversations.has(failure.conversationId);
4916
+ }
4917
+ var EvidenceClock = class {
4918
+ last = 0;
4919
+ completions = [];
4920
+ start() {
4921
+ return ++this.last;
4922
+ }
4923
+ complete(kind, conversations) {
4924
+ const entry = { at: ++this.last, kind, conversations: new Set(conversations) };
4925
+ this.completions.push(entry);
4926
+ if (this.completions.length > EVIDENCE_MEMORY) this.completions.shift();
4927
+ return entry;
4928
+ }
4929
+ /** A completion since the failed attempt started that is evidence for it (`evidences`). */
4930
+ since(failure) {
4931
+ return this.completions.some((c) => evidences(c, failure));
4932
+ }
4933
+ };
4784
4934
  var ReceiveLoop = class {
4785
4935
  options;
4786
4936
  client;
@@ -4798,7 +4948,51 @@ var ReceiveLoop = class {
4798
4948
  /** When a single-run invite's silent run was counted (D5 pacing in single-run mode). */
4799
4949
  silentAt = /* @__PURE__ */ new Map();
4800
4950
  paceMs;
4951
+ /** Turns and runs waiting for a slot; `drop` ends what else the entry holds (an invite run's other invites). */
4801
4952
  waiting = [];
4953
+ /** Conversation and invite runs started and not yet concluded: `idle()` and `stop()` wait for them. */
4954
+ runWork = /* @__PURE__ */ new Set();
4955
+ /** Could not process: the order of attempts and completions. */
4956
+ evidence = new EvidenceClock();
4957
+ /** Could not process: failures waiting for a completion (the evidence a report needs), by conversation. */
4958
+ awaitingEvidence = /* @__PURE__ */ new Map();
4959
+ /** Waiting failures the runtime check has already been asked about (once each). */
4960
+ checkedFailures = /* @__PURE__ */ new WeakSet();
4961
+ /**
4962
+ * Per kind of work, the conversations whose attempt failed since that kind
4963
+ * last completed. Two or more: several failing together is the runtime, so
4964
+ * a passing `checkRuntime()` is no evidence for any of them.
4965
+ */
4966
+ failingSince = { gate: /* @__PURE__ */ new Set(), turn: /* @__PURE__ */ new Set(), run: /* @__PURE__ */ new Set() };
4967
+ /** gateCall: conversations whose last gate call failed; gated alone, after the others. */
4968
+ gateAlone = /* @__PURE__ */ new Set();
4969
+ /**
4970
+ * gateCall: the running cycle's gate: its cards (`members`) and its
4971
+ * single-card queue. A `retry` answer for one of its cards joins the queue;
4972
+ * a `hidden` one skips the card here (its card, read before the hide, is
4973
+ * stale) and gates it in the next cycle.
4974
+ */
4975
+ activeSplit = null;
4976
+ /**
4977
+ * gateCall: reply turns to start again on a `retry` / `hidden` answer that
4978
+ * came while a gate was deciding: they start after that cycle's own turns
4979
+ * (no turn starts while cards of a cycle still wait for their gate call).
4980
+ */
4981
+ turnRerunsAfterGate = [];
4982
+ lastRuntimeCheck = null;
4983
+ failureCounts = {
4984
+ reported: 0,
4985
+ retry: 0,
4986
+ hidden: 0,
4987
+ paused: 0,
4988
+ none: 0,
4989
+ reportErrors: 0,
4990
+ reruns: 0,
4991
+ rerunsCapped: 0,
4992
+ runtimeChecksOk: 0,
4993
+ runtimeChecksFailed: 0,
4994
+ splitsStopped: 0
4995
+ };
4802
4996
  /** Conversations whose verdict a gate call is recording right now (an abandoned cycle's included). */
4803
4997
  recordsInFlight = /* @__PURE__ */ new Set();
4804
4998
  /** Turns holding a slot (admitted, not yet ended or released). */
@@ -4833,6 +5027,8 @@ var ReceiveLoop = class {
4833
5027
  runsNotStarted: 0,
4834
5028
  chunksOk: 0,
4835
5029
  chunksFailed: 0,
5030
+ splitCallsOk: 0,
5031
+ splitCallsFailed: 0,
4836
5032
  outcomeRecordFailures: 0
4837
5033
  };
4838
5034
  outcomes = {};
@@ -4930,7 +5126,10 @@ var ReceiveLoop = class {
4930
5126
  this.clearMoreTimer();
4931
5127
  this.abort.abort();
4932
5128
  this.cycleAbort?.abort();
4933
- for (const { handle } of this.waiting.splice(0)) this.tracker.end(handle);
5129
+ for (const { handle, drop } of this.waiting.splice(0)) {
5130
+ this.tracker.end(handle);
5131
+ drop?.();
5132
+ }
4934
5133
  for (const off of this.unsubscribe.splice(0)) {
4935
5134
  try {
4936
5135
  off();
@@ -4942,11 +5141,21 @@ var ReceiveLoop = class {
4942
5141
  } catch {
4943
5142
  }
4944
5143
  await this.coalescer.idle();
4945
- await Promise.allSettled([...this.pendingWork]);
5144
+ await Promise.allSettled([...this.pendingWork, ...this.runWork]);
4946
5145
  }
4947
- /** Resolves when the running cycle has finished (tests, graceful stops). */
4948
- idle() {
4949
- return this.coalescer.idle();
5146
+ /**
5147
+ * Resolves when the running cycle has finished (tests, graceful stops) and,
5148
+ * in single-run mode, no run is running or waiting for a slot (conversation
5149
+ * runs go on after the cycle that started them). Gate-call turns are not
5150
+ * waited for.
5151
+ */
5152
+ async idle() {
5153
+ for (; ; ) {
5154
+ await this.coalescer.idle();
5155
+ const runs = [...this.runWork];
5156
+ if (runs.length === 0) return;
5157
+ await Promise.allSettled(runs);
5158
+ }
4950
5159
  }
4951
5160
  /** Let go of a turn whose end the runtime will never confirm (an operator's call). Nothing is recorded for it. */
4952
5161
  releaseTurn(key) {
@@ -4986,6 +5195,11 @@ var ReceiveLoop = class {
4986
5195
  turnsWaiting: this.waiting.length,
4987
5196
  outcomes: { ...this.outcomes }
4988
5197
  },
5198
+ processingFailures: {
5199
+ ...this.failureCounts,
5200
+ awaitingEvidence: this.awaitingEvidence.size,
5201
+ lastRuntimeCheck: this.lastRuntimeCheck === null ? null : { ...this.lastRuntimeCheck }
5202
+ },
4989
5203
  lastError: this.lastError
4990
5204
  };
4991
5205
  }
@@ -5037,7 +5251,7 @@ var ReceiveLoop = class {
5037
5251
  let excludedMs = 0;
5038
5252
  let excludedSince = null;
5039
5253
  let depth = 0;
5040
- const run2 = {
5254
+ const run3 = {
5041
5255
  token,
5042
5256
  signal: controller.signal,
5043
5257
  stale: () => this.cycleToken !== token || this.stopped,
@@ -5055,8 +5269,10 @@ var ReceiveLoop = class {
5055
5269
  }
5056
5270
  };
5057
5271
  const work = (async () => {
5058
- const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(run2) : await this.singleRunCycle(run2);
5059
- if (!run2.abandoned()) this.finishCycle(summary);
5272
+ const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(run3) : await this.singleRunCycle(run3);
5273
+ if (!run3.abandoned()) this.finishCycle(summary);
5274
+ this.flushTurnReruns();
5275
+ void this.track(this.checkParked(this.options.mode === "gateCall" ? "turn" : "run"));
5060
5276
  })();
5061
5277
  let timer = null;
5062
5278
  const overdue = new Promise((resolve) => {
@@ -5100,7 +5316,7 @@ var ReceiveLoop = class {
5100
5316
  * an abandoned cycle: the server may already have taken it, and a second
5101
5317
  * one could climb the defer ladder twice.
5102
5318
  */
5103
- recordingClient(run2) {
5319
+ recordingClient(run3) {
5104
5320
  const decisions = this.client.decisions;
5105
5321
  return {
5106
5322
  decisions: {
@@ -5110,7 +5326,7 @@ var ReceiveLoop = class {
5110
5326
  return await decisions.record(conversationId, options);
5111
5327
  } finally {
5112
5328
  this.recordsInFlight.delete(conversationId);
5113
- if (run2.stale()) this.afterTurnEnded();
5329
+ if (run3.stale()) this.afterTurnEnded();
5114
5330
  }
5115
5331
  }
5116
5332
  }
@@ -5124,44 +5340,46 @@ var ReceiveLoop = class {
5124
5340
  * cycle that is making progress is not abandoned for it. With the deadline
5125
5341
  * off the watchdog is the calls' only bound, so they count.
5126
5342
  */
5127
- boundedModelCall(run2) {
5128
- const call = this.deadlineModelCall(run2);
5129
- if (!Number.isFinite(this.gateCallTimeoutMs)) return call;
5130
- return (prompt, options) => run2.exclude(() => call(prompt, options));
5343
+ boundedModelCall(run3, timedOut) {
5344
+ const call2 = this.deadlineModelCall(run3, timedOut);
5345
+ if (!Number.isFinite(this.gateCallTimeoutMs)) return call2;
5346
+ return (prompt, options) => run3.exclude(() => call2(prompt, options));
5131
5347
  }
5132
- deadlineModelCall(run2) {
5348
+ /** `timedOut` is set when a call runs past its deadline (a could-not-process report then says `timed_out`). */
5349
+ deadlineModelCall(run3, timedOut) {
5133
5350
  return (prompt) => new Promise((resolve, reject) => {
5134
5351
  const controller = new AbortController();
5135
5352
  const abort = () => {
5136
5353
  controller.abort();
5137
5354
  reject(new Error("the cycle was abandoned"));
5138
5355
  };
5139
- if (run2.signal.aborted) {
5356
+ if (run3.signal.aborted) {
5140
5357
  abort();
5141
5358
  return;
5142
5359
  }
5143
- run2.signal.addEventListener("abort", abort, { once: true });
5360
+ run3.signal.addEventListener("abort", abort, { once: true });
5144
5361
  const timer = Number.isFinite(this.gateCallTimeoutMs) ? this._setTimeout(() => {
5145
- run2.signal.removeEventListener("abort", abort);
5362
+ run3.signal.removeEventListener("abort", abort);
5363
+ if (timedOut) timedOut.value = true;
5146
5364
  controller.abort();
5147
5365
  reject(new Error(`no answer within ${this.gateCallTimeoutMs} ms`));
5148
5366
  }, this.gateCallTimeoutMs) : null;
5149
5367
  if (timer !== null) timer.unref?.();
5150
- let call;
5368
+ let call2;
5151
5369
  try {
5152
- call = Promise.resolve(this.options.callModel(prompt, { signal: controller.signal }));
5370
+ call2 = Promise.resolve(this.options.callModel(prompt, { signal: controller.signal }));
5153
5371
  } catch (err) {
5154
- call = Promise.reject(err);
5372
+ call2 = Promise.reject(err);
5155
5373
  }
5156
- call.then(
5157
- (text) => {
5374
+ call2.then(
5375
+ (text2) => {
5158
5376
  if (timer !== null) this._clearTimeout(timer);
5159
- run2.signal.removeEventListener("abort", abort);
5160
- resolve(text);
5377
+ run3.signal.removeEventListener("abort", abort);
5378
+ resolve(text2);
5161
5379
  },
5162
5380
  (err) => {
5163
5381
  if (timer !== null) this._clearTimeout(timer);
5164
- run2.signal.removeEventListener("abort", abort);
5382
+ run3.signal.removeEventListener("abort", abort);
5165
5383
  reject(err);
5166
5384
  }
5167
5385
  );
@@ -5189,9 +5407,9 @@ var ReceiveLoop = class {
5189
5407
  return err instanceof Error ? err.message : String(err);
5190
5408
  }
5191
5409
  }
5192
- async gateCallCycle(run2) {
5410
+ async gateCallCycle(run3) {
5193
5411
  const tray = await this.readTray();
5194
- if (run2.stale()) return this.summary("abandoned");
5412
+ if (run3.stale()) return this.summary("abandoned");
5195
5413
  if (tray === null) return this.summary("tray_failed", { failure: this.lastError });
5196
5414
  const cards = cardsOf(tray);
5197
5415
  const invites = trayInvites(tray);
@@ -5207,10 +5425,10 @@ var ReceiveLoop = class {
5207
5425
  if (cards.length === 0 && invites.length === 0) return this.summary("empty", base);
5208
5426
  if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
5209
5427
  const texts = await this.options.texts.ensure();
5210
- if (run2.stale()) return this.summary("abandoned", base);
5428
+ if (run3.stale()) return this.summary("abandoned", base);
5211
5429
  if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
5212
5430
  const unready = await this.checkReady();
5213
- if (run2.stale()) return this.summary("abandoned", base);
5431
+ if (run3.stale()) return this.summary("abandoned", base);
5214
5432
  if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5215
5433
  const tally = {
5216
5434
  gated: 0,
@@ -5224,13 +5442,16 @@ var ReceiveLoop = class {
5224
5442
  turnsRefused: 0,
5225
5443
  turnsQueued: 0,
5226
5444
  chunksOk: 0,
5227
- chunksFailed: 0
5445
+ chunksFailed: 0,
5446
+ splitCallsOk: 0,
5447
+ splitCallsFailed: 0
5228
5448
  };
5229
5449
  let heldDuringGate = 0;
5450
+ let splitStopped = false;
5230
5451
  let outcome = "invites_only";
5231
5452
  let failure = null;
5232
5453
  if (owedCards.length > 0) {
5233
- const gate = await this.gateInChunks(run2, tray, gateCards, texts);
5454
+ const gate = await this.gateInChunks(run3, tray, gateCards, texts);
5234
5455
  heldDuringGate = gate.held;
5235
5456
  tally.gated = gate.gated;
5236
5457
  tally.reply = gate.verdicts.reply;
@@ -5241,25 +5462,28 @@ var ReceiveLoop = class {
5241
5462
  tally.recordFailures = gate.recordFailures;
5242
5463
  tally.chunksOk = gate.chunks.filter((c) => c.outcome === "decided").length;
5243
5464
  tally.chunksFailed = gate.chunks.length - tally.chunksOk;
5244
- failure = chunkFailure(gate.chunks);
5245
- if (tally.chunksOk > 0) {
5465
+ tally.splitCallsOk = gate.split.filter((c) => c.outcome === "decided").length;
5466
+ tally.splitCallsFailed = gate.split.length - tally.splitCallsOk;
5467
+ splitStopped = gate.splitStopped;
5468
+ failure = gateFailureText(gate.chunks, gate.split);
5469
+ if (tally.chunksOk + tally.splitCallsOk > 0) {
5246
5470
  outcome = "decided";
5247
5471
  for (const reply of gate.reply) {
5248
- if (run2.stale()) break;
5249
- tally[launchKey(await run2.exclude(() => this.startReplyTurn(reply, texts)))] += 1;
5472
+ if (run3.stale()) break;
5473
+ tally[launchKey(await run3.exclude(() => this.startReplyTurn(reply, texts)))] += 1;
5250
5474
  }
5251
- } else if (tally.chunksFailed > 0) {
5475
+ } else if (tally.chunksFailed + tally.splitCallsFailed > 0) {
5252
5476
  outcome = "fail_closed";
5253
- } else if (owedInvites.length === 0 && !run2.stale()) {
5477
+ } else if (owedInvites.length === 0 && !run3.stale()) {
5254
5478
  return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate });
5255
5479
  }
5256
5480
  }
5257
5481
  for (const invite of owedInvites) {
5258
- if (run2.stale()) break;
5259
- tally[launchKey(await run2.exclude(() => this.startInviteTurn(invite, texts)))] += 1;
5482
+ if (run3.stale()) break;
5483
+ tally[launchKey(await run3.exclude(() => this.startInviteTurn(invite, texts)))] += 1;
5260
5484
  }
5261
- const parts = { ...base, heldByTurns: heldByTurns + heldDuringGate, ...tally };
5262
- if (run2.stale()) return this.summary("abandoned", parts);
5485
+ const parts = { ...base, heldByTurns: heldByTurns + heldDuringGate, ...tally, splitStopped };
5486
+ if (run3.stale()) return this.summary("abandoned", parts);
5263
5487
  if (tray.truncated === true && outcome === "decided") {
5264
5488
  this.readTheRest(tally.recorded > 0 || tally.turnsStarted > 0);
5265
5489
  }
@@ -5286,12 +5510,22 @@ var ReceiveLoop = class {
5286
5510
  * cards only (or none) is not called. Stops once the cycle is stale; a call
5287
5511
  * a stop cut short is not counted as a failed chunk, and a cycle the
5288
5512
  * watchdog abandoned reports and counts no chunk after its summary.
5513
+ *
5514
+ * The split (could not process): every owed card of a chunk of more than
5515
+ * one card that failed closed is then gated again alone, one call per card,
5516
+ * in tray order, before any turn starts, so one card the model cannot
5517
+ * handle fails only its own call. A card whose last gate call failed is
5518
+ * kept out of the chunks and gated alone after them. A single-card call that
5519
+ * fails is the card's failure (reported with evidence; a `retry` answer
5520
+ * gates it once more at the end of the queue). When the queue is empty, a
5521
+ * failure still waiting gets the runtime check. After
5522
+ * `SPLIT_STOP_AFTER_FAILURES` single-card calls in a row failed with nothing
5523
+ * decided in the cycle, the split goes on only if `checkRuntime()` passes;
5524
+ * otherwise it stops (`split_stopped`).
5289
5525
  */
5290
- async gateInChunks(run2, tray, cards, texts) {
5526
+ async gateInChunks(run3, tray, cards, texts) {
5291
5527
  const size = this.gateChunkSize;
5292
- const of = Math.ceil(cards.length / size);
5293
- const callModel = this.boundedModelCall(run2);
5294
- const client = this.recordingClient(run2);
5528
+ const client = this.recordingClient(run3);
5295
5529
  const out = {
5296
5530
  gated: 0,
5297
5531
  held: 0,
@@ -5300,48 +5534,165 @@ var ReceiveLoop = class {
5300
5534
  undecided: 0,
5301
5535
  recorded: 0,
5302
5536
  recordFailures: 0,
5303
- chunks: []
5537
+ chunks: [],
5538
+ split: [],
5539
+ splitStopped: false
5304
5540
  };
5305
- for (let index = 1; index <= of; index++) {
5306
- if (run2.stale()) break;
5307
- const planned = cards.slice((index - 1) * size, index * size);
5308
- const chunk = this.unheld(planned);
5309
- out.held += planned.length - chunk.length;
5310
- if (chunk.length < planned.length) this.heldWhileRunning = true;
5311
- if (!chunk.some((card) => card.muted !== true)) continue;
5312
- const result = await run({
5313
- tray: { ...tray, conversations: chunk },
5314
- callModel,
5315
- client,
5316
- texts,
5317
- signal: run2.signal,
5318
- ...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
5319
- });
5320
- if (run2.abandoned()) break;
5321
- if (run2.stale() && result.outcome !== "decided") break;
5322
- out.gated += chunk.length;
5541
+ const gated = /* @__PURE__ */ new Set();
5542
+ const decided = /* @__PURE__ */ new Set();
5543
+ const take = (result, sent) => {
5544
+ for (const card of sent) gated.add(card.conversation_id);
5323
5545
  const undecided = new Set(result.undecided);
5324
5546
  for (const verdict of result.verdicts) {
5325
- if (!undecided.has(verdict.conversation_id)) out.verdicts[verdict.decision] += 1;
5547
+ if (undecided.has(verdict.conversation_id) || decided.has(verdict.conversation_id)) continue;
5548
+ decided.add(verdict.conversation_id);
5549
+ out.verdicts[verdict.decision] += 1;
5326
5550
  }
5327
5551
  out.reply.push(...result.reply);
5328
- out.undecided += result.undecided.length;
5329
5552
  out.recorded += result.recorded;
5330
5553
  out.recordFailures += result.recordFailures.length;
5331
- const report = {
5332
- cycle: run2.token,
5333
- index,
5334
- of,
5335
- cards: chunk.length,
5336
- outcome: result.outcome === "decided" ? "decided" : "fail_closed",
5337
- undecided: result.undecided.length,
5338
- failure: result.failure
5339
- };
5340
- out.chunks.push(report);
5341
- if (report.outcome === "decided") this.counts.chunksOk += 1;
5342
- else this.counts.chunksFailed += 1;
5343
- this.emit({ type: "gate_chunk", ...report });
5554
+ };
5555
+ const gateOne = (card, timedOut) => run({
5556
+ tray: { ...tray, conversations: [card] },
5557
+ callModel: this.boundedModelCall(run3, timedOut),
5558
+ client,
5559
+ texts,
5560
+ signal: run3.signal,
5561
+ ...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
5562
+ });
5563
+ const queue = [];
5564
+ const alone = cards.filter((card) => card.muted !== true && this.gateAlone.has(card.conversation_id));
5565
+ const chunked = alone.length === 0 ? cards : cards.filter((card) => !alone.includes(card));
5566
+ const split = {
5567
+ token: run3.token,
5568
+ members: new Map(cards.map((card) => [card.conversation_id, card])),
5569
+ queue,
5570
+ skip: /* @__PURE__ */ new Set()
5571
+ };
5572
+ this.activeSplit = split;
5573
+ try {
5574
+ const of = Math.ceil(chunked.length / size);
5575
+ for (let index2 = 1; index2 <= of; index2++) {
5576
+ if (run3.stale()) break;
5577
+ const planned = chunked.slice((index2 - 1) * size, index2 * size);
5578
+ const chunk = this.unheld(planned);
5579
+ out.held += planned.length - chunk.length;
5580
+ if (chunk.length < planned.length) this.heldWhileRunning = true;
5581
+ if (!chunk.some((card) => card.muted !== true)) continue;
5582
+ const startedAt = this.evidence.start();
5583
+ const timedOut = { value: false };
5584
+ const result = await run({
5585
+ tray: { ...tray, conversations: chunk },
5586
+ callModel: this.boundedModelCall(run3, timedOut),
5587
+ client,
5588
+ texts,
5589
+ signal: run3.signal,
5590
+ ...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
5591
+ });
5592
+ if (run3.abandoned()) break;
5593
+ if (run3.stale() && result.outcome !== "decided") break;
5594
+ take(result, chunk);
5595
+ const report = {
5596
+ cycle: run3.token,
5597
+ index: index2,
5598
+ of,
5599
+ cards: chunk.length,
5600
+ outcome: result.outcome === "decided" ? "decided" : "fail_closed",
5601
+ undecided: result.undecided.length,
5602
+ failure: result.failure
5603
+ };
5604
+ out.chunks.push(report);
5605
+ if (report.outcome === "decided") this.counts.chunksOk += 1;
5606
+ else this.counts.chunksFailed += 1;
5607
+ this.emit({ type: "gate_chunk", ...report });
5608
+ if (report.outcome === "decided") {
5609
+ const through = decidedBy(result);
5610
+ for (const id of through) this.gateAlone.delete(id);
5611
+ await run3.exclude(() => this.reportDue(this.completed("gate", through)));
5612
+ continue;
5613
+ }
5614
+ this.failedAttempt("gate", chunk.filter((card) => card.muted !== true).map((card) => card.conversation_id));
5615
+ if (chunk.length === 1) {
5616
+ this.rememberGateAlone(chunk[0].conversation_id);
5617
+ await run3.exclude(() => this.failed(gateFailure(chunk[0], startedAt, 0, timedOut.value, this.now())));
5618
+ } else {
5619
+ for (const card of chunk) if (card.muted !== true) queue.push({ card, reruns: 0 });
5620
+ }
5621
+ }
5622
+ for (const card of alone) {
5623
+ if (!queue.some((item) => item.card.conversation_id === card.conversation_id)) queue.push({ card, reruns: 0 });
5624
+ }
5625
+ let index = 0;
5626
+ let failuresInARow = 0;
5627
+ splitting: for (; ; ) {
5628
+ while (queue.length > 0) {
5629
+ if (run3.stale()) break splitting;
5630
+ const { card, reruns } = queue.shift();
5631
+ const id = card.conversation_id;
5632
+ if (decided.has(id) || split.skip.has(id)) continue;
5633
+ if (this.unheld([card]).length === 0) {
5634
+ if (!gated.has(id)) out.held += 1;
5635
+ this.heldWhileRunning = true;
5636
+ continue;
5637
+ }
5638
+ index += 1;
5639
+ const startedAt = this.evidence.start();
5640
+ const timedOut = { value: false };
5641
+ const result = await gateOne(card, timedOut);
5642
+ if (run3.abandoned()) break splitting;
5643
+ if (run3.stale() && result.outcome !== "decided") break splitting;
5644
+ take(result, [card]);
5645
+ const report = {
5646
+ cycle: run3.token,
5647
+ index,
5648
+ of: index + queue.length,
5649
+ cards: 1,
5650
+ outcome: result.outcome === "decided" ? "decided" : "fail_closed",
5651
+ undecided: result.undecided.length,
5652
+ failure: result.failure,
5653
+ split: true,
5654
+ conversationId: id
5655
+ };
5656
+ out.split.push(report);
5657
+ if (report.outcome === "decided") this.counts.splitCallsOk += 1;
5658
+ else this.counts.splitCallsFailed += 1;
5659
+ this.emit({ type: "gate_chunk", ...report });
5660
+ if (report.outcome === "decided") {
5661
+ failuresInARow = 0;
5662
+ this.gateAlone.delete(id);
5663
+ await run3.exclude(() => this.reportDue(this.completed("gate", decidedBy(result))));
5664
+ continue;
5665
+ }
5666
+ this.rememberGateAlone(id);
5667
+ this.failedAttempt("gate", [id]);
5668
+ await run3.exclude(() => this.failed(gateFailure(card, startedAt, reruns, timedOut.value, this.now())));
5669
+ failuresInARow += 1;
5670
+ if (failuresInARow >= SPLIT_STOP_AFTER_FAILURES && decided.size === 0) {
5671
+ const ok = this.options.checkRuntime ? await run3.exclude(() => this.runtimeCheck()) : false;
5672
+ if (run3.stale()) break splitting;
5673
+ if (!ok) {
5674
+ out.splitStopped = true;
5675
+ this.failureCounts.splitsStopped += 1;
5676
+ this.emit({
5677
+ type: "split_stopped",
5678
+ cycle: run3.token,
5679
+ remaining: queue.filter((item) => !decided.has(item.card.conversation_id)).length,
5680
+ reason: this.options.checkRuntime ? "runtime_check_failed" : "no_runtime_check"
5681
+ });
5682
+ break splitting;
5683
+ }
5684
+ failuresInARow = 0;
5685
+ }
5686
+ }
5687
+ if (run3.stale()) break;
5688
+ await run3.exclude(() => this.checkParked("gate"));
5689
+ if (queue.length === 0) break;
5690
+ }
5691
+ } finally {
5692
+ if (this.activeSplit === split) this.activeSplit = null;
5344
5693
  }
5694
+ out.gated = gated.size;
5695
+ out.undecided = gated.size - decided.size;
5345
5696
  return out;
5346
5697
  }
5347
5698
  /**
@@ -5373,9 +5724,9 @@ var ReceiveLoop = class {
5373
5724
  this.moreTimer = null;
5374
5725
  }
5375
5726
  }
5376
- async singleRunCycle(run2) {
5727
+ async singleRunCycle(run3) {
5377
5728
  const tray = await this.readTray();
5378
- if (run2.stale()) return this.summary("abandoned");
5729
+ if (run3.stale()) return this.summary("abandoned");
5379
5730
  let cards = null;
5380
5731
  let invites = null;
5381
5732
  let base = { cards: 0, invites: 0, heldByTurns: 0, truncated: false };
@@ -5387,29 +5738,196 @@ var ReceiveLoop = class {
5387
5738
  if (cards === 0 && invites === 0) return this.summary("nothing_owed", base);
5388
5739
  }
5389
5740
  const texts = await this.options.texts.ensure();
5390
- if (run2.stale()) return this.summary("abandoned", base);
5741
+ if (run3.stale()) return this.summary("abandoned", base);
5391
5742
  if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
5743
+ if (this.options.conversationRuns !== false && conversationRunTemplate(texts) !== null) {
5744
+ if (tray !== null) return this.conversationRunCycle(run3, tray, texts);
5745
+ if (this.runWork.size > 0 || this.waiting.length > 0) this.heldWhileRunning = true;
5746
+ return this.summary("tray_failed", { ...base, failure: this.lastError });
5747
+ }
5392
5748
  const unready = await this.checkReady();
5393
- if (run2.stale()) return this.summary("abandoned", base);
5749
+ if (run3.stale()) return this.summary("abandoned", base);
5394
5750
  if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5395
5751
  const prompt = cards === 0 && (invites ?? 0) > 0 ? texts.invite_prompt.trim() : (invites ?? 0) > 0 ? `${texts.wake_instruction.trim()}
5396
5752
 
5397
5753
  ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5754
+ const kind = cards === 0 && (invites ?? 0) > 0 ? "invite" : "tray";
5398
5755
  this.counts.runsStarted += 1;
5399
- let end;
5756
+ const end = await run3.exclude(() => this.callRun({ prompt, texts, cards, invites, signal: this.abort.signal, kind }));
5757
+ this.countRunEnd(end);
5758
+ this.emit({ type: "run", end, kind });
5759
+ const startedWith = tray === null || this.options.dismissIgnoredInvites === false ? [] : trayInvites(tray);
5760
+ if (startedWith.length > 0) await this.track(this.afterRunInvites(startedWith, end));
5761
+ const outcome = end.status === "completed" ? "run_completed" : end.status === "failed" ? "run_failed" : "run_not_started";
5762
+ return this.summary(outcome, { ...base, failure: end.status === "completed" ? null : end.detail ?? null });
5763
+ }
5764
+ /**
5765
+ * Conversation runs (single-run mode, texts with `conversation_run_template`):
5766
+ * one run per owed card (unmuted, with a preview: a notices-only card is not
5767
+ * owed), prompted for that one conversation, and one invite run for the
5768
+ * pending invites. A conversation whose run is running or
5769
+ * waiting for a slot is held out (the tracker), and so is one paced after a
5770
+ * completed run that left its card at the same anchor (D5). Runs take a slot
5771
+ * each (`maxConcurrentTurns`) in the order queued: the cards whose last run
5772
+ * failed go last, after the invite run, so they never hold up the others.
5773
+ * The loop records no verdict for a card: the run decides.
5774
+ */
5775
+ async conversationRunCycle(run3, tray, texts) {
5776
+ const cards = cardsOf(tray);
5777
+ const invites = trayInvites(tray);
5778
+ const unheld = this.unheld(cards);
5779
+ const heldByTurns = cards.length - unheld.length;
5780
+ if (heldByTurns > 0) this.heldWhileRunning = true;
5781
+ const runCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
5782
+ const openInvites = invites.filter((invite) => !this.tracker.inviteRunning(invite.invite_id));
5783
+ const owedInvites = openInvites.filter((invite) => !this.pacer.held(`invite:${invite.invite_id}`, null));
5784
+ const paced = unheld.length - runCards.length + (openInvites.length - owedInvites.length);
5785
+ 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 };
5787
+ if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
5788
+ const unready = await this.checkReady();
5789
+ if (run3.stale()) return this.summary("abandoned", base);
5790
+ if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5791
+ const tally = { turnsStarted: 0, turnsRefused: 0, turnsQueued: 0 };
5792
+ const failedLast = owedCards.filter((card) => this.awaitingEvidence.has(card.conversation_id));
5793
+ for (const card of owedCards.filter((card2) => !failedLast.includes(card2))) {
5794
+ if (run3.stale()) break;
5795
+ tally[launchKey(await this.startConversationRun(card, texts))] += 1;
5796
+ }
5797
+ if (owedInvites.length > 0 && !run3.stale()) tally[launchKey(await this.startInviteRun(owedInvites, texts))] += 1;
5798
+ for (const card of failedLast) {
5799
+ if (run3.stale()) break;
5800
+ tally[launchKey(await this.startConversationRun(card, texts))] += 1;
5801
+ }
5802
+ const parts = { ...base, ...tally };
5803
+ if (run3.stale()) return this.summary("abandoned", parts);
5804
+ const launched = tally.turnsStarted + tally.turnsQueued;
5805
+ if (tray.truncated === true) this.readTheRest(launched > 0);
5806
+ return this.summary(launched > 0 ? "runs_started" : "nothing_owed", parts);
5807
+ }
5808
+ /** One conversation run: a slot (or a place in the queue), the run, then what its end says. */
5809
+ async startConversationRun(card, texts, reruns = 0) {
5810
+ const conversationId = card.conversation_id;
5811
+ const anchor = anchorFrom(card);
5812
+ const handle = this.tracker.begin({ kind: "reply", conversationId, anchor });
5813
+ if (handle === null) return "refused";
5814
+ const request = {
5815
+ kind: "conversation",
5816
+ conversationId,
5817
+ prompt: conversationRunPrompt(texts, conversationId),
5818
+ texts,
5819
+ cards: 1,
5820
+ invites: 0,
5821
+ signal: this.abort.signal
5822
+ };
5823
+ return this.launch(handle, async () => {
5824
+ const attempt = { conversationId, source: "run", card, anchor, startedAt: this.evidence.start(), reruns };
5825
+ this.counts.runsStarted += 1;
5826
+ this.trackRun(this.afterConversationRun(handle, attempt, this.callRun(request)));
5827
+ return true;
5828
+ });
5829
+ }
5830
+ async afterConversationRun(handle, attempt, done) {
5831
+ const end = await done;
5832
+ const held = this.tracker.holds(handle);
5833
+ let completion = null;
5834
+ let failure = null;
5400
5835
  try {
5401
- end = await run2.exclude(() => this.options.startRun({ prompt, texts, cards, invites, signal: this.abort.signal }));
5402
- } catch (err) {
5403
- end = { status: "not_started", detail: err instanceof Error ? err.message : String(err) };
5836
+ this.countRunEnd(end);
5837
+ this.emit({ type: "run", end, kind: "conversation", conversationId: attempt.conversationId });
5838
+ if (!held) return;
5839
+ if (end.status === "completed") {
5840
+ completion = this.completed("run", [attempt.conversationId]);
5841
+ this.pacer.hold(`conversation:${attempt.conversationId}`, attempt.anchor);
5842
+ } else if (end.status === "failed" && !this.stopped) {
5843
+ this.failedAttempt("run", [attempt.conversationId]);
5844
+ if (untouched(attempt.card, await this.readTray())) {
5845
+ failure = { ...attempt, outcome: end.timedOut === true ? "timed_out" : "failed", failedAt: this.now(), holding: handle };
5846
+ }
5847
+ }
5848
+ } finally {
5849
+ if (failure === null) this.tracker.end(handle);
5850
+ this.releaseSlot(handle);
5851
+ if (failure === null) this.afterTurnEnded();
5852
+ }
5853
+ if (failure !== null) {
5854
+ try {
5855
+ if (!this.stopped) await this.failed(failure);
5856
+ } finally {
5857
+ this.tracker.end(handle);
5858
+ this.afterTurnEnded();
5859
+ }
5860
+ }
5861
+ if (!this.stopped && completion !== null) await this.reportDue(completion);
5862
+ await this.checkParked("run");
5863
+ }
5864
+ /** The invite run: one run for the pending invites, holding each of them until it ends. */
5865
+ async startInviteRun(invites, texts) {
5866
+ const handles = [];
5867
+ const held = [];
5868
+ for (const invite of invites) {
5869
+ const handle = this.tracker.begin({ kind: "invite", inviteId: invite.invite_id });
5870
+ if (handle === null) continue;
5871
+ handles.push(handle);
5872
+ held.push(invite);
5873
+ }
5874
+ const slot = handles[0];
5875
+ if (slot === void 0) return "refused";
5876
+ const endAll = () => {
5877
+ for (const handle of handles) this.tracker.end(handle);
5878
+ };
5879
+ const request = {
5880
+ kind: "invite",
5881
+ prompt: texts.invite_prompt.trim(),
5882
+ texts,
5883
+ cards: 0,
5884
+ invites: held.length,
5885
+ signal: this.abort.signal
5886
+ };
5887
+ return this.launch(
5888
+ slot,
5889
+ async () => {
5890
+ this.counts.runsStarted += 1;
5891
+ this.trackRun(this.afterInviteRun(slot, held, endAll, this.callRun(request)));
5892
+ return true;
5893
+ },
5894
+ endAll
5895
+ );
5896
+ }
5897
+ async afterInviteRun(slot, invites, endAll, done) {
5898
+ const end = await done;
5899
+ const held = this.tracker.holds(slot);
5900
+ let completion = null;
5901
+ try {
5902
+ this.countRunEnd(end);
5903
+ this.emit({ type: "run", end, kind: "invite" });
5904
+ if (!held) return;
5905
+ if (end.status === "completed") {
5906
+ completion = this.completed("invite", []);
5907
+ for (const invite of invites) this.pacer.hold(`invite:${invite.invite_id}`, null);
5908
+ }
5909
+ if (this.options.dismissIgnoredInvites !== false) await this.afterRunInvites(invites, end);
5910
+ } finally {
5911
+ endAll();
5912
+ this.releaseSlot(slot);
5913
+ this.afterTurnEnded();
5404
5914
  }
5915
+ if (!this.stopped && completion !== null) await this.reportDue(completion);
5916
+ await this.checkParked("run");
5917
+ }
5918
+ /** The runtime's `startRun`, never rejecting: a throw is a run that did not start. */
5919
+ callRun(request) {
5920
+ return Promise.resolve().then(() => this.options.startRun(request)).catch((err) => ({ status: "not_started", detail: err instanceof Error ? err.message : String(err) }));
5921
+ }
5922
+ countRunEnd(end) {
5405
5923
  if (end.status === "completed") this.counts.runsCompleted += 1;
5406
5924
  else if (end.status === "failed") this.counts.runsFailed += 1;
5407
5925
  else this.counts.runsNotStarted += 1;
5408
- this.emit({ type: "run", end });
5409
- const startedWith = tray === null || this.options.dismissIgnoredInvites === false ? [] : trayInvites(tray);
5410
- if (startedWith.length > 0) await this.track(this.afterRunInvites(startedWith, end));
5411
- const outcome = end.status === "completed" ? "run_completed" : end.status === "failed" ? "run_failed" : "run_not_started";
5412
- return this.summary(outcome, { ...base, failure: end.status === "completed" ? null : end.detail ?? null });
5926
+ }
5927
+ /** A run's whole course after its start: `idle()` and `stop()` wait for it. */
5928
+ trackRun(work) {
5929
+ const tracked = work.catch((err) => this.fail(err)).finally(() => this.runWork.delete(tracked));
5930
+ this.runWork.add(tracked);
5413
5931
  }
5414
5932
  async afterRunInvites(invites, end) {
5415
5933
  const completed = end.status === "completed";
@@ -5420,7 +5938,7 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5420
5938
  }
5421
5939
  }
5422
5940
  // ─── turns (gate-call mode) ─────────────────────────────────────────────
5423
- async startReplyTurn(reply, texts) {
5941
+ async startReplyTurn(reply, texts, reruns = 0) {
5424
5942
  const anchor = anchorFrom(reply.card);
5425
5943
  const handle = this.tracker.begin({ kind: "reply", conversationId: reply.conversationId, anchor });
5426
5944
  if (handle === null) return "refused";
@@ -5435,6 +5953,7 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5435
5953
  signal: this.abort.signal
5436
5954
  };
5437
5955
  return this.launch(handle, async () => {
5956
+ const startedAt = this.evidence.start();
5438
5957
  const admission = await this.admit(this.options.startTurn, request);
5439
5958
  if (!admission.started) {
5440
5959
  this.tracker.end(handle);
@@ -5444,7 +5963,8 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5444
5963
  }
5445
5964
  this.counts.turnsStarted += 1;
5446
5965
  this.emit({ type: "turn_started", request: withoutRuntime(request) });
5447
- void this.afterReplyTurn(handle, reply, admission.done);
5966
+ const attempt = { conversationId: reply.conversationId, source: "turn", card: reply.card, anchor, startedAt, reruns, reply };
5967
+ void this.afterReplyTurn(handle, attempt, admission.done);
5448
5968
  return true;
5449
5969
  });
5450
5970
  }
@@ -5484,9 +6004,9 @@ invite_id: ${invite.invite_id}`,
5484
6004
  * queues behind them instead of taking the slot. A refused admission here
5485
6005
  * hands its slot on the same way.
5486
6006
  */
5487
- async launch(handle, admit) {
6007
+ async launch(handle, admit, drop) {
5488
6008
  if (this.waiting.length > 0 || this.activeTurns >= this.maxTurns) {
5489
- this.waiting.push({ handle, admit });
6009
+ this.waiting.push({ handle, admit, ...drop ? { drop } : {} });
5490
6010
  this.counts.turnsQueued += 1;
5491
6011
  if (this.activeTurns < this.maxTurns) void this.pump();
5492
6012
  return "queued";
@@ -5506,7 +6026,7 @@ invite_id: ${invite.invite_id}`,
5506
6026
  releaseSlot(handle, options = {}) {
5507
6027
  if (this.slotted.delete(handle)) this.activeTurns = Math.max(0, this.activeTurns - 1);
5508
6028
  const queued = this.waiting.findIndex((w) => w.handle === handle);
5509
- if (queued >= 0) this.waiting.splice(queued, 1);
6029
+ if (queued >= 0) this.waiting.splice(queued, 1)[0].drop?.();
5510
6030
  if (options.pump !== false) void this.pump();
5511
6031
  }
5512
6032
  async pump() {
@@ -5516,20 +6036,38 @@ invite_id: ${invite.invite_id}`,
5516
6036
  await this.admitInSlot(next.handle, next.admit);
5517
6037
  }
5518
6038
  }
5519
- async afterReplyTurn(handle, reply, done) {
6039
+ async afterReplyTurn(handle, attempt, done) {
6040
+ const reply = attempt.reply;
6041
+ let completion = null;
6042
+ let failure = null;
5520
6043
  try {
5521
6044
  const end = await this.tracker.confirmedEnd(handle, done);
5522
6045
  if (end === null || !this.tracker.holds(handle)) return;
5523
- await this.track(this.recordReplyOutcome(handle, reply, end));
6046
+ if (end.status === "completed") completion = this.completed("turn", [reply.conversationId]);
6047
+ const recorded = await this.track(this.recordReplyOutcome(handle, reply, end));
6048
+ if (end.status === "failed" && !this.stopped) this.failedAttempt("turn", [reply.conversationId]);
6049
+ if (end.status === "failed" && recorded?.freshRead === true && recorded.outcome.reason === "turn_failed") {
6050
+ failure = { ...attempt, outcome: end.timedOut === true ? "timed_out" : "failed", failedAt: this.now(), holding: handle };
6051
+ }
5524
6052
  } finally {
5525
- this.tracker.end(handle);
6053
+ if (failure === null) this.tracker.end(handle);
5526
6054
  this.releaseSlot(handle);
5527
- this.afterTurnEnded();
6055
+ if (failure === null) this.afterTurnEnded();
6056
+ }
6057
+ if (failure !== null) {
6058
+ try {
6059
+ if (!this.stopped) await this.track(this.failed(failure));
6060
+ } finally {
6061
+ this.tracker.end(handle);
6062
+ this.afterTurnEnded();
6063
+ }
5528
6064
  }
6065
+ if (!this.stopped && completion !== null) await this.track(this.reportDue(completion));
6066
+ await this.track(this.checkParked("turn"));
5529
6067
  }
5530
6068
  async recordReplyOutcome(handle, reply, end) {
5531
6069
  const fresh = await this.readTray();
5532
- if (!this.tracker.holds(handle)) return;
6070
+ if (!this.tracker.holds(handle)) return null;
5533
6071
  const anchor = anchorFrom(reply.card);
5534
6072
  const key = `${reply.conversationId}|${anchor ?? ""}`;
5535
6073
  const silentBefore = this.silent.get(key) ?? 0;
@@ -5559,6 +6097,7 @@ invite_id: ${invite.invite_id}`,
5559
6097
  }
5560
6098
  }
5561
6099
  this.emit({ type: "turn_outcome", outcome, recorded });
6100
+ return { outcome, freshRead: fresh !== null };
5562
6101
  }
5563
6102
  async afterInviteTurn(handle, invite, done) {
5564
6103
  try {
@@ -5614,9 +6153,9 @@ invite_id: ${invite.invite_id}`,
5614
6153
  }
5615
6154
  this.emit({ type: "invite_outcome", outcome, recorded });
5616
6155
  }
5617
- async admit(start, request) {
6156
+ async admit(start2, request) {
5618
6157
  try {
5619
- return await start(request);
6158
+ return await start2(request);
5620
6159
  } catch (err) {
5621
6160
  return { started: false, error: err instanceof Error ? err.message : String(err) };
5622
6161
  }
@@ -5628,6 +6167,257 @@ invite_id: ${invite.invite_id}`,
5628
6167
  this.wakeFrom("more");
5629
6168
  }
5630
6169
  }
6170
+ // ─── could not process: failures, evidence, the server's answer ─────────
6171
+ /**
6172
+ * A run, turn or gate call that completed, on the evidence clock. A failure
6173
+ * it clears (the same kind of attempt for the same conversation went
6174
+ * through since) waits no more. Call it the moment the work ended, before
6175
+ * its slot frees, so the next attempt starts after it.
6176
+ */
6177
+ completed(kind, conversations) {
6178
+ const completion = this.evidence.complete(kind, conversations);
6179
+ if (kind !== "invite") this.failingSince[kind].clear();
6180
+ for (const id of conversations) {
6181
+ const failure = this.awaitingEvidence.get(id);
6182
+ if (failure !== void 0 && clears(completion, failure)) this.awaitingEvidence.delete(id);
6183
+ }
6184
+ return completion;
6185
+ }
6186
+ /**
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.
6190
+ */
6191
+ async reportDue(completion) {
6192
+ const now2 = this.now();
6193
+ const due = [];
6194
+ for (const failure of [...this.awaitingEvidence.values()]) {
6195
+ if (now2 - failure.failedAt > AWAITING_EVIDENCE_MS) {
6196
+ this.awaitingEvidence.delete(failure.conversationId);
6197
+ continue;
6198
+ }
6199
+ if (evidences(completion, failure)) {
6200
+ this.awaitingEvidence.delete(failure.conversationId);
6201
+ due.push(failure);
6202
+ }
6203
+ }
6204
+ for (const failure of due) await this.reportFailure(failure, "other_run_completed");
6205
+ }
6206
+ /** An attempt of this kind failed for these conversations (whatever comes of it): see `failingSince`. */
6207
+ failedAttempt(kind, conversations) {
6208
+ for (const id of conversations) this.failingSince[kind].add(id);
6209
+ }
6210
+ /**
6211
+ * A conversation's run, reply turn or single-card gate call failed. It is
6212
+ * reported only with evidence that the runtime otherwise works:
6213
+ * (a) a later completion of the same kind of work for another conversation
6214
+ * (`evidences`), or (b) `checkRuntime()` passing while no other
6215
+ * conversation of that kind has failed since that kind last completed.
6216
+ * Without (a) it waits: the work already queued runs first (cheap
6217
+ * evidence), and the runtime check is asked only once nothing of that kind
6218
+ * is queued (`checkParked`). It waits at most `AWAITING_EVIDENCE_MS`.
6219
+ * Nothing is reported after `stop()`: a run the stop cut short did not
6220
+ * fail on its conversation.
6221
+ */
6222
+ async failed(failure) {
6223
+ if (this.stopped) return;
6224
+ this.awaitingEvidence.delete(failure.conversationId);
6225
+ if (this.evidence.since(failure)) {
6226
+ await this.reportFailure(failure, "other_run_completed");
6227
+ return;
6228
+ }
6229
+ if (!this.canReport(failure)) return;
6230
+ this.awaitingEvidence.set(failure.conversationId, failure);
6231
+ while (this.awaitingEvidence.size > SILENT_MEMORY) {
6232
+ const oldest = this.awaitingEvidence.keys().next().value;
6233
+ if (oldest === void 0) break;
6234
+ this.awaitingEvidence.delete(oldest);
6235
+ }
6236
+ if (failure.source !== "gate") await this.checkParked(failure.source);
6237
+ }
6238
+ /**
6239
+ * Evidence (b), once nothing of this kind is queued: ask `checkRuntime()`
6240
+ * about the failure still waiting for evidence, if it is the only
6241
+ * conversation of that kind failing since that kind last completed. Several
6242
+ * failing together is the runtime: none of them is reported on (b), and
6243
+ * they keep waiting for (a). A `timed_out` failure is never reported on
6244
+ * (b): a timeout is ambiguous (a brownout, a hung hook) and the check does
6245
+ * not exercise those paths; it waits for (a). Each failure is asked about
6246
+ * once. A check that fails drops it (a broken runtime reports nothing).
6247
+ */
6248
+ async checkParked(kind) {
6249
+ if (!this.options.checkRuntime || this.stopped || !this.idleFor(kind)) return;
6250
+ const failing = this.failingSince[kind];
6251
+ const due = [...this.awaitingEvidence.values()].filter(
6252
+ (failure) => failure.source === kind && // A timeout is ambiguous (a brownout, a hung hook) and the runtime
6253
+ // check does not exercise those paths: only (a) can report it.
6254
+ failure.outcome !== "timed_out" && !this.checkedFailures.has(failure) && this.now() - failure.failedAt <= AWAITING_EVIDENCE_MS && [...failing].every((id) => id === failure.conversationId)
6255
+ );
6256
+ if (due.length === 0) return;
6257
+ for (const failure of due) this.checkedFailures.add(failure);
6258
+ const ok = await this.runtimeCheck();
6259
+ for (const failure of due) {
6260
+ if (this.stopped || this.awaitingEvidence.get(failure.conversationId) !== failure) continue;
6261
+ if (!ok) {
6262
+ this.awaitingEvidence.delete(failure.conversationId);
6263
+ continue;
6264
+ }
6265
+ if (![...failing].every((id) => id === failure.conversationId)) continue;
6266
+ this.awaitingEvidence.delete(failure.conversationId);
6267
+ await this.reportFailure(failure, "runtime_check");
6268
+ }
6269
+ }
6270
+ /** Nothing of this kind is running or queued: the runtime check may be asked now. */
6271
+ idleFor(kind) {
6272
+ if (kind === "gate") return this.activeSplit === null || this.activeSplit.queue.length === 0;
6273
+ if (kind === "turn" && this.activeSplit !== null) return false;
6274
+ return this.activeTurns === 0 && this.waiting.length === 0;
6275
+ }
6276
+ canReport(failure) {
6277
+ return failure.anchor !== null && typeof this.client.conversations?.reportProcessingFailure === "function";
6278
+ }
6279
+ /** `checkRuntime()`, bounded by `RUNTIME_CHECK_TIMEOUT_MS`; a throw or a timeout is not ok. */
6280
+ async runtimeCheck() {
6281
+ const check = this.options.checkRuntime;
6282
+ let timer = null;
6283
+ let answer;
6284
+ try {
6285
+ answer = await Promise.race([
6286
+ Promise.resolve().then(() => check()),
6287
+ new Promise((resolve) => {
6288
+ timer = this._setTimeout(
6289
+ () => resolve({ ok: false, detail: `no answer within ${RUNTIME_CHECK_TIMEOUT_MS} ms` }),
6290
+ RUNTIME_CHECK_TIMEOUT_MS
6291
+ );
6292
+ timer.unref?.();
6293
+ })
6294
+ ]);
6295
+ } catch (err) {
6296
+ answer = { ok: false, detail: `the check threw: ${err instanceof Error ? err.message : String(err)}` };
6297
+ } finally {
6298
+ if (timer !== null) this._clearTimeout(timer);
6299
+ }
6300
+ const ok = answer?.ok === true;
6301
+ if (ok) this.failureCounts.runtimeChecksOk += 1;
6302
+ else this.failureCounts.runtimeChecksFailed += 1;
6303
+ this.lastRuntimeCheck = { at: new Date(this.now()).toISOString(), ok, detail: typeof answer?.detail === "string" ? answer.detail : null };
6304
+ return ok;
6305
+ }
6306
+ /** Tell the server, and do what it answers: run the conversation again (`retry`, `hidden`) or stop (`paused`, `none`). */
6307
+ async reportFailure(failure, evidence) {
6308
+ const conversations = this.client.conversations;
6309
+ if (!this.canReport(failure) || conversations === void 0 || this.stopped) return;
6310
+ const base = {
6311
+ conversationId: failure.conversationId,
6312
+ source: failure.source,
6313
+ throughMessageId: failure.anchor,
6314
+ outcome: failure.outcome,
6315
+ evidence
6316
+ };
6317
+ let result;
6318
+ try {
6319
+ result = await conversations.reportProcessingFailure(failure.conversationId, {
6320
+ throughMessageId: failure.anchor,
6321
+ outcome: failure.outcome,
6322
+ evidence
6323
+ });
6324
+ } catch (err) {
6325
+ this.failureCounts.reportErrors += 1;
6326
+ this.fail(err);
6327
+ this.emit({ type: "processing_failure", ...base, result: null, error: err instanceof Error ? err.message : String(err), next: "stop" });
6328
+ return;
6329
+ }
6330
+ this.failureCounts.reported += 1;
6331
+ this.failureCounts[result.action] += 1;
6332
+ let next = "stop";
6333
+ if (result.action === "retry" || result.action === "hidden") {
6334
+ if (failure.reruns >= MAX_RERUNS_PER_CYCLE) {
6335
+ next = "rerun_capped";
6336
+ this.failureCounts.rerunsCapped += 1;
6337
+ } else {
6338
+ next = this.rerun(failure, result.action === "hidden");
6339
+ }
6340
+ }
6341
+ if (result.action === "paused") this.dropWaiting(failure.conversationId);
6342
+ if (next === "stop" || next === "rerun_capped") this.activeSplit?.skip.add(failure.conversationId);
6343
+ this.emit({ type: "processing_failure", ...base, result, next });
6344
+ }
6345
+ /**
6346
+ * Run the conversation again after a `retry` or `hidden` answer, after the
6347
+ * others already queued, and say what was done. Its run or reply turn takes
6348
+ * a place at the back of the queue (it reads the conversation itself, so it
6349
+ * sees a hidden span as the note); a reply turn asked for while a gate is
6350
+ * deciding starts after that cycle's own turns. A gate call sees only the
6351
+ * card: after `retry` it joins the end of the running gate's single-card
6352
+ * calls (once, with the card as this cycle read it); after `hidden`, or
6353
+ * when no gate is running for it, the next cycle reads the tray again and
6354
+ * gates it alone. `running`: nothing started, because its next attempt is
6355
+ * under way already (running, queued, or being decided by the gate now).
6356
+ */
6357
+ rerun(failure, hidden) {
6358
+ if (this.stopped) return "stop";
6359
+ const id = failure.conversationId;
6360
+ const reruns = failure.reruns + 1;
6361
+ this.pacer.release(`conversation:${id}`);
6362
+ if (failure.holding !== void 0) this.tracker.end(failure.holding);
6363
+ const split = this.activeSplit;
6364
+ const current = split?.members.get(id);
6365
+ if (failure.source === "gate") {
6366
+ this.rememberGateAlone(id);
6367
+ if (split !== null && current !== void 0 && !hidden) {
6368
+ split.skip.delete(id);
6369
+ if (split.queue.some((item) => item.card.conversation_id === id)) return "running";
6370
+ split.queue.push({ card: current, reruns });
6371
+ } else {
6372
+ split?.skip.add(id);
6373
+ this.wakeFrom("more");
6374
+ }
6375
+ this.failureCounts.reruns += 1;
6376
+ return "rerun";
6377
+ }
6378
+ if (this.tracker.conversationRunning(id) || current !== void 0) return "running";
6379
+ const texts = this.options.texts.current();
6380
+ this.failureCounts.reruns += 1;
6381
+ if (texts !== null && failure.source === "turn" && failure.reply !== void 0) {
6382
+ if (split !== null) this.turnRerunsAfterGate.push({ reply: failure.reply, reruns });
6383
+ else void this.startReplyTurn(failure.reply, texts, reruns);
6384
+ } else if (texts !== null && failure.source === "run" && conversationRunTemplate(texts) !== null) {
6385
+ void this.startConversationRun(failure.card, texts, reruns);
6386
+ } else {
6387
+ this.wakeFrom("more");
6388
+ }
6389
+ return "rerun";
6390
+ }
6391
+ /** The reply turns asked for while a gate was deciding: started now, after the cycle's own turns. */
6392
+ flushTurnReruns() {
6393
+ const due = this.turnRerunsAfterGate.splice(0);
6394
+ if (this.stopped || due.length === 0) return;
6395
+ const texts = this.options.texts.current();
6396
+ for (const { reply, reruns } of due) {
6397
+ if (this.tracker.conversationRunning(reply.conversationId)) continue;
6398
+ if (texts === null) this.wakeFrom("more");
6399
+ else void this.startReplyTurn(reply, texts, reruns);
6400
+ }
6401
+ }
6402
+ /** A `paused` conversation: a run or turn still waiting for a slot for it does not start. */
6403
+ dropWaiting(conversationId) {
6404
+ for (const entry of [...this.waiting]) {
6405
+ const turn = entry.handle.turn;
6406
+ if (turn.kind !== "reply" || turn.conversationId !== conversationId) continue;
6407
+ this.waiting.splice(this.waiting.indexOf(entry), 1);
6408
+ this.tracker.end(entry.handle);
6409
+ entry.drop?.();
6410
+ }
6411
+ }
6412
+ rememberGateAlone(conversationId) {
6413
+ this.gateAlone.delete(conversationId);
6414
+ this.gateAlone.add(conversationId);
6415
+ while (this.gateAlone.size > SILENT_MEMORY) {
6416
+ const oldest = this.gateAlone.values().next().value;
6417
+ if (oldest === void 0) break;
6418
+ this.gateAlone.delete(oldest);
6419
+ }
6420
+ }
5631
6421
  // ─── small things ───────────────────────────────────────────────────────
5632
6422
  /** Recording under way after a turn's confirmed end: `stop()` waits for it. */
5633
6423
  track(work) {
@@ -5667,6 +6457,9 @@ invite_id: ${invite.invite_id}`,
5667
6457
  paced: 0,
5668
6458
  chunksOk: 0,
5669
6459
  chunksFailed: 0,
6460
+ splitCallsOk: 0,
6461
+ splitCallsFailed: 0,
6462
+ splitStopped: false,
5670
6463
  truncated: false,
5671
6464
  failure: null,
5672
6465
  ...parts
@@ -5697,6 +6490,23 @@ conversation_id: ${conversationId}`;
5697
6490
 
5698
6491
  conversation_id: ${conversationId}`;
5699
6492
  }
6493
+ function conversationRunTemplate(texts) {
6494
+ const raw = texts.conversation_run_template;
6495
+ const template = typeof raw === "string" ? raw.trim() : "";
6496
+ return template.length > 0 ? template : null;
6497
+ }
6498
+ function conversationRunPrompt(texts, conversationId) {
6499
+ const template = conversationRunTemplate(texts);
6500
+ if (template === null) return replyPrompt(texts, conversationId);
6501
+ if (template.includes(REPLY_TURN_PLACEHOLDER)) return template.split(REPLY_TURN_PLACEHOLDER).join(conversationId);
6502
+ return `${template}
6503
+
6504
+ conversation_id: ${conversationId}`;
6505
+ }
6506
+ function untouched(card, fresh) {
6507
+ if (fresh === null) return false;
6508
+ return turnOutcome({ turn: { status: "failed" }, gateCard: card, freshTray: fresh }).reason === "turn_failed";
6509
+ }
5700
6510
  function chunkFailure(chunks) {
5701
6511
  const failed = chunks.filter((chunk) => chunk.outcome === "fail_closed");
5702
6512
  const first = failed[0];
@@ -5705,6 +6515,34 @@ function chunkFailure(chunks) {
5705
6515
  if (chunks.length === 1) return reason;
5706
6516
  return `${failed.length} of ${chunks.length} gate chunks failed; chunk ${first.index}: ${reason}`;
5707
6517
  }
6518
+ function gateFailureText(chunks, split) {
6519
+ const parts = [];
6520
+ const chunked = chunkFailure(chunks);
6521
+ if (chunked !== null) parts.push(chunked);
6522
+ const failed = split.filter((call2) => call2.outcome === "fail_closed");
6523
+ const first = failed[0];
6524
+ if (first !== void 0) {
6525
+ const reason = first.failure ?? "no usable verdicts in the answer";
6526
+ parts.push(`${failed.length} of ${split.length} single-card calls failed; ${first.conversationId ?? "a card"}: ${reason}`);
6527
+ }
6528
+ return parts.length === 0 ? null : parts.join("; ");
6529
+ }
6530
+ function gateFailure(card, startedAt, reruns, timedOut, failedAt) {
6531
+ return {
6532
+ conversationId: card.conversation_id,
6533
+ source: "gate",
6534
+ card,
6535
+ anchor: anchorFrom(card),
6536
+ startedAt,
6537
+ reruns,
6538
+ outcome: timedOut ? "timed_out" : "failed",
6539
+ failedAt
6540
+ };
6541
+ }
6542
+ function decidedBy(result) {
6543
+ const undecided = new Set(result.undecided);
6544
+ return result.verdicts.map((verdict) => verdict.conversation_id).filter((id) => !undecided.has(id));
6545
+ }
5708
6546
  function timeoutOption(value, fallback, name) {
5709
6547
  if (value === void 0) return fallback;
5710
6548
  if (value === 0 || value === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY;
@@ -5733,6 +6571,466 @@ function wsBase(httpBase) {
5733
6571
  return base.replace(/^http/, "ws");
5734
6572
  }
5735
6573
 
6574
+ // src/integration/account.ts
6575
+ var account_exports = {};
6576
+ __export(account_exports, {
6577
+ DEFAULT_LABELS: () => DEFAULT_LABELS,
6578
+ MAX_AUTO_WAITS: () => MAX_AUTO_WAITS,
6579
+ MAX_WAIT_S: () => MAX_WAIT_S,
6580
+ MIN_WAIT_MS: () => MIN_WAIT_MS,
6581
+ actionOf: () => actionOf,
6582
+ checkKey: () => checkKey,
6583
+ flowOf: () => flowOf,
6584
+ run: () => run2,
6585
+ start: () => start,
6586
+ submitCode: () => submitCode
6587
+ });
6588
+ var DEFAULT_API_BASE = "https://api.agentchat.me";
6589
+ var MAX_WAIT_S = 60;
6590
+ var DEFAULT_LABELS = Object.freeze({
6591
+ email: "Email address",
6592
+ handle: "Handle",
6593
+ code: "Enter the 6-digit code"
6594
+ });
6595
+ var START_STEPS = /* @__PURE__ */ new Set(["register", "recover", "rotate_key"]);
6596
+ var VERIFY_STEPS = /* @__PURE__ */ new Set(["verify", "recover_verify", "rotate_key_verify"]);
6597
+ var KNOWN_STEPS = /* @__PURE__ */ new Set([...START_STEPS, ...VERIFY_STEPS, "done"]);
6598
+ function isRecord(value) {
6599
+ return value !== null && typeof value === "object" && !Array.isArray(value);
6600
+ }
6601
+ function wholeNumber(value) {
6602
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
6603
+ }
6604
+ function text(value) {
6605
+ return typeof value === "string" && value.length > 0 ? value : void 0;
6606
+ }
6607
+ function flowOf(bodyOrError) {
6608
+ let source;
6609
+ if (bodyOrError instanceof AgentChatError) source = bodyOrError.details;
6610
+ else if (isRecord(bodyOrError)) source = typeof bodyOrError.code === "string" ? bodyOrError.details : bodyOrError;
6611
+ if (!isRecord(source)) return null;
6612
+ const nextStep = text(source.next_step);
6613
+ if (nextStep === void 0) return null;
6614
+ const flow = {
6615
+ version: typeof source.version === "number" ? source.version : 1,
6616
+ flow: text(source.flow) ?? "",
6617
+ next_step: nextStep
6618
+ };
6619
+ const strings = ["status", "pending_id", "param", "expires_at"];
6620
+ for (const key of strings) {
6621
+ const value = text(source[key]);
6622
+ if (value !== void 0) flow[key] = value;
6623
+ }
6624
+ const numbers = [
6625
+ "expires_in_s",
6626
+ "code_length",
6627
+ "attempts",
6628
+ "max_attempts",
6629
+ "resend_after_s",
6630
+ "retry_after_s"
6631
+ ];
6632
+ for (const key of numbers) {
6633
+ const value = wholeNumber(source[key]);
6634
+ if (value !== void 0) flow[key] = value;
6635
+ }
6636
+ return flow;
6637
+ }
6638
+ function isStartStep(step) {
6639
+ return START_STEPS.has(step);
6640
+ }
6641
+ function isVerifyStep(step) {
6642
+ return VERIFY_STEPS.has(step);
6643
+ }
6644
+ function actionOf(flow, httpStatus, calledStep) {
6645
+ if (flow === null) return "legacy";
6646
+ const step = flow.next_step;
6647
+ if (step === "done") return "done";
6648
+ if (httpStatus >= 500 || !KNOWN_STEPS.has(step)) return "stop";
6649
+ const wait = flow.retry_after_s;
6650
+ if (isVerifyStep(step) && wait === void 0) return "ask_code";
6651
+ if (isStartStep(step)) {
6652
+ if (flow.param !== void 0) return "ask_param";
6653
+ const codeGone = flow.status === "expired" || flow.status === "max_attempts_reached" || httpStatus === 429 && isVerifyStep(calledStep);
6654
+ if (codeGone && (wait === void 0 || wait <= MAX_WAIT_S)) return "offer_new_code";
6655
+ }
6656
+ if (httpStatus === 429 && wait !== void 0 && wait <= MAX_WAIT_S && step === calledStep) return "wait_then_retry";
6657
+ return "stop";
6658
+ }
6659
+ var STEPS = {
6660
+ register: { start: "register", verify: "verify", startPath: "/v1/register", verifyPath: "/v1/register/verify" },
6661
+ recover: {
6662
+ start: "recover",
6663
+ verify: "recover_verify",
6664
+ startPath: "/v1/agents/recover",
6665
+ verifyPath: "/v1/agents/recover/verify"
6666
+ }
6667
+ };
6668
+ function transport(options, apiKey) {
6669
+ return new HttpTransport({
6670
+ baseUrl: options.apiBase ?? DEFAULT_API_BASE,
6671
+ defaultHeaders: clientIdentityHeaders(options.clientIdentity),
6672
+ ...apiKey !== void 0 ? { apiKey } : {},
6673
+ ...options.fetch ? { fetch: options.fetch } : {},
6674
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
6675
+ });
6676
+ }
6677
+ async function call(options, method, path, body, apiKey) {
6678
+ try {
6679
+ const res = await transport(options, apiKey).request(method, path, {
6680
+ ...body !== void 0 ? { body } : {},
6681
+ retry: "never",
6682
+ ...options.signal ? { signal: options.signal } : {},
6683
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
6684
+ });
6685
+ return { httpStatus: res.status, body: res.data, error: null };
6686
+ } catch (err) {
6687
+ if (err instanceof AgentChatError) return { httpStatus: err.status, body: void 0, error: err };
6688
+ throw err;
6689
+ }
6690
+ }
6691
+ function successMessage(body) {
6692
+ return isRecord(body) && typeof body.message === "string" ? body.message : "";
6693
+ }
6694
+ function keyAndHandle(body) {
6695
+ if (!isRecord(body)) return {};
6696
+ const apiKey = text(body.api_key);
6697
+ const agent = isRecord(body.agent) ? body.agent : null;
6698
+ const handle = text(body.handle) ?? text(agent?.handle);
6699
+ return { ...apiKey !== void 0 ? { apiKey } : {}, ...handle !== void 0 ? { handle } : {} };
6700
+ }
6701
+ function handlesOf(error) {
6702
+ const raw = error?.details?.handles;
6703
+ if (!Array.isArray(raw)) return void 0;
6704
+ return raw.filter((h) => typeof h === "string");
6705
+ }
6706
+ function legacyWaitSeconds(error) {
6707
+ if (error.retryAfterS !== null) return error.retryAfterS;
6708
+ if (error instanceof RateLimitedError && error.retryAfterMs !== null) return Math.ceil(error.retryAfterMs / 1e3);
6709
+ return void 0;
6710
+ }
6711
+ function legacyFieldOf(error) {
6712
+ const fieldErrors = error.details?.fieldErrors;
6713
+ if (!isRecord(fieldErrors)) return void 0;
6714
+ const named = ["email", "handle", "code"].filter((f) => fieldErrors[f] !== void 0);
6715
+ return named.length === 1 ? named[0] : void 0;
6716
+ }
6717
+ function legacyFlow(kind, stepCalled, answer, submitted) {
6718
+ const steps = STEPS[kind];
6719
+ const startFlow = (extra = {}) => ({
6720
+ version: 1,
6721
+ flow: kind,
6722
+ next_step: steps.start,
6723
+ ...extra
6724
+ });
6725
+ const pendingAgain = (extra = {}) => ({
6726
+ version: 1,
6727
+ flow: kind,
6728
+ next_step: steps.verify,
6729
+ status: "pending",
6730
+ ...submitted?.pending_id !== void 0 ? { pending_id: submitted.pending_id } : {},
6731
+ code_length: submitted?.code_length ?? 6,
6732
+ ...extra
6733
+ });
6734
+ const { error, body } = answer;
6735
+ if (error === null) {
6736
+ if (stepCalled === "start") {
6737
+ const pendingId = isRecord(body) ? text(body.pending_id) : void 0;
6738
+ if (pendingId === void 0) return startFlow();
6739
+ return { version: 1, flow: kind, next_step: steps.verify, status: "pending", pending_id: pendingId, code_length: 6 };
6740
+ }
6741
+ const { apiKey } = keyAndHandle(body);
6742
+ if (apiKey === void 0) return startFlow();
6743
+ return { version: 1, flow: kind, next_step: "done", status: "approved" };
6744
+ }
6745
+ if (error.status === 429) {
6746
+ if (error.code === "OTP_ATTEMPTS_EXHAUSTED") return startFlow({ status: "max_attempts_reached" });
6747
+ const wait = legacyWaitSeconds(error);
6748
+ if (wait === void 0) return startFlow();
6749
+ return stepCalled === "verify" ? pendingAgain({ retry_after_s: wait }) : startFlow({ retry_after_s: wait });
6750
+ }
6751
+ switch (error.code) {
6752
+ case "HANDLE_TAKEN":
6753
+ case "INVALID_HANDLE":
6754
+ case "HANDLE_REQUIRED":
6755
+ return startFlow({ param: "handle" });
6756
+ case "EMAIL_LIMIT_REACHED":
6757
+ case "EMAIL_TAKEN":
6758
+ case "EMAIL_EXHAUSTED":
6759
+ return startFlow({ param: "email" });
6760
+ case "INVALID_CODE":
6761
+ return pendingAgain({ param: "code" });
6762
+ case "EXPIRED":
6763
+ return startFlow({ status: "expired" });
6764
+ case "VALIDATION_ERROR": {
6765
+ const field = legacyFieldOf(error);
6766
+ if (stepCalled === "verify") return field === "code" ? pendingAgain({ param: "code" }) : startFlow();
6767
+ return field === "email" || field === "handle" ? startFlow({ param: field }) : startFlow();
6768
+ }
6769
+ default:
6770
+ return startFlow();
6771
+ }
6772
+ }
6773
+ function read(kind, stepCalled, answer, submitted) {
6774
+ const { error, body, httpStatus } = answer;
6775
+ const served = flowOf(error ?? body);
6776
+ const legacy = served === null;
6777
+ let flow = served ?? legacyFlow(kind, stepCalled, answer, submitted);
6778
+ if (!legacy && submitted?.pending_id !== void 0 && flow.pending_id === void 0 && flow.next_step === submitted.next_step) {
6779
+ flow = { ...flow, pending_id: submitted.pending_id };
6780
+ }
6781
+ const calledStep = stepCalled === "start" ? STEPS[kind].start : STEPS[kind].verify;
6782
+ let action = actionOf(flow, httpStatus, calledStep);
6783
+ const credentials = error === null ? keyAndHandle(body) : {};
6784
+ if (action === "done" && (credentials.apiKey === void 0 || credentials.handle === void 0)) action = "stop";
6785
+ if (action === "ask_code" && flow.pending_id === void 0) action = "stop";
6786
+ const handles = handlesOf(error);
6787
+ return {
6788
+ flow,
6789
+ message: error !== null ? error.message : successMessage(body),
6790
+ action,
6791
+ httpStatus,
6792
+ calledStep,
6793
+ legacy,
6794
+ ...error !== null ? { code: error.code } : {},
6795
+ ...action === "done" ? credentials : {},
6796
+ ...handles !== void 0 ? { handles } : {}
6797
+ };
6798
+ }
6799
+ async function start(kind, input, options) {
6800
+ const steps = STEPS[kind];
6801
+ if (steps === void 0) throw new TypeError(`integration.account.start: unknown kind ${JSON.stringify(kind)}`);
6802
+ if (!isRecord(input)) throw new TypeError("integration.account.start: input must be an object");
6803
+ const body = kind === "register" ? {
6804
+ email: input.email,
6805
+ handle: input.handle,
6806
+ display_name: input.display_name,
6807
+ description: input.description
6808
+ } : { email: input.email, handle: input.handle };
6809
+ const answer = await call(options, "POST", steps.startPath, body);
6810
+ return read(kind, "start", answer, null);
6811
+ }
6812
+ async function submitCode(flow, code, options) {
6813
+ if (!isRecord(flow) || typeof flow.next_step !== "string") {
6814
+ throw new TypeError("integration.account.submitCode: flow must be a sign-up flow object");
6815
+ }
6816
+ const kind = flow.next_step === "verify" ? "register" : flow.next_step === "recover_verify" ? "recover" : null;
6817
+ if (kind === null) {
6818
+ throw new TypeError(
6819
+ `integration.account.submitCode: the flow is not waiting for a code (next_step ${JSON.stringify(flow.next_step)}); submit only to next_step "verify" or "recover_verify" (key rotation: AgentChatClient.rotateKeyVerify)`
6820
+ );
6821
+ }
6822
+ if (typeof flow.pending_id !== "string" || flow.pending_id.length === 0) {
6823
+ throw new TypeError("integration.account.submitCode: the flow carries no pending_id");
6824
+ }
6825
+ const answer = await call(options, "POST", STEPS[kind].verifyPath, { pending_id: flow.pending_id, code });
6826
+ return read(kind, "verify", answer, flow);
6827
+ }
6828
+ async function checkKey(apiKey, options) {
6829
+ const answer = await call(options, "GET", "/v1/agents/me", void 0, apiKey);
6830
+ if (answer.error !== null) return { ok: false, code: answer.error.code, message: answer.error.message };
6831
+ const handle = isRecord(answer.body) ? text(answer.body.handle) : void 0;
6832
+ if (handle === void 0) {
6833
+ throw new Error(`integration.account.checkKey: GET /v1/agents/me answered ${answer.httpStatus} without a handle`);
6834
+ }
6835
+ return { ok: true, handle };
6836
+ }
6837
+ function defaultSleep(signal) {
6838
+ return (ms) => new Promise((resolve, reject) => {
6839
+ if (signal?.aborted) {
6840
+ reject(abortError());
6841
+ return;
6842
+ }
6843
+ const timer = setTimeout(() => {
6844
+ signal?.removeEventListener("abort", onAbort);
6845
+ resolve();
6846
+ }, ms);
6847
+ const onAbort = () => {
6848
+ clearTimeout(timer);
6849
+ reject(abortError());
6850
+ };
6851
+ signal?.addEventListener("abort", onAbort, { once: true });
6852
+ });
6853
+ }
6854
+ function abortError() {
6855
+ const err = new Error("Aborted");
6856
+ err.name = "AbortError";
6857
+ return err;
6858
+ }
6859
+ var FIELD_ANSWERS = ["value", "cancel"];
6860
+ var CODE_ANSWERS = ["value", "new_code", "cancel"];
6861
+ var NEW_CODE_ANSWERS = ["new_code", "cancel"];
6862
+ var MIN_WAIT_MS = 1e3;
6863
+ var MAX_AUTO_WAITS = 3;
6864
+ async function run2(options) {
6865
+ const { kind, ask, show } = options;
6866
+ if (STEPS[kind] === void 0) throw new TypeError(`integration.account.run: unknown kind ${JSON.stringify(kind)}`);
6867
+ const labels = { ...DEFAULT_LABELS, ...options.labels };
6868
+ const sleep2 = options.sleep ?? defaultSleep(options.signal);
6869
+ const callOptions = {
6870
+ clientIdentity: options.clientIdentity,
6871
+ ...options.apiBase !== void 0 ? { apiBase: options.apiBase } : {},
6872
+ ...options.fetch ? { fetch: options.fetch } : {},
6873
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
6874
+ ...options.signal ? { signal: options.signal } : {}
6875
+ };
6876
+ const input = {
6877
+ ...options.input
6878
+ };
6879
+ let waitsInARow = 0;
6880
+ const askOne = async (question) => {
6881
+ waitsInARow = 0;
6882
+ const answer = await ask(question);
6883
+ if (!isRecord(answer) || !question.answers.includes(answer.answer)) {
6884
+ throw new TypeError(
6885
+ `integration.account.run: ask answered ${JSON.stringify(answer)} to a ${question.field} question (allowed: ${question.answers.join(", ")})`
6886
+ );
6887
+ }
6888
+ if (answer.answer === "value" && typeof answer.value !== "string") {
6889
+ throw new TypeError("integration.account.run: a value answer carries a string value");
6890
+ }
6891
+ return answer;
6892
+ };
6893
+ const askField = async (field, flow, handles) => {
6894
+ const answer = await askOne({
6895
+ field,
6896
+ label: labels[field],
6897
+ answers: FIELD_ANSWERS,
6898
+ ...handles !== void 0 && handles.length > 0 ? { handles } : {},
6899
+ flow
6900
+ });
6901
+ if (answer.answer !== "value") return false;
6902
+ input[field] = answer.value.trim();
6903
+ return true;
6904
+ };
6905
+ const wait = async (ms) => {
6906
+ waitsInARow += 1;
6907
+ await sleep2(Math.max(MIN_WAIT_MS, ms));
6908
+ };
6909
+ const required = kind === "register" ? ["email", "handle"] : ["email"];
6910
+ for (const field of required) {
6911
+ if (typeof input[field] === "string" && input[field].trim().length > 0) continue;
6912
+ if (!await askField(field, null)) return { outcome: "cancelled" };
6913
+ }
6914
+ const startCall = {
6915
+ step: "start",
6916
+ call: () => {
6917
+ const email = input.email ?? "";
6918
+ if (kind === "recover") {
6919
+ return start("recover", { email, ...input.handle ? { handle: input.handle } : {} }, callOptions);
6920
+ }
6921
+ return start(
6922
+ "register",
6923
+ {
6924
+ email,
6925
+ handle: input.handle ?? "",
6926
+ ...input.display_name !== void 0 ? { display_name: input.display_name } : {},
6927
+ ...input.description !== void 0 ? { description: input.description } : {}
6928
+ },
6929
+ callOptions
6930
+ );
6931
+ }
6932
+ };
6933
+ let held = null;
6934
+ const holdsAWorkingCode = () => held !== null && held.expiresAtMs !== null && held.expiresAtMs > Date.now();
6935
+ let resend = null;
6936
+ const beforeStart = async () => {
6937
+ if (resend === null || resend.email !== (input.email ?? "")) return true;
6938
+ const leftMs = resend.afterMs - (Date.now() - resend.receivedAt);
6939
+ if (leftMs > MAX_WAIT_S * 1e3) return false;
6940
+ if (leftMs > 0) await wait(leftMs);
6941
+ return true;
6942
+ };
6943
+ const askCode = async (flow) => {
6944
+ for (; ; ) {
6945
+ const answer = await askOne({ field: "code", label: labels.code, answers: CODE_ANSWERS, flow });
6946
+ if (answer.answer === "cancel") return null;
6947
+ if (answer.answer === "value") {
6948
+ const code = answer.value.trim();
6949
+ return { step: "verify", call: () => submitCode(flow, code, callOptions) };
6950
+ }
6951
+ if (await beforeStart()) return startCall;
6952
+ if (holdsAWorkingCode()) continue;
6953
+ return STOP;
6954
+ }
6955
+ };
6956
+ const offerNewCode = async (flow) => {
6957
+ const answer = await askOne({ field: "new_code", label: null, answers: NEW_CODE_ANSWERS, flow });
6958
+ if (answer.answer !== "new_code") return null;
6959
+ const retryAfterS = flow.retry_after_s;
6960
+ if (retryAfterS !== void 0 && retryAfterS > 0 && retryAfterS <= MAX_WAIT_S) await wait(retryAfterS * 1e3);
6961
+ return await beforeStart() ? true : STOP;
6962
+ };
6963
+ let repeat = startCall;
6964
+ let result = await repeat.call();
6965
+ let receivedAt = Date.now();
6966
+ for (; ; ) {
6967
+ const after = result.flow.resend_after_s;
6968
+ if (after !== void 0) resend = { email: input.email ?? "", afterMs: after * 1e3, receivedAt };
6969
+ if (result.message.length > 0) await show(result.message);
6970
+ let next = STOP;
6971
+ switch (result.action) {
6972
+ case "done":
6973
+ return { outcome: "done", apiKey: result.apiKey, handle: result.handle };
6974
+ case "ask_code": {
6975
+ const flow = result.flow;
6976
+ const expiresAtMs = expiryOf(flow, receivedAt) ?? (held !== null && held.flow.pending_id === flow.pending_id ? held.expiresAtMs : null);
6977
+ held = { flow, expiresAtMs };
6978
+ next = await askCode(flow);
6979
+ break;
6980
+ }
6981
+ case "ask_param": {
6982
+ held = null;
6983
+ const param = result.flow.param;
6984
+ const field = param === "email" ? "email" : param === "handle" ? "handle" : null;
6985
+ if (field === null) break;
6986
+ if (!await askField(field, result.flow, result.handles)) return { outcome: "cancelled" };
6987
+ if (await beforeStart()) next = startCall;
6988
+ break;
6989
+ }
6990
+ case "offer_new_code": {
6991
+ held = null;
6992
+ const offered = await offerNewCode(result.flow);
6993
+ next = offered === true ? startCall : offered;
6994
+ break;
6995
+ }
6996
+ case "wait_then_retry": {
6997
+ if (waitsInARow >= MAX_AUTO_WAITS) {
6998
+ if (repeat.step === "verify") {
6999
+ next = await askCode(held?.flow ?? result.flow);
7000
+ break;
7001
+ }
7002
+ const again = await askOne({ field: "new_code", label: null, answers: NEW_CODE_ANSWERS, flow: result.flow });
7003
+ if (again.answer !== "new_code") return { outcome: "cancelled" };
7004
+ }
7005
+ await wait(result.flow.retry_after_s * 1e3);
7006
+ next = repeat;
7007
+ break;
7008
+ }
7009
+ default:
7010
+ if (result.httpStatus === 429 && repeat.step === "start" && held !== null && holdsAWorkingCode()) {
7011
+ next = await askCode(held.flow);
7012
+ }
7013
+ }
7014
+ if (next === null) return { outcome: "cancelled" };
7015
+ if (next === STOP) return stopped(result);
7016
+ repeat = next;
7017
+ result = await repeat.call();
7018
+ receivedAt = Date.now();
7019
+ }
7020
+ }
7021
+ function expiryOf(flow, receivedAt) {
7022
+ if (flow.expires_in_s !== void 0) return receivedAt + flow.expires_in_s * 1e3;
7023
+ if (flow.expires_at !== void 0) {
7024
+ const at = Date.parse(flow.expires_at);
7025
+ if (Number.isFinite(at)) return at;
7026
+ }
7027
+ return null;
7028
+ }
7029
+ var STOP = /* @__PURE__ */ Symbol("stop");
7030
+ function stopped(result) {
7031
+ return { outcome: "stopped", code: result.code ?? null, message: result.message };
7032
+ }
7033
+
5736
7034
  // src/wake-webhook-verify.ts
5737
7035
  var WakeWebhookVerificationError = class extends Error {
5738
7036
  reason;
@@ -5944,8 +7242,8 @@ function renderMessageContext(message, opts = {}) {
5944
7242
  if (self && conv?.type === "group" && (ctx?.mentions ?? []).includes(self)) {
5945
7243
  lines.push("You were @-mentioned in this message.");
5946
7244
  }
5947
- const text = message.content?.text;
5948
- lines.push("", text ? text : `(a ${"non-text"} message \u2014 no text body)`);
7245
+ const text2 = message.content?.text;
7246
+ lines.push("", text2 ? text2 : `(a ${"non-text"} message \u2014 no text body)`);
5949
7247
  return lines.join("\n");
5950
7248
  }
5951
7249
 
@@ -5995,6 +7293,7 @@ exports.INBOX_TRAY_MAX_LIMIT = INBOX_TRAY_MAX_LIMIT;
5995
7293
  exports.INBOX_WAIT_MAX_MS = INBOX_WAIT_MAX_MS;
5996
7294
  exports.MAX_ATTACHMENT_SIZE = MAX_ATTACHMENT_SIZE;
5997
7295
  exports.NotFoundError = NotFoundError;
7296
+ exports.OtpAttemptsExhaustedError = OtpAttemptsExhaustedError;
5998
7297
  exports.RateLimitedError = RateLimitedError;
5999
7298
  exports.RealtimeClient = RealtimeClient;
6000
7299
  exports.RecipientBackloggedError = RecipientBackloggedError;