@reinsjs/core 0.6.0 → 0.8.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 +16 -0
- package/README.md +1 -1
- package/dist/index.d.ts +134 -56
- package/dist/index.js +314 -194
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/{types-BOSGqMVX.d.ts → types-DkOLu2fW.d.ts} +121 -116
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -24,145 +24,6 @@ function contextOverheadOf(timeline) {
|
|
|
24
24
|
return 0;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
// src/loop/fork.ts
|
|
28
|
-
async function forkSession(log, opts) {
|
|
29
|
-
const toSessionId = opts.toSessionId ?? uuidv7();
|
|
30
|
-
await log.fork(opts.fromSessionId, opts.atSeq, toSessionId);
|
|
31
|
-
return { toSessionId };
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// src/lowering/errors.ts
|
|
35
|
-
var LoweringError = class extends Error {
|
|
36
|
-
constructor(code, message, context = {}) {
|
|
37
|
-
super(`[${code}] ${message}`);
|
|
38
|
-
this.code = code;
|
|
39
|
-
this.context = context;
|
|
40
|
-
this.name = "LoweringError";
|
|
41
|
-
}
|
|
42
|
-
code;
|
|
43
|
-
context;
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
// src/loop/retry.ts
|
|
47
|
-
var DEFAULT_RETRY_MAX_ATTEMPTS = 3;
|
|
48
|
-
var DEFAULT_RETRY_BASE_DELAY_MS = 1e3;
|
|
49
|
-
var DEFAULT_RETRY_MAX_DELAY_MS = 8e3;
|
|
50
|
-
var TRANSIENT_STATUS = (status) => status === 408 || status === 409 || status === 429 || status >= 500;
|
|
51
|
-
var TRANSIENT_CODES = /* @__PURE__ */ new Set([
|
|
52
|
-
"ECONNRESET",
|
|
53
|
-
"ECONNREFUSED",
|
|
54
|
-
"ETIMEDOUT",
|
|
55
|
-
"EAI_AGAIN",
|
|
56
|
-
"EPIPE",
|
|
57
|
-
"ENOTFOUND",
|
|
58
|
-
"ENETUNREACH",
|
|
59
|
-
"ECONNABORTED",
|
|
60
|
-
"UND_ERR_SOCKET",
|
|
61
|
-
"UND_ERR_CONNECT_TIMEOUT",
|
|
62
|
-
"UND_ERR_HEADERS_TIMEOUT",
|
|
63
|
-
"UND_ERR_BODY_TIMEOUT"
|
|
64
|
-
]);
|
|
65
|
-
var TRANSIENT_PATTERNS = [
|
|
66
|
-
/\b(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|EPIPE|ENOTFOUND|ENETUNREACH|ECONNABORTED|UND_ERR_[A-Z_]+TIMEOUT|UND_ERR_SOCKET)\b/,
|
|
67
|
-
/\bterminated\b/i,
|
|
68
|
-
/connection (error|closed|reset|refused)/i,
|
|
69
|
-
/socket hang up/i,
|
|
70
|
-
/\bfetch failed\b/i,
|
|
71
|
-
/\b(timeout|timed out)\b/i,
|
|
72
|
-
/\boverloaded\b/i,
|
|
73
|
-
/rate[ _-]?limit/i,
|
|
74
|
-
/too many requests/i,
|
|
75
|
-
/temporarily unavailable/i,
|
|
76
|
-
/service unavailable/i,
|
|
77
|
-
/\bstream (ended|closed) (before|prematurely)/i,
|
|
78
|
-
/pi-ai 流在 done \/ error 之前就结束了/
|
|
79
|
-
];
|
|
80
|
-
var CONNECTION_ERROR_NAMES = /* @__PURE__ */ new Set([
|
|
81
|
-
"APIConnectionError",
|
|
82
|
-
"APIConnectionTimeoutError"
|
|
83
|
-
]);
|
|
84
|
-
function isDefinitelyPermanent(err) {
|
|
85
|
-
if (err instanceof LoweringError) return true;
|
|
86
|
-
const name = err?.name;
|
|
87
|
-
return name === "AbortError" || name === "APIUserAbortError";
|
|
88
|
-
}
|
|
89
|
-
function statusFromMessage(message) {
|
|
90
|
-
const m = /^\s*(\d{3})\b/.exec(message) ?? /\b(?:status(?:\s+code)?|HTTP)[\s:=]+(\d{3})\b/i.exec(message);
|
|
91
|
-
if (!m?.[1]) return void 0;
|
|
92
|
-
const status = Number(m[1]);
|
|
93
|
-
return status >= 100 && status <= 599 ? status : void 0;
|
|
94
|
-
}
|
|
95
|
-
function structuredOf(error) {
|
|
96
|
-
const layers = [];
|
|
97
|
-
let cur = error;
|
|
98
|
-
for (let depth = 0; cur && typeof cur === "object" && depth < 4; depth++) {
|
|
99
|
-
layers.push(cur);
|
|
100
|
-
cur = cur.cause;
|
|
101
|
-
}
|
|
102
|
-
const out = { texts: [] };
|
|
103
|
-
for (const l of layers) {
|
|
104
|
-
if (out.status === void 0 && typeof l.status === "number") out.status = l.status;
|
|
105
|
-
if (out.code === void 0 && typeof l.code === "string") out.code = l.code;
|
|
106
|
-
if (out.name === void 0 && typeof l.name === "string") out.name = l.name;
|
|
107
|
-
if (out.shouldRetry === void 0 && l.headers instanceof Headers) {
|
|
108
|
-
const h = l.headers.get("x-should-retry");
|
|
109
|
-
if (h === "true") out.shouldRetry = true;
|
|
110
|
-
else if (h === "false") out.shouldRetry = false;
|
|
111
|
-
}
|
|
112
|
-
if (typeof l.message === "string") out.texts.push(l.message);
|
|
113
|
-
}
|
|
114
|
-
return out;
|
|
115
|
-
}
|
|
116
|
-
function isTransientFailure(failure) {
|
|
117
|
-
if (failure.kind === "outcome") {
|
|
118
|
-
const status2 = statusFromMessage(failure.message);
|
|
119
|
-
if (status2 !== void 0) return TRANSIENT_STATUS(status2);
|
|
120
|
-
return TRANSIENT_PATTERNS.some((re) => re.test(failure.message));
|
|
121
|
-
}
|
|
122
|
-
if (isDefinitelyPermanent(failure.error)) return false;
|
|
123
|
-
const info = structuredOf(failure.error);
|
|
124
|
-
if (info.name !== void 0 && CONNECTION_ERROR_NAMES.has(info.name)) return true;
|
|
125
|
-
if (info.shouldRetry !== void 0) return info.shouldRetry;
|
|
126
|
-
const status = info.status ?? info.texts.map(statusFromMessage).find((s) => s !== void 0);
|
|
127
|
-
if (status !== void 0) return TRANSIENT_STATUS(status);
|
|
128
|
-
if (info.code !== void 0 && TRANSIENT_CODES.has(info.code)) return true;
|
|
129
|
-
return TRANSIENT_PATTERNS.some((re) => info.texts.some((t) => re.test(t)));
|
|
130
|
-
}
|
|
131
|
-
function backoffDelayMs(attempt, opts = {}) {
|
|
132
|
-
const base = opts.baseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;
|
|
133
|
-
const max = opts.maxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;
|
|
134
|
-
return Math.min(max, base * 2 ** Math.max(0, attempt - 1));
|
|
135
|
-
}
|
|
136
|
-
function defaultSleep(ms, signal) {
|
|
137
|
-
return new Promise((resolve2) => {
|
|
138
|
-
if (signal?.aborted) return resolve2();
|
|
139
|
-
const timer = setTimeout(done, ms);
|
|
140
|
-
function done() {
|
|
141
|
-
signal?.removeEventListener("abort", done);
|
|
142
|
-
clearTimeout(timer);
|
|
143
|
-
resolve2();
|
|
144
|
-
}
|
|
145
|
-
signal?.addEventListener("abort", done, { once: true });
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
function resolveRetry(opts = {}) {
|
|
149
|
-
const maxAttempts = opts.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;
|
|
150
|
-
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
|
|
151
|
-
throw new RangeError(`retry.maxAttempts must be an integer >= 1, got ${String(maxAttempts)}`);
|
|
152
|
-
}
|
|
153
|
-
return {
|
|
154
|
-
maxAttempts,
|
|
155
|
-
delayFor: (attempt) => backoffDelayMs(attempt, opts),
|
|
156
|
-
isTransient: opts.isTransient ?? isTransientFailure,
|
|
157
|
-
sleep: opts.sleep ?? defaultSleep
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// src/lowering/types.ts
|
|
162
|
-
function lossesOf(req) {
|
|
163
|
-
return req.landings.filter((l) => l.kind !== "exact");
|
|
164
|
-
}
|
|
165
|
-
|
|
166
27
|
// src/projection/filter.ts
|
|
167
28
|
var DEFAULT_MODEL_INVISIBLE_TYPES = /* @__PURE__ */ new Set([
|
|
168
29
|
"core.approval_request",
|
|
@@ -624,6 +485,223 @@ function project(opts) {
|
|
|
624
485
|
};
|
|
625
486
|
}
|
|
626
487
|
|
|
488
|
+
// src/replay/replay.ts
|
|
489
|
+
var MODEL_OUTPUT_TYPES = /* @__PURE__ */ new Set([
|
|
490
|
+
"core.model_thinking",
|
|
491
|
+
"core.model_text",
|
|
492
|
+
"core.tool_call"
|
|
493
|
+
]);
|
|
494
|
+
function isModelOutput(e) {
|
|
495
|
+
return MODEL_OUTPUT_TYPES.has(e.type);
|
|
496
|
+
}
|
|
497
|
+
function replayTurns(timeline, opts) {
|
|
498
|
+
const sessionId = timeline[0]?.sessionId;
|
|
499
|
+
const turns = [];
|
|
500
|
+
const preamble = [];
|
|
501
|
+
let i = 0;
|
|
502
|
+
while (i < timeline.length && !isModelOutput(timeline[i])) preamble.push(timeline[i++]);
|
|
503
|
+
while (i < timeline.length) {
|
|
504
|
+
const first = timeline[i];
|
|
505
|
+
const requestAtSeq = first.seq - 1;
|
|
506
|
+
const output = [];
|
|
507
|
+
while (i < timeline.length && isModelOutput(timeline[i])) output.push(timeline[i++]);
|
|
508
|
+
const aftermath = [];
|
|
509
|
+
while (i < timeline.length && !isModelOutput(timeline[i])) aftermath.push(timeline[i++]);
|
|
510
|
+
const prefix = timeline.slice(0, requestAtSeq);
|
|
511
|
+
const projected = project({
|
|
512
|
+
timeline: prefix,
|
|
513
|
+
budget: opts.budget,
|
|
514
|
+
// 回放不该产生新 id,也不依赖当前时间;给确定值让输出可比对
|
|
515
|
+
now: first.at,
|
|
516
|
+
newId: (at) => `replay-${at}-${requestAtSeq}`,
|
|
517
|
+
...sessionId !== void 0 ? { sessionId } : {},
|
|
518
|
+
...opts.strategies ? { strategies: opts.strategies } : {},
|
|
519
|
+
...opts.estimate ? { estimate: opts.estimate } : {},
|
|
520
|
+
...opts.registry ? { registry: opts.registry } : {}
|
|
521
|
+
});
|
|
522
|
+
const usage = aftermath.find(
|
|
523
|
+
(e) => e.type === "core.budget_usage"
|
|
524
|
+
)?.payload;
|
|
525
|
+
turns.push({
|
|
526
|
+
index: turns.length + 1,
|
|
527
|
+
requestAtSeq,
|
|
528
|
+
visible: projected.events,
|
|
529
|
+
stats: projected.stats,
|
|
530
|
+
diverged: projected.emitted.length > 0,
|
|
531
|
+
output,
|
|
532
|
+
aftermath,
|
|
533
|
+
...usage ? { usage } : {}
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
return { turns, preamble };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// src/loop/batch.ts
|
|
540
|
+
function inBatchSpan(e) {
|
|
541
|
+
return isModelOutput(e) || DEFAULT_MODEL_INVISIBLE_TYPES.has(e.type);
|
|
542
|
+
}
|
|
543
|
+
function toolBatchOf(timeline, pending) {
|
|
544
|
+
const anchor = pending[0];
|
|
545
|
+
if (!anchor) return { calls: [], results: [] };
|
|
546
|
+
const at = timeline.findIndex((e) => e.id === anchor.id);
|
|
547
|
+
if (at < 0) return { calls: [...pending], results: [] };
|
|
548
|
+
let start = at;
|
|
549
|
+
while (start > 0 && inBatchSpan(timeline[start - 1])) start--;
|
|
550
|
+
let end = at;
|
|
551
|
+
while (end + 1 < timeline.length && inBatchSpan(timeline[end + 1])) end++;
|
|
552
|
+
const calls = [];
|
|
553
|
+
for (let i = start; i <= end; i++) {
|
|
554
|
+
const e = timeline[i];
|
|
555
|
+
if (e.type === "core.tool_call") calls.push(e);
|
|
556
|
+
}
|
|
557
|
+
const ids = new Set(calls.map((c) => c.payload.toolCallId));
|
|
558
|
+
const results = [];
|
|
559
|
+
for (const raw of timeline) {
|
|
560
|
+
const e = raw;
|
|
561
|
+
if (e.type === "core.tool_result" && ids.has(e.payload.toolCallId)) results.push(e);
|
|
562
|
+
}
|
|
563
|
+
return { calls, results };
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// src/loop/fork.ts
|
|
567
|
+
async function forkSession(log, opts) {
|
|
568
|
+
const toSessionId = opts.toSessionId ?? uuidv7();
|
|
569
|
+
await log.fork(opts.fromSessionId, opts.atSeq, toSessionId);
|
|
570
|
+
return { toSessionId };
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// src/lowering/errors.ts
|
|
574
|
+
var LoweringError = class extends Error {
|
|
575
|
+
constructor(code, message, context = {}) {
|
|
576
|
+
super(`[${code}] ${message}`);
|
|
577
|
+
this.code = code;
|
|
578
|
+
this.context = context;
|
|
579
|
+
this.name = "LoweringError";
|
|
580
|
+
}
|
|
581
|
+
code;
|
|
582
|
+
context;
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
// src/loop/retry.ts
|
|
586
|
+
var DEFAULT_RETRY_MAX_ATTEMPTS = 3;
|
|
587
|
+
var DEFAULT_RETRY_BASE_DELAY_MS = 1e3;
|
|
588
|
+
var DEFAULT_RETRY_MAX_DELAY_MS = 8e3;
|
|
589
|
+
var TRANSIENT_STATUS = (status) => status === 408 || status === 409 || status === 429 || status >= 500;
|
|
590
|
+
var TRANSIENT_CODES = /* @__PURE__ */ new Set([
|
|
591
|
+
"ECONNRESET",
|
|
592
|
+
"ECONNREFUSED",
|
|
593
|
+
"ETIMEDOUT",
|
|
594
|
+
"EAI_AGAIN",
|
|
595
|
+
"EPIPE",
|
|
596
|
+
"ENOTFOUND",
|
|
597
|
+
"ENETUNREACH",
|
|
598
|
+
"ECONNABORTED",
|
|
599
|
+
"UND_ERR_SOCKET",
|
|
600
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
601
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
602
|
+
"UND_ERR_BODY_TIMEOUT"
|
|
603
|
+
]);
|
|
604
|
+
var TRANSIENT_PATTERNS = [
|
|
605
|
+
/\b(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|EPIPE|ENOTFOUND|ENETUNREACH|ECONNABORTED|UND_ERR_[A-Z_]+TIMEOUT|UND_ERR_SOCKET)\b/,
|
|
606
|
+
/\bterminated\b/i,
|
|
607
|
+
/connection (error|closed|reset|refused)/i,
|
|
608
|
+
/socket hang up/i,
|
|
609
|
+
/\bfetch failed\b/i,
|
|
610
|
+
/\b(timeout|timed out)\b/i,
|
|
611
|
+
/\boverloaded\b/i,
|
|
612
|
+
/rate[ _-]?limit/i,
|
|
613
|
+
/too many requests/i,
|
|
614
|
+
/temporarily unavailable/i,
|
|
615
|
+
/service unavailable/i,
|
|
616
|
+
/\bstream (ended|closed) (before|prematurely)/i,
|
|
617
|
+
/pi-ai 流在 done \/ error 之前就结束了/
|
|
618
|
+
];
|
|
619
|
+
var CONNECTION_ERROR_NAMES = /* @__PURE__ */ new Set([
|
|
620
|
+
"APIConnectionError",
|
|
621
|
+
"APIConnectionTimeoutError"
|
|
622
|
+
]);
|
|
623
|
+
function isDefinitelyPermanent(err) {
|
|
624
|
+
if (err instanceof LoweringError) return true;
|
|
625
|
+
const name = err?.name;
|
|
626
|
+
return name === "AbortError" || name === "APIUserAbortError";
|
|
627
|
+
}
|
|
628
|
+
function statusFromMessage(message) {
|
|
629
|
+
const m = /^\s*(\d{3})\b/.exec(message) ?? /\b(?:status(?:\s+code)?|HTTP)[\s:=]+(\d{3})\b/i.exec(message);
|
|
630
|
+
if (!m?.[1]) return void 0;
|
|
631
|
+
const status = Number(m[1]);
|
|
632
|
+
return status >= 100 && status <= 599 ? status : void 0;
|
|
633
|
+
}
|
|
634
|
+
function structuredOf(error) {
|
|
635
|
+
const layers = [];
|
|
636
|
+
let cur = error;
|
|
637
|
+
for (let depth = 0; cur && typeof cur === "object" && depth < 4; depth++) {
|
|
638
|
+
layers.push(cur);
|
|
639
|
+
cur = cur.cause;
|
|
640
|
+
}
|
|
641
|
+
const out = { texts: [] };
|
|
642
|
+
for (const l of layers) {
|
|
643
|
+
if (out.status === void 0 && typeof l.status === "number") out.status = l.status;
|
|
644
|
+
if (out.code === void 0 && typeof l.code === "string") out.code = l.code;
|
|
645
|
+
if (out.name === void 0 && typeof l.name === "string") out.name = l.name;
|
|
646
|
+
if (out.shouldRetry === void 0 && l.headers instanceof Headers) {
|
|
647
|
+
const h = l.headers.get("x-should-retry");
|
|
648
|
+
if (h === "true") out.shouldRetry = true;
|
|
649
|
+
else if (h === "false") out.shouldRetry = false;
|
|
650
|
+
}
|
|
651
|
+
if (typeof l.message === "string") out.texts.push(l.message);
|
|
652
|
+
}
|
|
653
|
+
return out;
|
|
654
|
+
}
|
|
655
|
+
function isTransientFailure(failure) {
|
|
656
|
+
if (failure.kind === "outcome") {
|
|
657
|
+
const status2 = statusFromMessage(failure.message);
|
|
658
|
+
if (status2 !== void 0) return TRANSIENT_STATUS(status2);
|
|
659
|
+
return TRANSIENT_PATTERNS.some((re) => re.test(failure.message));
|
|
660
|
+
}
|
|
661
|
+
if (isDefinitelyPermanent(failure.error)) return false;
|
|
662
|
+
const info = structuredOf(failure.error);
|
|
663
|
+
if (info.name !== void 0 && CONNECTION_ERROR_NAMES.has(info.name)) return true;
|
|
664
|
+
if (info.shouldRetry !== void 0) return info.shouldRetry;
|
|
665
|
+
const status = info.status ?? info.texts.map(statusFromMessage).find((s) => s !== void 0);
|
|
666
|
+
if (status !== void 0) return TRANSIENT_STATUS(status);
|
|
667
|
+
if (info.code !== void 0 && TRANSIENT_CODES.has(info.code)) return true;
|
|
668
|
+
return TRANSIENT_PATTERNS.some((re) => info.texts.some((t) => re.test(t)));
|
|
669
|
+
}
|
|
670
|
+
function backoffDelayMs(attempt, opts = {}) {
|
|
671
|
+
const base = opts.baseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;
|
|
672
|
+
const max = opts.maxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;
|
|
673
|
+
return Math.min(max, base * 2 ** Math.max(0, attempt - 1));
|
|
674
|
+
}
|
|
675
|
+
function defaultSleep(ms, signal) {
|
|
676
|
+
return new Promise((resolve2) => {
|
|
677
|
+
if (signal?.aborted) return resolve2();
|
|
678
|
+
const timer = setTimeout(done, ms);
|
|
679
|
+
function done() {
|
|
680
|
+
signal?.removeEventListener("abort", done);
|
|
681
|
+
clearTimeout(timer);
|
|
682
|
+
resolve2();
|
|
683
|
+
}
|
|
684
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
function resolveRetry(opts = {}) {
|
|
688
|
+
const maxAttempts = opts.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;
|
|
689
|
+
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
|
|
690
|
+
throw new RangeError(`retry.maxAttempts must be an integer >= 1, got ${String(maxAttempts)}`);
|
|
691
|
+
}
|
|
692
|
+
return {
|
|
693
|
+
maxAttempts,
|
|
694
|
+
delayFor: (attempt) => backoffDelayMs(attempt, opts),
|
|
695
|
+
isTransient: opts.isTransient ?? isTransientFailure,
|
|
696
|
+
sleep: opts.sleep ?? defaultSleep
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// src/lowering/types.ts
|
|
701
|
+
function lossesOf(req) {
|
|
702
|
+
return req.landings.filter((l) => l.kind !== "exact");
|
|
703
|
+
}
|
|
704
|
+
|
|
627
705
|
// src/store/read-timeline.ts
|
|
628
706
|
async function* readEvents(log, sessionId, opts) {
|
|
629
707
|
const { registry, ...range } = opts;
|
|
@@ -1137,6 +1215,7 @@ async function* runLoop(cfg) {
|
|
|
1137
1215
|
yield* projected.emitted;
|
|
1138
1216
|
}
|
|
1139
1217
|
const emitted = [];
|
|
1218
|
+
const batch = { calls: [], results: [], held: [], resumed: false };
|
|
1140
1219
|
const ctx = {
|
|
1141
1220
|
session: { id: sessionId, turn: turns + 1 },
|
|
1142
1221
|
...cfg.principal ? { principal: cfg.principal } : {},
|
|
@@ -1159,6 +1238,7 @@ async function* runLoop(cfg) {
|
|
|
1159
1238
|
...lastUsage ? { lastUsage } : {}
|
|
1160
1239
|
},
|
|
1161
1240
|
...cfg.signal ? { signal: cfg.signal } : {},
|
|
1241
|
+
batch,
|
|
1162
1242
|
emit: (d) => emitted.push(d)
|
|
1163
1243
|
};
|
|
1164
1244
|
const flush = async () => {
|
|
@@ -1174,13 +1254,18 @@ async function* runLoop(cfg) {
|
|
|
1174
1254
|
}
|
|
1175
1255
|
const pending = pendingToolCalls(timeline);
|
|
1176
1256
|
if (pending.length > 0) {
|
|
1257
|
+
const located = toolBatchOf(timeline, pending);
|
|
1258
|
+
batch.calls.push(...located.calls);
|
|
1259
|
+
batch.results.push(...located.results);
|
|
1260
|
+
batch.resumed = true;
|
|
1177
1261
|
const settled = yield* executeToolCalls(ctx, pending, timeline, {
|
|
1178
1262
|
cfg,
|
|
1179
1263
|
sockets,
|
|
1180
1264
|
append,
|
|
1181
1265
|
flush,
|
|
1182
1266
|
forwardedDecisions,
|
|
1183
|
-
spend: spendInto(ctx)
|
|
1267
|
+
spend: spendInto(ctx),
|
|
1268
|
+
batch
|
|
1184
1269
|
});
|
|
1185
1270
|
toolCallsTotal += settled.executed;
|
|
1186
1271
|
if (settled.interruptions.length > 0) {
|
|
@@ -1310,6 +1395,7 @@ async function* runLoop(cfg) {
|
|
|
1310
1395
|
}
|
|
1311
1396
|
if (!outcome)
|
|
1312
1397
|
throw new Error("runLoop internal error: the model call produced neither an outcome nor a failure");
|
|
1398
|
+
for (const e of modelEvents) if (e.type === "core.tool_call") batch.calls.push(e);
|
|
1313
1399
|
for (const s of sockets) await s.afterModel?.(ctx, modelEvents);
|
|
1314
1400
|
yield* await flush();
|
|
1315
1401
|
if (outcome.stopReason === "aborted") {
|
|
@@ -1328,7 +1414,8 @@ async function* runLoop(cfg) {
|
|
|
1328
1414
|
append,
|
|
1329
1415
|
flush,
|
|
1330
1416
|
forwardedDecisions,
|
|
1331
|
-
spend: spendInto(ctx)
|
|
1417
|
+
spend: spendInto(ctx),
|
|
1418
|
+
batch
|
|
1332
1419
|
});
|
|
1333
1420
|
toolCallsTotal += settled.executed;
|
|
1334
1421
|
ctx.budget.toolCalls = toolCallsTotal;
|
|
@@ -1433,7 +1520,12 @@ function withResultTrust(input, tools) {
|
|
|
1433
1520
|
return { ...input, ...withTrust(toolResultTrust(tool, payload?.isError === true)) };
|
|
1434
1521
|
}
|
|
1435
1522
|
async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
1436
|
-
const { cfg, sockets,
|
|
1523
|
+
const { cfg, sockets, flush, forwardedDecisions, spend, batch } = deps;
|
|
1524
|
+
const append = async (drafts) => {
|
|
1525
|
+
const events = await deps.append(drafts);
|
|
1526
|
+
for (const e of events) if (e.type === "core.tool_result") batch.results.push(e);
|
|
1527
|
+
return events;
|
|
1528
|
+
};
|
|
1437
1529
|
const decisions = /* @__PURE__ */ new Map();
|
|
1438
1530
|
const requested = /* @__PURE__ */ new Set();
|
|
1439
1531
|
for (const raw of timeline) {
|
|
@@ -1520,10 +1612,12 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
|
1520
1612
|
});
|
|
1521
1613
|
}
|
|
1522
1614
|
summary.interruptions.push({ kind: "approval", toolCallId, request, call: call.payload });
|
|
1615
|
+
batch.held.push(toolCallId);
|
|
1523
1616
|
continue;
|
|
1524
1617
|
}
|
|
1525
1618
|
if (!tool.execute || tool.side === "client") {
|
|
1526
1619
|
summary.interruptions.push({ kind: "client_tool", toolCallId, call: call.payload });
|
|
1620
|
+
batch.held.push(toolCallId);
|
|
1527
1621
|
continue;
|
|
1528
1622
|
}
|
|
1529
1623
|
let result;
|
|
@@ -1532,6 +1626,7 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
|
1532
1626
|
const out = await tool.execute(args, toolCtx);
|
|
1533
1627
|
if (isSubagentPause(out)) {
|
|
1534
1628
|
summary.interruptions.push({ kind: "subagent", toolCallId, call: call.payload, ...out.detail });
|
|
1629
|
+
batch.held.push(toolCallId);
|
|
1535
1630
|
if (cfg.signal?.aborted) break;
|
|
1536
1631
|
continue;
|
|
1537
1632
|
}
|
|
@@ -1558,6 +1653,78 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
|
1558
1653
|
return summary;
|
|
1559
1654
|
}
|
|
1560
1655
|
|
|
1656
|
+
// src/lowering/tool-arguments.ts
|
|
1657
|
+
function unwrapToolArguments(parsed) {
|
|
1658
|
+
if (typeof parsed !== "string") return { args: parsed, unwrapped: false };
|
|
1659
|
+
const inner = parseLenient(parsed);
|
|
1660
|
+
if (typeof inner === "object" && inner !== null && !Array.isArray(inner))
|
|
1661
|
+
return { args: inner, unwrapped: true };
|
|
1662
|
+
return { args: parsed, unwrapped: false };
|
|
1663
|
+
}
|
|
1664
|
+
function decodeToolArgumentsText(raw) {
|
|
1665
|
+
if (raw.trim() === "") return { args: {}, unwrapped: false };
|
|
1666
|
+
let once;
|
|
1667
|
+
try {
|
|
1668
|
+
once = JSON.parse(raw);
|
|
1669
|
+
} catch {
|
|
1670
|
+
return { args: raw, unwrapped: false };
|
|
1671
|
+
}
|
|
1672
|
+
if (typeof once !== "string") return { args: once, unwrapped: false };
|
|
1673
|
+
const decoded = unwrapToolArguments(once);
|
|
1674
|
+
return decoded.unwrapped ? decoded : { args: raw, unwrapped: false };
|
|
1675
|
+
}
|
|
1676
|
+
function toolCallArgumentsMeta(decoded) {
|
|
1677
|
+
return decoded.unwrapped ? { meta: { argumentsUnwrapped: true } } : {};
|
|
1678
|
+
}
|
|
1679
|
+
function parseLenient(text) {
|
|
1680
|
+
try {
|
|
1681
|
+
return JSON.parse(text);
|
|
1682
|
+
} catch {
|
|
1683
|
+
const repaired = escapeControlCharsInStrings(text);
|
|
1684
|
+
if (repaired === text) return void 0;
|
|
1685
|
+
try {
|
|
1686
|
+
return JSON.parse(repaired);
|
|
1687
|
+
} catch {
|
|
1688
|
+
return void 0;
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
function escapeControlCharsInStrings(text) {
|
|
1693
|
+
let out = "";
|
|
1694
|
+
let inString = false;
|
|
1695
|
+
let escaped = false;
|
|
1696
|
+
for (const ch of text) {
|
|
1697
|
+
if (!inString) {
|
|
1698
|
+
if (ch === '"') inString = true;
|
|
1699
|
+
out += ch;
|
|
1700
|
+
continue;
|
|
1701
|
+
}
|
|
1702
|
+
if (escaped) {
|
|
1703
|
+
escaped = false;
|
|
1704
|
+
out += ch;
|
|
1705
|
+
continue;
|
|
1706
|
+
}
|
|
1707
|
+
if (ch === "\\") escaped = true;
|
|
1708
|
+
else if (ch === '"') inString = false;
|
|
1709
|
+
else {
|
|
1710
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
1711
|
+
if (code < 32) {
|
|
1712
|
+
out += CONTROL_ESCAPES[ch] ?? `\\u${code.toString(16).padStart(4, "0")}`;
|
|
1713
|
+
continue;
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
out += ch;
|
|
1717
|
+
}
|
|
1718
|
+
return out;
|
|
1719
|
+
}
|
|
1720
|
+
var CONTROL_ESCAPES = {
|
|
1721
|
+
"\n": "\\n",
|
|
1722
|
+
"\r": "\\r",
|
|
1723
|
+
" ": "\\t",
|
|
1724
|
+
"\b": "\\b",
|
|
1725
|
+
"\f": "\\f"
|
|
1726
|
+
};
|
|
1727
|
+
|
|
1561
1728
|
// src/lowering/trust.ts
|
|
1562
1729
|
var UNTRUSTED_TAG = "untrusted";
|
|
1563
1730
|
function untrustedSourceOf(e) {
|
|
@@ -1611,57 +1778,6 @@ function needsUntrustedMark(e) {
|
|
|
1611
1778
|
return e.trust === "untrusted";
|
|
1612
1779
|
}
|
|
1613
1780
|
|
|
1614
|
-
// src/replay/replay.ts
|
|
1615
|
-
var MODEL_OUTPUT_TYPES = /* @__PURE__ */ new Set([
|
|
1616
|
-
"core.model_thinking",
|
|
1617
|
-
"core.model_text",
|
|
1618
|
-
"core.tool_call"
|
|
1619
|
-
]);
|
|
1620
|
-
function isModelOutput(e) {
|
|
1621
|
-
return MODEL_OUTPUT_TYPES.has(e.type);
|
|
1622
|
-
}
|
|
1623
|
-
function replayTurns(timeline, opts) {
|
|
1624
|
-
const sessionId = timeline[0]?.sessionId;
|
|
1625
|
-
const turns = [];
|
|
1626
|
-
const preamble = [];
|
|
1627
|
-
let i = 0;
|
|
1628
|
-
while (i < timeline.length && !isModelOutput(timeline[i])) preamble.push(timeline[i++]);
|
|
1629
|
-
while (i < timeline.length) {
|
|
1630
|
-
const first = timeline[i];
|
|
1631
|
-
const requestAtSeq = first.seq - 1;
|
|
1632
|
-
const output = [];
|
|
1633
|
-
while (i < timeline.length && isModelOutput(timeline[i])) output.push(timeline[i++]);
|
|
1634
|
-
const aftermath = [];
|
|
1635
|
-
while (i < timeline.length && !isModelOutput(timeline[i])) aftermath.push(timeline[i++]);
|
|
1636
|
-
const prefix = timeline.slice(0, requestAtSeq);
|
|
1637
|
-
const projected = project({
|
|
1638
|
-
timeline: prefix,
|
|
1639
|
-
budget: opts.budget,
|
|
1640
|
-
// 回放不该产生新 id,也不依赖当前时间;给确定值让输出可比对
|
|
1641
|
-
now: first.at,
|
|
1642
|
-
newId: (at) => `replay-${at}-${requestAtSeq}`,
|
|
1643
|
-
...sessionId !== void 0 ? { sessionId } : {},
|
|
1644
|
-
...opts.strategies ? { strategies: opts.strategies } : {},
|
|
1645
|
-
...opts.estimate ? { estimate: opts.estimate } : {},
|
|
1646
|
-
...opts.registry ? { registry: opts.registry } : {}
|
|
1647
|
-
});
|
|
1648
|
-
const usage = aftermath.find(
|
|
1649
|
-
(e) => e.type === "core.budget_usage"
|
|
1650
|
-
)?.payload;
|
|
1651
|
-
turns.push({
|
|
1652
|
-
index: turns.length + 1,
|
|
1653
|
-
requestAtSeq,
|
|
1654
|
-
visible: projected.events,
|
|
1655
|
-
stats: projected.stats,
|
|
1656
|
-
diverged: projected.emitted.length > 0,
|
|
1657
|
-
output,
|
|
1658
|
-
aftermath,
|
|
1659
|
-
...usage ? { usage } : {}
|
|
1660
|
-
});
|
|
1661
|
-
}
|
|
1662
|
-
return { turns, preamble };
|
|
1663
|
-
}
|
|
1664
|
-
|
|
1665
1781
|
// src/store/errors.ts
|
|
1666
1782
|
var StoreError = class extends Error {
|
|
1667
1783
|
constructor(code, message, context = {}) {
|
|
@@ -1809,7 +1925,7 @@ function memoryStore() {
|
|
|
1809
1925
|
}
|
|
1810
1926
|
|
|
1811
1927
|
// src/index.ts
|
|
1812
|
-
var REINS_VERSION = "0.
|
|
1928
|
+
var REINS_VERSION = "0.8.0";
|
|
1813
1929
|
export {
|
|
1814
1930
|
BUILTIN_APPROVAL_POLICY,
|
|
1815
1931
|
CORE_SCHEMAS,
|
|
@@ -1845,6 +1961,7 @@ export {
|
|
|
1845
1961
|
createCoreEvent,
|
|
1846
1962
|
createCoreRegistry,
|
|
1847
1963
|
createEvent,
|
|
1964
|
+
decodeToolArgumentsText,
|
|
1848
1965
|
defaultProjectionChain,
|
|
1849
1966
|
defaultSleep,
|
|
1850
1967
|
defaultThresholdSummary,
|
|
@@ -1894,11 +2011,14 @@ export {
|
|
|
1894
2011
|
statusFromMessage,
|
|
1895
2012
|
subagentPause,
|
|
1896
2013
|
supersededIds,
|
|
2014
|
+
toolBatchOf,
|
|
2015
|
+
toolCallArgumentsMeta,
|
|
1897
2016
|
toolResultTrust,
|
|
1898
2017
|
toolSpecOf,
|
|
1899
2018
|
toolsBoundDrafts,
|
|
1900
2019
|
untrustedOpenTag,
|
|
1901
2020
|
untrustedSourceOf,
|
|
2021
|
+
unwrapToolArguments,
|
|
1902
2022
|
uuidv7,
|
|
1903
2023
|
validateResume,
|
|
1904
2024
|
verifyRunState,
|