@reinsjs/core 0.17.0 → 0.18.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
@@ -38,13 +38,18 @@ var DEFAULT_MODEL_INVISIBLE_TYPES = /* @__PURE__ */ new Set([
38
38
  "core.tool_started",
39
39
  "core.run_ended"
40
40
  ]);
41
+ function isModelInvisibleByDefault(type) {
42
+ return DEFAULT_MODEL_INVISIBLE_TYPES.has(type) || type.startsWith("ext.");
43
+ }
41
44
  function visibilityFilter(opts = {}) {
42
- const invisible = opts.invisibleTypes ? new Set(opts.invisibleTypes) : DEFAULT_MODEL_INVISIBLE_TYPES;
43
45
  const extra = opts.isVisible;
46
+ const keepExt = opts.keepExtEvents === true;
47
+ const custom = opts.invisibleTypes ? new Set(opts.invisibleTypes) : void 0;
48
+ const hidden = !custom && !keepExt ? isModelInvisibleByDefault : (type) => (custom ?? DEFAULT_MODEL_INVISIBLE_TYPES).has(type) || !keepExt && type.startsWith("ext.");
44
49
  return {
45
50
  name: "visibility-filter",
46
51
  apply(events) {
47
- return { events: events.filter((e) => !invisible.has(e.type) && (extra ? extra(e) : true)) };
52
+ return { events: events.filter((e) => !hidden(e.type) && (extra ? extra(e) : true)) };
48
53
  }
49
54
  };
50
55
  }
@@ -287,19 +292,25 @@ function fmtChars(n) {
287
292
  }
288
293
  function renderFoldedToolResults(items, opts) {
289
294
  if (items.length === 0) return "";
290
- const maxItems = opts.maxItems ?? 80;
291
- const lines = [opts.heading];
292
- const shown = items.slice(0, maxItems);
295
+ const { shown, omittedLine } = keepLatest(items, opts.maxItems);
296
+ const lines = omittedLine ? [opts.heading, omittedLine] : [opts.heading];
293
297
  for (const it of shown) {
294
- const tail = it.spilledBlobId ? `stored as blob "${it.spilledBlobId}", read with fetch_blob` : `${fmtChars(it.chars)}${it.isError ? ", error" : ""}`;
298
+ const tail = it.spilledBlobId ? (
299
+ // 与 brain recall 的说法一致:core 不知道本 run 有没有 fetch_blob(spill({ tool: false })、后来去掉了 spill),只附条件(第二波返修)
300
+ `stored as blob "${it.spilledBlobId}"; read it with fetch_blob if that tool is in your tool list`
301
+ ) : `${fmtChars(it.chars)}${it.isError ? ", error" : ""}`;
295
302
  lines.push(`- seq ${it.seq} ${it.name}(${digestArgs(it.args, opts.maxArgsChars)}) \u2014 ${tail}`);
296
303
  }
297
- if (items.length > shown.length) {
298
- const rest = items.slice(shown.length);
299
- lines.push(`- \u2026and ${rest.length} more (seq ${rest[0]?.seq}\u2013${rest[rest.length - 1]?.seq})`);
300
- }
301
304
  return lines.join("\n");
302
305
  }
306
+ function keepLatest(items, maxItems = 80) {
307
+ if (items.length <= maxItems) return { shown: items };
308
+ const cut = items.length - maxItems;
309
+ const first = items[0]?.seq;
310
+ const last = items[cut - 1]?.seq;
311
+ const range = first === last ? `seq ${first}` : `seq ${first}\u2013${last}`;
312
+ return { shown: items.slice(cut), omittedLine: `- \u2026${cut} earlier (${range})` };
313
+ }
303
314
  function foldedUserMedia(removed) {
304
315
  const out = [];
305
316
  for (const e of removed) {
@@ -327,19 +338,14 @@ function foldedUserMedia(removed) {
327
338
  }
328
339
  function renderFoldedUserMedia(items, opts) {
329
340
  if (items.length === 0) return "";
330
- const maxItems = opts.maxItems ?? 80;
331
- const lines = [opts.heading];
332
- const shown = items.slice(0, maxItems);
341
+ const { shown, omittedLine } = keepLatest(items, opts.maxItems);
342
+ const lines = omittedLine ? [opts.heading, omittedLine] : [opts.heading];
333
343
  for (const it of shown) {
334
344
  const byType = /* @__PURE__ */ new Map();
335
345
  for (const m of it.media) byType.set(m.type, [...byType.get(m.type) ?? [], m.mime]);
336
346
  const desc = [...byType.entries()].map(([type, mimes]) => `${mimes.length} ${type}${mimes.length > 1 ? "s" : ""} (${mimes.join(", ")})`).join(", ");
337
347
  lines.push(`- seq ${it.seq} user message \u2014 ${desc}`);
338
348
  }
339
- if (items.length > shown.length) {
340
- const rest = items.slice(shown.length);
341
- lines.push(`- \u2026and ${rest.length} more (seq ${rest[0]?.seq}\u2013${rest[rest.length - 1]?.seq})`);
342
- }
343
349
  return lines.join("\n");
344
350
  }
345
351
 
@@ -396,7 +402,9 @@ var defaultThresholdSummary = (removed, ctx) => {
396
402
  for (const e of fresh) counts.set(e.type, (counts.get(e.type) ?? 0) + 1);
397
403
  const countText = [...counts.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([type, n]) => `${n} ${type.replace(/^core\./, "")}`).join(", ");
398
404
  const lines = [
399
- `[Context truncated by budget] Events seq ${from}-${to} were removed to fit the context window. They remain in the session log and can be recovered by the host if needed.`
405
+ // 只陈述事实:core 不知道模型手里有没有取回工具(compact 的 recall),怎么取回由装了它的模块在规则里说;
406
+ // 原先写"由宿主取回"会与 compact 规则"recall 可取回"相左(全库审查 2026-11-25 #66)
407
+ `[Context truncated by budget] Events seq ${from}-${to} were removed to fit the context window. They remain in the session log.`
400
408
  ];
401
409
  if (countText) lines.push(`Removed: ${countText}.`);
402
410
  if (prior.length > 0) {
@@ -510,6 +518,19 @@ function defaultProjectionChain(opts = {}) {
510
518
  budgetTruncate({ autoKeepPinNotes: opts.fold?.autoKeepPinNotes ?? true, ...opts.truncate })
511
519
  ];
512
520
  }
521
+ function resolveReserveTokens(budget) {
522
+ const { contextLimit } = budget;
523
+ if (typeof contextLimit !== "number" || !Number.isFinite(contextLimit) || contextLimit <= 0) {
524
+ throw new RangeError(`budget.contextLimit must be a positive finite number, got ${String(contextLimit)}`);
525
+ }
526
+ const reserveTokens = budget.reserveTokens ?? Math.floor(contextLimit * DEFAULT_RESERVE_RATIO);
527
+ if (typeof reserveTokens !== "number" || !Number.isFinite(reserveTokens) || reserveTokens < 0 || reserveTokens >= contextLimit) {
528
+ throw new RangeError(
529
+ `budget.reserveTokens must be a non-negative finite number below contextLimit (${contextLimit}), got ${String(reserveTokens)}`
530
+ );
531
+ }
532
+ return reserveTokens;
533
+ }
513
534
  var defaultRegistry;
514
535
  function coreRegistry() {
515
536
  if (!defaultRegistry) defaultRegistry = createCoreRegistry();
@@ -529,7 +550,7 @@ function project(opts) {
529
550
  const last = timeline[timeline.length - 1];
530
551
  const sessionId = opts.sessionId ?? last?.sessionId;
531
552
  if (sessionId === void 0) throw new RangeError("an empty timeline requires an explicit sessionId");
532
- const reserveTokens = opts.budget.reserveTokens ?? Math.floor(opts.budget.contextLimit * DEFAULT_RESERVE_RATIO);
553
+ const reserveTokens = resolveReserveTokens(opts.budget);
533
554
  const overheadTokens = opts.budget.overheadTokens ?? contextOverheadOf(timeline);
534
555
  if (!Number.isFinite(overheadTokens) || overheadTokens < 0) {
535
556
  throw new RangeError(`budget.overheadTokens must be a non-negative finite number, got ${overheadTokens}`);
@@ -630,7 +651,7 @@ function replayTurns(timeline, opts) {
630
651
 
631
652
  // src/loop/batch.ts
632
653
  function inBatchSpan(e) {
633
- return isModelOutput(e) || DEFAULT_MODEL_INVISIBLE_TYPES.has(e.type);
654
+ return isModelOutput(e) || isModelInvisibleByDefault(e.type);
634
655
  }
635
656
  function toolBatchOf(timeline, pending) {
636
657
  const anchor = pending[0];
@@ -662,6 +683,48 @@ async function forkSession(log, opts) {
662
683
  return { toSessionId };
663
684
  }
664
685
 
686
+ // src/loop/handoff.ts
687
+ var HANDOFF_PROVENANCE_SOURCE = "handoff";
688
+ function userTextOf(e) {
689
+ return e.payload.content.map((p) => p.type === "text" ? p.text : "").join("").trim();
690
+ }
691
+ function handoffOpeningDrafts(intent, handoffEvent, timeline) {
692
+ const by = intent.by ?? "model";
693
+ const fromHandoff = { source: HANDOFF_PROVENANCE_SOURCE, ref: handoffEvent.id };
694
+ const opening = [
695
+ {
696
+ type: "core.system_note",
697
+ actor: by,
698
+ payload: { kind: "host", text: intent.summary },
699
+ provenance: fromHandoff
700
+ },
701
+ ...intent.opening ?? []
702
+ ];
703
+ if (intent.triggerMessage === void 0) return opening;
704
+ const wanted = intent.triggerMessage.trim();
705
+ let source;
706
+ for (let i = timeline.length - 1; i >= 0; i--) {
707
+ const e = timeline[i];
708
+ if (e.type !== "core.user_message") continue;
709
+ const u = e;
710
+ if (userTextOf(u) === wanted) {
711
+ source = u;
712
+ break;
713
+ }
714
+ }
715
+ const content = [{ type: "text", text: intent.triggerMessage }];
716
+ opening.push(
717
+ source ? {
718
+ type: "core.user_message",
719
+ actor: source.actor,
720
+ trust: source.trust,
721
+ payload: { content },
722
+ provenance: { source: HANDOFF_PROVENANCE_SOURCE, ref: source.id }
723
+ } : { type: "core.user_message", actor: by, payload: { content }, provenance: fromHandoff }
724
+ );
725
+ return opening;
726
+ }
727
+
665
728
  // src/store/errors.ts
666
729
  var StoreError = class extends Error {
667
730
  constructor(code, message, context = {}) {
@@ -896,6 +959,8 @@ var LoweringError = class extends Error {
896
959
  var STOPPED_NOTE = "stopped by the user";
897
960
  var STOPPED_NOT_EXECUTED_TEXT = "Not executed: the run was stopped by the user before this call started.";
898
961
  var STOPPED_IN_PROGRESS_TEXT = "Interrupted: the run was stopped by the user while this call was in progress; it may have partly taken effect.";
962
+ var MODEL_FAILED_NOT_EXECUTED_TEXT = "Not executed: the model response failed before it was complete, so this call was dropped.";
963
+ var MODEL_INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: the model response was interrupted before it was complete, so this call was dropped.";
899
964
  var INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: an earlier run was interrupted before this call started.";
900
965
  var INTERRUPTED_IN_PROGRESS_TEXT = "Interrupted: an earlier run was interrupted while this call was in progress; it may have partly taken effect.";
901
966
  var OUTCOME_UNKNOWN_TEXT = "Execution was interrupted before a result was recorded; the outcome is unknown. Check the current state before retrying.";
@@ -1098,6 +1163,15 @@ function deferredToolSpecOf(tool, deferred) {
1098
1163
  function isDuration(x) {
1099
1164
  return x === void 0 || typeof x === "number" && Number.isFinite(x) && x > 0;
1100
1165
  }
1166
+ var SUPPORTED_IMAGE_MIMES = /* @__PURE__ */ new Set([
1167
+ "image/jpeg",
1168
+ "image/png",
1169
+ "image/gif",
1170
+ "image/webp"
1171
+ ]);
1172
+ function isSupportedImageMime(mime) {
1173
+ return typeof mime === "string" && SUPPORTED_IMAGE_MIMES.has(mime);
1174
+ }
1101
1175
  function isContentPart(x) {
1102
1176
  if (typeof x !== "object" || x === null) return false;
1103
1177
  const p = x;
@@ -1105,8 +1179,9 @@ function isContentPart(x) {
1105
1179
  case "text":
1106
1180
  return typeof p.text === "string";
1107
1181
  case "image":
1182
+ if (!isSupportedImageMime(p.mime)) return false;
1108
1183
  if (p.blobId !== void 0) return isImageRef(p);
1109
- return typeof p.mime === "string" && typeof p.data === "string";
1184
+ return typeof p.data === "string";
1110
1185
  case "video":
1111
1186
  case "audio":
1112
1187
  return typeof p.mime === "string" && p.mime.startsWith(`${p.type}/`) && typeof p.data === "string" && isDuration(p.durationSec);
@@ -1116,16 +1191,40 @@ function isContentPart(x) {
1116
1191
  return false;
1117
1192
  }
1118
1193
  }
1119
- function isToolResult(x) {
1194
+ function unsupportedImageText(mime) {
1195
+ return `[image omitted: ${mime} is not a supported image type; supported types are ${[...SUPPORTED_IMAGE_MIMES].join(", ")}]`;
1196
+ }
1197
+ function isUnsupportedImagePart(x) {
1120
1198
  if (typeof x !== "object" || x === null) return false;
1121
- const r = x;
1122
- return Array.isArray(r.content) && r.content.every(isContentPart) && (r.isError === void 0 || typeof r.isError === "boolean");
1199
+ const p = x;
1200
+ return p.type === "image" && typeof p.mime === "string" && !isSupportedImageMime(p.mime) && typeof p.data === "string" !== (typeof p.blobId === "string");
1201
+ }
1202
+ function withUnsupportedImagesReplaced(parts) {
1203
+ let replaced = false;
1204
+ const out = [];
1205
+ for (const p of parts) {
1206
+ if (isContentPart(p)) out.push(p);
1207
+ else if (isUnsupportedImagePart(p)) {
1208
+ replaced = true;
1209
+ out.push({ type: "text", text: unsupportedImageText(p.mime) });
1210
+ } else return void 0;
1211
+ }
1212
+ return replaced ? out : parts;
1123
1213
  }
1124
1214
  function normalizeToolOutput(output) {
1125
1215
  if (typeof output === "string") return { content: [{ type: "text", text: output }] };
1126
1216
  if (output === void 0 || output === null) return { content: [{ type: "text", text: "" }] };
1127
- if (Array.isArray(output) && output.every(isContentPart)) return { content: output };
1128
- if (isToolResult(output)) return output;
1217
+ if (Array.isArray(output)) {
1218
+ const content = withUnsupportedImagesReplaced(output);
1219
+ if (content) return { content };
1220
+ } else if (typeof output === "object") {
1221
+ const r = output;
1222
+ if (Array.isArray(r.content) && (r.isError === void 0 || typeof r.isError === "boolean")) {
1223
+ const content = withUnsupportedImagesReplaced(r.content);
1224
+ if (content)
1225
+ return content === r.content ? output : { ...output, content };
1226
+ }
1227
+ }
1129
1228
  const json = JSON.stringify(output);
1130
1229
  return { content: [{ type: "text", text: typeof json === "string" ? json : String(output) }] };
1131
1230
  }
@@ -1434,6 +1533,28 @@ async function validateResume(input) {
1434
1533
  }
1435
1534
  return pending;
1436
1535
  }
1536
+ function assertDecisionsAwaitApproval(input) {
1537
+ const pending = pendingToolCalls(input.timeline);
1538
+ const pendingIds = new Set(pending.map((c) => c.payload.toolCallId));
1539
+ const awaiting = new Set(
1540
+ awaitingOf({ timeline: input.timeline, pending, tools: [], interruptions: [] }).filter((a) => a.kind === "approval").map((a) => a.toolCallId)
1541
+ );
1542
+ const seen = /* @__PURE__ */ new Set();
1543
+ for (const d of input.decisions) {
1544
+ if (d.sessionId !== void 0 && d.sessionId !== input.sessionId) continue;
1545
+ const problem = !pendingIds.has(d.toolCallId) ? "which is not pending" : !awaiting.has(d.toolCallId) ? "which is not waiting for approval" : seen.has(d.toolCallId) ? "more than once in the same request" : void 0;
1546
+ if (problem !== void 0) {
1547
+ throw new RunStateError(
1548
+ "unknown_tool_call",
1549
+ `approval decision refers to call ${d.toolCallId}, ${problem}`,
1550
+ {
1551
+ toolCallId: d.toolCallId
1552
+ }
1553
+ );
1554
+ }
1555
+ seen.add(d.toolCallId);
1556
+ }
1557
+ }
1437
1558
 
1438
1559
  // src/loop/static.ts
1439
1560
  async function resolve(contribution, setup) {
@@ -1715,6 +1836,34 @@ function describe(value) {
1715
1836
  function isInputArray(input) {
1716
1837
  return Array.isArray(input);
1717
1838
  }
1839
+ function checkInputToolResults(input, timeline) {
1840
+ const results = input.filter((d) => d.type === "core.tool_result");
1841
+ if (results.length === 0) return;
1842
+ const pendingCalls = pendingToolCalls(timeline);
1843
+ const pending = new Map(pendingCalls.map((c) => [c.payload.toolCallId, c.payload.name]));
1844
+ const awaitingApproval = new Set(
1845
+ awaitingOf({ timeline, pending: pendingCalls, tools: [], interruptions: [] }).filter((a) => a.kind === "approval").map((a) => a.toolCallId)
1846
+ );
1847
+ const seen = /* @__PURE__ */ new Set();
1848
+ for (const d of results) {
1849
+ const { toolCallId, name } = d.payload;
1850
+ const expected = pending.get(toolCallId);
1851
+ if (expected === void 0 || seen.has(toolCallId)) {
1852
+ throw new RangeError(
1853
+ `input draft core.tool_result: call ${toolCallId} is not pending (already answered, unknown, or answered twice in this input)`
1854
+ );
1855
+ }
1856
+ if (name !== expected) {
1857
+ throw new RangeError(`input draft core.tool_result: name must be ${expected}, got ${name}`);
1858
+ }
1859
+ if (awaitingApproval.has(toolCallId)) {
1860
+ throw new RangeError(
1861
+ `input draft core.tool_result: call ${toolCallId} is waiting for approval; pass the decision in decisions first`
1862
+ );
1863
+ }
1864
+ seen.add(toolCallId);
1865
+ }
1866
+ }
1718
1867
  function draftParts(draft) {
1719
1868
  if (draft.type !== "core.user_message" && draft.type !== "core.tool_result") return [];
1720
1869
  return draft.payload.content;
@@ -1733,6 +1882,10 @@ async function* runLoop(cfg) {
1733
1882
  if (!registry.has(d.type)) throw new RangeError(`input draft type ${d.type} is not registered`);
1734
1883
  }
1735
1884
  const capabilities = lowering.capabilities(model);
1885
+ resolveReserveTokens({
1886
+ contextLimit: capabilities.contextWindow,
1887
+ ...cfg.projection?.reserveTokens !== void 0 ? { reserveTokens: cfg.projection.reserveTokens } : {}
1888
+ });
1736
1889
  const configHash = await computeConfigHash({
1737
1890
  model,
1738
1891
  tools: baseTools,
@@ -1741,6 +1894,7 @@ async function* runLoop(cfg) {
1741
1894
  const startedAt = now();
1742
1895
  const startTimeline = await readTimeline(log, sessionId, { registry });
1743
1896
  let lastSeq = startTimeline.at(-1)?.seq ?? 0;
1897
+ checkInputToolResults(input, startTimeline);
1744
1898
  const imageCache = /* @__PURE__ */ new Map();
1745
1899
  const startProblem = await checkImageRefs(input.flatMap(draftParts), {
1746
1900
  sessionId,
@@ -1825,12 +1979,13 @@ async function* runLoop(cfg) {
1825
1979
  tokensSpent += usage.input + usage.output;
1826
1980
  ctx.budget.tokensSpent = tokensSpent;
1827
1981
  };
1828
- const fail = async (payload) => {
1982
+ const fail = async (payload, settle = []) => {
1829
1983
  const events = await append([
1984
+ ...settle,
1830
1985
  { type: "core.error", actor: "system", payload },
1831
1986
  { type: "core.run_ended", actor: "system", payload: { status: "error", category: payload.category } }
1832
1987
  ]);
1833
- const error = events[0];
1988
+ const error = events[settle.length];
1834
1989
  return { events, result: { status: "error", sessionId, lastSeq, error } };
1835
1990
  };
1836
1991
  const ownDecisions = (cfg.decisions ?? []).filter(
@@ -1854,19 +2009,7 @@ async function* runLoop(cfg) {
1854
2009
  ...cfg.allowConfigDrift !== void 0 ? { allowConfigDrift: cfg.allowConfigDrift } : {}
1855
2010
  });
1856
2011
  }
1857
- const decisions = ownDecisions;
1858
- const pendingIds = new Set(pendingToolCalls(timeline).map((c) => c.payload.toolCallId));
1859
- for (const d of decisions) {
1860
- if (!pendingIds.has(d.toolCallId)) {
1861
- throw new RunStateError(
1862
- "unknown_tool_call",
1863
- `approval decision refers to call ${d.toolCallId}, which is not pending`,
1864
- {
1865
- toolCallId: d.toolCallId
1866
- }
1867
- );
1868
- }
1869
- }
2012
+ assertDecisionsAwaitApproval({ sessionId, timeline, decisions: ownDecisions });
1870
2013
  }
1871
2014
  if (!cfg.signal?.aborted) {
1872
2015
  yield* await append(
@@ -2044,9 +2187,9 @@ async function* runLoop(cfg) {
2044
2187
  imageCache
2045
2188
  });
2046
2189
  toolCallsTotal += settled.executed;
2047
- if (settled.interruptions.length > 0 || isStopped(cfg.signal)) {
2048
- const reason = pauseReasonOf(settled.interruptions);
2049
- const { events, result } = await pause(reason, settled.interruptions);
2190
+ if (settled.interruptions.length > 0 || isStopped(cfg.signal) || abortedMidBatch(cfg.signal, batch)) {
2191
+ const interruptions2 = withBatchAbortNote(settled.interruptions, abortedMidBatch(cfg.signal, batch));
2192
+ const { events, result } = await pause(pauseReasonOf(interruptions2), interruptions2);
2050
2193
  yield* events;
2051
2194
  return result;
2052
2195
  }
@@ -2079,12 +2222,14 @@ async function* runLoop(cfg) {
2079
2222
  }
2080
2223
  const injected = await flush();
2081
2224
  yield* injected;
2082
- visible = [...visible, ...injected.filter((e) => !DEFAULT_MODEL_INVISIBLE_TYPES.has(e.type))];
2225
+ visible = [...visible, ...injected.filter((e) => !isModelInvisibleByDefault(e.type))];
2083
2226
  ctx.events = visible;
2084
2227
  ctx.tools = tools;
2228
+ const sentEstimate = estimateTotal(visible, cfg.projection?.estimate ?? roughTokenEstimate);
2085
2229
  let outcome;
2086
2230
  const modelEvents = [];
2087
2231
  let hydrated;
2232
+ const usedCallIds = toolCallIdsOf(timeline);
2088
2233
  for (let attempt = 1; ; attempt++) {
2089
2234
  let failure;
2090
2235
  let attemptOutput = 0;
@@ -2108,7 +2253,7 @@ async function* runLoop(cfg) {
2108
2253
  outcome = step.value;
2109
2254
  break;
2110
2255
  }
2111
- const appended = await append([step.value]);
2256
+ const appended = await append([withUniqueToolCallId(step.value, usedCallIds, () => newId(now()))]);
2112
2257
  modelEvents.push(...appended);
2113
2258
  attemptOutput += appended.length;
2114
2259
  yield* appended;
@@ -2137,22 +2282,28 @@ async function* runLoop(cfg) {
2137
2282
  detail: { usage: outcome?.usage }
2138
2283
  };
2139
2284
  if (!canRetry && cfg.signal?.aborted) {
2285
+ const dropped = await append(droppedCallResults(modelEvents, cfg.signal));
2140
2286
  const { events, result } = await pause("host", [
2141
2287
  { kind: "host", note: "host aborted the model request" }
2142
2288
  ]);
2289
+ yield* dropped;
2143
2290
  yield* events;
2144
2291
  return result;
2145
2292
  }
2146
2293
  if (!canRetry) {
2147
- const { events, result } = await fail({
2148
- ...base,
2149
- retryable: transient,
2150
- detail: {
2151
- ...base.detail,
2152
- attempts: attempt,
2153
- ...attemptOutput > 0 ? { partialOutput: attemptOutput } : {}
2154
- }
2155
- });
2294
+ const dropped = notExecutedResults(modelEvents, MODEL_FAILED_NOT_EXECUTED_TEXT);
2295
+ const { events, result } = await fail(
2296
+ {
2297
+ ...base,
2298
+ retryable: transient,
2299
+ detail: {
2300
+ ...base.detail,
2301
+ attempts: attempt,
2302
+ ...attemptOutput > 0 ? { partialOutput: attemptOutput } : {}
2303
+ }
2304
+ },
2305
+ dropped
2306
+ );
2156
2307
  yield* events;
2157
2308
  return result;
2158
2309
  }
@@ -2184,9 +2335,11 @@ async function* runLoop(cfg) {
2184
2335
  for (const s of sockets) await s.afterModel?.(ctx, modelEvents);
2185
2336
  yield* await flush();
2186
2337
  if (outcome.stopReason === "aborted") {
2338
+ const dropped = await append(droppedCallResults(modelEvents, cfg.signal));
2187
2339
  const { events, result } = await pause("host", [
2188
2340
  { kind: "host", note: "host aborted the model response" }
2189
2341
  ]);
2342
+ yield* dropped;
2190
2343
  yield* events;
2191
2344
  return result;
2192
2345
  }
@@ -2215,11 +2368,12 @@ async function* runLoop(cfg) {
2215
2368
  tokens: outcome.usage,
2216
2369
  toolCalls: calls.length,
2217
2370
  wallMs: now() - turnStartedAt,
2218
- contextEstimate: projected.stats.estimatedTokens
2371
+ contextEstimate: sentEstimate
2219
2372
  }
2220
2373
  }
2221
2374
  ]);
2222
- if (interruptions.length > 0 || calls.length > 0 && isStopped(cfg.signal)) {
2375
+ if (interruptions.length > 0 || calls.length > 0 && isStopped(cfg.signal) || abortedMidBatch(cfg.signal, batch)) {
2376
+ interruptions = withBatchAbortNote(interruptions, abortedMidBatch(cfg.signal, batch));
2223
2377
  const { events, result } = await pause(pauseReasonOf(interruptions), interruptions);
2224
2378
  yield* events;
2225
2379
  return result;
@@ -2228,6 +2382,7 @@ async function* runLoop(cfg) {
2228
2382
  if (ended) return ended;
2229
2383
  }
2230
2384
  async function* endTurn(ctx, fallback, flush) {
2385
+ ctx.budget.wallMs = now() - startedAt;
2231
2386
  let decision = fallback;
2232
2387
  for (const s of sockets) {
2233
2388
  const d = await s.onTurnEnd?.(ctx);
@@ -2253,7 +2408,7 @@ async function* runLoop(cfg) {
2253
2408
  }
2254
2409
  const intent = decision.handoff;
2255
2410
  const toSessionId = intent.toSessionId ?? newId(now());
2256
- yield* await append([
2411
+ const handoffEvents = await append([
2257
2412
  {
2258
2413
  type: "core.handoff",
2259
2414
  actor: intent.by ?? "model",
@@ -2265,23 +2420,17 @@ async function* runLoop(cfg) {
2265
2420
  }
2266
2421
  }
2267
2422
  ]);
2423
+ yield* handoffEvents;
2268
2424
  const at = now();
2269
- const opening = [
2270
- { type: "core.system_note", actor: "host", payload: { kind: "host", text: intent.summary } },
2271
- ...intent.opening ?? []
2272
- ];
2273
- if (intent.triggerMessage !== void 0) {
2274
- opening.push({
2275
- type: "core.user_message",
2276
- actor: "user",
2277
- payload: { content: [{ type: "text", text: intent.triggerMessage }] }
2278
- });
2279
- }
2425
+ const opening = handoffOpeningDrafts(
2426
+ intent,
2427
+ handoffEvents[0],
2428
+ await readTimeline(log, sessionId, { registry })
2429
+ );
2280
2430
  const openingEvents = opening.map(
2281
2431
  (d, i) => createEvent(registry, { ...d, sessionId: toSessionId, seq: i + 1, at, id: newId(at) })
2282
2432
  );
2283
2433
  await log.append(openingEvents);
2284
- yield* openingEvents;
2285
2434
  yield* await append([
2286
2435
  { type: "core.run_ended", actor: "system", payload: { status: "handoff", toSessionId } }
2287
2436
  ]);
@@ -2289,6 +2438,59 @@ async function* runLoop(cfg) {
2289
2438
  return { status: "handoff", sessionId, lastSeq, toSessionId };
2290
2439
  }
2291
2440
  }
2441
+ function abortedMidBatch(signal, batch) {
2442
+ if (!signal?.aborted) return false;
2443
+ const answered = new Set(batch.results.map((r) => r.payload.toolCallId));
2444
+ return batch.calls.some((c) => !answered.has(c.payload.toolCallId));
2445
+ }
2446
+ function notExecutedResults(modelEvents, text) {
2447
+ return modelEvents.filter((e) => e.type === "core.tool_call").map(
2448
+ (call) => ({
2449
+ type: "core.tool_result",
2450
+ actor: "tool",
2451
+ parentId: call.id,
2452
+ provenance: { source: call.payload.name },
2453
+ payload: {
2454
+ toolCallId: call.payload.toolCallId,
2455
+ name: call.payload.name,
2456
+ content: [{ type: "text", text }],
2457
+ isError: true
2458
+ }
2459
+ })
2460
+ );
2461
+ }
2462
+ function droppedCallResults(modelEvents, signal) {
2463
+ return isStopped(signal) ? [] : notExecutedResults(modelEvents, MODEL_INTERRUPTED_NOT_EXECUTED_TEXT);
2464
+ }
2465
+ function withBatchAbortNote(interruptions, abortedMid) {
2466
+ if (interruptions.length > 0 && !abortedMid) return interruptions;
2467
+ return [...interruptions, { kind: "host", note: "host aborted during the tool batch" }];
2468
+ }
2469
+ function toolCallIdsOf(timeline) {
2470
+ const ids = /* @__PURE__ */ new Set();
2471
+ for (const raw of timeline) {
2472
+ const e = raw;
2473
+ if (e.type === "core.tool_call") ids.add(e.payload.toolCallId);
2474
+ }
2475
+ return ids;
2476
+ }
2477
+ function withUniqueToolCallId(draft, used, freshId) {
2478
+ if (draft.type !== "core.tool_call") return draft;
2479
+ const payload = draft.payload;
2480
+ const original = payload.toolCallId;
2481
+ if (typeof original === "string" && original.length > 0 && !used.has(original)) {
2482
+ used.add(original);
2483
+ return draft;
2484
+ }
2485
+ const base = `reins_${freshId().replace(/[^A-Za-z0-9_-]/g, "_")}`.slice(0, 64);
2486
+ let id = base;
2487
+ for (let i = 2; used.has(id); i++) id = `${base.slice(0, 63 - String(i).length)}_${i}`;
2488
+ used.add(id);
2489
+ return {
2490
+ ...draft,
2491
+ payload: { ...payload, toolCallId: id, meta: { ...payload.meta, originalToolCallId: original } }
2492
+ };
2493
+ }
2292
2494
  function pauseReasonOf(interruptions) {
2293
2495
  const reasons = interruptions.map(
2294
2496
  (i) => i.kind === "subagent" ? i.reason : i.kind === "client_tool" ? "host" : i.kind
@@ -2313,6 +2515,7 @@ function withResultTrust(input, tools) {
2313
2515
  const tool = tools.find((t) => t.name === payload?.name);
2314
2516
  return { ...input, ...withTrust(toolResultTrust(tool, payload?.isError === true)) };
2315
2517
  }
2518
+ var toolUnavailableOnResumeText = (name) => `Tool not available on resume: ${name} is not in the current tool list (it may have been offered only for the turn in which it was called, or removed since), so the call was not executed. Call a currently available tool instead.`;
2316
2519
  async function* executeToolCalls(ctx, calls, timeline, deps) {
2317
2520
  const { cfg, sockets, flush, forwardedDecisions, spend, batch, imageCache } = deps;
2318
2521
  const append = async (drafts) => {
@@ -2352,6 +2555,10 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
2352
2555
  yield* await append([errorResult(`Approval denied${decided.reason ? `: ${decided.reason}` : ""}`)]);
2353
2556
  continue;
2354
2557
  }
2558
+ if (!tool && batch.resumed) {
2559
+ yield* await settle(errorResult(toolUnavailableOnResumeText(name)));
2560
+ continue;
2561
+ }
2355
2562
  let args = call.payload.args;
2356
2563
  let seen = call;
2357
2564
  let verdict = "proceed";
@@ -2395,7 +2602,23 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
2395
2602
  };
2396
2603
  let approval = typeof verdict === "object" && "defer" in verdict ? verdict.defer : void 0;
2397
2604
  if (!approval && !decided?.approved && tool.needsApproval !== void 0) {
2398
- const need = typeof tool.needsApproval === "function" ? await tool.needsApproval(args, toolCtx) : tool.needsApproval;
2605
+ let need;
2606
+ try {
2607
+ need = typeof tool.needsApproval === "function" ? await tool.needsApproval(args, toolCtx) : tool.needsApproval;
2608
+ } catch (err) {
2609
+ ctx.emit({
2610
+ type: "core.error",
2611
+ actor: "system",
2612
+ payload: {
2613
+ category: "host",
2614
+ message: `needsApproval of ${name} threw: ${describeThrown(err)}`,
2615
+ retryable: false,
2616
+ detail: { phase: "needsApproval", toolCallId }
2617
+ }
2618
+ });
2619
+ yield* await settle(errorResult(`Approval check failed: ${errorMessageOf(err)}`));
2620
+ continue;
2621
+ }
2399
2622
  if (need) {
2400
2623
  approval = { policyId: BUILTIN_APPROVAL_POLICY, summary: `${name}(${JSON.stringify(args) ?? ""})` };
2401
2624
  }
@@ -2608,6 +2831,28 @@ function untrustedOpenTag(source) {
2608
2831
  return `<${UNTRUSTED_TAG} source="${source.replace(/"/g, "&quot;")}">`;
2609
2832
  }
2610
2833
  var UNTRUSTED_CLOSE_TAG = `</${UNTRUSTED_TAG}>`;
2834
+ function escapeDeep(v, hit) {
2835
+ if (typeof v === "string") {
2836
+ const e = escapeUntrustedText(v);
2837
+ if (e.escaped) hit.escaped = true;
2838
+ return e.text;
2839
+ }
2840
+ if (Array.isArray(v)) return v.map((x) => escapeDeep(x, hit));
2841
+ if (v !== null && typeof v === "object") {
2842
+ const out = {};
2843
+ for (const [k, x] of Object.entries(v)) out[escapeDeep(k, hit)] = escapeDeep(x, hit);
2844
+ return out;
2845
+ }
2846
+ return v;
2847
+ }
2848
+ function escapeToolReference(p) {
2849
+ const hit = { escaped: false };
2850
+ const name = escapeDeep(p.name, hit);
2851
+ const description = escapeDeep(p.description, hit);
2852
+ const inputSchema = escapeDeep(p.inputSchema, hit);
2853
+ if (!hit.escaped) return { part: p, escaped: false };
2854
+ return { part: { type: "tool_reference", name, description, inputSchema }, escaped: true };
2855
+ }
2611
2856
  function markUntrustedText(text, source) {
2612
2857
  const e = escapeUntrustedText(text);
2613
2858
  return { text: `${untrustedOpenTag(source)}
@@ -2617,6 +2862,11 @@ ${UNTRUSTED_CLOSE_TAG}`, escaped: e.escaped };
2617
2862
  function markUntrusted(parts, source) {
2618
2863
  let escaped = false;
2619
2864
  const body = parts.map((p) => {
2865
+ if (p.type === "tool_reference") {
2866
+ const r = escapeToolReference(p);
2867
+ escaped = escaped || r.escaped;
2868
+ return r.part;
2869
+ }
2620
2870
  if (p.type !== "text") return p;
2621
2871
  const e = escapeUntrustedText(p.text);
2622
2872
  escaped = escaped || e.escaped;
@@ -2778,7 +3028,7 @@ function memoryStore() {
2778
3028
  }
2779
3029
 
2780
3030
  // src/index.ts
2781
- var REINS_VERSION = "0.17.0";
3031
+ var REINS_VERSION = "0.18.0";
2782
3032
  export {
2783
3033
  BUILTIN_APPROVAL_POLICY,
2784
3034
  CORE_SCHEMAS,
@@ -2791,6 +3041,7 @@ export {
2791
3041
  DEFAULT_RETRY_MAX_DELAY_MS,
2792
3042
  DEFAULT_TRUST,
2793
3043
  EventSchemaRegistry,
3044
+ HANDOFF_PROVENANCE_SOURCE,
2794
3045
  IMAGE_REF_ID_MAX,
2795
3046
  INPUT_DRAFT_TYPES,
2796
3047
  INTERRUPTED_IN_PROGRESS_TEXT,
@@ -2801,6 +3052,8 @@ export {
2801
3052
  InMemoryRunLease,
2802
3053
  LoweringError,
2803
3054
  MAX_TURNS_PAUSE_CODE,
3055
+ MODEL_FAILED_NOT_EXECUTED_TEXT,
3056
+ MODEL_INTERRUPTED_NOT_EXECUTED_TEXT,
2804
3057
  OUTCOME_UNKNOWN_TEXT,
2805
3058
  PAUSE_CODE_RE,
2806
3059
  REINS_VERSION,
@@ -2810,10 +3063,12 @@ export {
2810
3063
  STOPPED_IN_PROGRESS_TEXT,
2811
3064
  STOPPED_NOTE,
2812
3065
  STOPPED_NOT_EXECUTED_TEXT,
3066
+ SUPPORTED_IMAGE_MIMES,
2813
3067
  SchemaError,
2814
3068
  StoreError,
2815
3069
  UNTRUSTED_CLOSE_TAG,
2816
3070
  UNTRUSTED_TAG,
3071
+ assertDecisionsAwaitApproval,
2817
3072
  assertRunStateShape,
2818
3073
  awaitingOf,
2819
3074
  backoffDelayMs,
@@ -2848,6 +3103,7 @@ export {
2848
3103
  foldedToolResults,
2849
3104
  foldedUserMedia,
2850
3105
  forkSession,
3106
+ handoffOpeningDrafts,
2851
3107
  hydrateImageRefs,
2852
3108
  imageRefNotFound,
2853
3109
  inputDrafts,
@@ -2855,6 +3111,7 @@ export {
2855
3111
  isCompaction,
2856
3112
  isContentPart,
2857
3113
  isImageRef,
3114
+ isModelInvisibleByDefault,
2858
3115
  isModelOutput,
2859
3116
  isPauseCode,
2860
3117
  isPinNote,
@@ -2862,6 +3119,7 @@ export {
2862
3119
  isStopReason,
2863
3120
  isStopped,
2864
3121
  isSubagentPause,
3122
+ isSupportedImageMime,
2865
3123
  isTransientFailure,
2866
3124
  keptBy,
2867
3125
  lastRunMarker,
@@ -2886,6 +3144,7 @@ export {
2886
3144
  renderToolChangeNote,
2887
3145
  renderToolReference,
2888
3146
  replayTurns,
3147
+ resolveReserveTokens,
2889
3148
  resolveRetry,
2890
3149
  resolveSocketContributions,
2891
3150
  resolveSocketPause,
@@ -2906,6 +3165,7 @@ export {
2906
3165
  toolSpecOf,
2907
3166
  toolStartedAt,
2908
3167
  toolsBoundDrafts,
3168
+ unsupportedImageText,
2909
3169
  untrustedOpenTag,
2910
3170
  untrustedSourceOf,
2911
3171
  unwrapToolArguments,