@reinsjs/core 0.16.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/CHANGELOG.md +6 -0
- package/README.md +2 -0
- package/dist/{core-BxGiBJ_p.d.ts → core-2MZcObOK.d.ts} +8 -0
- package/dist/index.d.ts +19 -7
- package/dist/index.js +107 -43
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +20 -0
- package/dist/testing/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @reinsjs/core
|
|
2
2
|
|
|
3
|
+
## 0.17.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 420e0f7: Image references are read concurrently. Checking a batch of references (initial `input`, everything one `pullInput` returns, a whole tool result) and swapping the images in view before a model call each read the uncached blobs in one wave — up to 16 at a time, each id once — then judge them in their original order, so the first problem reported is the same as before. On object storage, ten new images now cost one round trip instead of ten. `BlobStore` gains an optional `stat(id): Promise<BlobMeta>` (metadata without bytes; must throw `StoreError("not_found")` for an unknown id and equal `get(id).meta`); the in-memory store implements it and `blobStoreConformance` checks it. `checkImageRefs` takes `metaOnly: true` to use `stat` when present and keep nothing in the cache — the HTTP handler uses it; the loop still decides with `get`. A `get` or `stat` that returns a non-object is treated as not found. Behaviour changes: when the same image appears twice in one tool result and the read fails transiently, both parts now get `storage error` (it is read once); after the first problem in a batch the remaining references are still read, so failing batches may read more than before. Successful batches read the same number of blobs as before.
|
|
8
|
+
|
|
3
9
|
## 0.16.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -135,6 +135,8 @@ An image can also be a reference: `{ type: "image", mime, blobId }`. The bytes l
|
|
|
135
135
|
- **Shape.** `mime` must start with `image/`; `blobId` is 1–128 characters; `data` and `blobId` never appear together. A spilled tool output (a text blob) can therefore never pass as an image.
|
|
136
136
|
- **When the bytes are gone.** If a referenced blob no longer exists (you deleted it, or there is no `BlobStore`), the lowering writes `[image unavailable]` in its place and records the event `lossy`; the run goes on. Any other storage error fails the model call like a network error (retried if transient), so the model never answers a placeholder because of a hiccup.
|
|
137
137
|
- **Blobs are immutable.** A `BlobStore` must never reuse an id or change bytes after `put`: "the log plus its blobs" is what the model saw. Replaying a session through a lowering (`replayTurns` + `toRequest`) needs the same `BlobStore` — call `hydrateImageRefs` first, as `examples/minimal/replay.ts` does.
|
|
138
|
+
- **Reads are concurrent.** Checking a batch of references and swapping the images in view each read the uncached blobs in one wave — up to 16 at a time, each id once — then judge them in order, so the first problem reported is the same as one-by-one reading would give. On object storage, ten new images cost one round trip instead of ten. Need a lower limit? Throttle inside your `BlobStore`.
|
|
139
|
+
- **Optional `stat(id)`.** A `BlobStore` may add `stat(id): Promise<BlobMeta>` that returns the metadata without the bytes. It must throw `StoreError("not_found")` for an unknown id (never return `null`) and must equal `get(id).meta`; `blobStoreConformance` checks both. Only the HTTP handler's pre-check uses it — the loop still decides with `get`, so the bytes sent to the provider and the check that let them into the log come from the same read. A `get` or `stat` that returns something other than an object is treated as not found.
|
|
138
140
|
- **Forks and cleanup.** `fork` copies events, not blobs; a forked session points at its parent's blobs. If you delete a parent session's blobs, references in its forks show as unavailable.
|
|
139
141
|
- **Only images.** Video and audio stay inline for now. The model has no separate "look again" tool: `recall({ seq })` brings back a folded message, and its result keeps the reference, so nothing is stored twice.
|
|
140
142
|
- **Paths without a `runLoop`.** The TanStack AI adapter neither checks nor loads blobs: a reference becomes `[image unavailable]` there (recorded `lossy`), and references in tool results are replaced with that text before they are logged. Hosts that call `toRequest` directly must call `hydrateImageRefs` themselves.
|
|
@@ -506,6 +506,14 @@ interface BlobStore {
|
|
|
506
506
|
start: number;
|
|
507
507
|
end: number;
|
|
508
508
|
}): Promise<Uint8Array>;
|
|
509
|
+
/**
|
|
510
|
+
* 可选:只取元信息、不读字节(对象存储上省一次整份下载)。合同:
|
|
511
|
+
* - 不存在必须抛 `StoreError("not_found")`,与 `get` 同一语义——**不能返回 null**(返回非对象会被当 not_found 处理,但请照合同写)
|
|
512
|
+
* - 返回值必须与 `get(id).meta` 逐字段一致(宿主若读独立登记表,登记表须与对象同批写入)
|
|
513
|
+
*
|
|
514
|
+
* 目前只有 server 的 HTTP 预校验用它;循环内写进日志前的最终裁决仍按 `get`,与发给厂商的字节出自同一次读取
|
|
515
|
+
*/
|
|
516
|
+
stat?(id: string): Promise<BlobMeta>;
|
|
509
517
|
}
|
|
510
518
|
/**
|
|
511
519
|
* 记忆后端:一个极简的文本 KV,键是路径。
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, B as BlobStore, c as BlobMeta, C as ContentPart, I as ImageRefPart, d as Interruption, e as ErrorPayload, L as LoopConfig, f as EventDraft, R as RunResult, P as PauseReason, A as AwaitingCall, g as Tool, h as EventSchemaRegistry, S as SerializedRunState, M as ModelRef, i as SubagentInterruption, j as ToolSpec, k as ToolResult, l as Trust, m as CoreEventOf, n as CoreEventDraft, o as ProjectionBudget, p as ProjectionStrategy, q as ProjectionContext, r as TokenEstimator, s as ProjectionResult, t as ProjectionStats, u as BudgetUsagePayload, v as ReadOptions, w as MemoryStore, x as RunLease, y as Stores } from './core-
|
|
2
|
-
export { z as Actor, D as AnyEvent, F as ApprovalDecisionInput, G as ApprovalDecisionPayload, H as ApprovalRequestPayload, J as ApprovalRequestSpec, K as AudioPart, N as BeforeModelPatch, O as BeforeToolDecision, Q as BoundModel, U as CORE_SCHEMAS, V as CompactionPayload, W as CoreEvent, X as CoreEventPayloads, Y as CoreEventType, Z as CreateEventInput, _ as DEFAULT_RETRY_BASE_DELAY_MS, $ as DEFAULT_RETRY_MAX_ATTEMPTS, a0 as DEFAULT_RETRY_MAX_DELAY_MS, a1 as DEFAULT_TRUST, a2 as ErrorEventPayload, a3 as EventBase, a4 as EventSchema, a5 as ExtEvent, a6 as HandoffIntent, a7 as HandoffPayload, a8 as ImageInlinePart, a9 as ImagePart, aa as LandingRecord, ab as LandingSpec, ac as LossKind, ad as LossMatrix, ae as LoweredRequest, af as Lowering, ag as LoweringCapabilities, ah as LoweringDelta, ai as LoweringOutcome, aj as LoweringStreamContext, ak as MaybePromise, al as MemoryOpPayload, am as ModelCallFailure, an as ModelTextPayload, ao as ModelThinkingPayload, ap as Principal, aq as ProjectionStep, ar as ProjectionStepStats, as as Provenance, at as PullInputContext, au as ResolvedRetry, av as RetryOptions, aw as RunEndedPayload, ax as RunPausedPayload, ay as RunResumedPayload, az as SchemaError, aA as SchemaErrorCode, aB as SessionInfo, aC as SkillSource, aD as Socket, aE as SocketSetup, aF as StaticContribution, aG as SystemNotePayload, aH as TextPart, aI as ToRequestInput, aJ as TokenUsage, aK as ToolBatch, aL as ToolCallPayload, aM as ToolContext, aN as ToolReferencePart, aO as ToolResultDraft, aP as ToolResultPayload, aQ as ToolSide, aR as ToolStartedPayload, aS as ToolsBoundPayload, aT as TurnContext, aU as TurnDecision, aV as Upcaster, aW as UserMessagePayload, aX as VideoPart, aY as backoffDelayMs, aZ as contextOverheadOf, a_ as contextTokensOf, a$ as createCoreEvent, b0 as createCoreRegistry, b1 as createEvent, b2 as defaultSleep, b3 as isTransientFailure, b4 as lossesOf, b5 as renderToolReference, b6 as resolveRetry, b7 as statusFromMessage } from './core-
|
|
1
|
+
import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, B as BlobStore, c as BlobMeta, C as ContentPart, I as ImageRefPart, d as Interruption, e as ErrorPayload, L as LoopConfig, f as EventDraft, R as RunResult, P as PauseReason, A as AwaitingCall, g as Tool, h as EventSchemaRegistry, S as SerializedRunState, M as ModelRef, i as SubagentInterruption, j as ToolSpec, k as ToolResult, l as Trust, m as CoreEventOf, n as CoreEventDraft, o as ProjectionBudget, p as ProjectionStrategy, q as ProjectionContext, r as TokenEstimator, s as ProjectionResult, t as ProjectionStats, u as BudgetUsagePayload, v as ReadOptions, w as MemoryStore, x as RunLease, y as Stores } from './core-2MZcObOK.js';
|
|
2
|
+
export { z as Actor, D as AnyEvent, F as ApprovalDecisionInput, G as ApprovalDecisionPayload, H as ApprovalRequestPayload, J as ApprovalRequestSpec, K as AudioPart, N as BeforeModelPatch, O as BeforeToolDecision, Q as BoundModel, U as CORE_SCHEMAS, V as CompactionPayload, W as CoreEvent, X as CoreEventPayloads, Y as CoreEventType, Z as CreateEventInput, _ as DEFAULT_RETRY_BASE_DELAY_MS, $ as DEFAULT_RETRY_MAX_ATTEMPTS, a0 as DEFAULT_RETRY_MAX_DELAY_MS, a1 as DEFAULT_TRUST, a2 as ErrorEventPayload, a3 as EventBase, a4 as EventSchema, a5 as ExtEvent, a6 as HandoffIntent, a7 as HandoffPayload, a8 as ImageInlinePart, a9 as ImagePart, aa as LandingRecord, ab as LandingSpec, ac as LossKind, ad as LossMatrix, ae as LoweredRequest, af as Lowering, ag as LoweringCapabilities, ah as LoweringDelta, ai as LoweringOutcome, aj as LoweringStreamContext, ak as MaybePromise, al as MemoryOpPayload, am as ModelCallFailure, an as ModelTextPayload, ao as ModelThinkingPayload, ap as Principal, aq as ProjectionStep, ar as ProjectionStepStats, as as Provenance, at as PullInputContext, au as ResolvedRetry, av as RetryOptions, aw as RunEndedPayload, ax as RunPausedPayload, ay as RunResumedPayload, az as SchemaError, aA as SchemaErrorCode, aB as SessionInfo, aC as SkillSource, aD as Socket, aE as SocketSetup, aF as StaticContribution, aG as SystemNotePayload, aH as TextPart, aI as ToRequestInput, aJ as TokenUsage, aK as ToolBatch, aL as ToolCallPayload, aM as ToolContext, aN as ToolReferencePart, aO as ToolResultDraft, aP as ToolResultPayload, aQ as ToolSide, aR as ToolStartedPayload, aS as ToolsBoundPayload, aT as TurnContext, aU as TurnDecision, aV as Upcaster, aW as UserMessagePayload, aX as VideoPart, aY as backoffDelayMs, aZ as contextOverheadOf, a_ as contextTokensOf, a$ as createCoreEvent, b0 as createCoreRegistry, b1 as createEvent, b2 as defaultSleep, b3 as isTransientFailure, b4 as lossesOf, b5 as renderToolReference, b6 as resolveRetry, b7 as statusFromMessage } from './core-2MZcObOK.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
|
|
@@ -51,6 +51,10 @@ declare function forkSession(log: EventLog, opts: ForkOptions): Promise<{
|
|
|
51
51
|
* 被折叠的图一个字节都不读。只有 not_found 留着引用(降级层落占位、记 lossy),其它存储错误抛出走模型调用失败的判定——
|
|
52
52
|
* 瞬时故障不能让模型对着占位作答、再把回答永久写进日志。
|
|
53
53
|
*
|
|
54
|
+
* 两件事的读取都走同一个并发池(`readBlobs`,2026-11-24 AdRate 建议 18):去重、在途 ≤ 16、等全部落定,
|
|
55
|
+
* 再按片段 / 视野原顺序判定——结局与串行逐个读完全一致,只是对象存储上 N 张图从 N 次往返变成一波。
|
|
56
|
+
* `get` / `stat` 返回的不是对象一律当 not_found(防探测,见 `readOne`)。
|
|
57
|
+
*
|
|
54
58
|
* 归属口径(`blobUsableBy`):blob 的 meta.sessionId 就是本会话,或本会话时间线里已被**图片引用**过
|
|
55
59
|
* (fork 出的会话凭此用父会话的图;recall 取回的结果里是引用,自然合规)。图片引用集合(`mediaRefsOf`)与
|
|
56
60
|
* brain `fetch_blob` 的外溢引用集合刻意分开:只被图片引用过的 blob 不能被 fetch_blob 读出字节,外溢 blob 也当不了图片。
|
|
@@ -91,11 +95,17 @@ interface CheckImageRefsContext {
|
|
|
91
95
|
/** 本会话时间线(归属判定"已引用过"那一支用;只在 blob 不归本会话时才扫) */
|
|
92
96
|
timeline: readonly Event[];
|
|
93
97
|
cache: ImageRefCache;
|
|
98
|
+
/**
|
|
99
|
+
* 只判归属与 mime、不留字节:存储有 `stat` 用 `stat`,否则退回 `get`;读到的不放进 cache。
|
|
100
|
+
* server 的 HTTP 预校验用(那份缓存用完即弃);循环内不传——写进日志前的最终裁决与发给厂商的字节出自同一次 `get`
|
|
101
|
+
*/
|
|
102
|
+
metaOnly?: boolean;
|
|
94
103
|
}
|
|
95
104
|
/**
|
|
96
105
|
* 校验一批片段里的图片引用。全部合规返回 undefined;任一不合规返回统一的那一句(`imageRefNotFound`)。
|
|
97
|
-
*
|
|
98
|
-
*
|
|
106
|
+
* 未缓存的 blob 先去重、并发读完,再**按片段顺序**逐个判、报第一个问题(与读取完成先后无关);
|
|
107
|
+
* 取到的字节放进 cache(`metaOnly` 时不放;缓存命中不再读存储,但归属与 mime 照判)。
|
|
108
|
+
* 存储抛的非 not_found 错误原样抛出(按片段顺序第一个),调用方按各自入口的口径处理
|
|
99
109
|
*/
|
|
100
110
|
declare function checkImageRefs(parts: readonly ContentPart[], ctx: CheckImageRefsContext): Promise<string | undefined>;
|
|
101
111
|
interface HydrateImageRefsContext {
|
|
@@ -104,9 +114,10 @@ interface HydrateImageRefsContext {
|
|
|
104
114
|
}
|
|
105
115
|
/**
|
|
106
116
|
* 视图里的图片引用换回内联(只碰 user_message / tool_result 的 content,其它事件原样返回同一对象)。
|
|
107
|
-
* -
|
|
117
|
+
* - 缓存里有的直接用;视野内未缓存的去重后并发 `get`(上限见 `BLOB_READ_CONCURRENCY`),读完按原顺序换回
|
|
108
118
|
* - `StoreError("not_found")` 与没配 BlobStore:片段保持引用形态交给降级层(落 `[image unavailable]` 占位、记 lossy),不进缓存
|
|
109
|
-
* -
|
|
119
|
+
* - 其它存储错误:读成功的先进缓存(重试只重读失败的),再按视野顺序抛第一个——循环把它当模型调用失败处理(走重试判定),
|
|
120
|
+
* 不让模型对着占位作答
|
|
110
121
|
*
|
|
111
122
|
* 换回后的事件只交给 `toRequest`,不回写日志、不回写 `ctx.events`(Socket 与估算看到的仍是引用)。
|
|
112
123
|
* 直接调 `toRequest` 的宿主(审计回放、探针)先过一遍它,降级层才看得到图
|
|
@@ -1040,6 +1051,7 @@ declare class InMemoryBlobStore implements BlobStore {
|
|
|
1040
1051
|
bytes: Uint8Array;
|
|
1041
1052
|
meta: BlobMeta;
|
|
1042
1053
|
}>;
|
|
1054
|
+
stat(id: string): Promise<BlobMeta>;
|
|
1043
1055
|
slice(id: string, range: {
|
|
1044
1056
|
start: number;
|
|
1045
1057
|
end: number;
|
|
@@ -1106,6 +1118,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
|
|
|
1106
1118
|
*/
|
|
1107
1119
|
|
|
1108
1120
|
/** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
|
|
1109
|
-
declare const REINS_VERSION = "0.
|
|
1121
|
+
declare const REINS_VERSION = "0.17.0";
|
|
1110
1122
|
|
|
1111
1123
|
export { AwaitingCall, BUILTIN_APPROVAL_POLICY, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CheckImageRefsContext, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, type DecodedToolArguments, type DefaultChainOptions, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type FoldedUserMedia, type ForkOptions, type HydrateImageRefsContext, IMAGE_REF_ID_MAX, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, type ImageRefCache, ImageRefPart, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, Interruption, LoopConfig, LoweringError, type LoweringErrorCode, MAX_TURNS_PAUSE_CODE, type MarkedContent, MemoryStore, ModelRef, OUTCOME_UNKNOWN_TEXT, PAUSE_CODE_RE, PauseReason, type ProjectOptions, ProjectionBudget, ProjectionContext, ProjectionResult, ProjectionStats, ProjectionStrategy, REINS_VERSION, RUN_MARKER_TYPES, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, RunLease, RunResult, RunStateError, type RunStateErrorCode, type RunStatus, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, SerializedRunState, type SocketPauseInterruption, type SocketPauseResolution, type StopTexts, StoreError, type StoreErrorCode, Stores, SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, TokenEstimator, Tool, ToolCallEvent, type ToolNamesDiff, ToolResult, ToolResultEvent, ToolSpec, type ToolsBoundEvent, Trust, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, awaitingOf, blobUsableBy, budgetTruncate, bytesToBase64, checkImageRefs, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, foldedUserMedia, forkSession, hydrateImageRefs, imageRefNotFound, inputDrafts, isClientTool, isCompaction, isContentPart, isImageRef, isModelOutput, isPauseCode, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, keptBy, lastRunMarker, lastToolsBound, markUntrusted, markUntrustedText, mediaRefsOf, memoryStore, needsUntrustedMark, normalizeToolOutput, outcomeUnknownText, pauseDetailOf, pausedStateOf, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderFoldedUserMedia, renderToolChangeNote, replayTurns, resolveSocketContributions, resolveSocketPause, roughTokenEstimate, runLoop, runStatusOf, serializeRunState, signRunState, splitTurns, startedToolCallIds, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolStartedAt, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter, withStartedAt };
|
package/dist/index.js
CHANGED
|
@@ -705,28 +705,58 @@ function imageRefNotFound(id) {
|
|
|
705
705
|
return `Blob ${id} not found in this session`;
|
|
706
706
|
}
|
|
707
707
|
async function checkImageRefs(parts, ctx) {
|
|
708
|
+
const reads = await prefetchImageRefs(parts, ctx);
|
|
708
709
|
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);
|
|
710
|
+
const problem = judgeImageRef(ref, ctx, reads);
|
|
711
|
+
if (problem !== void 0) return problem;
|
|
726
712
|
}
|
|
727
713
|
return void 0;
|
|
728
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
|
+
}
|
|
729
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
|
+
}
|
|
730
760
|
const out = [];
|
|
731
761
|
for (const e of events) {
|
|
732
762
|
const parts = contentOf(e);
|
|
@@ -740,26 +770,56 @@ async function hydrateImageRefs(events, ctx) {
|
|
|
740
770
|
next.push(p);
|
|
741
771
|
continue;
|
|
742
772
|
}
|
|
743
|
-
const data =
|
|
773
|
+
const data = hydratedData(p.blobId, ctx.cache, reads);
|
|
744
774
|
next.push(data === void 0 ? p : { type: "image", mime: p.mime, data });
|
|
745
775
|
}
|
|
746
776
|
out.push({ ...e, payload: { ...e.payload, content: next } });
|
|
747
777
|
}
|
|
748
778
|
return out;
|
|
749
779
|
}
|
|
750
|
-
|
|
751
|
-
const cached =
|
|
780
|
+
function hydratedData(id, cache, reads) {
|
|
781
|
+
const cached = cache.get(id);
|
|
752
782
|
if (cached !== void 0) return cached.data;
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
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 };
|
|
762
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";
|
|
763
823
|
}
|
|
764
824
|
var BASE64_CHUNK = 32768;
|
|
765
825
|
function bytesToBase64(bytes) {
|
|
@@ -1682,15 +1742,13 @@ async function* runLoop(cfg) {
|
|
|
1682
1742
|
const startTimeline = await readTimeline(log, sessionId, { registry });
|
|
1683
1743
|
let lastSeq = startTimeline.at(-1)?.seq ?? 0;
|
|
1684
1744
|
const imageCache = /* @__PURE__ */ new Map();
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
if (problem !== void 0) throw new RangeError(problem);
|
|
1693
|
-
}
|
|
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);
|
|
1694
1752
|
let turns = 0;
|
|
1695
1753
|
let tokensSpent = 0;
|
|
1696
1754
|
let toolCallsTotal = 0;
|
|
@@ -1883,10 +1941,9 @@ async function* runLoop(cfg) {
|
|
|
1883
1941
|
pulled = [];
|
|
1884
1942
|
problem = describeThrown(err);
|
|
1885
1943
|
}
|
|
1886
|
-
|
|
1887
|
-
if (problem !== void 0 || storageFailure !== void 0) break;
|
|
1944
|
+
if (problem === void 0) {
|
|
1888
1945
|
try {
|
|
1889
|
-
problem = await checkImageRefs(draftParts
|
|
1946
|
+
problem = await checkImageRefs(pulled.flatMap(draftParts), {
|
|
1890
1947
|
sessionId,
|
|
1891
1948
|
blobs: cfg.blobs,
|
|
1892
1949
|
timeline,
|
|
@@ -2421,6 +2478,8 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
|
2421
2478
|
return summary;
|
|
2422
2479
|
}
|
|
2423
2480
|
async function checkToolResultRefs(parts, ctx) {
|
|
2481
|
+
if (!parts.some(isImageRef)) return { content: parts, storageFailures: [] };
|
|
2482
|
+
const reads = await prefetchImageRefs(parts, ctx);
|
|
2424
2483
|
const storageFailures = [];
|
|
2425
2484
|
let changed = false;
|
|
2426
2485
|
const content = [];
|
|
@@ -2431,7 +2490,7 @@ async function checkToolResultRefs(parts, ctx) {
|
|
|
2431
2490
|
}
|
|
2432
2491
|
let text;
|
|
2433
2492
|
try {
|
|
2434
|
-
text =
|
|
2493
|
+
text = judgeImageRef(p, ctx, reads);
|
|
2435
2494
|
} catch (err) {
|
|
2436
2495
|
text = `Could not read blob ${p.blobId}: storage error`;
|
|
2437
2496
|
storageFailures.push({
|
|
@@ -2661,6 +2720,11 @@ var InMemoryBlobStore = class {
|
|
|
2661
2720
|
if (!hit) throw new StoreError("not_found", `blob not found: ${id}`, { id });
|
|
2662
2721
|
return { bytes: hit.bytes.slice(), meta: { ...hit.meta } };
|
|
2663
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
|
+
}
|
|
2664
2728
|
async slice(id, range) {
|
|
2665
2729
|
const { bytes } = await this.get(id);
|
|
2666
2730
|
return bytes.slice(Math.max(0, range.start), Math.min(bytes.byteLength, range.end));
|
|
@@ -2714,7 +2778,7 @@ function memoryStore() {
|
|
|
2714
2778
|
}
|
|
2715
2779
|
|
|
2716
2780
|
// src/index.ts
|
|
2717
|
-
var REINS_VERSION = "0.
|
|
2781
|
+
var REINS_VERSION = "0.17.0";
|
|
2718
2782
|
export {
|
|
2719
2783
|
BUILTIN_APPROVAL_POLICY,
|
|
2720
2784
|
CORE_SCHEMAS,
|