@reinsjs/core 0.16.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/CHANGELOG.md +43 -0
- package/README.md +19 -10
- package/dist/{core-BxGiBJ_p.d.ts → core-CfHjZdUU.d.ts} +36 -7
- package/dist/index.d.ts +129 -17
- package/dist/index.js +438 -114
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +8 -2
- package/dist/testing/index.js +178 -1
- package/dist/testing/index.js.map +1 -1
- package/package.json +1 -1
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) => !
|
|
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
|
|
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 ?
|
|
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
|
|
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
|
-
|
|
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 =
|
|
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) ||
|
|
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 = {}) {
|
|
@@ -705,28 +768,58 @@ function imageRefNotFound(id) {
|
|
|
705
768
|
return `Blob ${id} not found in this session`;
|
|
706
769
|
}
|
|
707
770
|
async function checkImageRefs(parts, ctx) {
|
|
771
|
+
const reads = await prefetchImageRefs(parts, ctx);
|
|
708
772
|
for (const ref of imageRefsIn(parts)) {
|
|
709
|
-
|
|
710
|
-
|
|
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);
|
|
773
|
+
const problem = judgeImageRef(ref, ctx, reads);
|
|
774
|
+
if (problem !== void 0) return problem;
|
|
726
775
|
}
|
|
727
776
|
return void 0;
|
|
728
777
|
}
|
|
778
|
+
async function prefetchImageRefs(parts, ctx) {
|
|
779
|
+
if (ctx.blobs === void 0) return /* @__PURE__ */ new Map();
|
|
780
|
+
const ids = imageRefsIn(parts).map((r) => r.blobId).filter((id) => !ctx.cache.has(id));
|
|
781
|
+
if (ids.length === 0) return /* @__PURE__ */ new Map();
|
|
782
|
+
const metaOnly = ctx.metaOnly === true;
|
|
783
|
+
const reads = await readBlobs(ctx.blobs, ids, metaOnly);
|
|
784
|
+
if (!metaOnly) {
|
|
785
|
+
for (const [id, r] of reads) {
|
|
786
|
+
if (r.ok && r.data !== void 0) ctx.cache.set(id, { data: r.data, meta: r.meta });
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
return reads;
|
|
790
|
+
}
|
|
791
|
+
function judgeImageRef(ref, ctx, reads) {
|
|
792
|
+
if (ctx.blobs === void 0) return imageRefNotFound(ref.blobId);
|
|
793
|
+
let meta;
|
|
794
|
+
const cached = ctx.cache.get(ref.blobId);
|
|
795
|
+
if (cached !== void 0) meta = cached.meta;
|
|
796
|
+
else {
|
|
797
|
+
const read = reads.get(ref.blobId);
|
|
798
|
+
if (read === void 0) throw new Error(`internal: blob ${ref.blobId} was not prefetched`);
|
|
799
|
+
if (!read.ok) {
|
|
800
|
+
if (isNotFound(read.error)) return imageRefNotFound(ref.blobId);
|
|
801
|
+
throw read.error;
|
|
802
|
+
}
|
|
803
|
+
meta = read.meta;
|
|
804
|
+
}
|
|
805
|
+
if (!blobUsableBy(ctx.sessionId, meta, ref.blobId, ctx.timeline)) return imageRefNotFound(ref.blobId);
|
|
806
|
+
if (meta.mime !== ref.mime) return imageRefNotFound(ref.blobId);
|
|
807
|
+
return void 0;
|
|
808
|
+
}
|
|
729
809
|
async function hydrateImageRefs(events, ctx) {
|
|
810
|
+
let reads = /* @__PURE__ */ new Map();
|
|
811
|
+
if (ctx.blobs !== void 0) {
|
|
812
|
+
const ids = [];
|
|
813
|
+
for (const e of events) {
|
|
814
|
+
const parts = contentOf(e);
|
|
815
|
+
if (!Array.isArray(parts)) continue;
|
|
816
|
+
for (const p of imageRefsIn(parts)) if (!ctx.cache.has(p.blobId)) ids.push(p.blobId);
|
|
817
|
+
}
|
|
818
|
+
if (ids.length > 0) reads = await readBlobs(ctx.blobs, ids, false);
|
|
819
|
+
for (const [id, r] of reads) {
|
|
820
|
+
if (r.ok && r.data !== void 0) ctx.cache.set(id, { data: r.data, meta: r.meta });
|
|
821
|
+
}
|
|
822
|
+
}
|
|
730
823
|
const out = [];
|
|
731
824
|
for (const e of events) {
|
|
732
825
|
const parts = contentOf(e);
|
|
@@ -740,26 +833,56 @@ async function hydrateImageRefs(events, ctx) {
|
|
|
740
833
|
next.push(p);
|
|
741
834
|
continue;
|
|
742
835
|
}
|
|
743
|
-
const data =
|
|
836
|
+
const data = hydratedData(p.blobId, ctx.cache, reads);
|
|
744
837
|
next.push(data === void 0 ? p : { type: "image", mime: p.mime, data });
|
|
745
838
|
}
|
|
746
839
|
out.push({ ...e, payload: { ...e.payload, content: next } });
|
|
747
840
|
}
|
|
748
841
|
return out;
|
|
749
842
|
}
|
|
750
|
-
|
|
751
|
-
const cached =
|
|
843
|
+
function hydratedData(id, cache, reads) {
|
|
844
|
+
const cached = cache.get(id);
|
|
752
845
|
if (cached !== void 0) return cached.data;
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
846
|
+
const read = reads.get(id);
|
|
847
|
+
if (read === void 0 || read.ok || isNotFound(read.error)) return void 0;
|
|
848
|
+
throw read.error;
|
|
849
|
+
}
|
|
850
|
+
var BLOB_READ_CONCURRENCY = 16;
|
|
851
|
+
async function readBlobs(blobs, ids, metaOnly) {
|
|
852
|
+
const queue = [...new Set(ids)];
|
|
853
|
+
const out = /* @__PURE__ */ new Map();
|
|
854
|
+
let next = 0;
|
|
855
|
+
const worker = async () => {
|
|
856
|
+
while (next < queue.length) {
|
|
857
|
+
const id = queue[next++];
|
|
858
|
+
try {
|
|
859
|
+
out.set(id, { ok: true, ...await readOne(blobs, id, metaOnly) });
|
|
860
|
+
} catch (error) {
|
|
861
|
+
out.set(id, { ok: false, error });
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
await Promise.all(Array.from({ length: Math.min(BLOB_READ_CONCURRENCY, queue.length) }, worker));
|
|
866
|
+
return out;
|
|
867
|
+
}
|
|
868
|
+
async function readOne(blobs, id, metaOnly) {
|
|
869
|
+
if (metaOnly && blobs.stat !== void 0) {
|
|
870
|
+
const meta = await blobs.stat(id);
|
|
871
|
+
if (!isObject(meta)) throw blobNotFound(id);
|
|
872
|
+
return { meta };
|
|
762
873
|
}
|
|
874
|
+
const got = await blobs.get(id);
|
|
875
|
+
if (!isObject(got) || !isObject(got.meta)) throw blobNotFound(id);
|
|
876
|
+
return metaOnly ? { meta: got.meta } : { meta: got.meta, data: bytesToBase64(got.bytes) };
|
|
877
|
+
}
|
|
878
|
+
function isObject(x) {
|
|
879
|
+
return typeof x === "object" && x !== null;
|
|
880
|
+
}
|
|
881
|
+
function blobNotFound(id) {
|
|
882
|
+
return new StoreError("not_found", `blob not found: ${id}`, { id });
|
|
883
|
+
}
|
|
884
|
+
function isNotFound(err) {
|
|
885
|
+
return err instanceof StoreError && err.code === "not_found";
|
|
763
886
|
}
|
|
764
887
|
var BASE64_CHUNK = 32768;
|
|
765
888
|
function bytesToBase64(bytes) {
|
|
@@ -836,6 +959,8 @@ var LoweringError = class extends Error {
|
|
|
836
959
|
var STOPPED_NOTE = "stopped by the user";
|
|
837
960
|
var STOPPED_NOT_EXECUTED_TEXT = "Not executed: the run was stopped by the user before this call started.";
|
|
838
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.";
|
|
839
964
|
var INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: an earlier run was interrupted before this call started.";
|
|
840
965
|
var INTERRUPTED_IN_PROGRESS_TEXT = "Interrupted: an earlier run was interrupted while this call was in progress; it may have partly taken effect.";
|
|
841
966
|
var OUTCOME_UNKNOWN_TEXT = "Execution was interrupted before a result was recorded; the outcome is unknown. Check the current state before retrying.";
|
|
@@ -1038,6 +1163,15 @@ function deferredToolSpecOf(tool, deferred) {
|
|
|
1038
1163
|
function isDuration(x) {
|
|
1039
1164
|
return x === void 0 || typeof x === "number" && Number.isFinite(x) && x > 0;
|
|
1040
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
|
+
}
|
|
1041
1175
|
function isContentPart(x) {
|
|
1042
1176
|
if (typeof x !== "object" || x === null) return false;
|
|
1043
1177
|
const p = x;
|
|
@@ -1045,8 +1179,9 @@ function isContentPart(x) {
|
|
|
1045
1179
|
case "text":
|
|
1046
1180
|
return typeof p.text === "string";
|
|
1047
1181
|
case "image":
|
|
1182
|
+
if (!isSupportedImageMime(p.mime)) return false;
|
|
1048
1183
|
if (p.blobId !== void 0) return isImageRef(p);
|
|
1049
|
-
return typeof p.
|
|
1184
|
+
return typeof p.data === "string";
|
|
1050
1185
|
case "video":
|
|
1051
1186
|
case "audio":
|
|
1052
1187
|
return typeof p.mime === "string" && p.mime.startsWith(`${p.type}/`) && typeof p.data === "string" && isDuration(p.durationSec);
|
|
@@ -1056,16 +1191,40 @@ function isContentPart(x) {
|
|
|
1056
1191
|
return false;
|
|
1057
1192
|
}
|
|
1058
1193
|
}
|
|
1059
|
-
function
|
|
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) {
|
|
1060
1198
|
if (typeof x !== "object" || x === null) return false;
|
|
1061
|
-
const
|
|
1062
|
-
return
|
|
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;
|
|
1063
1213
|
}
|
|
1064
1214
|
function normalizeToolOutput(output) {
|
|
1065
1215
|
if (typeof output === "string") return { content: [{ type: "text", text: output }] };
|
|
1066
1216
|
if (output === void 0 || output === null) return { content: [{ type: "text", text: "" }] };
|
|
1067
|
-
if (Array.isArray(output)
|
|
1068
|
-
|
|
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
|
+
}
|
|
1069
1228
|
const json = JSON.stringify(output);
|
|
1070
1229
|
return { content: [{ type: "text", text: typeof json === "string" ? json : String(output) }] };
|
|
1071
1230
|
}
|
|
@@ -1374,6 +1533,28 @@ async function validateResume(input) {
|
|
|
1374
1533
|
}
|
|
1375
1534
|
return pending;
|
|
1376
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
|
+
}
|
|
1377
1558
|
|
|
1378
1559
|
// src/loop/static.ts
|
|
1379
1560
|
async function resolve(contribution, setup) {
|
|
@@ -1655,6 +1836,34 @@ function describe(value) {
|
|
|
1655
1836
|
function isInputArray(input) {
|
|
1656
1837
|
return Array.isArray(input);
|
|
1657
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
|
+
}
|
|
1658
1867
|
function draftParts(draft) {
|
|
1659
1868
|
if (draft.type !== "core.user_message" && draft.type !== "core.tool_result") return [];
|
|
1660
1869
|
return draft.payload.content;
|
|
@@ -1673,6 +1882,10 @@ async function* runLoop(cfg) {
|
|
|
1673
1882
|
if (!registry.has(d.type)) throw new RangeError(`input draft type ${d.type} is not registered`);
|
|
1674
1883
|
}
|
|
1675
1884
|
const capabilities = lowering.capabilities(model);
|
|
1885
|
+
resolveReserveTokens({
|
|
1886
|
+
contextLimit: capabilities.contextWindow,
|
|
1887
|
+
...cfg.projection?.reserveTokens !== void 0 ? { reserveTokens: cfg.projection.reserveTokens } : {}
|
|
1888
|
+
});
|
|
1676
1889
|
const configHash = await computeConfigHash({
|
|
1677
1890
|
model,
|
|
1678
1891
|
tools: baseTools,
|
|
@@ -1681,16 +1894,15 @@ async function* runLoop(cfg) {
|
|
|
1681
1894
|
const startedAt = now();
|
|
1682
1895
|
const startTimeline = await readTimeline(log, sessionId, { registry });
|
|
1683
1896
|
let lastSeq = startTimeline.at(-1)?.seq ?? 0;
|
|
1897
|
+
checkInputToolResults(input, startTimeline);
|
|
1684
1898
|
const imageCache = /* @__PURE__ */ new Map();
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
if (problem !== void 0) throw new RangeError(problem);
|
|
1693
|
-
}
|
|
1899
|
+
const startProblem = await checkImageRefs(input.flatMap(draftParts), {
|
|
1900
|
+
sessionId,
|
|
1901
|
+
blobs: cfg.blobs,
|
|
1902
|
+
timeline: startTimeline,
|
|
1903
|
+
cache: imageCache
|
|
1904
|
+
});
|
|
1905
|
+
if (startProblem !== void 0) throw new RangeError(startProblem);
|
|
1694
1906
|
let turns = 0;
|
|
1695
1907
|
let tokensSpent = 0;
|
|
1696
1908
|
let toolCallsTotal = 0;
|
|
@@ -1767,12 +1979,13 @@ async function* runLoop(cfg) {
|
|
|
1767
1979
|
tokensSpent += usage.input + usage.output;
|
|
1768
1980
|
ctx.budget.tokensSpent = tokensSpent;
|
|
1769
1981
|
};
|
|
1770
|
-
const fail = async (payload) => {
|
|
1982
|
+
const fail = async (payload, settle = []) => {
|
|
1771
1983
|
const events = await append([
|
|
1984
|
+
...settle,
|
|
1772
1985
|
{ type: "core.error", actor: "system", payload },
|
|
1773
1986
|
{ type: "core.run_ended", actor: "system", payload: { status: "error", category: payload.category } }
|
|
1774
1987
|
]);
|
|
1775
|
-
const error = events[
|
|
1988
|
+
const error = events[settle.length];
|
|
1776
1989
|
return { events, result: { status: "error", sessionId, lastSeq, error } };
|
|
1777
1990
|
};
|
|
1778
1991
|
const ownDecisions = (cfg.decisions ?? []).filter(
|
|
@@ -1796,19 +2009,7 @@ async function* runLoop(cfg) {
|
|
|
1796
2009
|
...cfg.allowConfigDrift !== void 0 ? { allowConfigDrift: cfg.allowConfigDrift } : {}
|
|
1797
2010
|
});
|
|
1798
2011
|
}
|
|
1799
|
-
|
|
1800
|
-
const pendingIds = new Set(pendingToolCalls(timeline).map((c) => c.payload.toolCallId));
|
|
1801
|
-
for (const d of decisions) {
|
|
1802
|
-
if (!pendingIds.has(d.toolCallId)) {
|
|
1803
|
-
throw new RunStateError(
|
|
1804
|
-
"unknown_tool_call",
|
|
1805
|
-
`approval decision refers to call ${d.toolCallId}, which is not pending`,
|
|
1806
|
-
{
|
|
1807
|
-
toolCallId: d.toolCallId
|
|
1808
|
-
}
|
|
1809
|
-
);
|
|
1810
|
-
}
|
|
1811
|
-
}
|
|
2012
|
+
assertDecisionsAwaitApproval({ sessionId, timeline, decisions: ownDecisions });
|
|
1812
2013
|
}
|
|
1813
2014
|
if (!cfg.signal?.aborted) {
|
|
1814
2015
|
yield* await append(
|
|
@@ -1883,10 +2084,9 @@ async function* runLoop(cfg) {
|
|
|
1883
2084
|
pulled = [];
|
|
1884
2085
|
problem = describeThrown(err);
|
|
1885
2086
|
}
|
|
1886
|
-
|
|
1887
|
-
if (problem !== void 0 || storageFailure !== void 0) break;
|
|
2087
|
+
if (problem === void 0) {
|
|
1888
2088
|
try {
|
|
1889
|
-
problem = await checkImageRefs(draftParts
|
|
2089
|
+
problem = await checkImageRefs(pulled.flatMap(draftParts), {
|
|
1890
2090
|
sessionId,
|
|
1891
2091
|
blobs: cfg.blobs,
|
|
1892
2092
|
timeline,
|
|
@@ -1987,9 +2187,9 @@ async function* runLoop(cfg) {
|
|
|
1987
2187
|
imageCache
|
|
1988
2188
|
});
|
|
1989
2189
|
toolCallsTotal += settled.executed;
|
|
1990
|
-
if (settled.interruptions.length > 0 || isStopped(cfg.signal)) {
|
|
1991
|
-
const
|
|
1992
|
-
const { events, result } = await pause(
|
|
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);
|
|
1993
2193
|
yield* events;
|
|
1994
2194
|
return result;
|
|
1995
2195
|
}
|
|
@@ -2022,12 +2222,14 @@ async function* runLoop(cfg) {
|
|
|
2022
2222
|
}
|
|
2023
2223
|
const injected = await flush();
|
|
2024
2224
|
yield* injected;
|
|
2025
|
-
visible = [...visible, ...injected.filter((e) => !
|
|
2225
|
+
visible = [...visible, ...injected.filter((e) => !isModelInvisibleByDefault(e.type))];
|
|
2026
2226
|
ctx.events = visible;
|
|
2027
2227
|
ctx.tools = tools;
|
|
2228
|
+
const sentEstimate = estimateTotal(visible, cfg.projection?.estimate ?? roughTokenEstimate);
|
|
2028
2229
|
let outcome;
|
|
2029
2230
|
const modelEvents = [];
|
|
2030
2231
|
let hydrated;
|
|
2232
|
+
const usedCallIds = toolCallIdsOf(timeline);
|
|
2031
2233
|
for (let attempt = 1; ; attempt++) {
|
|
2032
2234
|
let failure;
|
|
2033
2235
|
let attemptOutput = 0;
|
|
@@ -2051,7 +2253,7 @@ async function* runLoop(cfg) {
|
|
|
2051
2253
|
outcome = step.value;
|
|
2052
2254
|
break;
|
|
2053
2255
|
}
|
|
2054
|
-
const appended = await append([step.value]);
|
|
2256
|
+
const appended = await append([withUniqueToolCallId(step.value, usedCallIds, () => newId(now()))]);
|
|
2055
2257
|
modelEvents.push(...appended);
|
|
2056
2258
|
attemptOutput += appended.length;
|
|
2057
2259
|
yield* appended;
|
|
@@ -2080,22 +2282,28 @@ async function* runLoop(cfg) {
|
|
|
2080
2282
|
detail: { usage: outcome?.usage }
|
|
2081
2283
|
};
|
|
2082
2284
|
if (!canRetry && cfg.signal?.aborted) {
|
|
2285
|
+
const dropped = await append(droppedCallResults(modelEvents, cfg.signal));
|
|
2083
2286
|
const { events, result } = await pause("host", [
|
|
2084
2287
|
{ kind: "host", note: "host aborted the model request" }
|
|
2085
2288
|
]);
|
|
2289
|
+
yield* dropped;
|
|
2086
2290
|
yield* events;
|
|
2087
2291
|
return result;
|
|
2088
2292
|
}
|
|
2089
2293
|
if (!canRetry) {
|
|
2090
|
-
const
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
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
|
+
);
|
|
2099
2307
|
yield* events;
|
|
2100
2308
|
return result;
|
|
2101
2309
|
}
|
|
@@ -2127,9 +2335,11 @@ async function* runLoop(cfg) {
|
|
|
2127
2335
|
for (const s of sockets) await s.afterModel?.(ctx, modelEvents);
|
|
2128
2336
|
yield* await flush();
|
|
2129
2337
|
if (outcome.stopReason === "aborted") {
|
|
2338
|
+
const dropped = await append(droppedCallResults(modelEvents, cfg.signal));
|
|
2130
2339
|
const { events, result } = await pause("host", [
|
|
2131
2340
|
{ kind: "host", note: "host aborted the model response" }
|
|
2132
2341
|
]);
|
|
2342
|
+
yield* dropped;
|
|
2133
2343
|
yield* events;
|
|
2134
2344
|
return result;
|
|
2135
2345
|
}
|
|
@@ -2158,11 +2368,12 @@ async function* runLoop(cfg) {
|
|
|
2158
2368
|
tokens: outcome.usage,
|
|
2159
2369
|
toolCalls: calls.length,
|
|
2160
2370
|
wallMs: now() - turnStartedAt,
|
|
2161
|
-
contextEstimate:
|
|
2371
|
+
contextEstimate: sentEstimate
|
|
2162
2372
|
}
|
|
2163
2373
|
}
|
|
2164
2374
|
]);
|
|
2165
|
-
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));
|
|
2166
2377
|
const { events, result } = await pause(pauseReasonOf(interruptions), interruptions);
|
|
2167
2378
|
yield* events;
|
|
2168
2379
|
return result;
|
|
@@ -2171,6 +2382,7 @@ async function* runLoop(cfg) {
|
|
|
2171
2382
|
if (ended) return ended;
|
|
2172
2383
|
}
|
|
2173
2384
|
async function* endTurn(ctx, fallback, flush) {
|
|
2385
|
+
ctx.budget.wallMs = now() - startedAt;
|
|
2174
2386
|
let decision = fallback;
|
|
2175
2387
|
for (const s of sockets) {
|
|
2176
2388
|
const d = await s.onTurnEnd?.(ctx);
|
|
@@ -2196,7 +2408,7 @@ async function* runLoop(cfg) {
|
|
|
2196
2408
|
}
|
|
2197
2409
|
const intent = decision.handoff;
|
|
2198
2410
|
const toSessionId = intent.toSessionId ?? newId(now());
|
|
2199
|
-
|
|
2411
|
+
const handoffEvents = await append([
|
|
2200
2412
|
{
|
|
2201
2413
|
type: "core.handoff",
|
|
2202
2414
|
actor: intent.by ?? "model",
|
|
@@ -2208,23 +2420,17 @@ async function* runLoop(cfg) {
|
|
|
2208
2420
|
}
|
|
2209
2421
|
}
|
|
2210
2422
|
]);
|
|
2423
|
+
yield* handoffEvents;
|
|
2211
2424
|
const at = now();
|
|
2212
|
-
const opening =
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
opening.push({
|
|
2218
|
-
type: "core.user_message",
|
|
2219
|
-
actor: "user",
|
|
2220
|
-
payload: { content: [{ type: "text", text: intent.triggerMessage }] }
|
|
2221
|
-
});
|
|
2222
|
-
}
|
|
2425
|
+
const opening = handoffOpeningDrafts(
|
|
2426
|
+
intent,
|
|
2427
|
+
handoffEvents[0],
|
|
2428
|
+
await readTimeline(log, sessionId, { registry })
|
|
2429
|
+
);
|
|
2223
2430
|
const openingEvents = opening.map(
|
|
2224
2431
|
(d, i) => createEvent(registry, { ...d, sessionId: toSessionId, seq: i + 1, at, id: newId(at) })
|
|
2225
2432
|
);
|
|
2226
2433
|
await log.append(openingEvents);
|
|
2227
|
-
yield* openingEvents;
|
|
2228
2434
|
yield* await append([
|
|
2229
2435
|
{ type: "core.run_ended", actor: "system", payload: { status: "handoff", toSessionId } }
|
|
2230
2436
|
]);
|
|
@@ -2232,6 +2438,59 @@ async function* runLoop(cfg) {
|
|
|
2232
2438
|
return { status: "handoff", sessionId, lastSeq, toSessionId };
|
|
2233
2439
|
}
|
|
2234
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
|
+
}
|
|
2235
2494
|
function pauseReasonOf(interruptions) {
|
|
2236
2495
|
const reasons = interruptions.map(
|
|
2237
2496
|
(i) => i.kind === "subagent" ? i.reason : i.kind === "client_tool" ? "host" : i.kind
|
|
@@ -2256,6 +2515,7 @@ function withResultTrust(input, tools) {
|
|
|
2256
2515
|
const tool = tools.find((t) => t.name === payload?.name);
|
|
2257
2516
|
return { ...input, ...withTrust(toolResultTrust(tool, payload?.isError === true)) };
|
|
2258
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.`;
|
|
2259
2519
|
async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
2260
2520
|
const { cfg, sockets, flush, forwardedDecisions, spend, batch, imageCache } = deps;
|
|
2261
2521
|
const append = async (drafts) => {
|
|
@@ -2295,6 +2555,10 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
|
2295
2555
|
yield* await append([errorResult(`Approval denied${decided.reason ? `: ${decided.reason}` : ""}`)]);
|
|
2296
2556
|
continue;
|
|
2297
2557
|
}
|
|
2558
|
+
if (!tool && batch.resumed) {
|
|
2559
|
+
yield* await settle(errorResult(toolUnavailableOnResumeText(name)));
|
|
2560
|
+
continue;
|
|
2561
|
+
}
|
|
2298
2562
|
let args = call.payload.args;
|
|
2299
2563
|
let seen = call;
|
|
2300
2564
|
let verdict = "proceed";
|
|
@@ -2338,7 +2602,23 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
|
2338
2602
|
};
|
|
2339
2603
|
let approval = typeof verdict === "object" && "defer" in verdict ? verdict.defer : void 0;
|
|
2340
2604
|
if (!approval && !decided?.approved && tool.needsApproval !== void 0) {
|
|
2341
|
-
|
|
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
|
+
}
|
|
2342
2622
|
if (need) {
|
|
2343
2623
|
approval = { policyId: BUILTIN_APPROVAL_POLICY, summary: `${name}(${JSON.stringify(args) ?? ""})` };
|
|
2344
2624
|
}
|
|
@@ -2421,6 +2701,8 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
|
2421
2701
|
return summary;
|
|
2422
2702
|
}
|
|
2423
2703
|
async function checkToolResultRefs(parts, ctx) {
|
|
2704
|
+
if (!parts.some(isImageRef)) return { content: parts, storageFailures: [] };
|
|
2705
|
+
const reads = await prefetchImageRefs(parts, ctx);
|
|
2424
2706
|
const storageFailures = [];
|
|
2425
2707
|
let changed = false;
|
|
2426
2708
|
const content = [];
|
|
@@ -2431,7 +2713,7 @@ async function checkToolResultRefs(parts, ctx) {
|
|
|
2431
2713
|
}
|
|
2432
2714
|
let text;
|
|
2433
2715
|
try {
|
|
2434
|
-
text =
|
|
2716
|
+
text = judgeImageRef(p, ctx, reads);
|
|
2435
2717
|
} catch (err) {
|
|
2436
2718
|
text = `Could not read blob ${p.blobId}: storage error`;
|
|
2437
2719
|
storageFailures.push({
|
|
@@ -2549,6 +2831,28 @@ function untrustedOpenTag(source) {
|
|
|
2549
2831
|
return `<${UNTRUSTED_TAG} source="${source.replace(/"/g, """)}">`;
|
|
2550
2832
|
}
|
|
2551
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
|
+
}
|
|
2552
2856
|
function markUntrustedText(text, source) {
|
|
2553
2857
|
const e = escapeUntrustedText(text);
|
|
2554
2858
|
return { text: `${untrustedOpenTag(source)}
|
|
@@ -2558,6 +2862,11 @@ ${UNTRUSTED_CLOSE_TAG}`, escaped: e.escaped };
|
|
|
2558
2862
|
function markUntrusted(parts, source) {
|
|
2559
2863
|
let escaped = false;
|
|
2560
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
|
+
}
|
|
2561
2870
|
if (p.type !== "text") return p;
|
|
2562
2871
|
const e = escapeUntrustedText(p.text);
|
|
2563
2872
|
escaped = escaped || e.escaped;
|
|
@@ -2661,6 +2970,11 @@ var InMemoryBlobStore = class {
|
|
|
2661
2970
|
if (!hit) throw new StoreError("not_found", `blob not found: ${id}`, { id });
|
|
2662
2971
|
return { bytes: hit.bytes.slice(), meta: { ...hit.meta } };
|
|
2663
2972
|
}
|
|
2973
|
+
async stat(id) {
|
|
2974
|
+
const hit = this.blobs.get(id);
|
|
2975
|
+
if (!hit) throw new StoreError("not_found", `blob not found: ${id}`, { id });
|
|
2976
|
+
return { ...hit.meta };
|
|
2977
|
+
}
|
|
2664
2978
|
async slice(id, range) {
|
|
2665
2979
|
const { bytes } = await this.get(id);
|
|
2666
2980
|
return bytes.slice(Math.max(0, range.start), Math.min(bytes.byteLength, range.end));
|
|
@@ -2714,7 +3028,7 @@ function memoryStore() {
|
|
|
2714
3028
|
}
|
|
2715
3029
|
|
|
2716
3030
|
// src/index.ts
|
|
2717
|
-
var REINS_VERSION = "0.
|
|
3031
|
+
var REINS_VERSION = "0.18.0";
|
|
2718
3032
|
export {
|
|
2719
3033
|
BUILTIN_APPROVAL_POLICY,
|
|
2720
3034
|
CORE_SCHEMAS,
|
|
@@ -2727,6 +3041,7 @@ export {
|
|
|
2727
3041
|
DEFAULT_RETRY_MAX_DELAY_MS,
|
|
2728
3042
|
DEFAULT_TRUST,
|
|
2729
3043
|
EventSchemaRegistry,
|
|
3044
|
+
HANDOFF_PROVENANCE_SOURCE,
|
|
2730
3045
|
IMAGE_REF_ID_MAX,
|
|
2731
3046
|
INPUT_DRAFT_TYPES,
|
|
2732
3047
|
INTERRUPTED_IN_PROGRESS_TEXT,
|
|
@@ -2737,6 +3052,8 @@ export {
|
|
|
2737
3052
|
InMemoryRunLease,
|
|
2738
3053
|
LoweringError,
|
|
2739
3054
|
MAX_TURNS_PAUSE_CODE,
|
|
3055
|
+
MODEL_FAILED_NOT_EXECUTED_TEXT,
|
|
3056
|
+
MODEL_INTERRUPTED_NOT_EXECUTED_TEXT,
|
|
2740
3057
|
OUTCOME_UNKNOWN_TEXT,
|
|
2741
3058
|
PAUSE_CODE_RE,
|
|
2742
3059
|
REINS_VERSION,
|
|
@@ -2746,10 +3063,12 @@ export {
|
|
|
2746
3063
|
STOPPED_IN_PROGRESS_TEXT,
|
|
2747
3064
|
STOPPED_NOTE,
|
|
2748
3065
|
STOPPED_NOT_EXECUTED_TEXT,
|
|
3066
|
+
SUPPORTED_IMAGE_MIMES,
|
|
2749
3067
|
SchemaError,
|
|
2750
3068
|
StoreError,
|
|
2751
3069
|
UNTRUSTED_CLOSE_TAG,
|
|
2752
3070
|
UNTRUSTED_TAG,
|
|
3071
|
+
assertDecisionsAwaitApproval,
|
|
2753
3072
|
assertRunStateShape,
|
|
2754
3073
|
awaitingOf,
|
|
2755
3074
|
backoffDelayMs,
|
|
@@ -2784,6 +3103,7 @@ export {
|
|
|
2784
3103
|
foldedToolResults,
|
|
2785
3104
|
foldedUserMedia,
|
|
2786
3105
|
forkSession,
|
|
3106
|
+
handoffOpeningDrafts,
|
|
2787
3107
|
hydrateImageRefs,
|
|
2788
3108
|
imageRefNotFound,
|
|
2789
3109
|
inputDrafts,
|
|
@@ -2791,6 +3111,7 @@ export {
|
|
|
2791
3111
|
isCompaction,
|
|
2792
3112
|
isContentPart,
|
|
2793
3113
|
isImageRef,
|
|
3114
|
+
isModelInvisibleByDefault,
|
|
2794
3115
|
isModelOutput,
|
|
2795
3116
|
isPauseCode,
|
|
2796
3117
|
isPinNote,
|
|
@@ -2798,6 +3119,7 @@ export {
|
|
|
2798
3119
|
isStopReason,
|
|
2799
3120
|
isStopped,
|
|
2800
3121
|
isSubagentPause,
|
|
3122
|
+
isSupportedImageMime,
|
|
2801
3123
|
isTransientFailure,
|
|
2802
3124
|
keptBy,
|
|
2803
3125
|
lastRunMarker,
|
|
@@ -2822,6 +3144,7 @@ export {
|
|
|
2822
3144
|
renderToolChangeNote,
|
|
2823
3145
|
renderToolReference,
|
|
2824
3146
|
replayTurns,
|
|
3147
|
+
resolveReserveTokens,
|
|
2825
3148
|
resolveRetry,
|
|
2826
3149
|
resolveSocketContributions,
|
|
2827
3150
|
resolveSocketPause,
|
|
@@ -2842,6 +3165,7 @@ export {
|
|
|
2842
3165
|
toolSpecOf,
|
|
2843
3166
|
toolStartedAt,
|
|
2844
3167
|
toolsBoundDrafts,
|
|
3168
|
+
unsupportedImageText,
|
|
2845
3169
|
untrustedOpenTag,
|
|
2846
3170
|
untrustedSourceOf,
|
|
2847
3171
|
unwrapToolArguments,
|