@reinsjs/core 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  createEvent,
9
9
  renderToolReference,
10
10
  uuidv7
11
- } from "./chunk-63AJKR7J.js";
11
+ } from "./chunk-GWU2JSFA.js";
12
12
 
13
13
  // src/events/core.ts
14
14
  function contextTokensOf(usage) {
@@ -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",
@@ -189,6 +50,16 @@ function visibilityFilter(opts = {}) {
189
50
  // src/projection/estimate.ts
190
51
  var PER_EVENT_OVERHEAD = 4;
191
52
  var IMAGE_TOKENS = 1600;
53
+ var VIDEO_TOKENS_PER_SEC = 100;
54
+ var AUDIO_TOKENS_PER_SEC = 32;
55
+ var VIDEO_BYTES_PER_SEC = 125e3;
56
+ var AUDIO_BYTES_PER_SEC = 8e3;
57
+ var MIN_GUESSED_SEC = 30;
58
+ function mediaSeconds(part, bytesPerSec) {
59
+ if (part.durationSec !== void 0) return part.durationSec;
60
+ const bytes = part.data.length * 3 / 4;
61
+ return Math.max(bytes / bytesPerSec, MIN_GUESSED_SEC);
62
+ }
192
63
  function estimateTextTokens(text) {
193
64
  let ascii = 0;
194
65
  let other = 0;
@@ -201,9 +72,27 @@ function estimateTextTokens(text) {
201
72
  function partsTokens(parts) {
202
73
  let n = 0;
203
74
  for (const p of parts) {
204
- if (p.type === "text") n += estimateTextTokens(p.text);
205
- else if (p.type === "tool_reference") n += estimateTextTokens(renderToolReference(p));
206
- else n += IMAGE_TOKENS;
75
+ switch (p.type) {
76
+ case "text":
77
+ n += estimateTextTokens(p.text);
78
+ break;
79
+ case "tool_reference":
80
+ n += estimateTextTokens(renderToolReference(p));
81
+ break;
82
+ case "image":
83
+ n += IMAGE_TOKENS;
84
+ break;
85
+ case "video":
86
+ n += Math.ceil(mediaSeconds(p, VIDEO_BYTES_PER_SEC) * VIDEO_TOKENS_PER_SEC);
87
+ break;
88
+ case "audio":
89
+ n += Math.ceil(mediaSeconds(p, AUDIO_BYTES_PER_SEC) * AUDIO_TOKENS_PER_SEC);
90
+ break;
91
+ default: {
92
+ const _exhaustive = p;
93
+ void _exhaustive;
94
+ }
95
+ }
207
96
  }
208
97
  return n;
209
98
  }
@@ -433,8 +322,24 @@ function splitTurns(events) {
433
322
  return turns;
434
323
  }
435
324
  var DEFAULT_CUT_TO_RATIO = 0.6;
325
+ function partExcerpt(p) {
326
+ switch (p.type) {
327
+ case "text":
328
+ return p.text;
329
+ case "image":
330
+ case "video":
331
+ case "audio":
332
+ return `[${p.type}]`;
333
+ case "tool_reference":
334
+ return `[tool ${p.name}]`;
335
+ default: {
336
+ const _exhaustive = p;
337
+ return _exhaustive;
338
+ }
339
+ }
340
+ }
436
341
  function excerpt(parts, max = 120) {
437
- const text = parts.map((p) => p.type === "text" ? p.text : "[image]").join(" ").replace(/\s+/g, " ").trim();
342
+ const text = parts.map(partExcerpt).join(" ").replace(/\s+/g, " ").trim();
438
343
  return text.length > max ? `${text.slice(0, max)}\u2026` : text;
439
344
  }
440
345
  var defaultThresholdSummary = (removed, ctx) => {
@@ -624,6 +529,223 @@ function project(opts) {
624
529
  };
625
530
  }
626
531
 
532
+ // src/replay/replay.ts
533
+ var MODEL_OUTPUT_TYPES = /* @__PURE__ */ new Set([
534
+ "core.model_thinking",
535
+ "core.model_text",
536
+ "core.tool_call"
537
+ ]);
538
+ function isModelOutput(e) {
539
+ return MODEL_OUTPUT_TYPES.has(e.type);
540
+ }
541
+ function replayTurns(timeline, opts) {
542
+ const sessionId = timeline[0]?.sessionId;
543
+ const turns = [];
544
+ const preamble = [];
545
+ let i = 0;
546
+ while (i < timeline.length && !isModelOutput(timeline[i])) preamble.push(timeline[i++]);
547
+ while (i < timeline.length) {
548
+ const first = timeline[i];
549
+ const requestAtSeq = first.seq - 1;
550
+ const output = [];
551
+ while (i < timeline.length && isModelOutput(timeline[i])) output.push(timeline[i++]);
552
+ const aftermath = [];
553
+ while (i < timeline.length && !isModelOutput(timeline[i])) aftermath.push(timeline[i++]);
554
+ const prefix = timeline.slice(0, requestAtSeq);
555
+ const projected = project({
556
+ timeline: prefix,
557
+ budget: opts.budget,
558
+ // 回放不该产生新 id,也不依赖当前时间;给确定值让输出可比对
559
+ now: first.at,
560
+ newId: (at) => `replay-${at}-${requestAtSeq}`,
561
+ ...sessionId !== void 0 ? { sessionId } : {},
562
+ ...opts.strategies ? { strategies: opts.strategies } : {},
563
+ ...opts.estimate ? { estimate: opts.estimate } : {},
564
+ ...opts.registry ? { registry: opts.registry } : {}
565
+ });
566
+ const usage = aftermath.find(
567
+ (e) => e.type === "core.budget_usage"
568
+ )?.payload;
569
+ turns.push({
570
+ index: turns.length + 1,
571
+ requestAtSeq,
572
+ visible: projected.events,
573
+ stats: projected.stats,
574
+ diverged: projected.emitted.length > 0,
575
+ output,
576
+ aftermath,
577
+ ...usage ? { usage } : {}
578
+ });
579
+ }
580
+ return { turns, preamble };
581
+ }
582
+
583
+ // src/loop/batch.ts
584
+ function inBatchSpan(e) {
585
+ return isModelOutput(e) || DEFAULT_MODEL_INVISIBLE_TYPES.has(e.type);
586
+ }
587
+ function toolBatchOf(timeline, pending) {
588
+ const anchor = pending[0];
589
+ if (!anchor) return { calls: [], results: [] };
590
+ const at = timeline.findIndex((e) => e.id === anchor.id);
591
+ if (at < 0) return { calls: [...pending], results: [] };
592
+ let start = at;
593
+ while (start > 0 && inBatchSpan(timeline[start - 1])) start--;
594
+ let end = at;
595
+ while (end + 1 < timeline.length && inBatchSpan(timeline[end + 1])) end++;
596
+ const calls = [];
597
+ for (let i = start; i <= end; i++) {
598
+ const e = timeline[i];
599
+ if (e.type === "core.tool_call") calls.push(e);
600
+ }
601
+ const ids = new Set(calls.map((c) => c.payload.toolCallId));
602
+ const results = [];
603
+ for (const raw of timeline) {
604
+ const e = raw;
605
+ if (e.type === "core.tool_result" && ids.has(e.payload.toolCallId)) results.push(e);
606
+ }
607
+ return { calls, results };
608
+ }
609
+
610
+ // src/loop/fork.ts
611
+ async function forkSession(log, opts) {
612
+ const toSessionId = opts.toSessionId ?? uuidv7();
613
+ await log.fork(opts.fromSessionId, opts.atSeq, toSessionId);
614
+ return { toSessionId };
615
+ }
616
+
617
+ // src/lowering/errors.ts
618
+ var LoweringError = class extends Error {
619
+ constructor(code, message, context = {}) {
620
+ super(`[${code}] ${message}`);
621
+ this.code = code;
622
+ this.context = context;
623
+ this.name = "LoweringError";
624
+ }
625
+ code;
626
+ context;
627
+ };
628
+
629
+ // src/loop/retry.ts
630
+ var DEFAULT_RETRY_MAX_ATTEMPTS = 3;
631
+ var DEFAULT_RETRY_BASE_DELAY_MS = 1e3;
632
+ var DEFAULT_RETRY_MAX_DELAY_MS = 8e3;
633
+ var TRANSIENT_STATUS = (status) => status === 408 || status === 409 || status === 429 || status >= 500;
634
+ var TRANSIENT_CODES = /* @__PURE__ */ new Set([
635
+ "ECONNRESET",
636
+ "ECONNREFUSED",
637
+ "ETIMEDOUT",
638
+ "EAI_AGAIN",
639
+ "EPIPE",
640
+ "ENOTFOUND",
641
+ "ENETUNREACH",
642
+ "ECONNABORTED",
643
+ "UND_ERR_SOCKET",
644
+ "UND_ERR_CONNECT_TIMEOUT",
645
+ "UND_ERR_HEADERS_TIMEOUT",
646
+ "UND_ERR_BODY_TIMEOUT"
647
+ ]);
648
+ var TRANSIENT_PATTERNS = [
649
+ /\b(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|EPIPE|ENOTFOUND|ENETUNREACH|ECONNABORTED|UND_ERR_[A-Z_]+TIMEOUT|UND_ERR_SOCKET)\b/,
650
+ /\bterminated\b/i,
651
+ /connection (error|closed|reset|refused)/i,
652
+ /socket hang up/i,
653
+ /\bfetch failed\b/i,
654
+ /\b(timeout|timed out)\b/i,
655
+ /\boverloaded\b/i,
656
+ /rate[ _-]?limit/i,
657
+ /too many requests/i,
658
+ /temporarily unavailable/i,
659
+ /service unavailable/i,
660
+ /\bstream (ended|closed) (before|prematurely)/i,
661
+ /pi-ai 流在 done \/ error 之前就结束了/
662
+ ];
663
+ var CONNECTION_ERROR_NAMES = /* @__PURE__ */ new Set([
664
+ "APIConnectionError",
665
+ "APIConnectionTimeoutError"
666
+ ]);
667
+ function isDefinitelyPermanent(err) {
668
+ if (err instanceof LoweringError) return true;
669
+ const name = err?.name;
670
+ return name === "AbortError" || name === "APIUserAbortError";
671
+ }
672
+ function statusFromMessage(message) {
673
+ const m = /^\s*(\d{3})\b/.exec(message) ?? /\b(?:status(?:\s+code)?|HTTP)[\s:=]+(\d{3})\b/i.exec(message);
674
+ if (!m?.[1]) return void 0;
675
+ const status = Number(m[1]);
676
+ return status >= 100 && status <= 599 ? status : void 0;
677
+ }
678
+ function structuredOf(error) {
679
+ const layers = [];
680
+ let cur = error;
681
+ for (let depth = 0; cur && typeof cur === "object" && depth < 4; depth++) {
682
+ layers.push(cur);
683
+ cur = cur.cause;
684
+ }
685
+ const out = { texts: [] };
686
+ for (const l of layers) {
687
+ if (out.status === void 0 && typeof l.status === "number") out.status = l.status;
688
+ if (out.code === void 0 && typeof l.code === "string") out.code = l.code;
689
+ if (out.name === void 0 && typeof l.name === "string") out.name = l.name;
690
+ if (out.shouldRetry === void 0 && l.headers instanceof Headers) {
691
+ const h = l.headers.get("x-should-retry");
692
+ if (h === "true") out.shouldRetry = true;
693
+ else if (h === "false") out.shouldRetry = false;
694
+ }
695
+ if (typeof l.message === "string") out.texts.push(l.message);
696
+ }
697
+ return out;
698
+ }
699
+ function isTransientFailure(failure) {
700
+ if (failure.kind === "outcome") {
701
+ const status2 = statusFromMessage(failure.message);
702
+ if (status2 !== void 0) return TRANSIENT_STATUS(status2);
703
+ return TRANSIENT_PATTERNS.some((re) => re.test(failure.message));
704
+ }
705
+ if (isDefinitelyPermanent(failure.error)) return false;
706
+ const info = structuredOf(failure.error);
707
+ if (info.name !== void 0 && CONNECTION_ERROR_NAMES.has(info.name)) return true;
708
+ if (info.shouldRetry !== void 0) return info.shouldRetry;
709
+ const status = info.status ?? info.texts.map(statusFromMessage).find((s) => s !== void 0);
710
+ if (status !== void 0) return TRANSIENT_STATUS(status);
711
+ if (info.code !== void 0 && TRANSIENT_CODES.has(info.code)) return true;
712
+ return TRANSIENT_PATTERNS.some((re) => info.texts.some((t) => re.test(t)));
713
+ }
714
+ function backoffDelayMs(attempt, opts = {}) {
715
+ const base = opts.baseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;
716
+ const max = opts.maxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;
717
+ return Math.min(max, base * 2 ** Math.max(0, attempt - 1));
718
+ }
719
+ function defaultSleep(ms, signal) {
720
+ return new Promise((resolve2) => {
721
+ if (signal?.aborted) return resolve2();
722
+ const timer = setTimeout(done, ms);
723
+ function done() {
724
+ signal?.removeEventListener("abort", done);
725
+ clearTimeout(timer);
726
+ resolve2();
727
+ }
728
+ signal?.addEventListener("abort", done, { once: true });
729
+ });
730
+ }
731
+ function resolveRetry(opts = {}) {
732
+ const maxAttempts = opts.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;
733
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
734
+ throw new RangeError(`retry.maxAttempts must be an integer >= 1, got ${String(maxAttempts)}`);
735
+ }
736
+ return {
737
+ maxAttempts,
738
+ delayFor: (attempt) => backoffDelayMs(attempt, opts),
739
+ isTransient: opts.isTransient ?? isTransientFailure,
740
+ sleep: opts.sleep ?? defaultSleep
741
+ };
742
+ }
743
+
744
+ // src/lowering/types.ts
745
+ function lossesOf(req) {
746
+ return req.landings.filter((l) => l.kind !== "exact");
747
+ }
748
+
627
749
  // src/store/read-timeline.ts
628
750
  async function* readEvents(log, sessionId, opts) {
629
751
  const { registry, ...range } = opts;
@@ -847,15 +969,25 @@ function toolSpecOf(tool) {
847
969
  function deferredToolSpecOf(tool, deferred) {
848
970
  return deferred ? { ...toolSpecOf(tool), deferLoading: true } : toolSpecOf(tool);
849
971
  }
972
+ function isDuration(x) {
973
+ return x === void 0 || typeof x === "number" && Number.isFinite(x) && x > 0;
974
+ }
850
975
  function isContentPart(x) {
851
976
  if (typeof x !== "object" || x === null) return false;
852
977
  const p = x;
853
- if (p.type === "text") return typeof p.text === "string";
854
- if (p.type === "image") return typeof p.mime === "string" && typeof p.data === "string";
855
- if (p.type === "tool_reference") {
856
- return typeof p.name === "string" && typeof p.description === "string" && typeof p.inputSchema === "object" && p.inputSchema !== null && !Array.isArray(p.inputSchema);
978
+ switch (p.type) {
979
+ case "text":
980
+ return typeof p.text === "string";
981
+ case "image":
982
+ return typeof p.mime === "string" && typeof p.data === "string";
983
+ case "video":
984
+ case "audio":
985
+ return typeof p.mime === "string" && p.mime.startsWith(`${p.type}/`) && typeof p.data === "string" && isDuration(p.durationSec);
986
+ case "tool_reference":
987
+ return typeof p.name === "string" && typeof p.description === "string" && typeof p.inputSchema === "object" && p.inputSchema !== null && !Array.isArray(p.inputSchema);
988
+ default:
989
+ return false;
857
990
  }
858
- return false;
859
991
  }
860
992
  function isToolResult(x) {
861
993
  if (typeof x !== "object" || x === null) return false;
@@ -924,7 +1056,7 @@ var INPUT_DRAFT_TYPES = /* @__PURE__ */ new Set([
924
1056
  "core.system_note"
925
1057
  ]);
926
1058
  var INPUT_ACTORS = /* @__PURE__ */ new Set(["user", "model", "tool", "system", "host"]);
927
- var CONTENT_PART_TYPES = /* @__PURE__ */ new Set(["text", "image", "tool_reference"]);
1059
+ var CONTENT_PART_TYPES = /* @__PURE__ */ new Set(["text", "image", "video", "audio", "tool_reference"]);
928
1060
  function classifyInputItem(item) {
929
1061
  if (typeof item !== "object" || item === null) return void 0;
930
1062
  const { type, actor } = item;
@@ -935,16 +1067,7 @@ function classifyInputItem(item) {
935
1067
  }
936
1068
  var NOTE_KINDS = /* @__PURE__ */ new Set(["perception", "pin", "budget", "host"]);
937
1069
  function isContentPartList(x) {
938
- if (!Array.isArray(x)) return false;
939
- return x.every((p) => {
940
- if (typeof p !== "object" || p === null) return false;
941
- const part = p;
942
- if (part.type === "text") return typeof part.text === "string";
943
- if (part.type === "image") return typeof part.mime === "string" && typeof part.data === "string";
944
- if (part.type === "tool_reference")
945
- return typeof part.name === "string" && typeof part.description === "string" && typeof part.inputSchema === "object" && part.inputSchema !== null;
946
- return false;
947
- });
1070
+ return Array.isArray(x) && x.every(isContentPart);
948
1071
  }
949
1072
  function corePayloadProblem(draft) {
950
1073
  const p = typeof draft.payload === "object" && draft.payload !== null ? draft.payload : {};
@@ -1137,6 +1260,7 @@ async function* runLoop(cfg) {
1137
1260
  yield* projected.emitted;
1138
1261
  }
1139
1262
  const emitted = [];
1263
+ const batch = { calls: [], results: [], held: [], resumed: false };
1140
1264
  const ctx = {
1141
1265
  session: { id: sessionId, turn: turns + 1 },
1142
1266
  ...cfg.principal ? { principal: cfg.principal } : {},
@@ -1159,6 +1283,7 @@ async function* runLoop(cfg) {
1159
1283
  ...lastUsage ? { lastUsage } : {}
1160
1284
  },
1161
1285
  ...cfg.signal ? { signal: cfg.signal } : {},
1286
+ batch,
1162
1287
  emit: (d) => emitted.push(d)
1163
1288
  };
1164
1289
  const flush = async () => {
@@ -1174,13 +1299,18 @@ async function* runLoop(cfg) {
1174
1299
  }
1175
1300
  const pending = pendingToolCalls(timeline);
1176
1301
  if (pending.length > 0) {
1302
+ const located = toolBatchOf(timeline, pending);
1303
+ batch.calls.push(...located.calls);
1304
+ batch.results.push(...located.results);
1305
+ batch.resumed = true;
1177
1306
  const settled = yield* executeToolCalls(ctx, pending, timeline, {
1178
1307
  cfg,
1179
1308
  sockets,
1180
1309
  append,
1181
1310
  flush,
1182
1311
  forwardedDecisions,
1183
- spend: spendInto(ctx)
1312
+ spend: spendInto(ctx),
1313
+ batch
1184
1314
  });
1185
1315
  toolCallsTotal += settled.executed;
1186
1316
  if (settled.interruptions.length > 0) {
@@ -1310,6 +1440,7 @@ async function* runLoop(cfg) {
1310
1440
  }
1311
1441
  if (!outcome)
1312
1442
  throw new Error("runLoop internal error: the model call produced neither an outcome nor a failure");
1443
+ for (const e of modelEvents) if (e.type === "core.tool_call") batch.calls.push(e);
1313
1444
  for (const s of sockets) await s.afterModel?.(ctx, modelEvents);
1314
1445
  yield* await flush();
1315
1446
  if (outcome.stopReason === "aborted") {
@@ -1328,7 +1459,8 @@ async function* runLoop(cfg) {
1328
1459
  append,
1329
1460
  flush,
1330
1461
  forwardedDecisions,
1331
- spend: spendInto(ctx)
1462
+ spend: spendInto(ctx),
1463
+ batch
1332
1464
  });
1333
1465
  toolCallsTotal += settled.executed;
1334
1466
  ctx.budget.toolCalls = toolCallsTotal;
@@ -1433,7 +1565,12 @@ function withResultTrust(input, tools) {
1433
1565
  return { ...input, ...withTrust(toolResultTrust(tool, payload?.isError === true)) };
1434
1566
  }
1435
1567
  async function* executeToolCalls(ctx, calls, timeline, deps) {
1436
- const { cfg, sockets, append, flush, forwardedDecisions, spend } = deps;
1568
+ const { cfg, sockets, flush, forwardedDecisions, spend, batch } = deps;
1569
+ const append = async (drafts) => {
1570
+ const events = await deps.append(drafts);
1571
+ for (const e of events) if (e.type === "core.tool_result") batch.results.push(e);
1572
+ return events;
1573
+ };
1437
1574
  const decisions = /* @__PURE__ */ new Map();
1438
1575
  const requested = /* @__PURE__ */ new Set();
1439
1576
  for (const raw of timeline) {
@@ -1520,10 +1657,12 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1520
1657
  });
1521
1658
  }
1522
1659
  summary.interruptions.push({ kind: "approval", toolCallId, request, call: call.payload });
1660
+ batch.held.push(toolCallId);
1523
1661
  continue;
1524
1662
  }
1525
1663
  if (!tool.execute || tool.side === "client") {
1526
1664
  summary.interruptions.push({ kind: "client_tool", toolCallId, call: call.payload });
1665
+ batch.held.push(toolCallId);
1527
1666
  continue;
1528
1667
  }
1529
1668
  let result;
@@ -1532,6 +1671,7 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1532
1671
  const out = await tool.execute(args, toolCtx);
1533
1672
  if (isSubagentPause(out)) {
1534
1673
  summary.interruptions.push({ kind: "subagent", toolCallId, call: call.payload, ...out.detail });
1674
+ batch.held.push(toolCallId);
1535
1675
  if (cfg.signal?.aborted) break;
1536
1676
  continue;
1537
1677
  }
@@ -1683,57 +1823,6 @@ function needsUntrustedMark(e) {
1683
1823
  return e.trust === "untrusted";
1684
1824
  }
1685
1825
 
1686
- // src/replay/replay.ts
1687
- var MODEL_OUTPUT_TYPES = /* @__PURE__ */ new Set([
1688
- "core.model_thinking",
1689
- "core.model_text",
1690
- "core.tool_call"
1691
- ]);
1692
- function isModelOutput(e) {
1693
- return MODEL_OUTPUT_TYPES.has(e.type);
1694
- }
1695
- function replayTurns(timeline, opts) {
1696
- const sessionId = timeline[0]?.sessionId;
1697
- const turns = [];
1698
- const preamble = [];
1699
- let i = 0;
1700
- while (i < timeline.length && !isModelOutput(timeline[i])) preamble.push(timeline[i++]);
1701
- while (i < timeline.length) {
1702
- const first = timeline[i];
1703
- const requestAtSeq = first.seq - 1;
1704
- const output = [];
1705
- while (i < timeline.length && isModelOutput(timeline[i])) output.push(timeline[i++]);
1706
- const aftermath = [];
1707
- while (i < timeline.length && !isModelOutput(timeline[i])) aftermath.push(timeline[i++]);
1708
- const prefix = timeline.slice(0, requestAtSeq);
1709
- const projected = project({
1710
- timeline: prefix,
1711
- budget: opts.budget,
1712
- // 回放不该产生新 id,也不依赖当前时间;给确定值让输出可比对
1713
- now: first.at,
1714
- newId: (at) => `replay-${at}-${requestAtSeq}`,
1715
- ...sessionId !== void 0 ? { sessionId } : {},
1716
- ...opts.strategies ? { strategies: opts.strategies } : {},
1717
- ...opts.estimate ? { estimate: opts.estimate } : {},
1718
- ...opts.registry ? { registry: opts.registry } : {}
1719
- });
1720
- const usage = aftermath.find(
1721
- (e) => e.type === "core.budget_usage"
1722
- )?.payload;
1723
- turns.push({
1724
- index: turns.length + 1,
1725
- requestAtSeq,
1726
- visible: projected.events,
1727
- stats: projected.stats,
1728
- diverged: projected.emitted.length > 0,
1729
- output,
1730
- aftermath,
1731
- ...usage ? { usage } : {}
1732
- });
1733
- }
1734
- return { turns, preamble };
1735
- }
1736
-
1737
1826
  // src/store/errors.ts
1738
1827
  var StoreError = class extends Error {
1739
1828
  constructor(code, message, context = {}) {
@@ -1881,7 +1970,7 @@ function memoryStore() {
1881
1970
  }
1882
1971
 
1883
1972
  // src/index.ts
1884
- var REINS_VERSION = "0.7.0";
1973
+ var REINS_VERSION = "0.9.0";
1885
1974
  export {
1886
1975
  BUILTIN_APPROVAL_POLICY,
1887
1976
  CORE_SCHEMAS,
@@ -1967,6 +2056,7 @@ export {
1967
2056
  statusFromMessage,
1968
2057
  subagentPause,
1969
2058
  supersededIds,
2059
+ toolBatchOf,
1970
2060
  toolCallArgumentsMeta,
1971
2061
  toolResultTrust,
1972
2062
  toolSpecOf,