@reinsjs/core 0.4.0 → 0.6.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,21 @@
1
1
  # @reinsjs/core
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a2ee718: `input` accepts an array of event drafts, appended in order in one write: e.g. a host briefing as `system_note(kind: "host")` followed by the `user_message`, so the model can tell what it is asked to do from what it is told. Every draft passes the type whitelist plus new checks — a valid actor, the basic payload shape of `core.user_message` / `core.tool_result` / `core.system_note` (and of plain content-part arrays), and registration in the registry — so one bad draft rejects the whole batch before anything is written. Previously an unregistered `ext.*` draft or a malformed payload failed only after `tools_bound` (and, on resume, `run_resumed`) had been appended, and a malformed user message could land in the log and break every later run of that session. Content parts cannot be mixed with drafts.
8
+
9
+ **Breaking:** the exported `inputDraft(input): EventDraft` is renamed `inputDrafts(input): EventDraft[]` and returns a list.
10
+
11
+ ## 0.5.0
12
+
13
+ ### Minor Changes
14
+
15
+ - 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`.
16
+ - 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.
17
+ - 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.
18
+
3
19
  ## 0.4.0
4
20
 
5
21
  ### Minor Changes
package/README.md CHANGED
@@ -39,6 +39,24 @@ type RunResult =
39
39
 
40
40
  Pausing is a return value, not a blocking callback. `state` is small (ids and hashes, HMAC-signed when you pass `secret`) and enough to resume in another process: `runLoop({ ...config, resume: state, decisions: [...] })` re-validates it against the log (config drift, pending-call digest) before writing anything.
41
41
 
42
+ ## Input: background and task in one run
43
+
44
+ `input` takes a string, content parts, one event draft, or an array of drafts appended in order in one write. Use the array when a run brings both something to do and something to know, so the model can tell a colleague's request from the host's briefing:
45
+
46
+ ```ts
47
+ /** Host briefing as a system note, then the actual request. One user message per batch. */
48
+ function briefedInput(background: string, request: string): EventDraft[] {
49
+ return [
50
+ { type: "core.system_note", actor: "host", payload: { kind: "host", text: background } },
51
+ { type: "core.user_message", actor: "user", payload: { content: [{ type: "text", text: request }] } },
52
+ ]
53
+ }
54
+
55
+ runLoop({ ...config, input: briefedInput("Ticket #12 was edited by Ana an hour ago.", "Review ticket #12.") })
56
+ ```
57
+
58
+ Every draft goes through the same checks — type whitelist (`core.user_message`, `core.tool_result`, `core.system_note`, `ext.*`), a valid actor, the basic payload shape of the three core types, and registration in your registry — and one bad draft rejects the whole batch before anything is written; content parts cannot be mixed with drafts. The envelope (`actor`, `trust`) and the shape of your own `ext.*` payloads are yours to get right: in-process input is trusted host code. Keep one user message per batch: compaction keeps only the most recent one verbatim, while background notes fold like any other note (put what must stay in a pin). Lowering keeps the order on Chat and Responses; on Anthropic models that accept mid-conversation system messages the note lands right after the user message, because a system message may not come first or follow an assistant one. The HTTP handler in `@reinsjs/server` does not accept draft arrays — this is for in-process hosts.
59
+
42
60
  ## Tools
43
61
 
44
62
  ```ts
@@ -71,6 +89,6 @@ A `Socket` is the seam brain modules use — five hooks (`beforeModel`, `afterMo
71
89
 
72
90
  ## Documentation
73
91
 
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`.
92
+ 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
93
 
76
94
  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-xpjHur3K.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-xpjHur3K.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 毫秒时间戳,字典序即时间序。
@@ -478,10 +478,13 @@ interface LoopConfig {
478
478
  sockets?: readonly Socket[];
479
479
  systemPrompt?: string;
480
480
  /**
481
- * 本次 run 要追加的新输入:字符串 / 内容片段 → user_message;也可直接给草稿(如宿主注入 system_note)。
481
+ * 本次 run 要追加的新输入:字符串 / 内容片段 → user_message;也可直接给草稿(如宿主注入 system_note),
482
+ * 或草稿数组——一次 append、按给定顺序写入,适合"背景 + 任务":`[system_note(kind: "host"), user_message]`,
483
+ * 每批只放一条 user_message(compact 只保最后一条)。片段与草稿不能混排;任一草稿不合规整批拒绝、日志不写。
484
+ * 草稿数组只给进程内宿主,HTTP 入口只收文本 / 内容片段与两种重建过的草稿(刻意不对称)。
482
485
  * 缺省不追加(续跑:日志里有未完成的工具调用就先补齐,再问模型)。
483
486
  */
484
- input?: string | ContentPart[] | EventDraft;
487
+ input?: string | ContentPart[] | EventDraft | readonly EventDraft[];
485
488
  principal?: Principal;
486
489
  projection?: {
487
490
  strategies?: readonly ProjectionStrategy[];
@@ -565,8 +568,11 @@ declare const BUILTIN_APPROVAL_POLICY = "tool.needsApproval";
565
568
  * 这些事件只能由循环自己按规则产生(审批结论走 `decisions`,经 T10 校验)。
566
569
  */
567
570
  declare const INPUT_DRAFT_TYPES: ReadonlySet<string>;
568
- /** 把 `input` 归一成草稿;不合规的草稿在写任何日志之前就抛 RangeError(fail-closed) */
569
- declare function inputDraft(input: NonNullable<LoopConfig["input"]>): EventDraft;
571
+ /**
572
+ * 把 `input` 归一成草稿列表:字符串 / 内容片段 → 一条 user_message;单条草稿 → 一条;草稿数组 → 按序多条。
573
+ * 全部校验完才返回,任一不合规在写任何日志之前就抛 RangeError(fail-closed)。片段与草稿混排、无法归类的元素一律拒绝
574
+ */
575
+ declare function inputDrafts(input: NonNullable<LoopConfig["input"]>): EventDraft[];
570
576
  declare function runLoop(cfg: LoopConfig): AsyncGenerator<Event, RunResult>;
571
577
 
572
578
  /**
@@ -670,7 +676,7 @@ declare function isSubagentPause(value: unknown): value is SubagentPause;
670
676
  /**
671
677
  * 工具结果事件该带的 trust(§14):工具声明了 `resultTrust` 且结果不是错误 → 按声明;否则 undefined(事件工厂按 actor 缺省,即 untrusted)。
672
678
  * 这是唯一的判定点——循环的两条路(execute 结果、宿主回填的客户端工具结果)与 TanStack 适配器的两条路都调它,
673
- * "同一个判定写两处必须同一个纯函数"(踩坑记录 configHash / pendingDigest / decisions 三次教训)。
679
+ * "同一个判定写两处必须同一个纯函数"(踩坑记录 #3 / #20 / #40 的教训)。
674
680
  */
675
681
  declare function toolResultTrust(tool: Tool | undefined, isError: boolean): Trust | undefined;
676
682
  /**
@@ -908,6 +914,10 @@ declare function reinjectPins(): ProjectionStrategy;
908
914
  * 做法:按"轮"从最旧的开始裁掉一个前缀,追加一条 compaction(decidedBy=threshold) 放在最前面,
909
915
  * 幸存的 pin 紧随其后。新造的 compaction 通过 emitted 交给循环 append,下一轮投影由折叠策略正常处理它。
910
916
  *
917
+ * 触发线与回落线分开(OPT-261030-2):过了触发线(contextLimit − reserveTokens,感知报的 autoFoldAt)才裁,
918
+ * 一裁就裁到回落线(缺省 contextLimit 的 60%)。只裁回触发线下会贴线磨刀——下一轮新结果一进来又过线,
919
+ * 几乎每轮裁一截、每裁一次缓存前缀整段作废、旧摘要再套一层。
920
+ *
911
921
  * 切点必须满足三条,否则降级层会产出厂商拒收的请求:
912
922
  * 1. 只在轮边界切。assistant 轮 = 连续的 model_thinking / model_text / tool_call;其余连续事件为一轮。
913
923
  * 2. 保留部分的第一轮若含 tool_result,其 tool_call 必在被裁掉的轮里 → 这种切点不合法。
@@ -925,7 +935,14 @@ interface BudgetTruncateOptions {
925
935
  autoKeepPinNotes?: boolean;
926
936
  /** 生成兜底摘要的文本;默认给模型一段英文的机械描述 */
927
937
  summarize?: ThresholdSummarizer;
938
+ /**
939
+ * 回落线:一旦触发,裁到真实上下文 ≤ contextLimit × cutToRatio。取 (0, 1],缺省 0.6;
940
+ * 高于触发线时按触发线算(给 1 即旧行为:只裁回触发线下)
941
+ */
942
+ cutToRatio?: number;
928
943
  }
944
+ /** 兜底裁剪的缺省回落线(占 contextLimit 的比例) */
945
+ declare const DEFAULT_CUT_TO_RATIO = 0.6;
929
946
  /**
930
947
  * 默认兜底摘要:没有模型参与,只能机械描述 —— 说明发生了什么、被裁掉多少、并入旧摘要、引用用户原话开头。
931
948
  * 给模型看的默认文案用英文;宿主可整体替换。
@@ -1146,6 +1163,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
1146
1163
  */
1147
1164
 
1148
1165
  /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
1149
- declare const REINS_VERSION = "0.4.0";
1166
+ declare const REINS_VERSION = "0.6.0";
1150
1167
 
1151
- 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, 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 };
1168
+ 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, inputDrafts, 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
@@ -432,6 +432,7 @@ function splitTurns(events) {
432
432
  if (current.length > 0) turns.push(current);
433
433
  return turns;
434
434
  }
435
+ var DEFAULT_CUT_TO_RATIO = 0.6;
435
436
  function excerpt(parts, max = 120) {
436
437
  const text = parts.map((p) => p.type === "text" ? p.text : "[image]").join(" ").replace(/\s+/g, " ").trim();
437
438
  return text.length > max ? `${text.slice(0, max)}\u2026` : text;
@@ -480,12 +481,20 @@ function minSeq(events) {
480
481
  function budgetTruncate(opts = {}) {
481
482
  const autoKeep = opts.autoKeepPinNotes ?? true;
482
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
+ }
483
488
  return {
484
489
  name: "budget-truncate",
485
490
  apply(events, ctx) {
486
491
  const target = estimateBudgetOf(ctx.budget);
487
492
  const total = estimateTotal(events, ctx.estimate);
488
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
+ );
489
498
  const turns = splitTurns(events);
490
499
  let chosen = null;
491
500
  let lastValid = null;
@@ -499,7 +508,7 @@ function budgetTruncate(opts = {}) {
499
508
  if (minSeq(kept2) <= maxSeq(removed2)) continue;
500
509
  lastValid = k2;
501
510
  const { survivors: survivors2, summaryTokens } = plan(removed2, ctx, autoKeep, summarize);
502
- if (total - removedTokens + summaryTokens + estimateTotal(survivors2, ctx.estimate) <= target) {
511
+ if (total - removedTokens + summaryTokens + estimateTotal(survivors2, ctx.estimate) <= cutTarget) {
503
512
  chosen = k2;
504
513
  break;
505
514
  }
@@ -914,17 +923,82 @@ var INPUT_DRAFT_TYPES = /* @__PURE__ */ new Set([
914
923
  "core.tool_result",
915
924
  "core.system_note"
916
925
  ]);
917
- function inputDraft(input) {
918
- if (typeof input === "string")
919
- return { type: "core.user_message", actor: "user", payload: { content: [{ type: "text", text: input }] } };
920
- if (Array.isArray(input))
921
- return { type: "core.user_message", actor: "user", payload: { content: input } };
922
- if (typeof input.type !== "string" || !INPUT_DRAFT_TYPES.has(input.type) && !input.type.startsWith("ext.")) {
926
+ var INPUT_ACTORS = /* @__PURE__ */ new Set(["user", "model", "tool", "system", "host"]);
927
+ var CONTENT_PART_TYPES = /* @__PURE__ */ new Set(["text", "image", "tool_reference"]);
928
+ function classifyInputItem(item) {
929
+ if (typeof item !== "object" || item === null) return void 0;
930
+ const { type, actor } = item;
931
+ if (actor !== void 0) return "draft";
932
+ if (typeof type !== "string") return void 0;
933
+ if (type.startsWith("core.") || type.startsWith("ext.")) return "draft";
934
+ return CONTENT_PART_TYPES.has(type) ? "part" : void 0;
935
+ }
936
+ var NOTE_KINDS = /* @__PURE__ */ new Set(["perception", "pin", "budget", "host"]);
937
+ function isContentPartList(x) {
938
+ if (!Array.isArray(x)) return false;
939
+ return x.every((p) => {
940
+ if (typeof p !== "object" || p === null) return false;
941
+ const part = p;
942
+ if (part.type === "text") return typeof part.text === "string";
943
+ if (part.type === "image") return typeof part.mime === "string" && typeof part.data === "string";
944
+ if (part.type === "tool_reference")
945
+ return typeof part.name === "string" && typeof part.description === "string" && typeof part.inputSchema === "object" && part.inputSchema !== null;
946
+ return false;
947
+ });
948
+ }
949
+ function corePayloadProblem(draft) {
950
+ const p = typeof draft.payload === "object" && draft.payload !== null ? draft.payload : {};
951
+ if (draft.type === "core.user_message")
952
+ return isContentPartList(p.content) ? void 0 : "payload.content must be an array of content parts";
953
+ if (draft.type === "core.tool_result") {
954
+ if (typeof p.toolCallId !== "string" || typeof p.name !== "string")
955
+ return "payload.toolCallId and payload.name must be strings";
956
+ return isContentPartList(p.content) ? void 0 : "payload.content must be an array of content parts";
957
+ }
958
+ if (draft.type === "core.system_note") {
959
+ if (typeof p.kind !== "string" || !NOTE_KINDS.has(p.kind))
960
+ return `payload.kind must be perception, pin, budget or host, got ${String(p.kind)}`;
961
+ return typeof p.text === "string" ? void 0 : "payload.text must be a string";
962
+ }
963
+ return void 0;
964
+ }
965
+ function checkInputDraft(draft) {
966
+ if (typeof draft.type !== "string" || !INPUT_DRAFT_TYPES.has(draft.type) && !draft.type.startsWith("ext.")) {
967
+ throw new RangeError(
968
+ `input draft rejects event type ${String(draft.type)}: only core.user_message, core.tool_result, core.system_note or ext.* are accepted`
969
+ );
970
+ }
971
+ if (typeof draft.actor !== "string" || !INPUT_ACTORS.has(draft.actor)) {
923
972
  throw new RangeError(
924
- `input draft rejects event type ${String(input.type)}: only core.user_message, core.tool_result, core.system_note or ext.* are accepted`
973
+ `input draft actor must be user, model, tool, system or host, got ${String(draft.actor)}`
925
974
  );
926
975
  }
927
- return input;
976
+ const problem = corePayloadProblem(draft);
977
+ if (problem !== void 0) throw new RangeError(`input draft ${draft.type}: ${problem}`);
978
+ return draft;
979
+ }
980
+ function inputDrafts(input) {
981
+ if (typeof input === "string")
982
+ return [
983
+ { type: "core.user_message", actor: "user", payload: { content: [{ type: "text", text: input }] } }
984
+ ];
985
+ if (isInputArray(input)) {
986
+ const kinds = new Set(input.map(classifyInputItem));
987
+ if (kinds.has(void 0) || kinds.size > 1) {
988
+ throw new RangeError(
989
+ `input must be content parts or event drafts, got ${kinds.size > 1 && !kinds.has(void 0) ? "a mix of both" : "an element that is neither"}`
990
+ );
991
+ }
992
+ if (!kinds.has("draft")) {
993
+ if (!isContentPartList(input)) throw new RangeError("input content parts are malformed");
994
+ return [{ type: "core.user_message", actor: "user", payload: { content: input } }];
995
+ }
996
+ return input.map(checkInputDraft);
997
+ }
998
+ return [checkInputDraft(input)];
999
+ }
1000
+ function isInputArray(input) {
1001
+ return Array.isArray(input);
928
1002
  }
929
1003
  async function* runLoop(cfg) {
930
1004
  const { sessionId, log, lowering, model } = cfg;
@@ -935,7 +1009,10 @@ async function* runLoop(cfg) {
935
1009
  const { tools: baseTools, systemPrompt: baseSystemPrompt } = await resolveSocketContributions(cfg);
936
1010
  const maxTurns = cfg.maxTurns ?? DEFAULT_MAX_TURNS;
937
1011
  const retry = resolveRetry(cfg.retry);
938
- const input = cfg.input !== void 0 ? inputDraft(cfg.input) : void 0;
1012
+ const input = cfg.input !== void 0 ? inputDrafts(cfg.input) : [];
1013
+ for (const d of input) {
1014
+ if (!registry.has(d.type)) throw new RangeError(`input draft type ${d.type} is not registered`);
1015
+ }
939
1016
  const capabilities = lowering.capabilities(model);
940
1017
  const configHash = await computeConfigHash({
941
1018
  model,
@@ -1036,7 +1113,7 @@ async function* runLoop(cfg) {
1036
1113
  announce: cfg.announceToolChanges ?? true
1037
1114
  })
1038
1115
  );
1039
- if (input !== void 0) yield* await append([withResultTrust(input, baseTools)]);
1116
+ yield* await append(input.map((d) => withResultTrust(d, baseTools)));
1040
1117
  while (true) {
1041
1118
  const turnStartedAt = now();
1042
1119
  const timeline = await readTimeline(log, sessionId, { registry });
@@ -1732,10 +1809,11 @@ function memoryStore() {
1732
1809
  }
1733
1810
 
1734
1811
  // src/index.ts
1735
- var REINS_VERSION = "0.4.0";
1812
+ var REINS_VERSION = "0.6.0";
1736
1813
  export {
1737
1814
  BUILTIN_APPROVAL_POLICY,
1738
1815
  CORE_SCHEMAS,
1816
+ DEFAULT_CUT_TO_RATIO,
1739
1817
  DEFAULT_MAX_TURNS,
1740
1818
  DEFAULT_MODEL_INVISIBLE_TYPES,
1741
1819
  DEFAULT_RESERVE_RATIO,
@@ -1782,7 +1860,7 @@ export {
1782
1860
  foldCompactions,
1783
1861
  foldedToolResults,
1784
1862
  forkSession,
1785
- inputDraft,
1863
+ inputDrafts,
1786
1864
  isCompaction,
1787
1865
  isContentPart,
1788
1866
  isModelOutput,