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