@reinsjs/core 0.15.0 → 0.16.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-DFXHUJV4.js";
11
+ } from "./chunk-7RHFFDGN.js";
12
12
 
13
13
  // src/events/core.ts
14
14
  function contextTokensOf(usage) {
@@ -300,6 +300,48 @@ function renderFoldedToolResults(items, opts) {
300
300
  }
301
301
  return lines.join("\n");
302
302
  }
303
+ function foldedUserMedia(removed) {
304
+ const out = [];
305
+ for (const e of removed) {
306
+ if (e.type !== "core.user_message") continue;
307
+ const media = [];
308
+ for (const p of e.payload.content) {
309
+ switch (p.type) {
310
+ case "image":
311
+ case "video":
312
+ case "audio":
313
+ media.push({ type: p.type, mime: p.mime });
314
+ break;
315
+ case "text":
316
+ case "tool_reference":
317
+ break;
318
+ default: {
319
+ const _exhaustive = p;
320
+ return _exhaustive;
321
+ }
322
+ }
323
+ }
324
+ if (media.length > 0) out.push({ seq: e.seq, media });
325
+ }
326
+ return out.sort((a, b) => a.seq - b.seq);
327
+ }
328
+ function renderFoldedUserMedia(items, opts) {
329
+ if (items.length === 0) return "";
330
+ const maxItems = opts.maxItems ?? 80;
331
+ const lines = [opts.heading];
332
+ const shown = items.slice(0, maxItems);
333
+ for (const it of shown) {
334
+ const byType = /* @__PURE__ */ new Map();
335
+ for (const m of it.media) byType.set(m.type, [...byType.get(m.type) ?? [], m.mime]);
336
+ const desc = [...byType.entries()].map(([type, mimes]) => `${mimes.length} ${type}${mimes.length > 1 ? "s" : ""} (${mimes.join(", ")})`).join(", ");
337
+ lines.push(`- seq ${it.seq} user message \u2014 ${desc}`);
338
+ }
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
+ return lines.join("\n");
344
+ }
303
345
 
304
346
  // src/projection/truncate.ts
305
347
  var ASSISTANT_TYPES = /* @__PURE__ */ new Set([
@@ -370,6 +412,10 @@ var defaultThresholdSummary = (removed, ctx) => {
370
412
  heading: "Tool results that were removed (still in the session log, by seq):"
371
413
  });
372
414
  if (manifest) lines.push(manifest);
415
+ const media = renderFoldedUserMedia(foldedUserMedia(fresh), {
416
+ heading: "Images, video or audio in removed user messages (still in the session log, by seq):"
417
+ });
418
+ if (media) lines.push(media);
373
419
  return lines.join("\n");
374
420
  };
375
421
  function turnStartsCleanly(turn) {
@@ -616,6 +662,114 @@ async function forkSession(log, opts) {
616
662
  return { toSessionId };
617
663
  }
618
664
 
665
+ // src/store/errors.ts
666
+ var StoreError = class extends Error {
667
+ constructor(code, message, context = {}) {
668
+ super(`[${code}] ${message}`);
669
+ this.code = code;
670
+ this.context = context;
671
+ this.name = "StoreError";
672
+ }
673
+ code;
674
+ context;
675
+ };
676
+
677
+ // src/loop/media-refs.ts
678
+ var IMAGE_REF_ID_MAX = 128;
679
+ function isImageRef(p) {
680
+ if (typeof p !== "object" || p === null) return false;
681
+ const r = p;
682
+ return r.type === "image" && typeof r.mime === "string" && r.mime.startsWith("image/") && typeof r.blobId === "string" && r.blobId.length > 0 && r.blobId.length <= IMAGE_REF_ID_MAX && r.data === void 0;
683
+ }
684
+ function imageRefsIn(parts) {
685
+ return parts.filter(isImageRef);
686
+ }
687
+ function contentOf(e) {
688
+ if (e.type === "core.user_message") return e.payload.content;
689
+ if (e.type === "core.tool_result") return e.payload.content;
690
+ return void 0;
691
+ }
692
+ function mediaRefsOf(timeline) {
693
+ const ids = /* @__PURE__ */ new Set();
694
+ for (const e of timeline) {
695
+ const parts = contentOf(e);
696
+ if (!Array.isArray(parts)) continue;
697
+ for (const p of imageRefsIn(parts)) ids.add(p.blobId);
698
+ }
699
+ return ids;
700
+ }
701
+ function blobUsableBy(sessionId, meta, id, timeline) {
702
+ return meta.sessionId === sessionId || mediaRefsOf(timeline).has(id);
703
+ }
704
+ function imageRefNotFound(id) {
705
+ return `Blob ${id} not found in this session`;
706
+ }
707
+ async function checkImageRefs(parts, ctx) {
708
+ for (const ref of imageRefsIn(parts)) {
709
+ if (ctx.blobs === void 0) return imageRefNotFound(ref.blobId);
710
+ let meta;
711
+ const cached = ctx.cache.get(ref.blobId);
712
+ if (cached !== void 0) meta = cached.meta;
713
+ else {
714
+ let got;
715
+ try {
716
+ got = await ctx.blobs.get(ref.blobId);
717
+ } catch (err) {
718
+ if (err instanceof StoreError && err.code === "not_found") return imageRefNotFound(ref.blobId);
719
+ throw err;
720
+ }
721
+ meta = got.meta;
722
+ ctx.cache.set(ref.blobId, { data: bytesToBase64(got.bytes), meta });
723
+ }
724
+ if (!blobUsableBy(ctx.sessionId, meta, ref.blobId, ctx.timeline)) return imageRefNotFound(ref.blobId);
725
+ if (meta.mime !== ref.mime) return imageRefNotFound(ref.blobId);
726
+ }
727
+ return void 0;
728
+ }
729
+ async function hydrateImageRefs(events, ctx) {
730
+ const out = [];
731
+ for (const e of events) {
732
+ const parts = contentOf(e);
733
+ if (!Array.isArray(parts) || !parts.some(isImageRef)) {
734
+ out.push(e);
735
+ continue;
736
+ }
737
+ const next = [];
738
+ for (const p of parts) {
739
+ if (!isImageRef(p)) {
740
+ next.push(p);
741
+ continue;
742
+ }
743
+ const data = await loadImage(p.blobId, ctx);
744
+ next.push(data === void 0 ? p : { type: "image", mime: p.mime, data });
745
+ }
746
+ out.push({ ...e, payload: { ...e.payload, content: next } });
747
+ }
748
+ return out;
749
+ }
750
+ async function loadImage(id, ctx) {
751
+ const cached = ctx.cache.get(id);
752
+ if (cached !== void 0) return cached.data;
753
+ if (ctx.blobs === void 0) return void 0;
754
+ try {
755
+ const { bytes, meta } = await ctx.blobs.get(id);
756
+ const data = bytesToBase64(bytes);
757
+ ctx.cache.set(id, { data, meta });
758
+ return data;
759
+ } catch (err) {
760
+ if (err instanceof StoreError && err.code === "not_found") return void 0;
761
+ throw err;
762
+ }
763
+ }
764
+ var BASE64_CHUNK = 32768;
765
+ function bytesToBase64(bytes) {
766
+ let binary = "";
767
+ for (let i = 0; i < bytes.length; i += BASE64_CHUNK) {
768
+ binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK));
769
+ }
770
+ return btoa(binary);
771
+ }
772
+
619
773
  // src/loop/pause-code.ts
620
774
  var PAUSE_CODE_RE = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
621
775
  function isPauseCode(x) {
@@ -891,6 +1045,7 @@ function isContentPart(x) {
891
1045
  case "text":
892
1046
  return typeof p.text === "string";
893
1047
  case "image":
1048
+ if (p.blobId !== void 0) return isImageRef(p);
894
1049
  return typeof p.mime === "string" && typeof p.data === "string";
895
1050
  case "video":
896
1051
  case "audio":
@@ -1500,6 +1655,10 @@ function describe(value) {
1500
1655
  function isInputArray(input) {
1501
1656
  return Array.isArray(input);
1502
1657
  }
1658
+ function draftParts(draft) {
1659
+ if (draft.type !== "core.user_message" && draft.type !== "core.tool_result") return [];
1660
+ return draft.payload.content;
1661
+ }
1503
1662
  async function* runLoop(cfg) {
1504
1663
  const { sessionId, log, lowering, model } = cfg;
1505
1664
  const registry = cfg.registry ?? createCoreRegistry();
@@ -1520,7 +1679,18 @@ async function* runLoop(cfg) {
1520
1679
  ...baseSystemPrompt !== void 0 ? { systemPrompt: baseSystemPrompt } : {}
1521
1680
  });
1522
1681
  const startedAt = now();
1523
- let lastSeq = (await readTimeline(log, sessionId, { registry })).at(-1)?.seq ?? 0;
1682
+ const startTimeline = await readTimeline(log, sessionId, { registry });
1683
+ let lastSeq = startTimeline.at(-1)?.seq ?? 0;
1684
+ const imageCache = /* @__PURE__ */ new Map();
1685
+ for (const d of input) {
1686
+ const problem = await checkImageRefs(draftParts(d), {
1687
+ sessionId,
1688
+ blobs: cfg.blobs,
1689
+ timeline: startTimeline,
1690
+ cache: imageCache
1691
+ });
1692
+ if (problem !== void 0) throw new RangeError(problem);
1693
+ }
1524
1694
  let turns = 0;
1525
1695
  let tokensSpent = 0;
1526
1696
  let toolCallsTotal = 0;
@@ -1692,36 +1862,58 @@ async function* runLoop(cfg) {
1692
1862
  thrown = { value: err };
1693
1863
  }
1694
1864
  if (cfg.signal?.aborted) continue;
1865
+ const hostFailure = async (message) => append([
1866
+ {
1867
+ type: "core.error",
1868
+ actor: "system",
1869
+ payload: { category: "host", message, retryable: true, detail: { phase: "pullInput" } }
1870
+ }
1871
+ ]);
1695
1872
  if (thrown !== void 0) {
1696
- const errors = await append([
1697
- {
1698
- type: "core.error",
1699
- actor: "system",
1700
- payload: {
1701
- category: "host",
1702
- message: `pullInput threw: ${describeThrown(thrown.value)}`,
1703
- retryable: true,
1704
- detail: { phase: "pullInput" }
1705
- }
1706
- }
1707
- ]);
1873
+ const errors = await hostFailure(`pullInput threw: ${describeThrown(thrown.value)}`);
1708
1874
  yield* errors;
1709
1875
  timeline = [...timeline, ...errors];
1710
1876
  } else {
1711
1877
  let pulled;
1878
+ let problem;
1879
+ let storageFailure;
1712
1880
  try {
1713
1881
  pulled = checkPulledDrafts(raw, registry);
1714
1882
  } catch (err) {
1883
+ pulled = [];
1884
+ problem = describeThrown(err);
1885
+ }
1886
+ for (const d of pulled) {
1887
+ if (problem !== void 0 || storageFailure !== void 0) break;
1888
+ try {
1889
+ problem = await checkImageRefs(draftParts(d), {
1890
+ sessionId,
1891
+ blobs: cfg.blobs,
1892
+ timeline,
1893
+ cache: imageCache
1894
+ });
1895
+ } catch (err) {
1896
+ storageFailure = { value: err };
1897
+ }
1898
+ }
1899
+ if (cfg.signal?.aborted) continue;
1900
+ if (problem !== void 0) {
1715
1901
  const { events, result } = await fail({
1716
1902
  category: "input",
1717
- message: describeThrown(err),
1903
+ message: problem,
1718
1904
  retryable: false,
1719
1905
  detail: { phase: "pullInput" }
1720
1906
  });
1721
1907
  yield* events;
1722
1908
  return result;
1723
1909
  }
1724
- if (pulled.length > 0) {
1910
+ if (storageFailure !== void 0) {
1911
+ const errors = await hostFailure(
1912
+ `reading a blob referenced by pulled input failed: ${describeThrown(storageFailure.value)}`
1913
+ );
1914
+ yield* errors;
1915
+ timeline = [...timeline, ...errors];
1916
+ } else if (pulled.length > 0) {
1725
1917
  const written = await append(pulled);
1726
1918
  yield* written;
1727
1919
  timeline = [...timeline, ...written];
@@ -1791,7 +1983,8 @@ async function* runLoop(cfg) {
1791
1983
  flush,
1792
1984
  forwardedDecisions,
1793
1985
  spend: spendInto(ctx),
1794
- batch
1986
+ batch,
1987
+ imageCache
1795
1988
  });
1796
1989
  toolCallsTotal += settled.executed;
1797
1990
  if (settled.interruptions.length > 0 || isStopped(cfg.signal)) {
@@ -1834,12 +2027,14 @@ async function* runLoop(cfg) {
1834
2027
  ctx.tools = tools;
1835
2028
  let outcome;
1836
2029
  const modelEvents = [];
2030
+ let hydrated;
1837
2031
  for (let attempt = 1; ; attempt++) {
1838
2032
  let failure;
1839
2033
  let attemptOutput = 0;
1840
2034
  try {
2035
+ hydrated ??= await hydrateImageRefs(visible, { blobs: cfg.blobs, cache: imageCache });
1841
2036
  const request = lowering.toRequest({
1842
- events: visible,
2037
+ events: hydrated,
1843
2038
  tools: tools.map((t) => deferredToolSpecOf(t, deferredTools.has(t.name))),
1844
2039
  model,
1845
2040
  ...systemPrompt !== void 0 ? { systemPrompt } : {}
@@ -1948,7 +2143,8 @@ async function* runLoop(cfg) {
1948
2143
  flush,
1949
2144
  forwardedDecisions,
1950
2145
  spend: spendInto(ctx),
1951
- batch
2146
+ batch,
2147
+ imageCache
1952
2148
  });
1953
2149
  toolCallsTotal += settled.executed;
1954
2150
  ctx.budget.toolCalls = toolCallsTotal;
@@ -2061,7 +2257,7 @@ function withResultTrust(input, tools) {
2061
2257
  return { ...input, ...withTrust(toolResultTrust(tool, payload?.isError === true)) };
2062
2258
  }
2063
2259
  async function* executeToolCalls(ctx, calls, timeline, deps) {
2064
- const { cfg, sockets, flush, forwardedDecisions, spend, batch } = deps;
2260
+ const { cfg, sockets, flush, forwardedDecisions, spend, batch, imageCache } = deps;
2065
2261
  const append = async (drafts) => {
2066
2262
  const events = await deps.append(drafts);
2067
2263
  for (const e of events) if (e.type === "core.tool_result") batch.results.push(e);
@@ -2210,11 +2406,53 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
2210
2406
  const replaced = await s.afterTool?.(ctx, call, result);
2211
2407
  if (replaced) result = replaced;
2212
2408
  }
2409
+ const refs = await checkToolResultRefs(result.payload.content, {
2410
+ sessionId: ctx.session.id,
2411
+ blobs: ctx.blobs,
2412
+ timeline,
2413
+ cache: imageCache
2414
+ });
2415
+ if (refs.content !== result.payload.content)
2416
+ result = { ...result, payload: { ...result.payload, content: refs.content } };
2417
+ for (const failure of refs.storageFailures) ctx.emit(failure);
2213
2418
  yield* await settle(result);
2214
2419
  if (cfg.signal?.aborted) break;
2215
2420
  }
2216
2421
  return summary;
2217
2422
  }
2423
+ async function checkToolResultRefs(parts, ctx) {
2424
+ const storageFailures = [];
2425
+ let changed = false;
2426
+ const content = [];
2427
+ for (const p of parts) {
2428
+ if (!isImageRef(p)) {
2429
+ content.push(p);
2430
+ continue;
2431
+ }
2432
+ let text;
2433
+ try {
2434
+ text = await checkImageRefs([p], ctx);
2435
+ } catch (err) {
2436
+ text = `Could not read blob ${p.blobId}: storage error`;
2437
+ storageFailures.push({
2438
+ type: "core.error",
2439
+ actor: "system",
2440
+ payload: {
2441
+ category: "host",
2442
+ message: `reading blob ${p.blobId} referenced by a tool result failed: ${describeThrown(err)}`,
2443
+ retryable: true,
2444
+ detail: { phase: "toolResult" }
2445
+ }
2446
+ });
2447
+ }
2448
+ if (text === void 0) content.push(p);
2449
+ else {
2450
+ changed = true;
2451
+ content.push({ type: "text", text });
2452
+ }
2453
+ }
2454
+ return { content: changed ? content : parts, storageFailures };
2455
+ }
2218
2456
 
2219
2457
  // src/lowering/tool-arguments.ts
2220
2458
  function unwrapToolArguments(parsed) {
@@ -2341,18 +2579,6 @@ function needsUntrustedMark(e) {
2341
2579
  return e.trust === "untrusted";
2342
2580
  }
2343
2581
 
2344
- // src/store/errors.ts
2345
- var StoreError = class extends Error {
2346
- constructor(code, message, context = {}) {
2347
- super(`[${code}] ${message}`);
2348
- this.code = code;
2349
- this.context = context;
2350
- this.name = "StoreError";
2351
- }
2352
- code;
2353
- context;
2354
- };
2355
-
2356
2582
  // src/store/in-memory.ts
2357
2583
  var InMemoryEventLog = class {
2358
2584
  sessions = /* @__PURE__ */ new Map();
@@ -2488,7 +2714,7 @@ function memoryStore() {
2488
2714
  }
2489
2715
 
2490
2716
  // src/index.ts
2491
- var REINS_VERSION = "0.15.0";
2717
+ var REINS_VERSION = "0.16.0";
2492
2718
  export {
2493
2719
  BUILTIN_APPROVAL_POLICY,
2494
2720
  CORE_SCHEMAS,
@@ -2501,6 +2727,7 @@ export {
2501
2727
  DEFAULT_RETRY_MAX_DELAY_MS,
2502
2728
  DEFAULT_TRUST,
2503
2729
  EventSchemaRegistry,
2730
+ IMAGE_REF_ID_MAX,
2504
2731
  INPUT_DRAFT_TYPES,
2505
2732
  INTERRUPTED_IN_PROGRESS_TEXT,
2506
2733
  INTERRUPTED_NOT_EXECUTED_TEXT,
@@ -2526,7 +2753,10 @@ export {
2526
2753
  assertRunStateShape,
2527
2754
  awaitingOf,
2528
2755
  backoffDelayMs,
2756
+ blobUsableBy,
2529
2757
  budgetTruncate,
2758
+ bytesToBase64,
2759
+ checkImageRefs,
2530
2760
  computeConfigHash,
2531
2761
  computeModelDigest,
2532
2762
  computePendingDigest,
@@ -2552,11 +2782,15 @@ export {
2552
2782
  estimateTotal,
2553
2783
  foldCompactions,
2554
2784
  foldedToolResults,
2785
+ foldedUserMedia,
2555
2786
  forkSession,
2787
+ hydrateImageRefs,
2788
+ imageRefNotFound,
2556
2789
  inputDrafts,
2557
2790
  isClientTool,
2558
2791
  isCompaction,
2559
2792
  isContentPart,
2793
+ isImageRef,
2560
2794
  isModelOutput,
2561
2795
  isPauseCode,
2562
2796
  isPinNote,
@@ -2571,6 +2805,7 @@ export {
2571
2805
  lossesOf,
2572
2806
  markUntrusted,
2573
2807
  markUntrustedText,
2808
+ mediaRefsOf,
2574
2809
  memoryStore,
2575
2810
  needsUntrustedMark,
2576
2811
  normalizeToolOutput,
@@ -2583,6 +2818,7 @@ export {
2583
2818
  readTimeline,
2584
2819
  reinjectPins,
2585
2820
  renderFoldedToolResults,
2821
+ renderFoldedUserMedia,
2586
2822
  renderToolChangeNote,
2587
2823
  renderToolReference,
2588
2824
  replayTurns,