@reinsjs/core 0.3.0 → 0.5.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 CHANGED
@@ -1,5 +1,19 @@
1
1
  # @reinsjs/core
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0455c28: Deliver `compact`'s request as a directive and ask twice. `SystemNotePayload` gains an optional `directive: true` for notes that ask the model to act; `@reinsjs/lowering-fetch` (all three protocols) and `@reinsjs/lowering-pi` send those as a framed `<system_note>` user message even when the model accepts mid-conversation system messages, and record the landing as `lossy(user-role)`. Measured on a pooled DeepSeek relay, the same request was ignored 4 of 4 times as a mid-conversation system message and followed 5 of 6 times as a framed user note; the official DeepSeek endpoint followed it 6 of 6 either way. Other notes (perception, pins) keep their current landing, and notes already in a log keep theirs, so cached prefixes do not change on upgrade. `compact({ force })` now asks at two lines by default (`at: [0.75, 0.8]`; a single number still works), uses blunter wording on the second request (`CompactRequestInfo.attempt`), skips the turn right after a compaction until the model has acted, and marks requests as directives unless `force.directive` is `false`.
8
+ - 24ba407: Ask the model to compact before the mechanical fallback kicks in. When the real context passes a soft line (`compact({ force: { at } })`, default `0.75` of the window) and nothing has been compacted since the last request, `compact` appends one runtime note at the end asking the model to call `compact` before doing anything else. A compaction made after such a request is recorded as `decidedBy: "forced"` (new value on `CompactionPayload.decidedBy`: the harness picked the timing, the model wrote the summary). The request is made once per segment; if the model ignores it, threshold truncation still folds mechanically at `contextLimit - reserveTokens`. Appending at the end keeps the prompt cache intact, unlike forcing `tool_choice` or narrowing the tool list. Pass `force: false` to turn it off (the default rules then drop the sentence that promises the request); `force.render` customizes the wording. `@reinsjs/eval` counts the new value separately (`CompactionCounts.forced`). The default `COMPACT_RULES` text gains one line, so sessions paused under an older version see a config change on resume.
9
+ - 4a57a7a: Threshold truncation now cuts down to a lower watermark instead of just under the trigger line. Once the context passes `contextLimit - reserveTokens`, `budgetTruncate` removes the oldest turns until the context fits within `contextLimit × cutToRatio` (new option, default `0.6`; values above the trigger line fall back to it). Previously each truncation landed just under the line, so the next tool result pushed it back over: a sliver was cut almost every turn, the prompt cache prefix was invalidated each time, and summaries nested deeper. Pass `defaultProjectionChain({ truncate: { cutToRatio: 1 } })` to restore the old behavior.
10
+
11
+ ## 0.4.0
12
+
13
+ ### Minor Changes
14
+
15
+ - fb032c1: core: the projection's threshold fallback now compares the calibrated context size — the estimate plus the fixed overhead the estimate cannot see (system prompt, tool definitions, thinking), measured from the last `budget_usage` — against `contextLimit - reserveTokens`. Before, it compared the raw estimate, so perception could report "≥85%, the harness auto-folds at 85%" while no fold happened, and a system prompt plus tool table larger than the reserve could overflow the window before the fallback ever fired. `contextOverheadOf` moves to core (brain still re-exports it) and returns 0 when the last usage record yields a non-finite value, so a malformed `budget_usage` cannot fail the run at start; `ProjectionStats.overheadTokens` is new; `project({ budget: { overheadTokens: 0 } })` restores the old comparison. The fallback now fires earlier by that overhead, and `reserveTokens` is effectively the output reserve.
16
+
3
17
  ## 0.3.0
4
18
 
5
19
  ### Minor Changes
package/README.md CHANGED
@@ -71,6 +71,6 @@ A `Socket` is the seam brain modules use — five hooks (`beforeModel`, `afterMo
71
71
 
72
72
  ## Documentation
73
73
 
74
- The design documents live in `docs/` at the repository root and are written in Chinese: `docs/技术方案.md` (spec, §6 run state, §7 sockets, §10 tools), `docs/模块盘点/core.md` (file-by-file map), `docs/DECISIONS.md`.
74
+ The design documents live in `docs/` at the repository root and are written in Chinese: `docs/archive/implementation-plans/2026-09-08-技术方案v1.0.md` (spec, §6 run state, §7 sockets, §10 tools), `docs/系统全景图_模块盘点/core.md` (file-by-file map), `docs/archive/2026-10-30-决策日志DECISIONS-0.1至0.4.md`.
75
75
 
76
76
  MIT © 2026 NewRate Limited.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EventLog, a as Event, b as EventSchemaRegistry, B as BlobStore, M as MemoryStore, c as EventDraft, T as TokenUsage, C as ContentPart, d as Trust, L as Lowering, e as ModelRef, f as LoweringCapabilities, g as CoreEventOf, h as ToolResultPayload, i as LoweringDelta, j as LandingRecord, k as LoweredRequest, l as ErrorPayload, A as ApprovalRequestPayload, m as ToolCallPayload, n as ToolSpec, o as CoreEventDraft, p as BudgetUsagePayload, q as BlobMeta, R as ReadOptions, r as RunLease, S as Stores } from './types-DJB-13o3.js';
2
- export { s as Actor, t as AnyEvent, u as ApprovalDecisionPayload, v as BoundModel, w as CORE_SCHEMAS, x as CompactionPayload, y as CoreEvent, z as CoreEventPayloads, D as CoreEventType, F as CreateEventInput, G as DEFAULT_TRUST, H as EventBase, I as EventSchema, J as ExtEvent, K as HandoffPayload, N as ImagePart, O as LandingSpec, P as LossKind, Q as LossMatrix, U as LoweringOutcome, V as LoweringStreamContext, W as MemoryOpPayload, X as ModelTextPayload, Y as ModelThinkingPayload, Z as Provenance, _ as RunPausedPayload, $ as RunResumedPayload, a0 as SchemaError, a1 as SchemaErrorCode, a2 as SkillSource, a3 as SystemNotePayload, a4 as TextPart, a5 as ToRequestInput, a6 as ToolReferencePart, a7 as ToolsBoundPayload, a8 as Upcaster, a9 as UserMessagePayload, aa as contextTokensOf, ab as createCoreEvent, ac as createCoreRegistry, ad as createEvent, ae as lossesOf, af as renderToolReference } from './types-DJB-13o3.js';
1
+ import { E as EventLog, a as Event, b as EventSchemaRegistry, B as BlobStore, M as MemoryStore, c as EventDraft, T as TokenUsage, C as ContentPart, d as Trust, L as Lowering, e as ModelRef, f as LoweringCapabilities, g as CoreEventOf, h as ToolResultPayload, i as LoweringDelta, j as LandingRecord, k as LoweredRequest, l as ErrorPayload, A as ApprovalRequestPayload, m as ToolCallPayload, n as ToolSpec, o as CoreEventDraft, p as BudgetUsagePayload, q as BlobMeta, R as ReadOptions, r as RunLease, S as Stores } from './types-BOSGqMVX.js';
2
+ export { s as Actor, t as AnyEvent, u as ApprovalDecisionPayload, v as BoundModel, w as CORE_SCHEMAS, x as CompactionPayload, y as CoreEvent, z as CoreEventPayloads, D as CoreEventType, F as CreateEventInput, G as DEFAULT_TRUST, H as EventBase, I as EventSchema, J as ExtEvent, K as HandoffPayload, N as ImagePart, O as LandingSpec, P as LossKind, Q as LossMatrix, U as LoweringOutcome, V as LoweringStreamContext, W as MemoryOpPayload, X as ModelTextPayload, Y as ModelThinkingPayload, Z as Provenance, _ as RunPausedPayload, $ as RunResumedPayload, a0 as SchemaError, a1 as SchemaErrorCode, a2 as SkillSource, a3 as SystemNotePayload, a4 as TextPart, a5 as ToRequestInput, a6 as ToolReferencePart, a7 as ToolsBoundPayload, a8 as Upcaster, a9 as UserMessagePayload, aa as contextOverheadOf, ab as contextTokensOf, ac as createCoreEvent, ad as createCoreRegistry, ae as createEvent, af as lossesOf, ag as renderToolReference } from './types-BOSGqMVX.js';
3
3
 
4
4
  /**
5
5
  * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
@@ -75,8 +75,13 @@ declare function resolveRetry(opts?: RetryOptions): ResolvedRetry;
75
75
  interface ProjectionBudget {
76
76
  /** 模型上下文窗口上限(token) */
77
77
  contextLimit: number;
78
- /** 为模型输出与工具定义预留的 token;裁剪目标 = contextLimit - reserveTokens */
78
+ /** 为模型输出预留的 token;裁剪目标 = contextLimit - reserveTokens,按真实上下文(估算 + overheadTokens)比 */
79
79
  reserveTokens: number;
80
+ /**
81
+ * 估算不含的固定开销(系统提示、工具表、thinking 等),见 contextOverheadOf。project() 总会填;
82
+ * 自己拼上下文直接调策略时缺省按 0
83
+ */
84
+ overheadTokens?: number;
80
85
  }
81
86
  /** 估算一条事件降级后大约占多少 token。核心包不带 tokenizer,默认是粗估,宿主可注入精确实现。 */
82
87
  type TokenEstimator = (event: Event) => number;
@@ -120,9 +125,11 @@ interface ProjectionStepStats {
120
125
  interface ProjectionStats {
121
126
  /** 最终可见事件的估算 token 总量 */
122
127
  estimatedTokens: number;
123
- /** contextLimit - reserveTokens */
128
+ /** contextLimit - reserveTokens,真实上下文口径:estimatedTokens + overheadTokens 超过它就兜底裁剪 */
124
129
  targetTokens: number;
125
- /** 裁到不能再裁仍超目标:只剩最后一轮也放不下,需要 spill 或更大的窗口。循环层据此告警 */
130
+ /** 本次投影用的固定开销(缺省从时间线校准,见 contextOverheadOf) */
131
+ overheadTokens: number;
132
+ /** 裁到不能再裁仍超目标(估算 + 开销):只剩最后一轮也放不下,需要 spill 或更大的窗口。循环层据此告警 */
126
133
  overBudget: boolean;
127
134
  steps: ProjectionStepStats[];
128
135
  }
@@ -294,7 +301,10 @@ interface TurnContext {
294
301
  capabilities: LoweringCapabilities;
295
302
  budget: {
296
303
  contextLimit: number;
297
- /** 投影的裁剪目标 = contextLimit - reserveTokens;估算超过它库就按阈值自动折叠最旧的轮次(感知据此提醒模型) */
304
+ /**
305
+ * 投影的裁剪目标 = contextLimit - reserveTokens,真实上下文口径:本轮估算 + 固定开销(contextOverheadOf(timeline))
306
+ * 超过它库就按阈值自动折叠最旧的轮次(感知用同一函数校准、据此提醒模型)
307
+ */
298
308
  targetTokens: number;
299
309
  /** 本轮投影的估算 token */
300
310
  used: number;
@@ -660,7 +670,7 @@ declare function isSubagentPause(value: unknown): value is SubagentPause;
660
670
  /**
661
671
  * 工具结果事件该带的 trust(§14):工具声明了 `resultTrust` 且结果不是错误 → 按声明;否则 undefined(事件工厂按 actor 缺省,即 untrusted)。
662
672
  * 这是唯一的判定点——循环的两条路(execute 结果、宿主回填的客户端工具结果)与 TanStack 适配器的两条路都调它,
663
- * "同一个判定写两处必须同一个纯函数"(踩坑记录 configHash / pendingDigest / decisions 三次教训)。
673
+ * "同一个判定写两处必须同一个纯函数"(踩坑记录 #3 / #20 / #40 的教训)。
664
674
  */
665
675
  declare function toolResultTrust(tool: Tool | undefined, isError: boolean): Trust | undefined;
666
676
  /**
@@ -781,6 +791,11 @@ declare function needsUntrustedMark(e: Event): boolean;
781
791
  declare function estimateTextTokens(text: string): number;
782
792
  declare function roughTokenEstimate(event: Event): number;
783
793
  declare function estimateTotal(events: readonly Event[], estimate: (e: Event) => number): number;
794
+ /**
795
+ * 投影估算可用的 token 数:裁剪目标减去估算不含的固定开销。
796
+ * 兜底裁剪"要不要裁、裁到哪"与 stats.overBudget 都按它判,同一口径只此一份
797
+ */
798
+ declare function estimateBudgetOf(budget: ProjectionBudget): number;
784
799
 
785
800
  /**
786
801
  * 策略 1:可见性过滤。
@@ -893,6 +908,10 @@ declare function reinjectPins(): ProjectionStrategy;
893
908
  * 做法:按"轮"从最旧的开始裁掉一个前缀,追加一条 compaction(decidedBy=threshold) 放在最前面,
894
909
  * 幸存的 pin 紧随其后。新造的 compaction 通过 emitted 交给循环 append,下一轮投影由折叠策略正常处理它。
895
910
  *
911
+ * 触发线与回落线分开(OPT-261030-2):过了触发线(contextLimit − reserveTokens,感知报的 autoFoldAt)才裁,
912
+ * 一裁就裁到回落线(缺省 contextLimit 的 60%)。只裁回触发线下会贴线磨刀——下一轮新结果一进来又过线,
913
+ * 几乎每轮裁一截、每裁一次缓存前缀整段作废、旧摘要再套一层。
914
+ *
896
915
  * 切点必须满足三条,否则降级层会产出厂商拒收的请求:
897
916
  * 1. 只在轮边界切。assistant 轮 = 连续的 model_thinking / model_text / tool_call;其余连续事件为一轮。
898
917
  * 2. 保留部分的第一轮若含 tool_result,其 tool_call 必在被裁掉的轮里 → 这种切点不合法。
@@ -910,7 +929,14 @@ interface BudgetTruncateOptions {
910
929
  autoKeepPinNotes?: boolean;
911
930
  /** 生成兜底摘要的文本;默认给模型一段英文的机械描述 */
912
931
  summarize?: ThresholdSummarizer;
932
+ /**
933
+ * 回落线:一旦触发,裁到真实上下文 ≤ contextLimit × cutToRatio。取 (0, 1],缺省 0.6;
934
+ * 高于触发线时按触发线算(给 1 即旧行为:只裁回触发线下)
935
+ */
936
+ cutToRatio?: number;
913
937
  }
938
+ /** 兜底裁剪的缺省回落线(占 contextLimit 的比例) */
939
+ declare const DEFAULT_CUT_TO_RATIO = 0.6;
914
940
  /**
915
941
  * 默认兜底摘要:没有模型参与,只能机械描述 —— 说明发生了什么、被裁掉多少、并入旧摘要、引用用户原话开头。
916
942
  * 给模型看的默认文案用英文;宿主可整体替换。
@@ -937,9 +963,14 @@ declare function defaultProjectionChain(opts?: DefaultChainOptions): ProjectionS
937
963
  interface ProjectOptions {
938
964
  /** 完整时间线快照,按 seq 升序、同一会话 */
939
965
  timeline: readonly Event[];
966
+ /**
967
+ * `overheadTokens` 缺省从时间线校准(contextOverheadOf:上一请求真实上下文 − 当时估算),与感知读数同一口径;
968
+ * 显式给 0 即只按估算判(校准前的行为)
969
+ */
940
970
  budget: {
941
971
  contextLimit: number;
942
972
  reserveTokens?: number;
973
+ overheadTokens?: number;
943
974
  };
944
975
  /** 缺省 defaultProjectionChain() */
945
976
  strategies?: readonly ProjectionStrategy[];
@@ -1126,6 +1157,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
1126
1157
  */
1127
1158
 
1128
1159
  /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
1129
- declare const REINS_VERSION = "0.3.0";
1160
+ declare const REINS_VERSION = "0.5.0";
1130
1161
 
1131
- export { type ApprovalDecisionInput, ApprovalRequestPayload, type ApprovalRequestSpec, BUILTIN_APPROVAL_POLICY, type BeforeModelPatch, type BeforeToolDecision, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, type DefaultChainOptions, type ErrorEventPayload, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, type HandoffIntent, INPUT_DRAFT_TYPES, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, type PauseReason, type Principal, type ProjectOptions, type ProjectionBudget, type ProjectionContext, type ProjectionResult, type ProjectionStats, type ProjectionStep, type ProjectionStepStats, type ProjectionStrategy, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, type ResolvedRetry, type RetryOptions, RunLease, type RunResult, RunStateError, type RunStateErrorCode, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, StoreError, type StoreErrorCode, Stores, type SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, type TokenEstimator, TokenUsage, type Tool, type ToolCallEvent, ToolCallPayload, type ToolContext, type ToolNamesDiff, type ToolResult, type ToolResultDraft, ToolResultPayload, type ToolSide, ToolSpec, type ToolsBoundEvent, Trust, type TurnContext, type TurnDecision, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, backoffDelayMs, budgetTruncate, computeConfigHash, computePendingDigest, covers, defaultProjectionChain, defaultSleep, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDraft, isCompaction, isContentPart, isModelOutput, isPinNote, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, statusFromMessage, subagentPause, supersededIds, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, uuidv7, validateResume, verifyRunState, visibilityFilter };
1162
+ export { type ApprovalDecisionInput, ApprovalRequestPayload, type ApprovalRequestSpec, BUILTIN_APPROVAL_POLICY, type BeforeModelPatch, type BeforeToolDecision, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, type DefaultChainOptions, type ErrorEventPayload, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, type HandoffIntent, INPUT_DRAFT_TYPES, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, type PauseReason, type Principal, type ProjectOptions, type ProjectionBudget, type ProjectionContext, type ProjectionResult, type ProjectionStats, type ProjectionStep, type ProjectionStepStats, type ProjectionStrategy, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, type ResolvedRetry, type RetryOptions, RunLease, type RunResult, RunStateError, type RunStateErrorCode, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, StoreError, type StoreErrorCode, Stores, type SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, type TokenEstimator, TokenUsage, type Tool, type ToolCallEvent, ToolCallPayload, type ToolContext, type ToolNamesDiff, type ToolResult, type ToolResultDraft, ToolResultPayload, type ToolSide, ToolSpec, type ToolsBoundEvent, Trust, type TurnContext, type TurnDecision, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, backoffDelayMs, budgetTruncate, computeConfigHash, computePendingDigest, covers, defaultProjectionChain, defaultSleep, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDraft, isCompaction, isContentPart, isModelOutput, isPinNote, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, statusFromMessage, subagentPause, supersededIds, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, uuidv7, validateResume, verifyRunState, visibilityFilter };
package/dist/index.js CHANGED
@@ -14,6 +14,15 @@ import {
14
14
  function contextTokensOf(usage) {
15
15
  return usage.input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
16
16
  }
17
+ function contextOverheadOf(timeline) {
18
+ for (let i = timeline.length - 1; i >= 0; i--) {
19
+ const e = timeline[i];
20
+ if (e?.type !== "core.budget_usage" || e.payload.contextEstimate === void 0) continue;
21
+ const overhead = contextTokensOf(e.payload.tokens) - e.payload.contextEstimate;
22
+ return Number.isFinite(overhead) && overhead > 0 ? overhead : 0;
23
+ }
24
+ return 0;
25
+ }
17
26
 
18
27
  // src/loop/fork.ts
19
28
  async function forkSession(log, opts) {
@@ -234,6 +243,9 @@ function estimateTotal(events, estimate) {
234
243
  for (const e of events) n += estimate(e);
235
244
  return n;
236
245
  }
246
+ function estimateBudgetOf(budget) {
247
+ return budget.contextLimit - budget.reserveTokens - (budget.overheadTokens ?? 0);
248
+ }
237
249
 
238
250
  // src/projection/fold.ts
239
251
  function isCompaction(e) {
@@ -420,6 +432,7 @@ function splitTurns(events) {
420
432
  if (current.length > 0) turns.push(current);
421
433
  return turns;
422
434
  }
435
+ var DEFAULT_CUT_TO_RATIO = 0.6;
423
436
  function excerpt(parts, max = 120) {
424
437
  const text = parts.map((p) => p.type === "text" ? p.text : "[image]").join(" ").replace(/\s+/g, " ").trim();
425
438
  return text.length > max ? `${text.slice(0, max)}\u2026` : text;
@@ -468,12 +481,20 @@ function minSeq(events) {
468
481
  function budgetTruncate(opts = {}) {
469
482
  const autoKeep = opts.autoKeepPinNotes ?? true;
470
483
  const summarize = opts.summarize ?? defaultThresholdSummary;
484
+ const cutToRatio = opts.cutToRatio ?? DEFAULT_CUT_TO_RATIO;
485
+ if (!(cutToRatio > 0 && cutToRatio <= 1)) {
486
+ throw new RangeError(`cutToRatio must be a number in (0, 1], got ${cutToRatio}`);
487
+ }
471
488
  return {
472
489
  name: "budget-truncate",
473
490
  apply(events, ctx) {
474
- const target = ctx.budget.contextLimit - ctx.budget.reserveTokens;
491
+ const target = estimateBudgetOf(ctx.budget);
475
492
  const total = estimateTotal(events, ctx.estimate);
476
493
  if (total <= target) return { events: [...events] };
494
+ const cutTarget = Math.min(
495
+ target,
496
+ Math.floor(ctx.budget.contextLimit * cutToRatio) - (ctx.budget.overheadTokens ?? 0)
497
+ );
477
498
  const turns = splitTurns(events);
478
499
  let chosen = null;
479
500
  let lastValid = null;
@@ -487,7 +508,7 @@ function budgetTruncate(opts = {}) {
487
508
  if (minSeq(kept2) <= maxSeq(removed2)) continue;
488
509
  lastValid = k2;
489
510
  const { survivors: survivors2, summaryTokens } = plan(removed2, ctx, autoKeep, summarize);
490
- if (total - removedTokens + summaryTokens + estimateTotal(survivors2, ctx.estimate) <= target) {
511
+ if (total - removedTokens + summaryTokens + estimateTotal(survivors2, ctx.estimate) <= cutTarget) {
491
512
  chosen = k2;
492
513
  break;
493
514
  }
@@ -556,7 +577,11 @@ function project(opts) {
556
577
  const sessionId = opts.sessionId ?? last?.sessionId;
557
578
  if (sessionId === void 0) throw new RangeError("an empty timeline requires an explicit sessionId");
558
579
  const reserveTokens = opts.budget.reserveTokens ?? Math.floor(opts.budget.contextLimit * DEFAULT_RESERVE_RATIO);
559
- const budget = { contextLimit: opts.budget.contextLimit, reserveTokens };
580
+ const overheadTokens = opts.budget.overheadTokens ?? contextOverheadOf(timeline);
581
+ if (!Number.isFinite(overheadTokens) || overheadTokens < 0) {
582
+ throw new RangeError(`budget.overheadTokens must be a non-negative finite number, got ${overheadTokens}`);
583
+ }
584
+ const budget = { contextLimit: opts.budget.contextLimit, reserveTokens, overheadTokens };
560
585
  const estimate = opts.estimate ?? roughTokenEstimate;
561
586
  const registry = opts.registry ?? coreRegistry();
562
587
  const now = opts.now ?? Date.now();
@@ -589,7 +614,13 @@ function project(opts) {
589
614
  return {
590
615
  events,
591
616
  emitted,
592
- stats: { estimatedTokens, targetTokens, overBudget: estimatedTokens > targetTokens, steps }
617
+ stats: {
618
+ estimatedTokens,
619
+ targetTokens,
620
+ overheadTokens,
621
+ overBudget: estimatedTokens > estimateBudgetOf(budget),
622
+ steps
623
+ }
593
624
  };
594
625
  }
595
626
 
@@ -1710,10 +1741,11 @@ function memoryStore() {
1710
1741
  }
1711
1742
 
1712
1743
  // src/index.ts
1713
- var REINS_VERSION = "0.3.0";
1744
+ var REINS_VERSION = "0.5.0";
1714
1745
  export {
1715
1746
  BUILTIN_APPROVAL_POLICY,
1716
1747
  CORE_SCHEMAS,
1748
+ DEFAULT_CUT_TO_RATIO,
1717
1749
  DEFAULT_MAX_TURNS,
1718
1750
  DEFAULT_MODEL_INVISIBLE_TYPES,
1719
1751
  DEFAULT_RESERVE_RATIO,
@@ -1739,6 +1771,7 @@ export {
1739
1771
  budgetTruncate,
1740
1772
  computeConfigHash,
1741
1773
  computePendingDigest,
1774
+ contextOverheadOf,
1742
1775
  contextTokensOf,
1743
1776
  covers,
1744
1777
  createCoreEvent,
@@ -1753,6 +1786,7 @@ export {
1753
1786
  digestArgs,
1754
1787
  errorMessageOf,
1755
1788
  escapeUntrustedText,
1789
+ estimateBudgetOf,
1756
1790
  estimateTextTokens,
1757
1791
  estimateTotal,
1758
1792
  foldCompactions,