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.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.
|
|
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
|
|
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
|
|
529
|
-
if (!
|
|
561
|
+
const text2 = await res.text();
|
|
562
|
+
if (!text2) return void 0;
|
|
530
563
|
try {
|
|
531
|
-
return JSON.parse(
|
|
564
|
+
return JSON.parse(text2);
|
|
532
565
|
} catch {
|
|
533
566
|
throw new ConnectionError(
|
|
534
|
-
`AgentChat SDK: expected JSON response but got: ${
|
|
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
|
|
541
|
-
if (!
|
|
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(
|
|
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(
|
|
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
|
-
|
|
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
|
|
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
|
|
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 =
|
|
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
|
|
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(
|
|
3317
|
-
const raw = extractJson(
|
|
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(
|
|
3355
|
-
if (typeof
|
|
3356
|
-
let s =
|
|
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
|
|
3362
|
-
const closer = s[
|
|
3418
|
+
const start2 = Math.min(...starts);
|
|
3419
|
+
const closer = s[start2] === "{" ? "}" : "]";
|
|
3363
3420
|
const end = s.lastIndexOf(closer);
|
|
3364
|
-
if (end <=
|
|
3365
|
-
return s.slice(
|
|
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
|
|
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
|
-
|
|
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(
|
|
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(
|
|
3805
|
-
const spans = blocksOf(
|
|
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 =
|
|
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(
|
|
3826
|
-
const spans = blocksOf(
|
|
3883
|
+
function replace(text2, block) {
|
|
3884
|
+
const spans = blocksOf(text2);
|
|
3827
3885
|
if (spans.length === 0) {
|
|
3828
|
-
const trimmed =
|
|
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(
|
|
3893
|
+
return rebuild(text2, spans, block);
|
|
3836
3894
|
}
|
|
3837
|
-
function remove(
|
|
3838
|
-
const spans = blocksOf(
|
|
3839
|
-
if (spans.length === 0) return
|
|
3840
|
-
return rebuild(
|
|
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(
|
|
3900
|
+
function linesOf(text2) {
|
|
3843
3901
|
const lines = [];
|
|
3844
3902
|
let at = 0;
|
|
3845
|
-
while (at <=
|
|
3846
|
-
const nl =
|
|
3847
|
-
const end = nl === -1 ?
|
|
3848
|
-
lines.push({ start: at, end, next: nl === -1 ?
|
|
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(
|
|
3912
|
+
function blocksOf(text2) {
|
|
3855
3913
|
const spans = [];
|
|
3856
3914
|
let open = null;
|
|
3857
|
-
for (const line of linesOf(
|
|
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(
|
|
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
|
|
3881
|
-
parts.push(
|
|
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(
|
|
3945
|
+
parts.push(text2.slice(previous.end, current.start).replace(/^\n+/, "").replace(/\n+$/, ""));
|
|
3888
3946
|
}
|
|
3889
|
-
parts.push(
|
|
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
|
|
4329
|
-
if (!
|
|
4330
|
-
let close =
|
|
4331
|
-
while (close >= 0 &&
|
|
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
|
|
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(
|
|
4343
|
-
const version = manualFrontMatter(
|
|
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
|
|
4641
|
+
let text2;
|
|
4584
4642
|
try {
|
|
4585
|
-
|
|
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(
|
|
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(
|
|
4620
|
-
if (
|
|
4621
|
-
const fields = manualFrontMatter(
|
|
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(
|
|
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
|
|
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
|
|
4670
|
-
return { res, result: readResult(
|
|
4727
|
+
const text2 = await res.text();
|
|
4728
|
+
return { res, result: readResult(text2) };
|
|
4671
4729
|
};
|
|
4672
4730
|
try {
|
|
4673
|
-
const init = await
|
|
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
|
|
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(
|
|
4777
|
+
function readResult(text2) {
|
|
4720
4778
|
const candidates = [];
|
|
4721
|
-
const trimmed =
|
|
4779
|
+
const trimmed = text2.trim();
|
|
4722
4780
|
if (trimmed.startsWith("{")) candidates.push(trimmed);
|
|
4723
|
-
for (const line of
|
|
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) {
|
|
@@ -4743,6 +4801,8 @@ var NO_PROGRESS_BACKOFF_MS = 1e3;
|
|
|
4743
4801
|
var NO_PROGRESS_BACKOFF_MAX_MS = 6e4;
|
|
4744
4802
|
var GATE_CALL_TIMEOUT_MS = 6e4;
|
|
4745
4803
|
var CYCLE_TIMEOUT_MS = 10 * 6e4;
|
|
4804
|
+
var GATE_CHUNK_SIZE = 10;
|
|
4805
|
+
var REPLY_TURN_PLACEHOLDER = "<conversation_id>";
|
|
4746
4806
|
var RECENT_CYCLES = 20;
|
|
4747
4807
|
var Pacer = class {
|
|
4748
4808
|
constructor(paceMs, now2) {
|
|
@@ -4813,10 +4873,12 @@ var ReceiveLoop = class {
|
|
|
4813
4873
|
cycleAbort = null;
|
|
4814
4874
|
gateCallTimeoutMs;
|
|
4815
4875
|
cycleTimeoutMs;
|
|
4876
|
+
gateChunkSize;
|
|
4816
4877
|
lastError = null;
|
|
4817
4878
|
counts = {
|
|
4818
4879
|
frames: 0,
|
|
4819
4880
|
echoes: 0,
|
|
4881
|
+
notices: 0,
|
|
4820
4882
|
turnsStarted: 0,
|
|
4821
4883
|
turnsRefused: 0,
|
|
4822
4884
|
turnsQueued: 0,
|
|
@@ -4825,6 +4887,8 @@ var ReceiveLoop = class {
|
|
|
4825
4887
|
runsCompleted: 0,
|
|
4826
4888
|
runsFailed: 0,
|
|
4827
4889
|
runsNotStarted: 0,
|
|
4890
|
+
chunksOk: 0,
|
|
4891
|
+
chunksFailed: 0,
|
|
4828
4892
|
outcomeRecordFailures: 0
|
|
4829
4893
|
};
|
|
4830
4894
|
outcomes = {};
|
|
@@ -4838,6 +4902,11 @@ var ReceiveLoop = class {
|
|
|
4838
4902
|
}
|
|
4839
4903
|
const maxTurns = options.maxConcurrentTurns ?? 1;
|
|
4840
4904
|
if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new RangeError("ReceiveLoop: maxConcurrentTurns must be an integer >= 1");
|
|
4905
|
+
const chunkSize = options.gateChunkSize ?? GATE_CHUNK_SIZE;
|
|
4906
|
+
if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > TRAY_LIMIT) {
|
|
4907
|
+
throw new RangeError(`ReceiveLoop: gateChunkSize must be an integer from 1 to ${TRAY_LIMIT}`);
|
|
4908
|
+
}
|
|
4909
|
+
this.gateChunkSize = chunkSize;
|
|
4841
4910
|
this.options = options;
|
|
4842
4911
|
this.client = options.client;
|
|
4843
4912
|
this.now = options.now ?? Date.now;
|
|
@@ -4981,6 +5050,11 @@ var ReceiveLoop = class {
|
|
|
4981
5050
|
this.counts.frames += 1;
|
|
4982
5051
|
const payload = message.payload ?? {};
|
|
4983
5052
|
const conversationId = typeof payload.conversation_id === "string" ? payload.conversation_id : void 0;
|
|
5053
|
+
if (payload.type === "system") {
|
|
5054
|
+
this.counts.notices += 1;
|
|
5055
|
+
this.emit({ type: "notice", ...conversationId ? { conversationId } : {} });
|
|
5056
|
+
return;
|
|
5057
|
+
}
|
|
4984
5058
|
const raw = payload.sender ?? payload.from ?? payload.sender_handle;
|
|
4985
5059
|
const sender = typeof raw === "string" ? normalizeHandle(raw) : "";
|
|
4986
5060
|
if (this.handle !== null && sender === this.handle) {
|
|
@@ -5019,10 +5093,11 @@ var ReceiveLoop = class {
|
|
|
5019
5093
|
let excludedMs = 0;
|
|
5020
5094
|
let excludedSince = null;
|
|
5021
5095
|
let depth = 0;
|
|
5022
|
-
const
|
|
5096
|
+
const run3 = {
|
|
5023
5097
|
token,
|
|
5024
5098
|
signal: controller.signal,
|
|
5025
5099
|
stale: () => this.cycleToken !== token || this.stopped,
|
|
5100
|
+
abandoned: () => this.cycleToken !== token,
|
|
5026
5101
|
exclude: async (work2) => {
|
|
5027
5102
|
if (depth++ === 0) excludedSince = this.now();
|
|
5028
5103
|
try {
|
|
@@ -5036,8 +5111,8 @@ var ReceiveLoop = class {
|
|
|
5036
5111
|
}
|
|
5037
5112
|
};
|
|
5038
5113
|
const work = (async () => {
|
|
5039
|
-
const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(
|
|
5040
|
-
if (!
|
|
5114
|
+
const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(run3) : await this.singleRunCycle(run3);
|
|
5115
|
+
if (!run3.abandoned()) this.finishCycle(summary);
|
|
5041
5116
|
})();
|
|
5042
5117
|
let timer = null;
|
|
5043
5118
|
const overdue = new Promise((resolve) => {
|
|
@@ -5081,7 +5156,7 @@ var ReceiveLoop = class {
|
|
|
5081
5156
|
* an abandoned cycle: the server may already have taken it, and a second
|
|
5082
5157
|
* one could climb the defer ladder twice.
|
|
5083
5158
|
*/
|
|
5084
|
-
recordingClient(
|
|
5159
|
+
recordingClient(run3) {
|
|
5085
5160
|
const decisions = this.client.decisions;
|
|
5086
5161
|
return {
|
|
5087
5162
|
decisions: {
|
|
@@ -5091,46 +5166,58 @@ var ReceiveLoop = class {
|
|
|
5091
5166
|
return await decisions.record(conversationId, options);
|
|
5092
5167
|
} finally {
|
|
5093
5168
|
this.recordsInFlight.delete(conversationId);
|
|
5094
|
-
if (
|
|
5169
|
+
if (run3.stale()) this.afterTurnEnded();
|
|
5095
5170
|
}
|
|
5096
5171
|
}
|
|
5097
5172
|
}
|
|
5098
5173
|
};
|
|
5099
5174
|
}
|
|
5100
|
-
/**
|
|
5101
|
-
|
|
5175
|
+
/**
|
|
5176
|
+
* The runtime's model call, bounded by `gateCallTimeoutMs` (and the cycle's
|
|
5177
|
+
* own abandonment). Every call (one per chunk) gets its own deadline and
|
|
5178
|
+
* its own `signal`. While a call has a deadline, its time does not count
|
|
5179
|
+
* against the cycle's: a tray gated in k chunks may take k deadlines, and a
|
|
5180
|
+
* cycle that is making progress is not abandoned for it. With the deadline
|
|
5181
|
+
* off the watchdog is the calls' only bound, so they count.
|
|
5182
|
+
*/
|
|
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));
|
|
5187
|
+
}
|
|
5188
|
+
deadlineModelCall(run3) {
|
|
5102
5189
|
return (prompt) => new Promise((resolve, reject) => {
|
|
5103
5190
|
const controller = new AbortController();
|
|
5104
5191
|
const abort = () => {
|
|
5105
5192
|
controller.abort();
|
|
5106
5193
|
reject(new Error("the cycle was abandoned"));
|
|
5107
5194
|
};
|
|
5108
|
-
if (
|
|
5195
|
+
if (run3.signal.aborted) {
|
|
5109
5196
|
abort();
|
|
5110
5197
|
return;
|
|
5111
5198
|
}
|
|
5112
|
-
|
|
5199
|
+
run3.signal.addEventListener("abort", abort, { once: true });
|
|
5113
5200
|
const timer = Number.isFinite(this.gateCallTimeoutMs) ? this._setTimeout(() => {
|
|
5114
|
-
|
|
5201
|
+
run3.signal.removeEventListener("abort", abort);
|
|
5115
5202
|
controller.abort();
|
|
5116
5203
|
reject(new Error(`no answer within ${this.gateCallTimeoutMs} ms`));
|
|
5117
5204
|
}, this.gateCallTimeoutMs) : null;
|
|
5118
5205
|
if (timer !== null) timer.unref?.();
|
|
5119
|
-
let
|
|
5206
|
+
let call2;
|
|
5120
5207
|
try {
|
|
5121
|
-
|
|
5208
|
+
call2 = Promise.resolve(this.options.callModel(prompt, { signal: controller.signal }));
|
|
5122
5209
|
} catch (err) {
|
|
5123
|
-
|
|
5210
|
+
call2 = Promise.reject(err);
|
|
5124
5211
|
}
|
|
5125
|
-
|
|
5126
|
-
(
|
|
5212
|
+
call2.then(
|
|
5213
|
+
(text2) => {
|
|
5127
5214
|
if (timer !== null) this._clearTimeout(timer);
|
|
5128
|
-
|
|
5129
|
-
resolve(
|
|
5215
|
+
run3.signal.removeEventListener("abort", abort);
|
|
5216
|
+
resolve(text2);
|
|
5130
5217
|
},
|
|
5131
5218
|
(err) => {
|
|
5132
5219
|
if (timer !== null) this._clearTimeout(timer);
|
|
5133
|
-
|
|
5220
|
+
run3.signal.removeEventListener("abort", abort);
|
|
5134
5221
|
reject(err);
|
|
5135
5222
|
}
|
|
5136
5223
|
);
|
|
@@ -5158,13 +5245,13 @@ var ReceiveLoop = class {
|
|
|
5158
5245
|
return err instanceof Error ? err.message : String(err);
|
|
5159
5246
|
}
|
|
5160
5247
|
}
|
|
5161
|
-
async gateCallCycle(
|
|
5248
|
+
async gateCallCycle(run3) {
|
|
5162
5249
|
const tray = await this.readTray();
|
|
5163
|
-
if (
|
|
5250
|
+
if (run3.stale()) return this.summary("abandoned");
|
|
5164
5251
|
if (tray === null) return this.summary("tray_failed", { failure: this.lastError });
|
|
5165
5252
|
const cards = cardsOf(tray);
|
|
5166
5253
|
const invites = trayInvites(tray);
|
|
5167
|
-
const unheld = this.
|
|
5254
|
+
const unheld = this.unheld(cards);
|
|
5168
5255
|
const heldByTurns = cards.length - unheld.length;
|
|
5169
5256
|
if (heldByTurns > 0) this.heldWhileRunning = true;
|
|
5170
5257
|
const gateCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
|
|
@@ -5176,13 +5263,13 @@ var ReceiveLoop = class {
|
|
|
5176
5263
|
if (cards.length === 0 && invites.length === 0) return this.summary("empty", base);
|
|
5177
5264
|
if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
|
|
5178
5265
|
const texts = await this.options.texts.ensure();
|
|
5179
|
-
if (
|
|
5266
|
+
if (run3.stale()) return this.summary("abandoned", base);
|
|
5180
5267
|
if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
|
|
5181
5268
|
const unready = await this.checkReady();
|
|
5182
|
-
if (
|
|
5269
|
+
if (run3.stale()) return this.summary("abandoned", base);
|
|
5183
5270
|
if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
|
|
5184
|
-
let gated = 0;
|
|
5185
5271
|
const tally = {
|
|
5272
|
+
gated: 0,
|
|
5186
5273
|
reply: 0,
|
|
5187
5274
|
dismiss: 0,
|
|
5188
5275
|
defer: 0,
|
|
@@ -5191,44 +5278,127 @@ var ReceiveLoop = class {
|
|
|
5191
5278
|
recordFailures: 0,
|
|
5192
5279
|
turnsStarted: 0,
|
|
5193
5280
|
turnsRefused: 0,
|
|
5194
|
-
turnsQueued: 0
|
|
5281
|
+
turnsQueued: 0,
|
|
5282
|
+
chunksOk: 0,
|
|
5283
|
+
chunksFailed: 0
|
|
5195
5284
|
};
|
|
5285
|
+
let heldDuringGate = 0;
|
|
5196
5286
|
let outcome = "invites_only";
|
|
5197
5287
|
let failure = null;
|
|
5198
5288
|
if (owedCards.length > 0) {
|
|
5199
|
-
|
|
5200
|
-
|
|
5201
|
-
|
|
5202
|
-
|
|
5203
|
-
|
|
5204
|
-
|
|
5205
|
-
|
|
5206
|
-
|
|
5207
|
-
|
|
5208
|
-
|
|
5209
|
-
tally.
|
|
5210
|
-
|
|
5211
|
-
tally.
|
|
5212
|
-
if (result.outcome === "fail_closed") {
|
|
5213
|
-
outcome = "fail_closed";
|
|
5214
|
-
failure = result.failure;
|
|
5215
|
-
} else {
|
|
5289
|
+
const gate = await this.gateInChunks(run3, tray, gateCards, texts);
|
|
5290
|
+
heldDuringGate = gate.held;
|
|
5291
|
+
tally.gated = gate.gated;
|
|
5292
|
+
tally.reply = gate.verdicts.reply;
|
|
5293
|
+
tally.dismiss = gate.verdicts.dismiss;
|
|
5294
|
+
tally.defer = gate.verdicts.defer;
|
|
5295
|
+
tally.undecided = gate.undecided;
|
|
5296
|
+
tally.recorded = gate.recorded;
|
|
5297
|
+
tally.recordFailures = gate.recordFailures;
|
|
5298
|
+
tally.chunksOk = gate.chunks.filter((c) => c.outcome === "decided").length;
|
|
5299
|
+
tally.chunksFailed = gate.chunks.length - tally.chunksOk;
|
|
5300
|
+
failure = chunkFailure(gate.chunks);
|
|
5301
|
+
if (tally.chunksOk > 0) {
|
|
5216
5302
|
outcome = "decided";
|
|
5217
|
-
for (const reply of
|
|
5218
|
-
if (
|
|
5219
|
-
tally[launchKey(await
|
|
5303
|
+
for (const reply of gate.reply) {
|
|
5304
|
+
if (run3.stale()) break;
|
|
5305
|
+
tally[launchKey(await run3.exclude(() => this.startReplyTurn(reply, texts)))] += 1;
|
|
5220
5306
|
}
|
|
5307
|
+
} else if (tally.chunksFailed > 0) {
|
|
5308
|
+
outcome = "fail_closed";
|
|
5309
|
+
} else if (owedInvites.length === 0 && !run3.stale()) {
|
|
5310
|
+
return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate });
|
|
5221
5311
|
}
|
|
5222
5312
|
}
|
|
5223
5313
|
for (const invite of owedInvites) {
|
|
5224
|
-
if (
|
|
5225
|
-
tally[launchKey(await
|
|
5314
|
+
if (run3.stale()) break;
|
|
5315
|
+
tally[launchKey(await run3.exclude(() => this.startInviteTurn(invite, texts)))] += 1;
|
|
5226
5316
|
}
|
|
5227
|
-
|
|
5317
|
+
const parts = { ...base, heldByTurns: heldByTurns + heldDuringGate, ...tally };
|
|
5318
|
+
if (run3.stale()) return this.summary("abandoned", parts);
|
|
5228
5319
|
if (tray.truncated === true && outcome === "decided") {
|
|
5229
5320
|
this.readTheRest(tally.recorded > 0 || tally.turnsStarted > 0);
|
|
5230
5321
|
}
|
|
5231
|
-
return this.summary(outcome, { ...
|
|
5322
|
+
return this.summary(outcome, { ...parts, failure });
|
|
5323
|
+
}
|
|
5324
|
+
/**
|
|
5325
|
+
* Held out of the gate: a running or waiting turn, or a verdict still being
|
|
5326
|
+
* recorded (an abandoned cycle's last call): gating it again could record
|
|
5327
|
+
* the same verdict twice (a second defer climbs the ladder).
|
|
5328
|
+
*/
|
|
5329
|
+
unheld(cards) {
|
|
5330
|
+
return this.tracker.withoutRunning(cards).filter((card) => !this.recordsInFlight.has(card.conversation_id));
|
|
5331
|
+
}
|
|
5332
|
+
/**
|
|
5333
|
+
* The gate in chunks (contract v1 §3.6): the cards, in tray order, split
|
|
5334
|
+
* into chunks of at most `gateChunkSize`, one gate call per chunk, one
|
|
5335
|
+
* after another. Each chunk's prompt is the gate prompt for its own cards
|
|
5336
|
+
* (N = the cards in that chunk), each call has its own deadline and the
|
|
5337
|
+
* cycle's cancellation, and each chunk's dismiss / defer verdicts are
|
|
5338
|
+
* recorded as soon as it answers. A chunk that fails closed leaves only its
|
|
5339
|
+
* own cards undecided. Before each call the chunk is checked again for
|
|
5340
|
+
* cards a turn has taken since the tray was read (a shared tracker), so a
|
|
5341
|
+
* longer gate never decides a card a turn holds; a chunk left with muted
|
|
5342
|
+
* cards only (or none) is not called. Stops once the cycle is stale; a call
|
|
5343
|
+
* a stop cut short is not counted as a failed chunk, and a cycle the
|
|
5344
|
+
* watchdog abandoned reports and counts no chunk after its summary.
|
|
5345
|
+
*/
|
|
5346
|
+
async gateInChunks(run3, tray, cards, texts) {
|
|
5347
|
+
const size = this.gateChunkSize;
|
|
5348
|
+
const of = Math.ceil(cards.length / size);
|
|
5349
|
+
const callModel = this.boundedModelCall(run3);
|
|
5350
|
+
const client = this.recordingClient(run3);
|
|
5351
|
+
const out = {
|
|
5352
|
+
gated: 0,
|
|
5353
|
+
held: 0,
|
|
5354
|
+
reply: [],
|
|
5355
|
+
verdicts: { reply: 0, dismiss: 0, defer: 0 },
|
|
5356
|
+
undecided: 0,
|
|
5357
|
+
recorded: 0,
|
|
5358
|
+
recordFailures: 0,
|
|
5359
|
+
chunks: []
|
|
5360
|
+
};
|
|
5361
|
+
for (let index = 1; index <= of; index++) {
|
|
5362
|
+
if (run3.stale()) break;
|
|
5363
|
+
const planned = cards.slice((index - 1) * size, index * size);
|
|
5364
|
+
const chunk = this.unheld(planned);
|
|
5365
|
+
out.held += planned.length - chunk.length;
|
|
5366
|
+
if (chunk.length < planned.length) this.heldWhileRunning = true;
|
|
5367
|
+
if (!chunk.some((card) => card.muted !== true)) continue;
|
|
5368
|
+
const result = await run({
|
|
5369
|
+
tray: { ...tray, conversations: chunk },
|
|
5370
|
+
callModel,
|
|
5371
|
+
client,
|
|
5372
|
+
texts,
|
|
5373
|
+
signal: run3.signal,
|
|
5374
|
+
...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
|
|
5375
|
+
});
|
|
5376
|
+
if (run3.abandoned()) break;
|
|
5377
|
+
if (run3.stale() && result.outcome !== "decided") break;
|
|
5378
|
+
out.gated += chunk.length;
|
|
5379
|
+
const undecided = new Set(result.undecided);
|
|
5380
|
+
for (const verdict of result.verdicts) {
|
|
5381
|
+
if (!undecided.has(verdict.conversation_id)) out.verdicts[verdict.decision] += 1;
|
|
5382
|
+
}
|
|
5383
|
+
out.reply.push(...result.reply);
|
|
5384
|
+
out.undecided += result.undecided.length;
|
|
5385
|
+
out.recorded += result.recorded;
|
|
5386
|
+
out.recordFailures += result.recordFailures.length;
|
|
5387
|
+
const report = {
|
|
5388
|
+
cycle: run3.token,
|
|
5389
|
+
index,
|
|
5390
|
+
of,
|
|
5391
|
+
cards: chunk.length,
|
|
5392
|
+
outcome: result.outcome === "decided" ? "decided" : "fail_closed",
|
|
5393
|
+
undecided: result.undecided.length,
|
|
5394
|
+
failure: result.failure
|
|
5395
|
+
};
|
|
5396
|
+
out.chunks.push(report);
|
|
5397
|
+
if (report.outcome === "decided") this.counts.chunksOk += 1;
|
|
5398
|
+
else this.counts.chunksFailed += 1;
|
|
5399
|
+
this.emit({ type: "gate_chunk", ...report });
|
|
5400
|
+
}
|
|
5401
|
+
return out;
|
|
5232
5402
|
}
|
|
5233
5403
|
/**
|
|
5234
5404
|
* More conversations wait than one tray shows. After a cycle that moved
|
|
@@ -5259,9 +5429,9 @@ var ReceiveLoop = class {
|
|
|
5259
5429
|
this.moreTimer = null;
|
|
5260
5430
|
}
|
|
5261
5431
|
}
|
|
5262
|
-
async singleRunCycle(
|
|
5432
|
+
async singleRunCycle(run3) {
|
|
5263
5433
|
const tray = await this.readTray();
|
|
5264
|
-
if (
|
|
5434
|
+
if (run3.stale()) return this.summary("abandoned");
|
|
5265
5435
|
let cards = null;
|
|
5266
5436
|
let invites = null;
|
|
5267
5437
|
let base = { cards: 0, invites: 0, heldByTurns: 0, truncated: false };
|
|
@@ -5273,10 +5443,10 @@ var ReceiveLoop = class {
|
|
|
5273
5443
|
if (cards === 0 && invites === 0) return this.summary("nothing_owed", base);
|
|
5274
5444
|
}
|
|
5275
5445
|
const texts = await this.options.texts.ensure();
|
|
5276
|
-
if (
|
|
5446
|
+
if (run3.stale()) return this.summary("abandoned", base);
|
|
5277
5447
|
if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
|
|
5278
5448
|
const unready = await this.checkReady();
|
|
5279
|
-
if (
|
|
5449
|
+
if (run3.stale()) return this.summary("abandoned", base);
|
|
5280
5450
|
if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
|
|
5281
5451
|
const prompt = cards === 0 && (invites ?? 0) > 0 ? texts.invite_prompt.trim() : (invites ?? 0) > 0 ? `${texts.wake_instruction.trim()}
|
|
5282
5452
|
|
|
@@ -5284,7 +5454,7 @@ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
|
|
|
5284
5454
|
this.counts.runsStarted += 1;
|
|
5285
5455
|
let end;
|
|
5286
5456
|
try {
|
|
5287
|
-
end = await
|
|
5457
|
+
end = await run3.exclude(() => this.options.startRun({ prompt, texts, cards, invites, signal: this.abort.signal }));
|
|
5288
5458
|
} catch (err) {
|
|
5289
5459
|
end = { status: "not_started", detail: err instanceof Error ? err.message : String(err) };
|
|
5290
5460
|
}
|
|
@@ -5500,9 +5670,9 @@ invite_id: ${invite.invite_id}`,
|
|
|
5500
5670
|
}
|
|
5501
5671
|
this.emit({ type: "invite_outcome", outcome, recorded });
|
|
5502
5672
|
}
|
|
5503
|
-
async admit(
|
|
5673
|
+
async admit(start2, request) {
|
|
5504
5674
|
try {
|
|
5505
|
-
return await
|
|
5675
|
+
return await start2(request);
|
|
5506
5676
|
} catch (err) {
|
|
5507
5677
|
return { started: false, error: err instanceof Error ? err.message : String(err) };
|
|
5508
5678
|
}
|
|
@@ -5551,6 +5721,8 @@ invite_id: ${invite.invite_id}`,
|
|
|
5551
5721
|
turnsQueued: 0,
|
|
5552
5722
|
heldByTurns: 0,
|
|
5553
5723
|
paced: 0,
|
|
5724
|
+
chunksOk: 0,
|
|
5725
|
+
chunksFailed: 0,
|
|
5554
5726
|
truncated: false,
|
|
5555
5727
|
failure: null,
|
|
5556
5728
|
...parts
|
|
@@ -5569,10 +5741,26 @@ invite_id: ${invite.invite_id}`,
|
|
|
5569
5741
|
}
|
|
5570
5742
|
};
|
|
5571
5743
|
function replyPrompt(texts, conversationId) {
|
|
5744
|
+
const raw = texts.reply_turn_template;
|
|
5745
|
+
const template = typeof raw === "string" ? raw.trim() : "";
|
|
5746
|
+
if (template.length > 0) {
|
|
5747
|
+
if (template.includes(REPLY_TURN_PLACEHOLDER)) return template.split(REPLY_TURN_PLACEHOLDER).join(conversationId);
|
|
5748
|
+
return `${template}
|
|
5749
|
+
|
|
5750
|
+
conversation_id: ${conversationId}`;
|
|
5751
|
+
}
|
|
5572
5752
|
return `${texts.wake_instruction.trim()}
|
|
5573
5753
|
|
|
5574
5754
|
conversation_id: ${conversationId}`;
|
|
5575
5755
|
}
|
|
5756
|
+
function chunkFailure(chunks) {
|
|
5757
|
+
const failed = chunks.filter((chunk) => chunk.outcome === "fail_closed");
|
|
5758
|
+
const first = failed[0];
|
|
5759
|
+
if (first === void 0) return null;
|
|
5760
|
+
const reason = first.failure ?? "no usable verdicts in the answer";
|
|
5761
|
+
if (chunks.length === 1) return reason;
|
|
5762
|
+
return `${failed.length} of ${chunks.length} gate chunks failed; chunk ${first.index}: ${reason}`;
|
|
5763
|
+
}
|
|
5576
5764
|
function timeoutOption(value, fallback, name) {
|
|
5577
5765
|
if (value === void 0) return fallback;
|
|
5578
5766
|
if (value === 0 || value === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY;
|
|
@@ -5601,6 +5789,466 @@ function wsBase(httpBase) {
|
|
|
5601
5789
|
return base.replace(/^http/, "ws");
|
|
5602
5790
|
}
|
|
5603
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
|
+
|
|
5604
6252
|
// src/wake-webhook-verify.ts
|
|
5605
6253
|
var WakeWebhookVerificationError = class extends Error {
|
|
5606
6254
|
reason;
|
|
@@ -5812,8 +6460,8 @@ function renderMessageContext(message, opts = {}) {
|
|
|
5812
6460
|
if (self && conv?.type === "group" && (ctx?.mentions ?? []).includes(self)) {
|
|
5813
6461
|
lines.push("You were @-mentioned in this message.");
|
|
5814
6462
|
}
|
|
5815
|
-
const
|
|
5816
|
-
lines.push("",
|
|
6463
|
+
const text2 = message.content?.text;
|
|
6464
|
+
lines.push("", text2 ? text2 : `(a ${"non-text"} message \u2014 no text body)`);
|
|
5817
6465
|
return lines.join("\n");
|
|
5818
6466
|
}
|
|
5819
6467
|
|
|
@@ -5841,6 +6489,6 @@ var ALLOWED_ATTACHMENT_MIME = [
|
|
|
5841
6489
|
"video/webm"
|
|
5842
6490
|
];
|
|
5843
6491
|
|
|
5844
|
-
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 };
|
|
5845
6493
|
//# sourceMappingURL=index.js.map
|
|
5846
6494
|
//# sourceMappingURL=index.js.map
|