agentchatme 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -37,6 +37,12 @@ var ErrorCode = {
37
37
  * lists the candidates; re-run `recover()` with one of them.
38
38
  */
39
39
  HANDLE_REQUIRED: "HANDLE_REQUIRED",
40
+ /**
41
+ * 429 from a sign-up verify call: the code's attempts are used up and the
42
+ * pending id is gone. Repeating never succeeds; request a new code.
43
+ * Mapped to `OtpAttemptsExhaustedError` (not `RateLimitedError`).
44
+ */
45
+ OTP_ATTEMPTS_EXHAUSTED: "OTP_ATTEMPTS_EXHAUSTED",
40
46
  SUSPENDED: "SUSPENDED",
41
47
  RESTRICTED: "RESTRICTED",
42
48
  CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND",
@@ -72,6 +78,12 @@ function parseRetryAfter(raw, now2 = Date.now()) {
72
78
  }
73
79
 
74
80
  // src/errors.ts
81
+ function wholeSeconds(value) {
82
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
83
+ }
84
+ function retryAfterSecondsOf(response) {
85
+ return wholeSeconds(response.retry_after_s) ?? wholeSeconds(response.details?.retry_after_s);
86
+ }
75
87
  var AgentChatError = class extends Error {
76
88
  code;
77
89
  status;
@@ -82,6 +94,13 @@ var AgentChatError = class extends Error {
82
94
  * server-side trace in seconds.
83
95
  */
84
96
  requestId;
97
+ /**
98
+ * The body's `retry_after_s` in seconds (top level, else
99
+ * `details.retry_after_s`), or null. The sign-up 429s carry it; so does
100
+ * the per-IP rate limit. `RateLimitedError.retryAfterMs` prefers the
101
+ * `Retry-After` header.
102
+ */
103
+ retryAfterS;
85
104
  constructor(response, status, requestId = null) {
86
105
  super(response.message);
87
106
  this.name = "AgentChatError";
@@ -89,6 +108,7 @@ var AgentChatError = class extends Error {
89
108
  this.status = status;
90
109
  this.details = response.details;
91
110
  this.requestId = requestId;
111
+ this.retryAfterS = retryAfterSecondsOf(response);
92
112
  Object.setPrototypeOf(this, new.target.prototype);
93
113
  }
94
114
  };
@@ -206,6 +226,12 @@ var HandleRequiredError = class extends AgentChatError {
206
226
  this.handles = Array.isArray(raw) ? raw.filter((h) => typeof h === "string") : [];
207
227
  }
208
228
  };
229
+ var OtpAttemptsExhaustedError = class extends AgentChatError {
230
+ constructor(response, status, requestId = null) {
231
+ super(response, status, requestId);
232
+ this.name = "OtpAttemptsExhaustedError";
233
+ }
234
+ };
209
235
  var ServerError = class extends AgentChatError {
210
236
  constructor(response, status, requestId = null) {
211
237
  super(response, status, requestId);
@@ -218,13 +244,17 @@ var ConnectionError = class extends Error {
218
244
  this.name = "ConnectionError";
219
245
  }
220
246
  };
247
+ function retryAfterMsOf(body) {
248
+ const seconds = retryAfterSecondsOf(body);
249
+ return seconds === null ? null : seconds * 1e3;
250
+ }
221
251
  function createAgentChatError(body, status, headers) {
222
252
  const requestId = headers?.get("x-request-id") ?? null;
223
253
  switch (body.code) {
224
254
  case ErrorCode.RATE_LIMITED: {
225
255
  const fromHeader = headers ? parseRetryAfter(headers.get("retry-after")) : null;
226
256
  const fromBody = typeof body.details?.retry_after_ms === "number" ? body.details.retry_after_ms : null;
227
- return new RateLimitedError(body, status, fromHeader ?? fromBody, requestId);
257
+ return new RateLimitedError(body, status, fromHeader ?? fromBody ?? retryAfterMsOf(body), requestId);
228
258
  }
229
259
  case ErrorCode.SUSPENDED:
230
260
  case ErrorCode.AGENT_SUSPENDED:
@@ -260,6 +290,8 @@ function createAgentChatError(body, status, headers) {
260
290
  return new EmailExhaustedError(body, status, requestId);
261
291
  case ErrorCode.HANDLE_REQUIRED:
262
292
  return new HandleRequiredError(body, status, requestId);
293
+ case ErrorCode.OTP_ATTEMPTS_EXHAUSTED:
294
+ return new OtpAttemptsExhaustedError(body, status, requestId);
263
295
  case ErrorCode.INTERNAL_ERROR:
264
296
  return new ServerError(body, status, requestId);
265
297
  default:
@@ -268,7 +300,7 @@ function createAgentChatError(body, status, headers) {
268
300
  if (status === 404) return new NotFoundError(body, status, requestId);
269
301
  if (status === 429) {
270
302
  const fromHeader = headers ? parseRetryAfter(headers.get("retry-after")) : null;
271
- return new RateLimitedError(body, status, fromHeader, requestId);
303
+ return new RateLimitedError(body, status, fromHeader ?? retryAfterMsOf(body), requestId);
272
304
  }
273
305
  if (status >= 500) return new ServerError(body, status, requestId);
274
306
  return new AgentChatError(body, status, requestId);
@@ -276,7 +308,7 @@ function createAgentChatError(body, status, headers) {
276
308
  }
277
309
 
278
310
  // src/version.ts
279
- var VERSION = "1.3.2" ;
311
+ var VERSION = "1.4.0" ;
280
312
 
281
313
  // src/runtime.ts
282
314
  function detectRuntime() {
@@ -410,8 +442,10 @@ var HttpTransport = class {
410
442
  }
411
443
  const errBody = await parseErrorBody(res);
412
444
  const error = createAgentChatError(errBody, res.status, res.headers);
413
- const isTerminal429 = error instanceof RecipientBackloggedError || error instanceof AwaitingReplyError;
414
- const retriable = canRetry && attempt < maxAttempts && RETRIABLE_STATUSES.has(res.status) && !isTerminal429;
445
+ const isTerminal429 = error instanceof RecipientBackloggedError || error instanceof AwaitingReplyError || error instanceof OtpAttemptsExhaustedError;
446
+ const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
447
+ const waitsTooLong = res.status === 429 && retryAfter !== null && retryAfter > policy.maxDelayMs;
448
+ const retriable = canRetry && attempt < maxAttempts && RETRIABLE_STATUSES.has(res.status) && !isTerminal429 && !waitsTooLong;
415
449
  await safeInvoke(this.hooks.onError, {
416
450
  ...requestInfo,
417
451
  status: res.status,
@@ -419,7 +453,6 @@ var HttpTransport = class {
419
453
  error
420
454
  });
421
455
  if (retriable) {
422
- const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
423
456
  const delayMs = computeDelay(policy, attempt, retryAfter);
424
457
  await safeInvoke(this.hooks.onRetry, {
425
458
  ...requestInfo,
@@ -527,23 +560,23 @@ function toConnectionError(err, userSignal) {
527
560
  }
528
561
  async function parseJsonOrVoid(res) {
529
562
  if (res.status === 204) return void 0;
530
- const text = await res.text();
531
- if (!text) return void 0;
563
+ const text2 = await res.text();
564
+ if (!text2) return void 0;
532
565
  try {
533
- return JSON.parse(text);
566
+ return JSON.parse(text2);
534
567
  } catch {
535
568
  throw new ConnectionError(
536
- `AgentChat SDK: expected JSON response but got: ${text.slice(0, 200)}`
569
+ `AgentChat SDK: expected JSON response but got: ${text2.slice(0, 200)}`
537
570
  );
538
571
  }
539
572
  }
540
573
  async function parseErrorBody(res) {
541
574
  try {
542
- const text = await res.text();
543
- if (!text) {
575
+ const text2 = await res.text();
576
+ if (!text2) {
544
577
  return { code: statusToCode(res.status), message: res.statusText || "Request failed" };
545
578
  }
546
- const body = JSON.parse(text);
579
+ const body = JSON.parse(text2);
547
580
  if (body && typeof body === "object" && typeof body.code === "string" && typeof body.message === "string") {
548
581
  return body;
549
582
  }
@@ -672,6 +705,30 @@ function generateClientMsgId() {
672
705
  }
673
706
  return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
674
707
  }
708
+ var SIGNUP_FLOW_FIELDS = [
709
+ "version",
710
+ "flow",
711
+ "next_step",
712
+ "status",
713
+ "param",
714
+ "expires_at",
715
+ "expires_in_s",
716
+ "code_length",
717
+ "attempts",
718
+ "max_attempts",
719
+ "resend_after_s",
720
+ "retry_after_s",
721
+ "message"
722
+ ];
723
+ function signupFlowFieldsOf(body) {
724
+ const out = {};
725
+ if (body === null || typeof body !== "object") return out;
726
+ const record = body;
727
+ for (const key of SIGNUP_FLOW_FIELDS) {
728
+ if (record[key] !== void 0) out[key] = record[key];
729
+ }
730
+ return out;
731
+ }
675
732
  var INBOX_WAIT_TIMEOUT_GRACE_MS = 1e4;
676
733
  var AgentChatClient = class _AgentChatClient {
677
734
  http;
@@ -882,7 +939,7 @@ var AgentChatClient = class _AgentChatClient {
882
939
  clientIdentity: options?.clientIdentity,
883
940
  ...options?.fetch ? { fetch: options.fetch } : {}
884
941
  });
885
- return { agent: res.data.agent, apiKey: res.data.api_key, client };
942
+ return { ...signupFlowFieldsOf(res.data), agent: res.data.agent, apiKey: res.data.api_key, client };
886
943
  }
887
944
  /**
888
945
  * Start account recovery for a lost API key. The server emails a 6-digit
@@ -933,7 +990,7 @@ var AgentChatClient = class _AgentChatClient {
933
990
  clientIdentity: options?.clientIdentity,
934
991
  ...options?.fetch ? { fetch: options.fetch } : {}
935
992
  });
936
- return { handle: res.data.handle, apiKey: res.data.api_key, client };
993
+ return { ...signupFlowFieldsOf(res.data), handle: res.data.handle, apiKey: res.data.api_key, client };
937
994
  }
938
995
  // ─── Agent profile ────────────────────────────────────────────────────────
939
996
  /**
@@ -2789,12 +2846,12 @@ var RealtimeClient = class {
2789
2846
  * `inFlightAdoptMs` at most — a handler that never finishes must not stop
2790
2847
  * its conversation for good (it keeps running; the next message goes on).
2791
2848
  */
2792
- heldAtMost(run2) {
2849
+ heldAtMost(run3) {
2793
2850
  const ms = this.options.inFlightAdoptMs;
2794
2851
  return new Promise((resolve) => {
2795
2852
  const timer = setTimeout(resolve, ms);
2796
2853
  unref(timer);
2797
- run2.then(
2854
+ run3.then(
2798
2855
  () => {
2799
2856
  clearTimeout(timer);
2800
2857
  resolve();
@@ -2926,16 +2983,16 @@ var RealtimeClient = class {
2926
2983
  return "payload is not an object";
2927
2984
  }
2928
2985
  const p = payload;
2929
- const text = (key) => typeof p[key] !== "string" || p[key] === "" ? `${key} is not a non-empty string` : null;
2986
+ const text2 = (key) => typeof p[key] !== "string" || p[key] === "" ? `${key} is not a non-empty string` : null;
2930
2987
  const integerStep = typeof p.step === "number" && Number.isInteger(p.step);
2931
2988
  if (!this.negotiated.has("rewake")) {
2932
- return text("reason") ?? text("conversation_id") ?? text("anchor_message_id") ?? text("at") ?? (integerStep ? null : "step is not an integer");
2989
+ return text2("reason") ?? text2("conversation_id") ?? text2("anchor_message_id") ?? text2("at") ?? (integerStep ? null : "step is not an integer");
2933
2990
  }
2934
- const reasonProblem = text("reason") ?? text("at");
2991
+ const reasonProblem = text2("reason") ?? text2("at");
2935
2992
  if (reasonProblem !== null) return reasonProblem;
2936
2993
  switch (p.reason) {
2937
2994
  case "reminder":
2938
- return text("conversation_id") ?? text("anchor_message_id") ?? (integerStep ? null : "step is not an integer");
2995
+ return text2("conversation_id") ?? text2("anchor_message_id") ?? (integerStep ? null : "step is not an integer");
2939
2996
  case "unanswered": {
2940
2997
  const ids = p.conversation_ids;
2941
2998
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) {
@@ -3315,8 +3372,8 @@ ${canonicalJson(card)}`);
3315
3372
  function servedText(value) {
3316
3373
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
3317
3374
  }
3318
- function parseVerdicts(text, tray) {
3319
- const raw = extractJson(text);
3375
+ function parseVerdicts(text2, tray) {
3376
+ const raw = extractJson(text2);
3320
3377
  if (raw === null) return null;
3321
3378
  let parsed;
3322
3379
  try {
@@ -3353,18 +3410,18 @@ function parseVerdicts(text, tray) {
3353
3410
  }
3354
3411
  return out;
3355
3412
  }
3356
- function extractJson(text) {
3357
- if (typeof text !== "string" || text.trim().length === 0) return null;
3358
- let s = text.trim();
3413
+ function extractJson(text2) {
3414
+ if (typeof text2 !== "string" || text2.trim().length === 0) return null;
3415
+ let s = text2.trim();
3359
3416
  const fence = FENCE_RE.exec(s);
3360
3417
  if (fence?.[1]) s = fence[1].trim();
3361
3418
  const starts = [s.indexOf("{"), s.indexOf("[")].filter((i) => i !== -1);
3362
3419
  if (starts.length === 0) return null;
3363
- const start = Math.min(...starts);
3364
- const closer = s[start] === "{" ? "}" : "]";
3420
+ const start2 = Math.min(...starts);
3421
+ const closer = s[start2] === "{" ? "}" : "]";
3365
3422
  const end = s.lastIndexOf(closer);
3366
- if (end <= start) return null;
3367
- return s.slice(start, end + 1);
3423
+ if (end <= start2) return null;
3424
+ return s.slice(start2, end + 1);
3368
3425
  }
3369
3426
  function normalizeDecision(value) {
3370
3427
  if (typeof value !== "string") return null;
@@ -3384,7 +3441,7 @@ async function run(options) {
3384
3441
  const ids = cards.map((card) => card.conversation_id);
3385
3442
  if (ids.length === 0) return emptyResult("empty", [], null);
3386
3443
  let prompt;
3387
- let text;
3444
+ let text2;
3388
3445
  try {
3389
3446
  prompt = buildPrompt(options.tray, { texts: options.texts, toolNamer: options.toolNamer });
3390
3447
  } catch (err) {
@@ -3392,12 +3449,12 @@ async function run(options) {
3392
3449
  }
3393
3450
  if (options.signal?.aborted) return emptyResult("fail_closed", ids, "the gate was stopped");
3394
3451
  try {
3395
- text = options.signal ? await options.callModel(prompt, { signal: options.signal }) : await options.callModel(prompt);
3452
+ text2 = options.signal ? await options.callModel(prompt, { signal: options.signal }) : await options.callModel(prompt);
3396
3453
  } catch (err) {
3397
3454
  return emptyResult("fail_closed", ids, `model call failed: ${describe(err)}`);
3398
3455
  }
3399
3456
  if (options.signal?.aborted) return emptyResult("fail_closed", ids, "the gate was stopped");
3400
- const verdicts = parseVerdicts(text, options.tray);
3457
+ const verdicts = parseVerdicts(text2, options.tray);
3401
3458
  if (verdicts === null || verdicts.length === 0) {
3402
3459
  return emptyResult("fail_closed", ids, "no usable verdicts in the answer");
3403
3460
  }
@@ -3501,6 +3558,7 @@ __export(integration_exports, {
3501
3558
  TextsCache: () => TextsCache,
3502
3559
  TurnTracker: () => TurnTracker,
3503
3560
  WakeCoalescer: () => WakeCoalescer,
3561
+ account: () => account_exports,
3504
3562
  anchor: () => anchor_exports,
3505
3563
  applyInviteOutcome: () => applyInviteOutcome,
3506
3564
  applyOutcome: () => applyOutcome,
@@ -3803,11 +3861,11 @@ function render(texts, handle) {
3803
3861
  }
3804
3862
  return [START_MARKER, handleLine(bare), line, END_MARKER].join("\n");
3805
3863
  }
3806
- function find(text, options = {}) {
3807
- const spans = blocksOf(text);
3864
+ function find(text2, options = {}) {
3865
+ const spans = blocksOf(text2);
3808
3866
  const span = spans.find((s) => !s.legacy) ?? spans[0];
3809
3867
  if (!span) return null;
3810
- const inner = text.slice(span.innerStart, span.innerEnd).replace(/\r\n/g, "\n");
3868
+ const inner = text2.slice(span.innerStart, span.innerEnd).replace(/\r\n/g, "\n");
3811
3869
  let handle = null;
3812
3870
  let marked = false;
3813
3871
  const kept = [];
@@ -3824,39 +3882,39 @@ function find(text, options = {}) {
3824
3882
  if (handle === null) handle = handleFromWording(body, options.template ?? null);
3825
3883
  return { start: span.start, end: span.end, handle, marked, legacy: span.legacy, body };
3826
3884
  }
3827
- function replace(text, block) {
3828
- const spans = blocksOf(text);
3885
+ function replace(text2, block) {
3886
+ const spans = blocksOf(text2);
3829
3887
  if (spans.length === 0) {
3830
- const trimmed = text.replace(/\n+$/, "");
3888
+ const trimmed = text2.replace(/\n+$/, "");
3831
3889
  return trimmed.length === 0 ? `${block}
3832
3890
  ` : `${trimmed}
3833
3891
 
3834
3892
  ${block}
3835
3893
  `;
3836
3894
  }
3837
- return rebuild(text, spans, block);
3895
+ return rebuild(text2, spans, block);
3838
3896
  }
3839
- function remove(text) {
3840
- const spans = blocksOf(text);
3841
- if (spans.length === 0) return text;
3842
- return rebuild(text, spans, null);
3897
+ function remove(text2) {
3898
+ const spans = blocksOf(text2);
3899
+ if (spans.length === 0) return text2;
3900
+ return rebuild(text2, spans, null);
3843
3901
  }
3844
- function linesOf(text) {
3902
+ function linesOf(text2) {
3845
3903
  const lines = [];
3846
3904
  let at = 0;
3847
- while (at <= text.length) {
3848
- const nl = text.indexOf("\n", at);
3849
- const end = nl === -1 ? text.length : nl;
3850
- lines.push({ start: at, end, next: nl === -1 ? text.length + 1 : nl + 1, trimmed: text.slice(at, end).trim() });
3905
+ while (at <= text2.length) {
3906
+ const nl = text2.indexOf("\n", at);
3907
+ const end = nl === -1 ? text2.length : nl;
3908
+ lines.push({ start: at, end, next: nl === -1 ? text2.length + 1 : nl + 1, trimmed: text2.slice(at, end).trim() });
3851
3909
  if (nl === -1) break;
3852
3910
  at = nl + 1;
3853
3911
  }
3854
3912
  return lines;
3855
3913
  }
3856
- function blocksOf(text) {
3914
+ function blocksOf(text2) {
3857
3915
  const spans = [];
3858
3916
  let open = null;
3859
- for (const line of linesOf(text)) {
3917
+ for (const line of linesOf(text2)) {
3860
3918
  if (line.trimmed === START_MARKER || line.trimmed === LEGACY_START_MARKER) {
3861
3919
  open = { line, legacy: line.trimmed === LEGACY_START_MARKER };
3862
3920
  continue;
@@ -3875,20 +3933,20 @@ function blocksOf(text) {
3875
3933
  }
3876
3934
  return spans;
3877
3935
  }
3878
- function rebuild(text, spans, replacement) {
3936
+ function rebuild(text2, spans, replacement) {
3879
3937
  const parts = [];
3880
3938
  const first = spans[0];
3881
3939
  const last = spans[spans.length - 1];
3882
- if (!first || !last) return text;
3883
- parts.push(text.slice(0, first.start).replace(/\n+$/, ""));
3940
+ if (!first || !last) return text2;
3941
+ parts.push(text2.slice(0, first.start).replace(/\n+$/, ""));
3884
3942
  if (replacement !== null) parts.push(replacement);
3885
3943
  for (let i = 1; i < spans.length; i++) {
3886
3944
  const previous = spans[i - 1];
3887
3945
  const current = spans[i];
3888
3946
  if (!previous || !current) continue;
3889
- parts.push(text.slice(previous.end, current.start).replace(/^\n+/, "").replace(/\n+$/, ""));
3947
+ parts.push(text2.slice(previous.end, current.start).replace(/^\n+/, "").replace(/\n+$/, ""));
3890
3948
  }
3891
- parts.push(text.slice(last.end).replace(/^\n+/, ""));
3949
+ parts.push(text2.slice(last.end).replace(/^\n+/, ""));
3892
3950
  const kept = parts.filter((part) => part.length > 0);
3893
3951
  if (kept.length === 0) return "";
3894
3952
  const out = kept.join("\n\n");
@@ -4327,13 +4385,13 @@ var MANUAL_FETCH_TIMEOUT_MS = 1e4;
4327
4385
  var MANUAL_MAX_REDIRECTS = 3;
4328
4386
  var MANUAL_SKILL_NAME = "agentchat";
4329
4387
  function manualFrontMatter(raw) {
4330
- const text = (raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw).replace(/\r\n/g, "\n");
4331
- if (!text.startsWith("---\n")) return null;
4332
- let close = text.indexOf("\n---", 3);
4333
- while (close >= 0 && text.charAt(close + 4) !== "\n" && close + 4 !== text.length) close = text.indexOf("\n---", close + 1);
4388
+ const text2 = (raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw).replace(/\r\n/g, "\n");
4389
+ if (!text2.startsWith("---\n")) return null;
4390
+ let close = text2.indexOf("\n---", 3);
4391
+ while (close >= 0 && text2.charAt(close + 4) !== "\n" && close + 4 !== text2.length) close = text2.indexOf("\n---", close + 1);
4334
4392
  if (close < 0) return null;
4335
4393
  const fields = /* @__PURE__ */ new Map();
4336
- for (const line of text.slice(4, close).split("\n")) {
4394
+ for (const line of text2.slice(4, close).split("\n")) {
4337
4395
  const match = /^([A-Za-z0-9_-]+):[ \t]*(.*?)[ \t]*$/.exec(line);
4338
4396
  if (match === null) continue;
4339
4397
  const value = match[2] ?? "";
@@ -4341,8 +4399,8 @@ function manualFrontMatter(raw) {
4341
4399
  }
4342
4400
  return fields;
4343
4401
  }
4344
- function manualVersion(text) {
4345
- const version = manualFrontMatter(text)?.get("version");
4402
+ function manualVersion(text2) {
4403
+ const version = manualFrontMatter(text2)?.get("version");
4346
4404
  return version !== void 0 && version.length > 0 ? version : null;
4347
4405
  }
4348
4406
  async function syncManual(options) {
@@ -4582,13 +4640,13 @@ async function downloadManual(served, hash, origin, options) {
4582
4640
  if (timeout.aborted) throw new Error(`no answer from ${served.url} within ${timeoutMs} ms`);
4583
4641
  throw err;
4584
4642
  }
4585
- let text;
4643
+ let text2;
4586
4644
  try {
4587
- text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
4645
+ text2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
4588
4646
  } catch {
4589
4647
  throw new Error("the body is not UTF-8 text");
4590
4648
  }
4591
- checkManualText(text, served.version);
4649
+ checkManualText(text2, served.version);
4592
4650
  if (hash !== null) {
4593
4651
  const got = await sha256(bytes);
4594
4652
  if (got !== hash) throw new Error(`the body's sha256 is ${got}, the server announced ${hash}`);
@@ -4618,12 +4676,12 @@ async function readCapped(response, maxBytes) {
4618
4676
  }
4619
4677
  return out;
4620
4678
  }
4621
- function checkManualText(text, announced) {
4622
- if (text.includes("\0")) throw new Error("the body is not text");
4623
- const fields = manualFrontMatter(text);
4679
+ function checkManualText(text2, announced) {
4680
+ if (text2.includes("\0")) throw new Error("the body is not text");
4681
+ const fields = manualFrontMatter(text2);
4624
4682
  if (fields === null) throw new Error("the body has no front matter \u2014 not the manual");
4625
4683
  if (fields.get("name") !== MANUAL_SKILL_NAME) throw new Error(`the front matter names "${fields.get("name") ?? ""}", not the ${MANUAL_SKILL_NAME} skill`);
4626
- const version = manualVersion(text);
4684
+ const version = manualVersion(text2);
4627
4685
  if (version !== announced) throw new Error(`the body is version ${version ?? "(none)"}, the server announced ${announced}`);
4628
4686
  }
4629
4687
  function anySignal(a, b) {
@@ -4661,18 +4719,18 @@ async function probeHostedTools(options) {
4661
4719
  accept: "application/json, text/event-stream",
4662
4720
  ...clientIdentityHeaders(options.clientIdentity)
4663
4721
  };
4664
- const call = async (id, method, params, extra = {}) => {
4722
+ const call2 = async (id, method, params, extra = {}) => {
4665
4723
  const res = await fetchImpl(hostedMcpUrl(options.apiBase), {
4666
4724
  method: "POST",
4667
4725
  headers: { ...headers, ...extra },
4668
4726
  body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
4669
4727
  signal: controller.signal
4670
4728
  });
4671
- const text = await res.text();
4672
- return { res, result: readResult(text) };
4729
+ const text2 = await res.text();
4730
+ return { res, result: readResult(text2) };
4673
4731
  };
4674
4732
  try {
4675
- const init = await call(1, "initialize", {
4733
+ const init = await call2(1, "initialize", {
4676
4734
  protocolVersion: MCP_PROTOCOL_VERSION,
4677
4735
  capabilities: {},
4678
4736
  clientInfo: { name: options.clientIdentity?.name ?? "typescript_sdk", version: options.clientIdentity?.version ?? "0" }
@@ -4693,7 +4751,7 @@ async function probeHostedTools(options) {
4693
4751
  ...typeof serverInfo.version === "string" ? { serverVersion: serverInfo.version } : {},
4694
4752
  protocolVersion
4695
4753
  };
4696
- const list = await call(2, "tools/list", {}, {
4754
+ const list = await call2(2, "tools/list", {}, {
4697
4755
  "mcp-protocol-version": protocolVersion,
4698
4756
  ...session ? { "mcp-session-id": session } : {}
4699
4757
  });
@@ -4718,11 +4776,11 @@ async function probeHostedTools(options) {
4718
4776
  clearTimeout(timer);
4719
4777
  }
4720
4778
  }
4721
- function readResult(text) {
4779
+ function readResult(text2) {
4722
4780
  const candidates = [];
4723
- const trimmed = text.trim();
4781
+ const trimmed = text2.trim();
4724
4782
  if (trimmed.startsWith("{")) candidates.push(trimmed);
4725
- for (const line of text.split(/\r?\n/)) {
4783
+ for (const line of text2.split(/\r?\n/)) {
4726
4784
  if (line.startsWith("data:")) candidates.push(line.slice(5).trim());
4727
4785
  }
4728
4786
  for (const candidate of candidates) {
@@ -5037,7 +5095,7 @@ var ReceiveLoop = class {
5037
5095
  let excludedMs = 0;
5038
5096
  let excludedSince = null;
5039
5097
  let depth = 0;
5040
- const run2 = {
5098
+ const run3 = {
5041
5099
  token,
5042
5100
  signal: controller.signal,
5043
5101
  stale: () => this.cycleToken !== token || this.stopped,
@@ -5055,8 +5113,8 @@ var ReceiveLoop = class {
5055
5113
  }
5056
5114
  };
5057
5115
  const work = (async () => {
5058
- const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(run2) : await this.singleRunCycle(run2);
5059
- if (!run2.abandoned()) this.finishCycle(summary);
5116
+ const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(run3) : await this.singleRunCycle(run3);
5117
+ if (!run3.abandoned()) this.finishCycle(summary);
5060
5118
  })();
5061
5119
  let timer = null;
5062
5120
  const overdue = new Promise((resolve) => {
@@ -5100,7 +5158,7 @@ var ReceiveLoop = class {
5100
5158
  * an abandoned cycle: the server may already have taken it, and a second
5101
5159
  * one could climb the defer ladder twice.
5102
5160
  */
5103
- recordingClient(run2) {
5161
+ recordingClient(run3) {
5104
5162
  const decisions = this.client.decisions;
5105
5163
  return {
5106
5164
  decisions: {
@@ -5110,7 +5168,7 @@ var ReceiveLoop = class {
5110
5168
  return await decisions.record(conversationId, options);
5111
5169
  } finally {
5112
5170
  this.recordsInFlight.delete(conversationId);
5113
- if (run2.stale()) this.afterTurnEnded();
5171
+ if (run3.stale()) this.afterTurnEnded();
5114
5172
  }
5115
5173
  }
5116
5174
  }
@@ -5124,44 +5182,44 @@ var ReceiveLoop = class {
5124
5182
  * cycle that is making progress is not abandoned for it. With the deadline
5125
5183
  * off the watchdog is the calls' only bound, so they count.
5126
5184
  */
5127
- boundedModelCall(run2) {
5128
- const call = this.deadlineModelCall(run2);
5129
- if (!Number.isFinite(this.gateCallTimeoutMs)) return call;
5130
- return (prompt, options) => run2.exclude(() => call(prompt, options));
5185
+ boundedModelCall(run3) {
5186
+ const call2 = this.deadlineModelCall(run3);
5187
+ if (!Number.isFinite(this.gateCallTimeoutMs)) return call2;
5188
+ return (prompt, options) => run3.exclude(() => call2(prompt, options));
5131
5189
  }
5132
- deadlineModelCall(run2) {
5190
+ deadlineModelCall(run3) {
5133
5191
  return (prompt) => new Promise((resolve, reject) => {
5134
5192
  const controller = new AbortController();
5135
5193
  const abort = () => {
5136
5194
  controller.abort();
5137
5195
  reject(new Error("the cycle was abandoned"));
5138
5196
  };
5139
- if (run2.signal.aborted) {
5197
+ if (run3.signal.aborted) {
5140
5198
  abort();
5141
5199
  return;
5142
5200
  }
5143
- run2.signal.addEventListener("abort", abort, { once: true });
5201
+ run3.signal.addEventListener("abort", abort, { once: true });
5144
5202
  const timer = Number.isFinite(this.gateCallTimeoutMs) ? this._setTimeout(() => {
5145
- run2.signal.removeEventListener("abort", abort);
5203
+ run3.signal.removeEventListener("abort", abort);
5146
5204
  controller.abort();
5147
5205
  reject(new Error(`no answer within ${this.gateCallTimeoutMs} ms`));
5148
5206
  }, this.gateCallTimeoutMs) : null;
5149
5207
  if (timer !== null) timer.unref?.();
5150
- let call;
5208
+ let call2;
5151
5209
  try {
5152
- call = Promise.resolve(this.options.callModel(prompt, { signal: controller.signal }));
5210
+ call2 = Promise.resolve(this.options.callModel(prompt, { signal: controller.signal }));
5153
5211
  } catch (err) {
5154
- call = Promise.reject(err);
5212
+ call2 = Promise.reject(err);
5155
5213
  }
5156
- call.then(
5157
- (text) => {
5214
+ call2.then(
5215
+ (text2) => {
5158
5216
  if (timer !== null) this._clearTimeout(timer);
5159
- run2.signal.removeEventListener("abort", abort);
5160
- resolve(text);
5217
+ run3.signal.removeEventListener("abort", abort);
5218
+ resolve(text2);
5161
5219
  },
5162
5220
  (err) => {
5163
5221
  if (timer !== null) this._clearTimeout(timer);
5164
- run2.signal.removeEventListener("abort", abort);
5222
+ run3.signal.removeEventListener("abort", abort);
5165
5223
  reject(err);
5166
5224
  }
5167
5225
  );
@@ -5189,9 +5247,9 @@ var ReceiveLoop = class {
5189
5247
  return err instanceof Error ? err.message : String(err);
5190
5248
  }
5191
5249
  }
5192
- async gateCallCycle(run2) {
5250
+ async gateCallCycle(run3) {
5193
5251
  const tray = await this.readTray();
5194
- if (run2.stale()) return this.summary("abandoned");
5252
+ if (run3.stale()) return this.summary("abandoned");
5195
5253
  if (tray === null) return this.summary("tray_failed", { failure: this.lastError });
5196
5254
  const cards = cardsOf(tray);
5197
5255
  const invites = trayInvites(tray);
@@ -5207,10 +5265,10 @@ var ReceiveLoop = class {
5207
5265
  if (cards.length === 0 && invites.length === 0) return this.summary("empty", base);
5208
5266
  if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
5209
5267
  const texts = await this.options.texts.ensure();
5210
- if (run2.stale()) return this.summary("abandoned", base);
5268
+ if (run3.stale()) return this.summary("abandoned", base);
5211
5269
  if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
5212
5270
  const unready = await this.checkReady();
5213
- if (run2.stale()) return this.summary("abandoned", base);
5271
+ if (run3.stale()) return this.summary("abandoned", base);
5214
5272
  if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5215
5273
  const tally = {
5216
5274
  gated: 0,
@@ -5230,7 +5288,7 @@ var ReceiveLoop = class {
5230
5288
  let outcome = "invites_only";
5231
5289
  let failure = null;
5232
5290
  if (owedCards.length > 0) {
5233
- const gate = await this.gateInChunks(run2, tray, gateCards, texts);
5291
+ const gate = await this.gateInChunks(run3, tray, gateCards, texts);
5234
5292
  heldDuringGate = gate.held;
5235
5293
  tally.gated = gate.gated;
5236
5294
  tally.reply = gate.verdicts.reply;
@@ -5245,21 +5303,21 @@ var ReceiveLoop = class {
5245
5303
  if (tally.chunksOk > 0) {
5246
5304
  outcome = "decided";
5247
5305
  for (const reply of gate.reply) {
5248
- if (run2.stale()) break;
5249
- tally[launchKey(await run2.exclude(() => this.startReplyTurn(reply, texts)))] += 1;
5306
+ if (run3.stale()) break;
5307
+ tally[launchKey(await run3.exclude(() => this.startReplyTurn(reply, texts)))] += 1;
5250
5308
  }
5251
5309
  } else if (tally.chunksFailed > 0) {
5252
5310
  outcome = "fail_closed";
5253
- } else if (owedInvites.length === 0 && !run2.stale()) {
5311
+ } else if (owedInvites.length === 0 && !run3.stale()) {
5254
5312
  return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate });
5255
5313
  }
5256
5314
  }
5257
5315
  for (const invite of owedInvites) {
5258
- if (run2.stale()) break;
5259
- tally[launchKey(await run2.exclude(() => this.startInviteTurn(invite, texts)))] += 1;
5316
+ if (run3.stale()) break;
5317
+ tally[launchKey(await run3.exclude(() => this.startInviteTurn(invite, texts)))] += 1;
5260
5318
  }
5261
5319
  const parts = { ...base, heldByTurns: heldByTurns + heldDuringGate, ...tally };
5262
- if (run2.stale()) return this.summary("abandoned", parts);
5320
+ if (run3.stale()) return this.summary("abandoned", parts);
5263
5321
  if (tray.truncated === true && outcome === "decided") {
5264
5322
  this.readTheRest(tally.recorded > 0 || tally.turnsStarted > 0);
5265
5323
  }
@@ -5287,11 +5345,11 @@ var ReceiveLoop = class {
5287
5345
  * a stop cut short is not counted as a failed chunk, and a cycle the
5288
5346
  * watchdog abandoned reports and counts no chunk after its summary.
5289
5347
  */
5290
- async gateInChunks(run2, tray, cards, texts) {
5348
+ async gateInChunks(run3, tray, cards, texts) {
5291
5349
  const size = this.gateChunkSize;
5292
5350
  const of = Math.ceil(cards.length / size);
5293
- const callModel = this.boundedModelCall(run2);
5294
- const client = this.recordingClient(run2);
5351
+ const callModel = this.boundedModelCall(run3);
5352
+ const client = this.recordingClient(run3);
5295
5353
  const out = {
5296
5354
  gated: 0,
5297
5355
  held: 0,
@@ -5303,7 +5361,7 @@ var ReceiveLoop = class {
5303
5361
  chunks: []
5304
5362
  };
5305
5363
  for (let index = 1; index <= of; index++) {
5306
- if (run2.stale()) break;
5364
+ if (run3.stale()) break;
5307
5365
  const planned = cards.slice((index - 1) * size, index * size);
5308
5366
  const chunk = this.unheld(planned);
5309
5367
  out.held += planned.length - chunk.length;
@@ -5314,11 +5372,11 @@ var ReceiveLoop = class {
5314
5372
  callModel,
5315
5373
  client,
5316
5374
  texts,
5317
- signal: run2.signal,
5375
+ signal: run3.signal,
5318
5376
  ...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
5319
5377
  });
5320
- if (run2.abandoned()) break;
5321
- if (run2.stale() && result.outcome !== "decided") break;
5378
+ if (run3.abandoned()) break;
5379
+ if (run3.stale() && result.outcome !== "decided") break;
5322
5380
  out.gated += chunk.length;
5323
5381
  const undecided = new Set(result.undecided);
5324
5382
  for (const verdict of result.verdicts) {
@@ -5329,7 +5387,7 @@ var ReceiveLoop = class {
5329
5387
  out.recorded += result.recorded;
5330
5388
  out.recordFailures += result.recordFailures.length;
5331
5389
  const report = {
5332
- cycle: run2.token,
5390
+ cycle: run3.token,
5333
5391
  index,
5334
5392
  of,
5335
5393
  cards: chunk.length,
@@ -5373,9 +5431,9 @@ var ReceiveLoop = class {
5373
5431
  this.moreTimer = null;
5374
5432
  }
5375
5433
  }
5376
- async singleRunCycle(run2) {
5434
+ async singleRunCycle(run3) {
5377
5435
  const tray = await this.readTray();
5378
- if (run2.stale()) return this.summary("abandoned");
5436
+ if (run3.stale()) return this.summary("abandoned");
5379
5437
  let cards = null;
5380
5438
  let invites = null;
5381
5439
  let base = { cards: 0, invites: 0, heldByTurns: 0, truncated: false };
@@ -5387,10 +5445,10 @@ var ReceiveLoop = class {
5387
5445
  if (cards === 0 && invites === 0) return this.summary("nothing_owed", base);
5388
5446
  }
5389
5447
  const texts = await this.options.texts.ensure();
5390
- if (run2.stale()) return this.summary("abandoned", base);
5448
+ if (run3.stale()) return this.summary("abandoned", base);
5391
5449
  if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
5392
5450
  const unready = await this.checkReady();
5393
- if (run2.stale()) return this.summary("abandoned", base);
5451
+ if (run3.stale()) return this.summary("abandoned", base);
5394
5452
  if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5395
5453
  const prompt = cards === 0 && (invites ?? 0) > 0 ? texts.invite_prompt.trim() : (invites ?? 0) > 0 ? `${texts.wake_instruction.trim()}
5396
5454
 
@@ -5398,7 +5456,7 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5398
5456
  this.counts.runsStarted += 1;
5399
5457
  let end;
5400
5458
  try {
5401
- end = await run2.exclude(() => this.options.startRun({ prompt, texts, cards, invites, signal: this.abort.signal }));
5459
+ end = await run3.exclude(() => this.options.startRun({ prompt, texts, cards, invites, signal: this.abort.signal }));
5402
5460
  } catch (err) {
5403
5461
  end = { status: "not_started", detail: err instanceof Error ? err.message : String(err) };
5404
5462
  }
@@ -5614,9 +5672,9 @@ invite_id: ${invite.invite_id}`,
5614
5672
  }
5615
5673
  this.emit({ type: "invite_outcome", outcome, recorded });
5616
5674
  }
5617
- async admit(start, request) {
5675
+ async admit(start2, request) {
5618
5676
  try {
5619
- return await start(request);
5677
+ return await start2(request);
5620
5678
  } catch (err) {
5621
5679
  return { started: false, error: err instanceof Error ? err.message : String(err) };
5622
5680
  }
@@ -5733,6 +5791,466 @@ function wsBase(httpBase) {
5733
5791
  return base.replace(/^http/, "ws");
5734
5792
  }
5735
5793
 
5794
+ // src/integration/account.ts
5795
+ var account_exports = {};
5796
+ __export(account_exports, {
5797
+ DEFAULT_LABELS: () => DEFAULT_LABELS,
5798
+ MAX_AUTO_WAITS: () => MAX_AUTO_WAITS,
5799
+ MAX_WAIT_S: () => MAX_WAIT_S,
5800
+ MIN_WAIT_MS: () => MIN_WAIT_MS,
5801
+ actionOf: () => actionOf,
5802
+ checkKey: () => checkKey,
5803
+ flowOf: () => flowOf,
5804
+ run: () => run2,
5805
+ start: () => start,
5806
+ submitCode: () => submitCode
5807
+ });
5808
+ var DEFAULT_API_BASE = "https://api.agentchat.me";
5809
+ var MAX_WAIT_S = 60;
5810
+ var DEFAULT_LABELS = Object.freeze({
5811
+ email: "Email address",
5812
+ handle: "Handle",
5813
+ code: "Enter the 6-digit code"
5814
+ });
5815
+ var START_STEPS = /* @__PURE__ */ new Set(["register", "recover", "rotate_key"]);
5816
+ var VERIFY_STEPS = /* @__PURE__ */ new Set(["verify", "recover_verify", "rotate_key_verify"]);
5817
+ var KNOWN_STEPS = /* @__PURE__ */ new Set([...START_STEPS, ...VERIFY_STEPS, "done"]);
5818
+ function isRecord(value) {
5819
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5820
+ }
5821
+ function wholeNumber(value) {
5822
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
5823
+ }
5824
+ function text(value) {
5825
+ return typeof value === "string" && value.length > 0 ? value : void 0;
5826
+ }
5827
+ function flowOf(bodyOrError) {
5828
+ let source;
5829
+ if (bodyOrError instanceof AgentChatError) source = bodyOrError.details;
5830
+ else if (isRecord(bodyOrError)) source = typeof bodyOrError.code === "string" ? bodyOrError.details : bodyOrError;
5831
+ if (!isRecord(source)) return null;
5832
+ const nextStep = text(source.next_step);
5833
+ if (nextStep === void 0) return null;
5834
+ const flow = {
5835
+ version: typeof source.version === "number" ? source.version : 1,
5836
+ flow: text(source.flow) ?? "",
5837
+ next_step: nextStep
5838
+ };
5839
+ const strings = ["status", "pending_id", "param", "expires_at"];
5840
+ for (const key of strings) {
5841
+ const value = text(source[key]);
5842
+ if (value !== void 0) flow[key] = value;
5843
+ }
5844
+ const numbers = [
5845
+ "expires_in_s",
5846
+ "code_length",
5847
+ "attempts",
5848
+ "max_attempts",
5849
+ "resend_after_s",
5850
+ "retry_after_s"
5851
+ ];
5852
+ for (const key of numbers) {
5853
+ const value = wholeNumber(source[key]);
5854
+ if (value !== void 0) flow[key] = value;
5855
+ }
5856
+ return flow;
5857
+ }
5858
+ function isStartStep(step) {
5859
+ return START_STEPS.has(step);
5860
+ }
5861
+ function isVerifyStep(step) {
5862
+ return VERIFY_STEPS.has(step);
5863
+ }
5864
+ function actionOf(flow, httpStatus, calledStep) {
5865
+ if (flow === null) return "legacy";
5866
+ const step = flow.next_step;
5867
+ if (step === "done") return "done";
5868
+ if (httpStatus >= 500 || !KNOWN_STEPS.has(step)) return "stop";
5869
+ const wait = flow.retry_after_s;
5870
+ if (isVerifyStep(step) && wait === void 0) return "ask_code";
5871
+ if (isStartStep(step)) {
5872
+ if (flow.param !== void 0) return "ask_param";
5873
+ const codeGone = flow.status === "expired" || flow.status === "max_attempts_reached" || httpStatus === 429 && isVerifyStep(calledStep);
5874
+ if (codeGone && (wait === void 0 || wait <= MAX_WAIT_S)) return "offer_new_code";
5875
+ }
5876
+ if (httpStatus === 429 && wait !== void 0 && wait <= MAX_WAIT_S && step === calledStep) return "wait_then_retry";
5877
+ return "stop";
5878
+ }
5879
+ var STEPS = {
5880
+ register: { start: "register", verify: "verify", startPath: "/v1/register", verifyPath: "/v1/register/verify" },
5881
+ recover: {
5882
+ start: "recover",
5883
+ verify: "recover_verify",
5884
+ startPath: "/v1/agents/recover",
5885
+ verifyPath: "/v1/agents/recover/verify"
5886
+ }
5887
+ };
5888
+ function transport(options, apiKey) {
5889
+ return new HttpTransport({
5890
+ baseUrl: options.apiBase ?? DEFAULT_API_BASE,
5891
+ defaultHeaders: clientIdentityHeaders(options.clientIdentity),
5892
+ ...apiKey !== void 0 ? { apiKey } : {},
5893
+ ...options.fetch ? { fetch: options.fetch } : {},
5894
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
5895
+ });
5896
+ }
5897
+ async function call(options, method, path, body, apiKey) {
5898
+ try {
5899
+ const res = await transport(options, apiKey).request(method, path, {
5900
+ ...body !== void 0 ? { body } : {},
5901
+ retry: "never",
5902
+ ...options.signal ? { signal: options.signal } : {},
5903
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
5904
+ });
5905
+ return { httpStatus: res.status, body: res.data, error: null };
5906
+ } catch (err) {
5907
+ if (err instanceof AgentChatError) return { httpStatus: err.status, body: void 0, error: err };
5908
+ throw err;
5909
+ }
5910
+ }
5911
+ function successMessage(body) {
5912
+ return isRecord(body) && typeof body.message === "string" ? body.message : "";
5913
+ }
5914
+ function keyAndHandle(body) {
5915
+ if (!isRecord(body)) return {};
5916
+ const apiKey = text(body.api_key);
5917
+ const agent = isRecord(body.agent) ? body.agent : null;
5918
+ const handle = text(body.handle) ?? text(agent?.handle);
5919
+ return { ...apiKey !== void 0 ? { apiKey } : {}, ...handle !== void 0 ? { handle } : {} };
5920
+ }
5921
+ function handlesOf(error) {
5922
+ const raw = error?.details?.handles;
5923
+ if (!Array.isArray(raw)) return void 0;
5924
+ return raw.filter((h) => typeof h === "string");
5925
+ }
5926
+ function legacyWaitSeconds(error) {
5927
+ if (error.retryAfterS !== null) return error.retryAfterS;
5928
+ if (error instanceof RateLimitedError && error.retryAfterMs !== null) return Math.ceil(error.retryAfterMs / 1e3);
5929
+ return void 0;
5930
+ }
5931
+ function legacyFieldOf(error) {
5932
+ const fieldErrors = error.details?.fieldErrors;
5933
+ if (!isRecord(fieldErrors)) return void 0;
5934
+ const named = ["email", "handle", "code"].filter((f) => fieldErrors[f] !== void 0);
5935
+ return named.length === 1 ? named[0] : void 0;
5936
+ }
5937
+ function legacyFlow(kind, stepCalled, answer, submitted) {
5938
+ const steps = STEPS[kind];
5939
+ const startFlow = (extra = {}) => ({
5940
+ version: 1,
5941
+ flow: kind,
5942
+ next_step: steps.start,
5943
+ ...extra
5944
+ });
5945
+ const pendingAgain = (extra = {}) => ({
5946
+ version: 1,
5947
+ flow: kind,
5948
+ next_step: steps.verify,
5949
+ status: "pending",
5950
+ ...submitted?.pending_id !== void 0 ? { pending_id: submitted.pending_id } : {},
5951
+ code_length: submitted?.code_length ?? 6,
5952
+ ...extra
5953
+ });
5954
+ const { error, body } = answer;
5955
+ if (error === null) {
5956
+ if (stepCalled === "start") {
5957
+ const pendingId = isRecord(body) ? text(body.pending_id) : void 0;
5958
+ if (pendingId === void 0) return startFlow();
5959
+ return { version: 1, flow: kind, next_step: steps.verify, status: "pending", pending_id: pendingId, code_length: 6 };
5960
+ }
5961
+ const { apiKey } = keyAndHandle(body);
5962
+ if (apiKey === void 0) return startFlow();
5963
+ return { version: 1, flow: kind, next_step: "done", status: "approved" };
5964
+ }
5965
+ if (error.status === 429) {
5966
+ if (error.code === "OTP_ATTEMPTS_EXHAUSTED") return startFlow({ status: "max_attempts_reached" });
5967
+ const wait = legacyWaitSeconds(error);
5968
+ if (wait === void 0) return startFlow();
5969
+ return stepCalled === "verify" ? pendingAgain({ retry_after_s: wait }) : startFlow({ retry_after_s: wait });
5970
+ }
5971
+ switch (error.code) {
5972
+ case "HANDLE_TAKEN":
5973
+ case "INVALID_HANDLE":
5974
+ case "HANDLE_REQUIRED":
5975
+ return startFlow({ param: "handle" });
5976
+ case "EMAIL_LIMIT_REACHED":
5977
+ case "EMAIL_TAKEN":
5978
+ case "EMAIL_EXHAUSTED":
5979
+ return startFlow({ param: "email" });
5980
+ case "INVALID_CODE":
5981
+ return pendingAgain({ param: "code" });
5982
+ case "EXPIRED":
5983
+ return startFlow({ status: "expired" });
5984
+ case "VALIDATION_ERROR": {
5985
+ const field = legacyFieldOf(error);
5986
+ if (stepCalled === "verify") return field === "code" ? pendingAgain({ param: "code" }) : startFlow();
5987
+ return field === "email" || field === "handle" ? startFlow({ param: field }) : startFlow();
5988
+ }
5989
+ default:
5990
+ return startFlow();
5991
+ }
5992
+ }
5993
+ function read(kind, stepCalled, answer, submitted) {
5994
+ const { error, body, httpStatus } = answer;
5995
+ const served = flowOf(error ?? body);
5996
+ const legacy = served === null;
5997
+ let flow = served ?? legacyFlow(kind, stepCalled, answer, submitted);
5998
+ if (!legacy && submitted?.pending_id !== void 0 && flow.pending_id === void 0 && flow.next_step === submitted.next_step) {
5999
+ flow = { ...flow, pending_id: submitted.pending_id };
6000
+ }
6001
+ const calledStep = stepCalled === "start" ? STEPS[kind].start : STEPS[kind].verify;
6002
+ let action = actionOf(flow, httpStatus, calledStep);
6003
+ const credentials = error === null ? keyAndHandle(body) : {};
6004
+ if (action === "done" && (credentials.apiKey === void 0 || credentials.handle === void 0)) action = "stop";
6005
+ if (action === "ask_code" && flow.pending_id === void 0) action = "stop";
6006
+ const handles = handlesOf(error);
6007
+ return {
6008
+ flow,
6009
+ message: error !== null ? error.message : successMessage(body),
6010
+ action,
6011
+ httpStatus,
6012
+ calledStep,
6013
+ legacy,
6014
+ ...error !== null ? { code: error.code } : {},
6015
+ ...action === "done" ? credentials : {},
6016
+ ...handles !== void 0 ? { handles } : {}
6017
+ };
6018
+ }
6019
+ async function start(kind, input, options) {
6020
+ const steps = STEPS[kind];
6021
+ if (steps === void 0) throw new TypeError(`integration.account.start: unknown kind ${JSON.stringify(kind)}`);
6022
+ if (!isRecord(input)) throw new TypeError("integration.account.start: input must be an object");
6023
+ const body = kind === "register" ? {
6024
+ email: input.email,
6025
+ handle: input.handle,
6026
+ display_name: input.display_name,
6027
+ description: input.description
6028
+ } : { email: input.email, handle: input.handle };
6029
+ const answer = await call(options, "POST", steps.startPath, body);
6030
+ return read(kind, "start", answer, null);
6031
+ }
6032
+ async function submitCode(flow, code, options) {
6033
+ if (!isRecord(flow) || typeof flow.next_step !== "string") {
6034
+ throw new TypeError("integration.account.submitCode: flow must be a sign-up flow object");
6035
+ }
6036
+ const kind = flow.next_step === "verify" ? "register" : flow.next_step === "recover_verify" ? "recover" : null;
6037
+ if (kind === null) {
6038
+ throw new TypeError(
6039
+ `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)`
6040
+ );
6041
+ }
6042
+ if (typeof flow.pending_id !== "string" || flow.pending_id.length === 0) {
6043
+ throw new TypeError("integration.account.submitCode: the flow carries no pending_id");
6044
+ }
6045
+ const answer = await call(options, "POST", STEPS[kind].verifyPath, { pending_id: flow.pending_id, code });
6046
+ return read(kind, "verify", answer, flow);
6047
+ }
6048
+ async function checkKey(apiKey, options) {
6049
+ const answer = await call(options, "GET", "/v1/agents/me", void 0, apiKey);
6050
+ if (answer.error !== null) return { ok: false, code: answer.error.code, message: answer.error.message };
6051
+ const handle = isRecord(answer.body) ? text(answer.body.handle) : void 0;
6052
+ if (handle === void 0) {
6053
+ throw new Error(`integration.account.checkKey: GET /v1/agents/me answered ${answer.httpStatus} without a handle`);
6054
+ }
6055
+ return { ok: true, handle };
6056
+ }
6057
+ function defaultSleep(signal) {
6058
+ return (ms) => new Promise((resolve, reject) => {
6059
+ if (signal?.aborted) {
6060
+ reject(abortError());
6061
+ return;
6062
+ }
6063
+ const timer = setTimeout(() => {
6064
+ signal?.removeEventListener("abort", onAbort);
6065
+ resolve();
6066
+ }, ms);
6067
+ const onAbort = () => {
6068
+ clearTimeout(timer);
6069
+ reject(abortError());
6070
+ };
6071
+ signal?.addEventListener("abort", onAbort, { once: true });
6072
+ });
6073
+ }
6074
+ function abortError() {
6075
+ const err = new Error("Aborted");
6076
+ err.name = "AbortError";
6077
+ return err;
6078
+ }
6079
+ var FIELD_ANSWERS = ["value", "cancel"];
6080
+ var CODE_ANSWERS = ["value", "new_code", "cancel"];
6081
+ var NEW_CODE_ANSWERS = ["new_code", "cancel"];
6082
+ var MIN_WAIT_MS = 1e3;
6083
+ var MAX_AUTO_WAITS = 3;
6084
+ async function run2(options) {
6085
+ const { kind, ask, show } = options;
6086
+ if (STEPS[kind] === void 0) throw new TypeError(`integration.account.run: unknown kind ${JSON.stringify(kind)}`);
6087
+ const labels = { ...DEFAULT_LABELS, ...options.labels };
6088
+ const sleep2 = options.sleep ?? defaultSleep(options.signal);
6089
+ const callOptions = {
6090
+ clientIdentity: options.clientIdentity,
6091
+ ...options.apiBase !== void 0 ? { apiBase: options.apiBase } : {},
6092
+ ...options.fetch ? { fetch: options.fetch } : {},
6093
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
6094
+ ...options.signal ? { signal: options.signal } : {}
6095
+ };
6096
+ const input = {
6097
+ ...options.input
6098
+ };
6099
+ let waitsInARow = 0;
6100
+ const askOne = async (question) => {
6101
+ waitsInARow = 0;
6102
+ const answer = await ask(question);
6103
+ if (!isRecord(answer) || !question.answers.includes(answer.answer)) {
6104
+ throw new TypeError(
6105
+ `integration.account.run: ask answered ${JSON.stringify(answer)} to a ${question.field} question (allowed: ${question.answers.join(", ")})`
6106
+ );
6107
+ }
6108
+ if (answer.answer === "value" && typeof answer.value !== "string") {
6109
+ throw new TypeError("integration.account.run: a value answer carries a string value");
6110
+ }
6111
+ return answer;
6112
+ };
6113
+ const askField = async (field, flow, handles) => {
6114
+ const answer = await askOne({
6115
+ field,
6116
+ label: labels[field],
6117
+ answers: FIELD_ANSWERS,
6118
+ ...handles !== void 0 && handles.length > 0 ? { handles } : {},
6119
+ flow
6120
+ });
6121
+ if (answer.answer !== "value") return false;
6122
+ input[field] = answer.value.trim();
6123
+ return true;
6124
+ };
6125
+ const wait = async (ms) => {
6126
+ waitsInARow += 1;
6127
+ await sleep2(Math.max(MIN_WAIT_MS, ms));
6128
+ };
6129
+ const required = kind === "register" ? ["email", "handle"] : ["email"];
6130
+ for (const field of required) {
6131
+ if (typeof input[field] === "string" && input[field].trim().length > 0) continue;
6132
+ if (!await askField(field, null)) return { outcome: "cancelled" };
6133
+ }
6134
+ const startCall = {
6135
+ step: "start",
6136
+ call: () => {
6137
+ const email = input.email ?? "";
6138
+ if (kind === "recover") {
6139
+ return start("recover", { email, ...input.handle ? { handle: input.handle } : {} }, callOptions);
6140
+ }
6141
+ return start(
6142
+ "register",
6143
+ {
6144
+ email,
6145
+ handle: input.handle ?? "",
6146
+ ...input.display_name !== void 0 ? { display_name: input.display_name } : {},
6147
+ ...input.description !== void 0 ? { description: input.description } : {}
6148
+ },
6149
+ callOptions
6150
+ );
6151
+ }
6152
+ };
6153
+ let held = null;
6154
+ const holdsAWorkingCode = () => held !== null && held.expiresAtMs !== null && held.expiresAtMs > Date.now();
6155
+ let resend = null;
6156
+ const beforeStart = async () => {
6157
+ if (resend === null || resend.email !== (input.email ?? "")) return true;
6158
+ const leftMs = resend.afterMs - (Date.now() - resend.receivedAt);
6159
+ if (leftMs > MAX_WAIT_S * 1e3) return false;
6160
+ if (leftMs > 0) await wait(leftMs);
6161
+ return true;
6162
+ };
6163
+ const askCode = async (flow) => {
6164
+ for (; ; ) {
6165
+ const answer = await askOne({ field: "code", label: labels.code, answers: CODE_ANSWERS, flow });
6166
+ if (answer.answer === "cancel") return null;
6167
+ if (answer.answer === "value") {
6168
+ const code = answer.value.trim();
6169
+ return { step: "verify", call: () => submitCode(flow, code, callOptions) };
6170
+ }
6171
+ if (await beforeStart()) return startCall;
6172
+ if (holdsAWorkingCode()) continue;
6173
+ return STOP;
6174
+ }
6175
+ };
6176
+ const offerNewCode = async (flow) => {
6177
+ const answer = await askOne({ field: "new_code", label: null, answers: NEW_CODE_ANSWERS, flow });
6178
+ if (answer.answer !== "new_code") return null;
6179
+ const retryAfterS = flow.retry_after_s;
6180
+ if (retryAfterS !== void 0 && retryAfterS > 0 && retryAfterS <= MAX_WAIT_S) await wait(retryAfterS * 1e3);
6181
+ return await beforeStart() ? true : STOP;
6182
+ };
6183
+ let repeat = startCall;
6184
+ let result = await repeat.call();
6185
+ let receivedAt = Date.now();
6186
+ for (; ; ) {
6187
+ const after = result.flow.resend_after_s;
6188
+ if (after !== void 0) resend = { email: input.email ?? "", afterMs: after * 1e3, receivedAt };
6189
+ if (result.message.length > 0) await show(result.message);
6190
+ let next = STOP;
6191
+ switch (result.action) {
6192
+ case "done":
6193
+ return { outcome: "done", apiKey: result.apiKey, handle: result.handle };
6194
+ case "ask_code": {
6195
+ const flow = result.flow;
6196
+ const expiresAtMs = expiryOf(flow, receivedAt) ?? (held !== null && held.flow.pending_id === flow.pending_id ? held.expiresAtMs : null);
6197
+ held = { flow, expiresAtMs };
6198
+ next = await askCode(flow);
6199
+ break;
6200
+ }
6201
+ case "ask_param": {
6202
+ held = null;
6203
+ const param = result.flow.param;
6204
+ const field = param === "email" ? "email" : param === "handle" ? "handle" : null;
6205
+ if (field === null) break;
6206
+ if (!await askField(field, result.flow, result.handles)) return { outcome: "cancelled" };
6207
+ if (await beforeStart()) next = startCall;
6208
+ break;
6209
+ }
6210
+ case "offer_new_code": {
6211
+ held = null;
6212
+ const offered = await offerNewCode(result.flow);
6213
+ next = offered === true ? startCall : offered;
6214
+ break;
6215
+ }
6216
+ case "wait_then_retry": {
6217
+ if (waitsInARow >= MAX_AUTO_WAITS) {
6218
+ if (repeat.step === "verify") {
6219
+ next = await askCode(held?.flow ?? result.flow);
6220
+ break;
6221
+ }
6222
+ const again = await askOne({ field: "new_code", label: null, answers: NEW_CODE_ANSWERS, flow: result.flow });
6223
+ if (again.answer !== "new_code") return { outcome: "cancelled" };
6224
+ }
6225
+ await wait(result.flow.retry_after_s * 1e3);
6226
+ next = repeat;
6227
+ break;
6228
+ }
6229
+ default:
6230
+ if (result.httpStatus === 429 && repeat.step === "start" && held !== null && holdsAWorkingCode()) {
6231
+ next = await askCode(held.flow);
6232
+ }
6233
+ }
6234
+ if (next === null) return { outcome: "cancelled" };
6235
+ if (next === STOP) return stopped(result);
6236
+ repeat = next;
6237
+ result = await repeat.call();
6238
+ receivedAt = Date.now();
6239
+ }
6240
+ }
6241
+ function expiryOf(flow, receivedAt) {
6242
+ if (flow.expires_in_s !== void 0) return receivedAt + flow.expires_in_s * 1e3;
6243
+ if (flow.expires_at !== void 0) {
6244
+ const at = Date.parse(flow.expires_at);
6245
+ if (Number.isFinite(at)) return at;
6246
+ }
6247
+ return null;
6248
+ }
6249
+ var STOP = /* @__PURE__ */ Symbol("stop");
6250
+ function stopped(result) {
6251
+ return { outcome: "stopped", code: result.code ?? null, message: result.message };
6252
+ }
6253
+
5736
6254
  // src/wake-webhook-verify.ts
5737
6255
  var WakeWebhookVerificationError = class extends Error {
5738
6256
  reason;
@@ -5944,8 +6462,8 @@ function renderMessageContext(message, opts = {}) {
5944
6462
  if (self && conv?.type === "group" && (ctx?.mentions ?? []).includes(self)) {
5945
6463
  lines.push("You were @-mentioned in this message.");
5946
6464
  }
5947
- const text = message.content?.text;
5948
- lines.push("", text ? text : `(a ${"non-text"} message \u2014 no text body)`);
6465
+ const text2 = message.content?.text;
6466
+ lines.push("", text2 ? text2 : `(a ${"non-text"} message \u2014 no text body)`);
5949
6467
  return lines.join("\n");
5950
6468
  }
5951
6469
 
@@ -5995,6 +6513,7 @@ exports.INBOX_TRAY_MAX_LIMIT = INBOX_TRAY_MAX_LIMIT;
5995
6513
  exports.INBOX_WAIT_MAX_MS = INBOX_WAIT_MAX_MS;
5996
6514
  exports.MAX_ATTACHMENT_SIZE = MAX_ATTACHMENT_SIZE;
5997
6515
  exports.NotFoundError = NotFoundError;
6516
+ exports.OtpAttemptsExhaustedError = OtpAttemptsExhaustedError;
5998
6517
  exports.RateLimitedError = RateLimitedError;
5999
6518
  exports.RealtimeClient = RealtimeClient;
6000
6519
  exports.RecipientBackloggedError = RecipientBackloggedError;