agentchatme 1.3.1 → 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/CHANGELOG.md +152 -0
- package/README.md +27 -5
- package/dist/index.cjs +785 -136
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +650 -60
- package/dist/index.d.ts +650 -60
- package/dist/index.js +785 -137
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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.
|
|
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
|
|
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
|
|
531
|
-
if (!
|
|
563
|
+
const text2 = await res.text();
|
|
564
|
+
if (!text2) return void 0;
|
|
532
565
|
try {
|
|
533
|
-
return JSON.parse(
|
|
566
|
+
return JSON.parse(text2);
|
|
534
567
|
} catch {
|
|
535
568
|
throw new ConnectionError(
|
|
536
|
-
`AgentChat SDK: expected JSON response but got: ${
|
|
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
|
|
543
|
-
if (!
|
|
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(
|
|
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(
|
|
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
|
-
|
|
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
|
|
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
|
|
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 =
|
|
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
|
|
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(
|
|
3319
|
-
const raw = extractJson(
|
|
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(
|
|
3357
|
-
if (typeof
|
|
3358
|
-
let s =
|
|
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
|
|
3364
|
-
const closer = s[
|
|
3420
|
+
const start2 = Math.min(...starts);
|
|
3421
|
+
const closer = s[start2] === "{" ? "}" : "]";
|
|
3365
3422
|
const end = s.lastIndexOf(closer);
|
|
3366
|
-
if (end <=
|
|
3367
|
-
return s.slice(
|
|
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
|
|
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
|
-
|
|
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(
|
|
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(
|
|
3807
|
-
const spans = blocksOf(
|
|
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 =
|
|
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(
|
|
3828
|
-
const spans = blocksOf(
|
|
3885
|
+
function replace(text2, block) {
|
|
3886
|
+
const spans = blocksOf(text2);
|
|
3829
3887
|
if (spans.length === 0) {
|
|
3830
|
-
const trimmed =
|
|
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(
|
|
3895
|
+
return rebuild(text2, spans, block);
|
|
3838
3896
|
}
|
|
3839
|
-
function remove(
|
|
3840
|
-
const spans = blocksOf(
|
|
3841
|
-
if (spans.length === 0) return
|
|
3842
|
-
return rebuild(
|
|
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(
|
|
3902
|
+
function linesOf(text2) {
|
|
3845
3903
|
const lines = [];
|
|
3846
3904
|
let at = 0;
|
|
3847
|
-
while (at <=
|
|
3848
|
-
const nl =
|
|
3849
|
-
const end = nl === -1 ?
|
|
3850
|
-
lines.push({ start: at, end, next: nl === -1 ?
|
|
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(
|
|
3914
|
+
function blocksOf(text2) {
|
|
3857
3915
|
const spans = [];
|
|
3858
3916
|
let open = null;
|
|
3859
|
-
for (const line of linesOf(
|
|
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(
|
|
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
|
|
3883
|
-
parts.push(
|
|
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(
|
|
3947
|
+
parts.push(text2.slice(previous.end, current.start).replace(/^\n+/, "").replace(/\n+$/, ""));
|
|
3890
3948
|
}
|
|
3891
|
-
parts.push(
|
|
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
|
|
4331
|
-
if (!
|
|
4332
|
-
let close =
|
|
4333
|
-
while (close >= 0 &&
|
|
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
|
|
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(
|
|
4345
|
-
const version = manualFrontMatter(
|
|
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
|
|
4643
|
+
let text2;
|
|
4586
4644
|
try {
|
|
4587
|
-
|
|
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(
|
|
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(
|
|
4622
|
-
if (
|
|
4623
|
-
const fields = manualFrontMatter(
|
|
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(
|
|
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
|
|
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
|
|
4672
|
-
return { res, result: readResult(
|
|
4729
|
+
const text2 = await res.text();
|
|
4730
|
+
return { res, result: readResult(text2) };
|
|
4673
4731
|
};
|
|
4674
4732
|
try {
|
|
4675
|
-
const init = await
|
|
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
|
|
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(
|
|
4779
|
+
function readResult(text2) {
|
|
4722
4780
|
const candidates = [];
|
|
4723
|
-
const trimmed =
|
|
4781
|
+
const trimmed = text2.trim();
|
|
4724
4782
|
if (trimmed.startsWith("{")) candidates.push(trimmed);
|
|
4725
|
-
for (const line of
|
|
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) {
|
|
@@ -4745,6 +4803,8 @@ var NO_PROGRESS_BACKOFF_MS = 1e3;
|
|
|
4745
4803
|
var NO_PROGRESS_BACKOFF_MAX_MS = 6e4;
|
|
4746
4804
|
var GATE_CALL_TIMEOUT_MS = 6e4;
|
|
4747
4805
|
var CYCLE_TIMEOUT_MS = 10 * 6e4;
|
|
4806
|
+
var GATE_CHUNK_SIZE = 10;
|
|
4807
|
+
var REPLY_TURN_PLACEHOLDER = "<conversation_id>";
|
|
4748
4808
|
var RECENT_CYCLES = 20;
|
|
4749
4809
|
var Pacer = class {
|
|
4750
4810
|
constructor(paceMs, now2) {
|
|
@@ -4815,10 +4875,12 @@ var ReceiveLoop = class {
|
|
|
4815
4875
|
cycleAbort = null;
|
|
4816
4876
|
gateCallTimeoutMs;
|
|
4817
4877
|
cycleTimeoutMs;
|
|
4878
|
+
gateChunkSize;
|
|
4818
4879
|
lastError = null;
|
|
4819
4880
|
counts = {
|
|
4820
4881
|
frames: 0,
|
|
4821
4882
|
echoes: 0,
|
|
4883
|
+
notices: 0,
|
|
4822
4884
|
turnsStarted: 0,
|
|
4823
4885
|
turnsRefused: 0,
|
|
4824
4886
|
turnsQueued: 0,
|
|
@@ -4827,6 +4889,8 @@ var ReceiveLoop = class {
|
|
|
4827
4889
|
runsCompleted: 0,
|
|
4828
4890
|
runsFailed: 0,
|
|
4829
4891
|
runsNotStarted: 0,
|
|
4892
|
+
chunksOk: 0,
|
|
4893
|
+
chunksFailed: 0,
|
|
4830
4894
|
outcomeRecordFailures: 0
|
|
4831
4895
|
};
|
|
4832
4896
|
outcomes = {};
|
|
@@ -4840,6 +4904,11 @@ var ReceiveLoop = class {
|
|
|
4840
4904
|
}
|
|
4841
4905
|
const maxTurns = options.maxConcurrentTurns ?? 1;
|
|
4842
4906
|
if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new RangeError("ReceiveLoop: maxConcurrentTurns must be an integer >= 1");
|
|
4907
|
+
const chunkSize = options.gateChunkSize ?? GATE_CHUNK_SIZE;
|
|
4908
|
+
if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > TRAY_LIMIT) {
|
|
4909
|
+
throw new RangeError(`ReceiveLoop: gateChunkSize must be an integer from 1 to ${TRAY_LIMIT}`);
|
|
4910
|
+
}
|
|
4911
|
+
this.gateChunkSize = chunkSize;
|
|
4843
4912
|
this.options = options;
|
|
4844
4913
|
this.client = options.client;
|
|
4845
4914
|
this.now = options.now ?? Date.now;
|
|
@@ -4983,6 +5052,11 @@ var ReceiveLoop = class {
|
|
|
4983
5052
|
this.counts.frames += 1;
|
|
4984
5053
|
const payload = message.payload ?? {};
|
|
4985
5054
|
const conversationId = typeof payload.conversation_id === "string" ? payload.conversation_id : void 0;
|
|
5055
|
+
if (payload.type === "system") {
|
|
5056
|
+
this.counts.notices += 1;
|
|
5057
|
+
this.emit({ type: "notice", ...conversationId ? { conversationId } : {} });
|
|
5058
|
+
return;
|
|
5059
|
+
}
|
|
4986
5060
|
const raw = payload.sender ?? payload.from ?? payload.sender_handle;
|
|
4987
5061
|
const sender = typeof raw === "string" ? normalizeHandle(raw) : "";
|
|
4988
5062
|
if (this.handle !== null && sender === this.handle) {
|
|
@@ -5021,10 +5095,11 @@ var ReceiveLoop = class {
|
|
|
5021
5095
|
let excludedMs = 0;
|
|
5022
5096
|
let excludedSince = null;
|
|
5023
5097
|
let depth = 0;
|
|
5024
|
-
const
|
|
5098
|
+
const run3 = {
|
|
5025
5099
|
token,
|
|
5026
5100
|
signal: controller.signal,
|
|
5027
5101
|
stale: () => this.cycleToken !== token || this.stopped,
|
|
5102
|
+
abandoned: () => this.cycleToken !== token,
|
|
5028
5103
|
exclude: async (work2) => {
|
|
5029
5104
|
if (depth++ === 0) excludedSince = this.now();
|
|
5030
5105
|
try {
|
|
@@ -5038,8 +5113,8 @@ var ReceiveLoop = class {
|
|
|
5038
5113
|
}
|
|
5039
5114
|
};
|
|
5040
5115
|
const work = (async () => {
|
|
5041
|
-
const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(
|
|
5042
|
-
if (!
|
|
5116
|
+
const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(run3) : await this.singleRunCycle(run3);
|
|
5117
|
+
if (!run3.abandoned()) this.finishCycle(summary);
|
|
5043
5118
|
})();
|
|
5044
5119
|
let timer = null;
|
|
5045
5120
|
const overdue = new Promise((resolve) => {
|
|
@@ -5083,7 +5158,7 @@ var ReceiveLoop = class {
|
|
|
5083
5158
|
* an abandoned cycle: the server may already have taken it, and a second
|
|
5084
5159
|
* one could climb the defer ladder twice.
|
|
5085
5160
|
*/
|
|
5086
|
-
recordingClient(
|
|
5161
|
+
recordingClient(run3) {
|
|
5087
5162
|
const decisions = this.client.decisions;
|
|
5088
5163
|
return {
|
|
5089
5164
|
decisions: {
|
|
@@ -5093,46 +5168,58 @@ var ReceiveLoop = class {
|
|
|
5093
5168
|
return await decisions.record(conversationId, options);
|
|
5094
5169
|
} finally {
|
|
5095
5170
|
this.recordsInFlight.delete(conversationId);
|
|
5096
|
-
if (
|
|
5171
|
+
if (run3.stale()) this.afterTurnEnded();
|
|
5097
5172
|
}
|
|
5098
5173
|
}
|
|
5099
5174
|
}
|
|
5100
5175
|
};
|
|
5101
5176
|
}
|
|
5102
|
-
/**
|
|
5103
|
-
|
|
5177
|
+
/**
|
|
5178
|
+
* The runtime's model call, bounded by `gateCallTimeoutMs` (and the cycle's
|
|
5179
|
+
* own abandonment). Every call (one per chunk) gets its own deadline and
|
|
5180
|
+
* its own `signal`. While a call has a deadline, its time does not count
|
|
5181
|
+
* against the cycle's: a tray gated in k chunks may take k deadlines, and a
|
|
5182
|
+
* cycle that is making progress is not abandoned for it. With the deadline
|
|
5183
|
+
* off the watchdog is the calls' only bound, so they count.
|
|
5184
|
+
*/
|
|
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));
|
|
5189
|
+
}
|
|
5190
|
+
deadlineModelCall(run3) {
|
|
5104
5191
|
return (prompt) => new Promise((resolve, reject) => {
|
|
5105
5192
|
const controller = new AbortController();
|
|
5106
5193
|
const abort = () => {
|
|
5107
5194
|
controller.abort();
|
|
5108
5195
|
reject(new Error("the cycle was abandoned"));
|
|
5109
5196
|
};
|
|
5110
|
-
if (
|
|
5197
|
+
if (run3.signal.aborted) {
|
|
5111
5198
|
abort();
|
|
5112
5199
|
return;
|
|
5113
5200
|
}
|
|
5114
|
-
|
|
5201
|
+
run3.signal.addEventListener("abort", abort, { once: true });
|
|
5115
5202
|
const timer = Number.isFinite(this.gateCallTimeoutMs) ? this._setTimeout(() => {
|
|
5116
|
-
|
|
5203
|
+
run3.signal.removeEventListener("abort", abort);
|
|
5117
5204
|
controller.abort();
|
|
5118
5205
|
reject(new Error(`no answer within ${this.gateCallTimeoutMs} ms`));
|
|
5119
5206
|
}, this.gateCallTimeoutMs) : null;
|
|
5120
5207
|
if (timer !== null) timer.unref?.();
|
|
5121
|
-
let
|
|
5208
|
+
let call2;
|
|
5122
5209
|
try {
|
|
5123
|
-
|
|
5210
|
+
call2 = Promise.resolve(this.options.callModel(prompt, { signal: controller.signal }));
|
|
5124
5211
|
} catch (err) {
|
|
5125
|
-
|
|
5212
|
+
call2 = Promise.reject(err);
|
|
5126
5213
|
}
|
|
5127
|
-
|
|
5128
|
-
(
|
|
5214
|
+
call2.then(
|
|
5215
|
+
(text2) => {
|
|
5129
5216
|
if (timer !== null) this._clearTimeout(timer);
|
|
5130
|
-
|
|
5131
|
-
resolve(
|
|
5217
|
+
run3.signal.removeEventListener("abort", abort);
|
|
5218
|
+
resolve(text2);
|
|
5132
5219
|
},
|
|
5133
5220
|
(err) => {
|
|
5134
5221
|
if (timer !== null) this._clearTimeout(timer);
|
|
5135
|
-
|
|
5222
|
+
run3.signal.removeEventListener("abort", abort);
|
|
5136
5223
|
reject(err);
|
|
5137
5224
|
}
|
|
5138
5225
|
);
|
|
@@ -5160,13 +5247,13 @@ var ReceiveLoop = class {
|
|
|
5160
5247
|
return err instanceof Error ? err.message : String(err);
|
|
5161
5248
|
}
|
|
5162
5249
|
}
|
|
5163
|
-
async gateCallCycle(
|
|
5250
|
+
async gateCallCycle(run3) {
|
|
5164
5251
|
const tray = await this.readTray();
|
|
5165
|
-
if (
|
|
5252
|
+
if (run3.stale()) return this.summary("abandoned");
|
|
5166
5253
|
if (tray === null) return this.summary("tray_failed", { failure: this.lastError });
|
|
5167
5254
|
const cards = cardsOf(tray);
|
|
5168
5255
|
const invites = trayInvites(tray);
|
|
5169
|
-
const unheld = this.
|
|
5256
|
+
const unheld = this.unheld(cards);
|
|
5170
5257
|
const heldByTurns = cards.length - unheld.length;
|
|
5171
5258
|
if (heldByTurns > 0) this.heldWhileRunning = true;
|
|
5172
5259
|
const gateCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
|
|
@@ -5178,13 +5265,13 @@ var ReceiveLoop = class {
|
|
|
5178
5265
|
if (cards.length === 0 && invites.length === 0) return this.summary("empty", base);
|
|
5179
5266
|
if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
|
|
5180
5267
|
const texts = await this.options.texts.ensure();
|
|
5181
|
-
if (
|
|
5268
|
+
if (run3.stale()) return this.summary("abandoned", base);
|
|
5182
5269
|
if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
|
|
5183
5270
|
const unready = await this.checkReady();
|
|
5184
|
-
if (
|
|
5271
|
+
if (run3.stale()) return this.summary("abandoned", base);
|
|
5185
5272
|
if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
|
|
5186
|
-
let gated = 0;
|
|
5187
5273
|
const tally = {
|
|
5274
|
+
gated: 0,
|
|
5188
5275
|
reply: 0,
|
|
5189
5276
|
dismiss: 0,
|
|
5190
5277
|
defer: 0,
|
|
@@ -5193,44 +5280,127 @@ var ReceiveLoop = class {
|
|
|
5193
5280
|
recordFailures: 0,
|
|
5194
5281
|
turnsStarted: 0,
|
|
5195
5282
|
turnsRefused: 0,
|
|
5196
|
-
turnsQueued: 0
|
|
5283
|
+
turnsQueued: 0,
|
|
5284
|
+
chunksOk: 0,
|
|
5285
|
+
chunksFailed: 0
|
|
5197
5286
|
};
|
|
5287
|
+
let heldDuringGate = 0;
|
|
5198
5288
|
let outcome = "invites_only";
|
|
5199
5289
|
let failure = null;
|
|
5200
5290
|
if (owedCards.length > 0) {
|
|
5201
|
-
|
|
5202
|
-
|
|
5203
|
-
|
|
5204
|
-
|
|
5205
|
-
|
|
5206
|
-
|
|
5207
|
-
|
|
5208
|
-
|
|
5209
|
-
|
|
5210
|
-
|
|
5211
|
-
tally.
|
|
5212
|
-
|
|
5213
|
-
tally.
|
|
5214
|
-
if (result.outcome === "fail_closed") {
|
|
5215
|
-
outcome = "fail_closed";
|
|
5216
|
-
failure = result.failure;
|
|
5217
|
-
} else {
|
|
5291
|
+
const gate = await this.gateInChunks(run3, tray, gateCards, texts);
|
|
5292
|
+
heldDuringGate = gate.held;
|
|
5293
|
+
tally.gated = gate.gated;
|
|
5294
|
+
tally.reply = gate.verdicts.reply;
|
|
5295
|
+
tally.dismiss = gate.verdicts.dismiss;
|
|
5296
|
+
tally.defer = gate.verdicts.defer;
|
|
5297
|
+
tally.undecided = gate.undecided;
|
|
5298
|
+
tally.recorded = gate.recorded;
|
|
5299
|
+
tally.recordFailures = gate.recordFailures;
|
|
5300
|
+
tally.chunksOk = gate.chunks.filter((c) => c.outcome === "decided").length;
|
|
5301
|
+
tally.chunksFailed = gate.chunks.length - tally.chunksOk;
|
|
5302
|
+
failure = chunkFailure(gate.chunks);
|
|
5303
|
+
if (tally.chunksOk > 0) {
|
|
5218
5304
|
outcome = "decided";
|
|
5219
|
-
for (const reply of
|
|
5220
|
-
if (
|
|
5221
|
-
tally[launchKey(await
|
|
5305
|
+
for (const reply of gate.reply) {
|
|
5306
|
+
if (run3.stale()) break;
|
|
5307
|
+
tally[launchKey(await run3.exclude(() => this.startReplyTurn(reply, texts)))] += 1;
|
|
5222
5308
|
}
|
|
5309
|
+
} else if (tally.chunksFailed > 0) {
|
|
5310
|
+
outcome = "fail_closed";
|
|
5311
|
+
} else if (owedInvites.length === 0 && !run3.stale()) {
|
|
5312
|
+
return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate });
|
|
5223
5313
|
}
|
|
5224
5314
|
}
|
|
5225
5315
|
for (const invite of owedInvites) {
|
|
5226
|
-
if (
|
|
5227
|
-
tally[launchKey(await
|
|
5316
|
+
if (run3.stale()) break;
|
|
5317
|
+
tally[launchKey(await run3.exclude(() => this.startInviteTurn(invite, texts)))] += 1;
|
|
5228
5318
|
}
|
|
5229
|
-
|
|
5319
|
+
const parts = { ...base, heldByTurns: heldByTurns + heldDuringGate, ...tally };
|
|
5320
|
+
if (run3.stale()) return this.summary("abandoned", parts);
|
|
5230
5321
|
if (tray.truncated === true && outcome === "decided") {
|
|
5231
5322
|
this.readTheRest(tally.recorded > 0 || tally.turnsStarted > 0);
|
|
5232
5323
|
}
|
|
5233
|
-
return this.summary(outcome, { ...
|
|
5324
|
+
return this.summary(outcome, { ...parts, failure });
|
|
5325
|
+
}
|
|
5326
|
+
/**
|
|
5327
|
+
* Held out of the gate: a running or waiting turn, or a verdict still being
|
|
5328
|
+
* recorded (an abandoned cycle's last call): gating it again could record
|
|
5329
|
+
* the same verdict twice (a second defer climbs the ladder).
|
|
5330
|
+
*/
|
|
5331
|
+
unheld(cards) {
|
|
5332
|
+
return this.tracker.withoutRunning(cards).filter((card) => !this.recordsInFlight.has(card.conversation_id));
|
|
5333
|
+
}
|
|
5334
|
+
/**
|
|
5335
|
+
* The gate in chunks (contract v1 §3.6): the cards, in tray order, split
|
|
5336
|
+
* into chunks of at most `gateChunkSize`, one gate call per chunk, one
|
|
5337
|
+
* after another. Each chunk's prompt is the gate prompt for its own cards
|
|
5338
|
+
* (N = the cards in that chunk), each call has its own deadline and the
|
|
5339
|
+
* cycle's cancellation, and each chunk's dismiss / defer verdicts are
|
|
5340
|
+
* recorded as soon as it answers. A chunk that fails closed leaves only its
|
|
5341
|
+
* own cards undecided. Before each call the chunk is checked again for
|
|
5342
|
+
* cards a turn has taken since the tray was read (a shared tracker), so a
|
|
5343
|
+
* longer gate never decides a card a turn holds; a chunk left with muted
|
|
5344
|
+
* cards only (or none) is not called. Stops once the cycle is stale; a call
|
|
5345
|
+
* a stop cut short is not counted as a failed chunk, and a cycle the
|
|
5346
|
+
* watchdog abandoned reports and counts no chunk after its summary.
|
|
5347
|
+
*/
|
|
5348
|
+
async gateInChunks(run3, tray, cards, texts) {
|
|
5349
|
+
const size = this.gateChunkSize;
|
|
5350
|
+
const of = Math.ceil(cards.length / size);
|
|
5351
|
+
const callModel = this.boundedModelCall(run3);
|
|
5352
|
+
const client = this.recordingClient(run3);
|
|
5353
|
+
const out = {
|
|
5354
|
+
gated: 0,
|
|
5355
|
+
held: 0,
|
|
5356
|
+
reply: [],
|
|
5357
|
+
verdicts: { reply: 0, dismiss: 0, defer: 0 },
|
|
5358
|
+
undecided: 0,
|
|
5359
|
+
recorded: 0,
|
|
5360
|
+
recordFailures: 0,
|
|
5361
|
+
chunks: []
|
|
5362
|
+
};
|
|
5363
|
+
for (let index = 1; index <= of; index++) {
|
|
5364
|
+
if (run3.stale()) break;
|
|
5365
|
+
const planned = cards.slice((index - 1) * size, index * size);
|
|
5366
|
+
const chunk = this.unheld(planned);
|
|
5367
|
+
out.held += planned.length - chunk.length;
|
|
5368
|
+
if (chunk.length < planned.length) this.heldWhileRunning = true;
|
|
5369
|
+
if (!chunk.some((card) => card.muted !== true)) continue;
|
|
5370
|
+
const result = await run({
|
|
5371
|
+
tray: { ...tray, conversations: chunk },
|
|
5372
|
+
callModel,
|
|
5373
|
+
client,
|
|
5374
|
+
texts,
|
|
5375
|
+
signal: run3.signal,
|
|
5376
|
+
...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
|
|
5377
|
+
});
|
|
5378
|
+
if (run3.abandoned()) break;
|
|
5379
|
+
if (run3.stale() && result.outcome !== "decided") break;
|
|
5380
|
+
out.gated += chunk.length;
|
|
5381
|
+
const undecided = new Set(result.undecided);
|
|
5382
|
+
for (const verdict of result.verdicts) {
|
|
5383
|
+
if (!undecided.has(verdict.conversation_id)) out.verdicts[verdict.decision] += 1;
|
|
5384
|
+
}
|
|
5385
|
+
out.reply.push(...result.reply);
|
|
5386
|
+
out.undecided += result.undecided.length;
|
|
5387
|
+
out.recorded += result.recorded;
|
|
5388
|
+
out.recordFailures += result.recordFailures.length;
|
|
5389
|
+
const report = {
|
|
5390
|
+
cycle: run3.token,
|
|
5391
|
+
index,
|
|
5392
|
+
of,
|
|
5393
|
+
cards: chunk.length,
|
|
5394
|
+
outcome: result.outcome === "decided" ? "decided" : "fail_closed",
|
|
5395
|
+
undecided: result.undecided.length,
|
|
5396
|
+
failure: result.failure
|
|
5397
|
+
};
|
|
5398
|
+
out.chunks.push(report);
|
|
5399
|
+
if (report.outcome === "decided") this.counts.chunksOk += 1;
|
|
5400
|
+
else this.counts.chunksFailed += 1;
|
|
5401
|
+
this.emit({ type: "gate_chunk", ...report });
|
|
5402
|
+
}
|
|
5403
|
+
return out;
|
|
5234
5404
|
}
|
|
5235
5405
|
/**
|
|
5236
5406
|
* More conversations wait than one tray shows. After a cycle that moved
|
|
@@ -5261,9 +5431,9 @@ var ReceiveLoop = class {
|
|
|
5261
5431
|
this.moreTimer = null;
|
|
5262
5432
|
}
|
|
5263
5433
|
}
|
|
5264
|
-
async singleRunCycle(
|
|
5434
|
+
async singleRunCycle(run3) {
|
|
5265
5435
|
const tray = await this.readTray();
|
|
5266
|
-
if (
|
|
5436
|
+
if (run3.stale()) return this.summary("abandoned");
|
|
5267
5437
|
let cards = null;
|
|
5268
5438
|
let invites = null;
|
|
5269
5439
|
let base = { cards: 0, invites: 0, heldByTurns: 0, truncated: false };
|
|
@@ -5275,10 +5445,10 @@ var ReceiveLoop = class {
|
|
|
5275
5445
|
if (cards === 0 && invites === 0) return this.summary("nothing_owed", base);
|
|
5276
5446
|
}
|
|
5277
5447
|
const texts = await this.options.texts.ensure();
|
|
5278
|
-
if (
|
|
5448
|
+
if (run3.stale()) return this.summary("abandoned", base);
|
|
5279
5449
|
if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
|
|
5280
5450
|
const unready = await this.checkReady();
|
|
5281
|
-
if (
|
|
5451
|
+
if (run3.stale()) return this.summary("abandoned", base);
|
|
5282
5452
|
if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
|
|
5283
5453
|
const prompt = cards === 0 && (invites ?? 0) > 0 ? texts.invite_prompt.trim() : (invites ?? 0) > 0 ? `${texts.wake_instruction.trim()}
|
|
5284
5454
|
|
|
@@ -5286,7 +5456,7 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
|
|
|
5286
5456
|
this.counts.runsStarted += 1;
|
|
5287
5457
|
let end;
|
|
5288
5458
|
try {
|
|
5289
|
-
end = await
|
|
5459
|
+
end = await run3.exclude(() => this.options.startRun({ prompt, texts, cards, invites, signal: this.abort.signal }));
|
|
5290
5460
|
} catch (err) {
|
|
5291
5461
|
end = { status: "not_started", detail: err instanceof Error ? err.message : String(err) };
|
|
5292
5462
|
}
|
|
@@ -5502,9 +5672,9 @@ invite_id: ${invite.invite_id}`,
|
|
|
5502
5672
|
}
|
|
5503
5673
|
this.emit({ type: "invite_outcome", outcome, recorded });
|
|
5504
5674
|
}
|
|
5505
|
-
async admit(
|
|
5675
|
+
async admit(start2, request) {
|
|
5506
5676
|
try {
|
|
5507
|
-
return await
|
|
5677
|
+
return await start2(request);
|
|
5508
5678
|
} catch (err) {
|
|
5509
5679
|
return { started: false, error: err instanceof Error ? err.message : String(err) };
|
|
5510
5680
|
}
|
|
@@ -5553,6 +5723,8 @@ invite_id: ${invite.invite_id}`,
|
|
|
5553
5723
|
turnsQueued: 0,
|
|
5554
5724
|
heldByTurns: 0,
|
|
5555
5725
|
paced: 0,
|
|
5726
|
+
chunksOk: 0,
|
|
5727
|
+
chunksFailed: 0,
|
|
5556
5728
|
truncated: false,
|
|
5557
5729
|
failure: null,
|
|
5558
5730
|
...parts
|
|
@@ -5571,10 +5743,26 @@ invite_id: ${invite.invite_id}`,
|
|
|
5571
5743
|
}
|
|
5572
5744
|
};
|
|
5573
5745
|
function replyPrompt(texts, conversationId) {
|
|
5746
|
+
const raw = texts.reply_turn_template;
|
|
5747
|
+
const template = typeof raw === "string" ? raw.trim() : "";
|
|
5748
|
+
if (template.length > 0) {
|
|
5749
|
+
if (template.includes(REPLY_TURN_PLACEHOLDER)) return template.split(REPLY_TURN_PLACEHOLDER).join(conversationId);
|
|
5750
|
+
return `${template}
|
|
5751
|
+
|
|
5752
|
+
conversation_id: ${conversationId}`;
|
|
5753
|
+
}
|
|
5574
5754
|
return `${texts.wake_instruction.trim()}
|
|
5575
5755
|
|
|
5576
5756
|
conversation_id: ${conversationId}`;
|
|
5577
5757
|
}
|
|
5758
|
+
function chunkFailure(chunks) {
|
|
5759
|
+
const failed = chunks.filter((chunk) => chunk.outcome === "fail_closed");
|
|
5760
|
+
const first = failed[0];
|
|
5761
|
+
if (first === void 0) return null;
|
|
5762
|
+
const reason = first.failure ?? "no usable verdicts in the answer";
|
|
5763
|
+
if (chunks.length === 1) return reason;
|
|
5764
|
+
return `${failed.length} of ${chunks.length} gate chunks failed; chunk ${first.index}: ${reason}`;
|
|
5765
|
+
}
|
|
5578
5766
|
function timeoutOption(value, fallback, name) {
|
|
5579
5767
|
if (value === void 0) return fallback;
|
|
5580
5768
|
if (value === 0 || value === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY;
|
|
@@ -5603,6 +5791,466 @@ function wsBase(httpBase) {
|
|
|
5603
5791
|
return base.replace(/^http/, "ws");
|
|
5604
5792
|
}
|
|
5605
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
|
+
|
|
5606
6254
|
// src/wake-webhook-verify.ts
|
|
5607
6255
|
var WakeWebhookVerificationError = class extends Error {
|
|
5608
6256
|
reason;
|
|
@@ -5814,8 +6462,8 @@ function renderMessageContext(message, opts = {}) {
|
|
|
5814
6462
|
if (self && conv?.type === "group" && (ctx?.mentions ?? []).includes(self)) {
|
|
5815
6463
|
lines.push("You were @-mentioned in this message.");
|
|
5816
6464
|
}
|
|
5817
|
-
const
|
|
5818
|
-
lines.push("",
|
|
6465
|
+
const text2 = message.content?.text;
|
|
6466
|
+
lines.push("", text2 ? text2 : `(a ${"non-text"} message \u2014 no text body)`);
|
|
5819
6467
|
return lines.join("\n");
|
|
5820
6468
|
}
|
|
5821
6469
|
|
|
@@ -5865,6 +6513,7 @@ exports.INBOX_TRAY_MAX_LIMIT = INBOX_TRAY_MAX_LIMIT;
|
|
|
5865
6513
|
exports.INBOX_WAIT_MAX_MS = INBOX_WAIT_MAX_MS;
|
|
5866
6514
|
exports.MAX_ATTACHMENT_SIZE = MAX_ATTACHMENT_SIZE;
|
|
5867
6515
|
exports.NotFoundError = NotFoundError;
|
|
6516
|
+
exports.OtpAttemptsExhaustedError = OtpAttemptsExhaustedError;
|
|
5868
6517
|
exports.RateLimitedError = RateLimitedError;
|
|
5869
6518
|
exports.RealtimeClient = RealtimeClient;
|
|
5870
6519
|
exports.RecipientBackloggedError = RecipientBackloggedError;
|