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