@reinsjs/core 0.15.0 → 0.17.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,174 @@ 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
+ const reads = await prefetchImageRefs(parts, ctx);
709
+ for (const ref of imageRefsIn(parts)) {
710
+ const problem = judgeImageRef(ref, ctx, reads);
711
+ if (problem !== void 0) return problem;
712
+ }
713
+ return void 0;
714
+ }
715
+ async function prefetchImageRefs(parts, ctx) {
716
+ if (ctx.blobs === void 0) return /* @__PURE__ */ new Map();
717
+ const ids = imageRefsIn(parts).map((r) => r.blobId).filter((id) => !ctx.cache.has(id));
718
+ if (ids.length === 0) return /* @__PURE__ */ new Map();
719
+ const metaOnly = ctx.metaOnly === true;
720
+ const reads = await readBlobs(ctx.blobs, ids, metaOnly);
721
+ if (!metaOnly) {
722
+ for (const [id, r] of reads) {
723
+ if (r.ok && r.data !== void 0) ctx.cache.set(id, { data: r.data, meta: r.meta });
724
+ }
725
+ }
726
+ return reads;
727
+ }
728
+ function judgeImageRef(ref, ctx, reads) {
729
+ if (ctx.blobs === void 0) return imageRefNotFound(ref.blobId);
730
+ let meta;
731
+ const cached = ctx.cache.get(ref.blobId);
732
+ if (cached !== void 0) meta = cached.meta;
733
+ else {
734
+ const read = reads.get(ref.blobId);
735
+ if (read === void 0) throw new Error(`internal: blob ${ref.blobId} was not prefetched`);
736
+ if (!read.ok) {
737
+ if (isNotFound(read.error)) return imageRefNotFound(ref.blobId);
738
+ throw read.error;
739
+ }
740
+ meta = read.meta;
741
+ }
742
+ if (!blobUsableBy(ctx.sessionId, meta, ref.blobId, ctx.timeline)) return imageRefNotFound(ref.blobId);
743
+ if (meta.mime !== ref.mime) return imageRefNotFound(ref.blobId);
744
+ return void 0;
745
+ }
746
+ async function hydrateImageRefs(events, ctx) {
747
+ let reads = /* @__PURE__ */ new Map();
748
+ if (ctx.blobs !== void 0) {
749
+ const ids = [];
750
+ for (const e of events) {
751
+ const parts = contentOf(e);
752
+ if (!Array.isArray(parts)) continue;
753
+ for (const p of imageRefsIn(parts)) if (!ctx.cache.has(p.blobId)) ids.push(p.blobId);
754
+ }
755
+ if (ids.length > 0) reads = await readBlobs(ctx.blobs, ids, false);
756
+ for (const [id, r] of reads) {
757
+ if (r.ok && r.data !== void 0) ctx.cache.set(id, { data: r.data, meta: r.meta });
758
+ }
759
+ }
760
+ const out = [];
761
+ for (const e of events) {
762
+ const parts = contentOf(e);
763
+ if (!Array.isArray(parts) || !parts.some(isImageRef)) {
764
+ out.push(e);
765
+ continue;
766
+ }
767
+ const next = [];
768
+ for (const p of parts) {
769
+ if (!isImageRef(p)) {
770
+ next.push(p);
771
+ continue;
772
+ }
773
+ const data = hydratedData(p.blobId, ctx.cache, reads);
774
+ next.push(data === void 0 ? p : { type: "image", mime: p.mime, data });
775
+ }
776
+ out.push({ ...e, payload: { ...e.payload, content: next } });
777
+ }
778
+ return out;
779
+ }
780
+ function hydratedData(id, cache, reads) {
781
+ const cached = cache.get(id);
782
+ if (cached !== void 0) return cached.data;
783
+ const read = reads.get(id);
784
+ if (read === void 0 || read.ok || isNotFound(read.error)) return void 0;
785
+ throw read.error;
786
+ }
787
+ var BLOB_READ_CONCURRENCY = 16;
788
+ async function readBlobs(blobs, ids, metaOnly) {
789
+ const queue = [...new Set(ids)];
790
+ const out = /* @__PURE__ */ new Map();
791
+ let next = 0;
792
+ const worker = async () => {
793
+ while (next < queue.length) {
794
+ const id = queue[next++];
795
+ try {
796
+ out.set(id, { ok: true, ...await readOne(blobs, id, metaOnly) });
797
+ } catch (error) {
798
+ out.set(id, { ok: false, error });
799
+ }
800
+ }
801
+ };
802
+ await Promise.all(Array.from({ length: Math.min(BLOB_READ_CONCURRENCY, queue.length) }, worker));
803
+ return out;
804
+ }
805
+ async function readOne(blobs, id, metaOnly) {
806
+ if (metaOnly && blobs.stat !== void 0) {
807
+ const meta = await blobs.stat(id);
808
+ if (!isObject(meta)) throw blobNotFound(id);
809
+ return { meta };
810
+ }
811
+ const got = await blobs.get(id);
812
+ if (!isObject(got) || !isObject(got.meta)) throw blobNotFound(id);
813
+ return metaOnly ? { meta: got.meta } : { meta: got.meta, data: bytesToBase64(got.bytes) };
814
+ }
815
+ function isObject(x) {
816
+ return typeof x === "object" && x !== null;
817
+ }
818
+ function blobNotFound(id) {
819
+ return new StoreError("not_found", `blob not found: ${id}`, { id });
820
+ }
821
+ function isNotFound(err) {
822
+ return err instanceof StoreError && err.code === "not_found";
823
+ }
824
+ var BASE64_CHUNK = 32768;
825
+ function bytesToBase64(bytes) {
826
+ let binary = "";
827
+ for (let i = 0; i < bytes.length; i += BASE64_CHUNK) {
828
+ binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK));
829
+ }
830
+ return btoa(binary);
831
+ }
832
+
619
833
  // src/loop/pause-code.ts
620
834
  var PAUSE_CODE_RE = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
621
835
  function isPauseCode(x) {
@@ -891,6 +1105,7 @@ function isContentPart(x) {
891
1105
  case "text":
892
1106
  return typeof p.text === "string";
893
1107
  case "image":
1108
+ if (p.blobId !== void 0) return isImageRef(p);
894
1109
  return typeof p.mime === "string" && typeof p.data === "string";
895
1110
  case "video":
896
1111
  case "audio":
@@ -1500,6 +1715,10 @@ function describe(value) {
1500
1715
  function isInputArray(input) {
1501
1716
  return Array.isArray(input);
1502
1717
  }
1718
+ function draftParts(draft) {
1719
+ if (draft.type !== "core.user_message" && draft.type !== "core.tool_result") return [];
1720
+ return draft.payload.content;
1721
+ }
1503
1722
  async function* runLoop(cfg) {
1504
1723
  const { sessionId, log, lowering, model } = cfg;
1505
1724
  const registry = cfg.registry ?? createCoreRegistry();
@@ -1520,7 +1739,16 @@ async function* runLoop(cfg) {
1520
1739
  ...baseSystemPrompt !== void 0 ? { systemPrompt: baseSystemPrompt } : {}
1521
1740
  });
1522
1741
  const startedAt = now();
1523
- let lastSeq = (await readTimeline(log, sessionId, { registry })).at(-1)?.seq ?? 0;
1742
+ const startTimeline = await readTimeline(log, sessionId, { registry });
1743
+ let lastSeq = startTimeline.at(-1)?.seq ?? 0;
1744
+ const imageCache = /* @__PURE__ */ new Map();
1745
+ const startProblem = await checkImageRefs(input.flatMap(draftParts), {
1746
+ sessionId,
1747
+ blobs: cfg.blobs,
1748
+ timeline: startTimeline,
1749
+ cache: imageCache
1750
+ });
1751
+ if (startProblem !== void 0) throw new RangeError(startProblem);
1524
1752
  let turns = 0;
1525
1753
  let tokensSpent = 0;
1526
1754
  let toolCallsTotal = 0;
@@ -1692,36 +1920,57 @@ async function* runLoop(cfg) {
1692
1920
  thrown = { value: err };
1693
1921
  }
1694
1922
  if (cfg.signal?.aborted) continue;
1923
+ const hostFailure = async (message) => append([
1924
+ {
1925
+ type: "core.error",
1926
+ actor: "system",
1927
+ payload: { category: "host", message, retryable: true, detail: { phase: "pullInput" } }
1928
+ }
1929
+ ]);
1695
1930
  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
- ]);
1931
+ const errors = await hostFailure(`pullInput threw: ${describeThrown(thrown.value)}`);
1708
1932
  yield* errors;
1709
1933
  timeline = [...timeline, ...errors];
1710
1934
  } else {
1711
1935
  let pulled;
1936
+ let problem;
1937
+ let storageFailure;
1712
1938
  try {
1713
1939
  pulled = checkPulledDrafts(raw, registry);
1714
1940
  } catch (err) {
1941
+ pulled = [];
1942
+ problem = describeThrown(err);
1943
+ }
1944
+ if (problem === void 0) {
1945
+ try {
1946
+ problem = await checkImageRefs(pulled.flatMap(draftParts), {
1947
+ sessionId,
1948
+ blobs: cfg.blobs,
1949
+ timeline,
1950
+ cache: imageCache
1951
+ });
1952
+ } catch (err) {
1953
+ storageFailure = { value: err };
1954
+ }
1955
+ }
1956
+ if (cfg.signal?.aborted) continue;
1957
+ if (problem !== void 0) {
1715
1958
  const { events, result } = await fail({
1716
1959
  category: "input",
1717
- message: describeThrown(err),
1960
+ message: problem,
1718
1961
  retryable: false,
1719
1962
  detail: { phase: "pullInput" }
1720
1963
  });
1721
1964
  yield* events;
1722
1965
  return result;
1723
1966
  }
1724
- if (pulled.length > 0) {
1967
+ if (storageFailure !== void 0) {
1968
+ const errors = await hostFailure(
1969
+ `reading a blob referenced by pulled input failed: ${describeThrown(storageFailure.value)}`
1970
+ );
1971
+ yield* errors;
1972
+ timeline = [...timeline, ...errors];
1973
+ } else if (pulled.length > 0) {
1725
1974
  const written = await append(pulled);
1726
1975
  yield* written;
1727
1976
  timeline = [...timeline, ...written];
@@ -1791,7 +2040,8 @@ async function* runLoop(cfg) {
1791
2040
  flush,
1792
2041
  forwardedDecisions,
1793
2042
  spend: spendInto(ctx),
1794
- batch
2043
+ batch,
2044
+ imageCache
1795
2045
  });
1796
2046
  toolCallsTotal += settled.executed;
1797
2047
  if (settled.interruptions.length > 0 || isStopped(cfg.signal)) {
@@ -1834,12 +2084,14 @@ async function* runLoop(cfg) {
1834
2084
  ctx.tools = tools;
1835
2085
  let outcome;
1836
2086
  const modelEvents = [];
2087
+ let hydrated;
1837
2088
  for (let attempt = 1; ; attempt++) {
1838
2089
  let failure;
1839
2090
  let attemptOutput = 0;
1840
2091
  try {
2092
+ hydrated ??= await hydrateImageRefs(visible, { blobs: cfg.blobs, cache: imageCache });
1841
2093
  const request = lowering.toRequest({
1842
- events: visible,
2094
+ events: hydrated,
1843
2095
  tools: tools.map((t) => deferredToolSpecOf(t, deferredTools.has(t.name))),
1844
2096
  model,
1845
2097
  ...systemPrompt !== void 0 ? { systemPrompt } : {}
@@ -1948,7 +2200,8 @@ async function* runLoop(cfg) {
1948
2200
  flush,
1949
2201
  forwardedDecisions,
1950
2202
  spend: spendInto(ctx),
1951
- batch
2203
+ batch,
2204
+ imageCache
1952
2205
  });
1953
2206
  toolCallsTotal += settled.executed;
1954
2207
  ctx.budget.toolCalls = toolCallsTotal;
@@ -2061,7 +2314,7 @@ function withResultTrust(input, tools) {
2061
2314
  return { ...input, ...withTrust(toolResultTrust(tool, payload?.isError === true)) };
2062
2315
  }
2063
2316
  async function* executeToolCalls(ctx, calls, timeline, deps) {
2064
- const { cfg, sockets, flush, forwardedDecisions, spend, batch } = deps;
2317
+ const { cfg, sockets, flush, forwardedDecisions, spend, batch, imageCache } = deps;
2065
2318
  const append = async (drafts) => {
2066
2319
  const events = await deps.append(drafts);
2067
2320
  for (const e of events) if (e.type === "core.tool_result") batch.results.push(e);
@@ -2210,11 +2463,55 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
2210
2463
  const replaced = await s.afterTool?.(ctx, call, result);
2211
2464
  if (replaced) result = replaced;
2212
2465
  }
2466
+ const refs = await checkToolResultRefs(result.payload.content, {
2467
+ sessionId: ctx.session.id,
2468
+ blobs: ctx.blobs,
2469
+ timeline,
2470
+ cache: imageCache
2471
+ });
2472
+ if (refs.content !== result.payload.content)
2473
+ result = { ...result, payload: { ...result.payload, content: refs.content } };
2474
+ for (const failure of refs.storageFailures) ctx.emit(failure);
2213
2475
  yield* await settle(result);
2214
2476
  if (cfg.signal?.aborted) break;
2215
2477
  }
2216
2478
  return summary;
2217
2479
  }
2480
+ async function checkToolResultRefs(parts, ctx) {
2481
+ if (!parts.some(isImageRef)) return { content: parts, storageFailures: [] };
2482
+ const reads = await prefetchImageRefs(parts, ctx);
2483
+ const storageFailures = [];
2484
+ let changed = false;
2485
+ const content = [];
2486
+ for (const p of parts) {
2487
+ if (!isImageRef(p)) {
2488
+ content.push(p);
2489
+ continue;
2490
+ }
2491
+ let text;
2492
+ try {
2493
+ text = judgeImageRef(p, ctx, reads);
2494
+ } catch (err) {
2495
+ text = `Could not read blob ${p.blobId}: storage error`;
2496
+ storageFailures.push({
2497
+ type: "core.error",
2498
+ actor: "system",
2499
+ payload: {
2500
+ category: "host",
2501
+ message: `reading blob ${p.blobId} referenced by a tool result failed: ${describeThrown(err)}`,
2502
+ retryable: true,
2503
+ detail: { phase: "toolResult" }
2504
+ }
2505
+ });
2506
+ }
2507
+ if (text === void 0) content.push(p);
2508
+ else {
2509
+ changed = true;
2510
+ content.push({ type: "text", text });
2511
+ }
2512
+ }
2513
+ return { content: changed ? content : parts, storageFailures };
2514
+ }
2218
2515
 
2219
2516
  // src/lowering/tool-arguments.ts
2220
2517
  function unwrapToolArguments(parsed) {
@@ -2341,18 +2638,6 @@ function needsUntrustedMark(e) {
2341
2638
  return e.trust === "untrusted";
2342
2639
  }
2343
2640
 
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
2641
  // src/store/in-memory.ts
2357
2642
  var InMemoryEventLog = class {
2358
2643
  sessions = /* @__PURE__ */ new Map();
@@ -2435,6 +2720,11 @@ var InMemoryBlobStore = class {
2435
2720
  if (!hit) throw new StoreError("not_found", `blob not found: ${id}`, { id });
2436
2721
  return { bytes: hit.bytes.slice(), meta: { ...hit.meta } };
2437
2722
  }
2723
+ async stat(id) {
2724
+ const hit = this.blobs.get(id);
2725
+ if (!hit) throw new StoreError("not_found", `blob not found: ${id}`, { id });
2726
+ return { ...hit.meta };
2727
+ }
2438
2728
  async slice(id, range) {
2439
2729
  const { bytes } = await this.get(id);
2440
2730
  return bytes.slice(Math.max(0, range.start), Math.min(bytes.byteLength, range.end));
@@ -2488,7 +2778,7 @@ function memoryStore() {
2488
2778
  }
2489
2779
 
2490
2780
  // src/index.ts
2491
- var REINS_VERSION = "0.15.0";
2781
+ var REINS_VERSION = "0.17.0";
2492
2782
  export {
2493
2783
  BUILTIN_APPROVAL_POLICY,
2494
2784
  CORE_SCHEMAS,
@@ -2501,6 +2791,7 @@ export {
2501
2791
  DEFAULT_RETRY_MAX_DELAY_MS,
2502
2792
  DEFAULT_TRUST,
2503
2793
  EventSchemaRegistry,
2794
+ IMAGE_REF_ID_MAX,
2504
2795
  INPUT_DRAFT_TYPES,
2505
2796
  INTERRUPTED_IN_PROGRESS_TEXT,
2506
2797
  INTERRUPTED_NOT_EXECUTED_TEXT,
@@ -2526,7 +2817,10 @@ export {
2526
2817
  assertRunStateShape,
2527
2818
  awaitingOf,
2528
2819
  backoffDelayMs,
2820
+ blobUsableBy,
2529
2821
  budgetTruncate,
2822
+ bytesToBase64,
2823
+ checkImageRefs,
2530
2824
  computeConfigHash,
2531
2825
  computeModelDigest,
2532
2826
  computePendingDigest,
@@ -2552,11 +2846,15 @@ export {
2552
2846
  estimateTotal,
2553
2847
  foldCompactions,
2554
2848
  foldedToolResults,
2849
+ foldedUserMedia,
2555
2850
  forkSession,
2851
+ hydrateImageRefs,
2852
+ imageRefNotFound,
2556
2853
  inputDrafts,
2557
2854
  isClientTool,
2558
2855
  isCompaction,
2559
2856
  isContentPart,
2857
+ isImageRef,
2560
2858
  isModelOutput,
2561
2859
  isPauseCode,
2562
2860
  isPinNote,
@@ -2571,6 +2869,7 @@ export {
2571
2869
  lossesOf,
2572
2870
  markUntrusted,
2573
2871
  markUntrustedText,
2872
+ mediaRefsOf,
2574
2873
  memoryStore,
2575
2874
  needsUntrustedMark,
2576
2875
  normalizeToolOutput,
@@ -2583,6 +2882,7 @@ export {
2583
2882
  readTimeline,
2584
2883
  reinjectPins,
2585
2884
  renderFoldedToolResults,
2885
+ renderFoldedUserMedia,
2586
2886
  renderToolChangeNote,
2587
2887
  renderToolReference,
2588
2888
  replayTurns,