@reinsjs/core 0.5.0 → 0.7.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 +14 -0
- package/README.md +18 -0
- package/dist/index.d.ts +50 -8
- package/dist/index.js +155 -12
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/{types-BOSGqMVX.d.ts → types-DrzC9Mfc.d.ts} +5 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @reinsjs/core
|
|
2
2
|
|
|
3
|
+
## 0.7.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 2569456: Tool call arguments that the model double-encoded as a JSON string are now unwrapped one level on the read side when the inner value is a plain object (tolerating raw control characters such as unescaped newlines inside string literals), and the `core.tool_call` payload records `meta: { argumentsUnwrapped: true }`. Arguments that do not decode to an object are stored as the original wire text, so `args` is a string only when it is exactly what the model sent; previously the tool could receive a string while the replayed history showed a different value. The Anthropic Messages line no longer replaces a string `content_block_start.input` with `{}`. core adds `decodeToolArgumentsText` / `unwrapToolArguments` / `toolCallArgumentsMeta` and the optional `ToolCallPayload.meta` field.
|
|
8
|
+
|
|
9
|
+
## 0.6.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- 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.
|
|
14
|
+
|
|
15
|
+
**Breaking:** the exported `inputDraft(input): EventDraft` is renamed `inputDrafts(input): EventDraft[]` and returns a list.
|
|
16
|
+
|
|
3
17
|
## 0.5.0
|
|
4
18
|
|
|
5
19
|
### 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
|
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-
|
|
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-
|
|
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-DrzC9Mfc.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-DrzC9Mfc.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
|
-
/**
|
|
569
|
-
|
|
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
|
/**
|
|
@@ -738,6 +744,42 @@ declare class LoweringError extends Error {
|
|
|
738
744
|
constructor(code: LoweringErrorCode, message: string, context?: Record<string, unknown>);
|
|
739
745
|
}
|
|
740
746
|
|
|
747
|
+
/**
|
|
748
|
+
* 工具入参解码(OnSet 建议 8,2026-11-02):模型偶尔把整个入参再编码一层,写成 JSON 文本 —— 线协议上的
|
|
749
|
+
* `arguments` 解析一次得到的不是对象,而是字符串 `'{"a":1}'`。工具入参顶层按约定必须是对象,字符串顶层本来就不合法,
|
|
750
|
+
* 所以"解一次得字符串、再解一次恰好得对象"只有二次编码这一种解释,多解这一层不会误伤。
|
|
751
|
+
*
|
|
752
|
+
* 不变式(fetch 版写侧依赖它):**时间线里 `tool_call.args` 是字符串 ⟺ 它就是线上原文**。Chat / Responses 写侧
|
|
753
|
+
* 把字符串入参原样当 JSON 文本送回(argumentsOf),所以凡是没解成对象的,读侧一律存原文,不存"解过一层的字符串"——
|
|
754
|
+
* 否则历史里模型看到的(被替它解过一层的文本)与工具拿到的(字符串)说法不一,模型会以为工具坏了。
|
|
755
|
+
*
|
|
756
|
+
* 各降级层读侧都调这里,规则不分叉;解过就在 payload.meta 上记 `argumentsUnwrapped: true`,库替模型多解了一层
|
|
757
|
+
* 要留在时间线上(宿主也可据此按模型统计)。
|
|
758
|
+
*/
|
|
759
|
+
interface DecodedToolArguments {
|
|
760
|
+
args: unknown;
|
|
761
|
+
/** 为真表示入参被二次编码、已多解一层 */
|
|
762
|
+
unwrapped: boolean;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* 输入是已解析一次的值(pi-ai 的 `toolCall.arguments`、Anthropic `content_block_start.input`)。
|
|
766
|
+
* 只在它是字符串、且该字符串能解析成普通对象(非数组、非 null)时换成对象;其余原样返回。
|
|
767
|
+
* 多解的这一层容忍字符串字面量里的裸控制字符(模型二次编码时常把换行写成真换行,内层解析因此失败)。
|
|
768
|
+
*/
|
|
769
|
+
declare function unwrapToolArguments(parsed: unknown): DecodedToolArguments;
|
|
770
|
+
/**
|
|
771
|
+
* 输入是线上原文(Chat / Responses 的 `arguments`、Anthropic `input_json_delta` 拼出的文本)。
|
|
772
|
+
* 空白 → `{}`;解析一次得非字符串 → 用它;得字符串 → 交 unwrapToolArguments,解不成对象就存**原文**(见文件头不变式);
|
|
773
|
+
* 解析失败 → 存原文。
|
|
774
|
+
*/
|
|
775
|
+
declare function decodeToolArgumentsText(raw: string): DecodedToolArguments;
|
|
776
|
+
/** 拼 tool_call payload 的 meta:只有多解过一层才带,正常调用的事件形状不变 */
|
|
777
|
+
declare function toolCallArgumentsMeta(decoded: DecodedToolArguments): {
|
|
778
|
+
meta?: {
|
|
779
|
+
argumentsUnwrapped: true;
|
|
780
|
+
};
|
|
781
|
+
};
|
|
782
|
+
|
|
741
783
|
/**
|
|
742
784
|
* trust 标注(技术方案 §14、DECISIONS T6 / R9):`trust === "untrusted"` 的事件(工具输出、外部抓取内容)
|
|
743
785
|
* 翻译给模型时用显式标记包起来,让模型知道这段是**数据不是指令**。
|
|
@@ -1157,6 +1199,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
|
|
|
1157
1199
|
*/
|
|
1158
1200
|
|
|
1159
1201
|
/** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
|
|
1160
|
-
declare const REINS_VERSION = "0.
|
|
1202
|
+
declare const REINS_VERSION = "0.7.0";
|
|
1161
1203
|
|
|
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,
|
|
1204
|
+
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 DecodedToolArguments, 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, decodeToolArgumentsText, 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, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter };
|
package/dist/index.js
CHANGED
|
@@ -923,17 +923,82 @@ var INPUT_DRAFT_TYPES = /* @__PURE__ */ new Set([
|
|
|
923
923
|
"core.tool_result",
|
|
924
924
|
"core.system_note"
|
|
925
925
|
]);
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
if (
|
|
930
|
-
|
|
931
|
-
if (
|
|
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.")) {
|
|
932
967
|
throw new RangeError(
|
|
933
|
-
`input draft rejects event type ${String(
|
|
968
|
+
`input draft rejects event type ${String(draft.type)}: only core.user_message, core.tool_result, core.system_note or ext.* are accepted`
|
|
934
969
|
);
|
|
935
970
|
}
|
|
936
|
-
|
|
971
|
+
if (typeof draft.actor !== "string" || !INPUT_ACTORS.has(draft.actor)) {
|
|
972
|
+
throw new RangeError(
|
|
973
|
+
`input draft actor must be user, model, tool, system or host, got ${String(draft.actor)}`
|
|
974
|
+
);
|
|
975
|
+
}
|
|
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);
|
|
937
1002
|
}
|
|
938
1003
|
async function* runLoop(cfg) {
|
|
939
1004
|
const { sessionId, log, lowering, model } = cfg;
|
|
@@ -944,7 +1009,10 @@ async function* runLoop(cfg) {
|
|
|
944
1009
|
const { tools: baseTools, systemPrompt: baseSystemPrompt } = await resolveSocketContributions(cfg);
|
|
945
1010
|
const maxTurns = cfg.maxTurns ?? DEFAULT_MAX_TURNS;
|
|
946
1011
|
const retry = resolveRetry(cfg.retry);
|
|
947
|
-
const input = 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
|
+
}
|
|
948
1016
|
const capabilities = lowering.capabilities(model);
|
|
949
1017
|
const configHash = await computeConfigHash({
|
|
950
1018
|
model,
|
|
@@ -1045,7 +1113,7 @@ async function* runLoop(cfg) {
|
|
|
1045
1113
|
announce: cfg.announceToolChanges ?? true
|
|
1046
1114
|
})
|
|
1047
1115
|
);
|
|
1048
|
-
|
|
1116
|
+
yield* await append(input.map((d) => withResultTrust(d, baseTools)));
|
|
1049
1117
|
while (true) {
|
|
1050
1118
|
const turnStartedAt = now();
|
|
1051
1119
|
const timeline = await readTimeline(log, sessionId, { registry });
|
|
@@ -1490,6 +1558,78 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
|
1490
1558
|
return summary;
|
|
1491
1559
|
}
|
|
1492
1560
|
|
|
1561
|
+
// src/lowering/tool-arguments.ts
|
|
1562
|
+
function unwrapToolArguments(parsed) {
|
|
1563
|
+
if (typeof parsed !== "string") return { args: parsed, unwrapped: false };
|
|
1564
|
+
const inner = parseLenient(parsed);
|
|
1565
|
+
if (typeof inner === "object" && inner !== null && !Array.isArray(inner))
|
|
1566
|
+
return { args: inner, unwrapped: true };
|
|
1567
|
+
return { args: parsed, unwrapped: false };
|
|
1568
|
+
}
|
|
1569
|
+
function decodeToolArgumentsText(raw) {
|
|
1570
|
+
if (raw.trim() === "") return { args: {}, unwrapped: false };
|
|
1571
|
+
let once;
|
|
1572
|
+
try {
|
|
1573
|
+
once = JSON.parse(raw);
|
|
1574
|
+
} catch {
|
|
1575
|
+
return { args: raw, unwrapped: false };
|
|
1576
|
+
}
|
|
1577
|
+
if (typeof once !== "string") return { args: once, unwrapped: false };
|
|
1578
|
+
const decoded = unwrapToolArguments(once);
|
|
1579
|
+
return decoded.unwrapped ? decoded : { args: raw, unwrapped: false };
|
|
1580
|
+
}
|
|
1581
|
+
function toolCallArgumentsMeta(decoded) {
|
|
1582
|
+
return decoded.unwrapped ? { meta: { argumentsUnwrapped: true } } : {};
|
|
1583
|
+
}
|
|
1584
|
+
function parseLenient(text) {
|
|
1585
|
+
try {
|
|
1586
|
+
return JSON.parse(text);
|
|
1587
|
+
} catch {
|
|
1588
|
+
const repaired = escapeControlCharsInStrings(text);
|
|
1589
|
+
if (repaired === text) return void 0;
|
|
1590
|
+
try {
|
|
1591
|
+
return JSON.parse(repaired);
|
|
1592
|
+
} catch {
|
|
1593
|
+
return void 0;
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
function escapeControlCharsInStrings(text) {
|
|
1598
|
+
let out = "";
|
|
1599
|
+
let inString = false;
|
|
1600
|
+
let escaped = false;
|
|
1601
|
+
for (const ch of text) {
|
|
1602
|
+
if (!inString) {
|
|
1603
|
+
if (ch === '"') inString = true;
|
|
1604
|
+
out += ch;
|
|
1605
|
+
continue;
|
|
1606
|
+
}
|
|
1607
|
+
if (escaped) {
|
|
1608
|
+
escaped = false;
|
|
1609
|
+
out += ch;
|
|
1610
|
+
continue;
|
|
1611
|
+
}
|
|
1612
|
+
if (ch === "\\") escaped = true;
|
|
1613
|
+
else if (ch === '"') inString = false;
|
|
1614
|
+
else {
|
|
1615
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
1616
|
+
if (code < 32) {
|
|
1617
|
+
out += CONTROL_ESCAPES[ch] ?? `\\u${code.toString(16).padStart(4, "0")}`;
|
|
1618
|
+
continue;
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
out += ch;
|
|
1622
|
+
}
|
|
1623
|
+
return out;
|
|
1624
|
+
}
|
|
1625
|
+
var CONTROL_ESCAPES = {
|
|
1626
|
+
"\n": "\\n",
|
|
1627
|
+
"\r": "\\r",
|
|
1628
|
+
" ": "\\t",
|
|
1629
|
+
"\b": "\\b",
|
|
1630
|
+
"\f": "\\f"
|
|
1631
|
+
};
|
|
1632
|
+
|
|
1493
1633
|
// src/lowering/trust.ts
|
|
1494
1634
|
var UNTRUSTED_TAG = "untrusted";
|
|
1495
1635
|
function untrustedSourceOf(e) {
|
|
@@ -1741,7 +1881,7 @@ function memoryStore() {
|
|
|
1741
1881
|
}
|
|
1742
1882
|
|
|
1743
1883
|
// src/index.ts
|
|
1744
|
-
var REINS_VERSION = "0.
|
|
1884
|
+
var REINS_VERSION = "0.7.0";
|
|
1745
1885
|
export {
|
|
1746
1886
|
BUILTIN_APPROVAL_POLICY,
|
|
1747
1887
|
CORE_SCHEMAS,
|
|
@@ -1777,6 +1917,7 @@ export {
|
|
|
1777
1917
|
createCoreEvent,
|
|
1778
1918
|
createCoreRegistry,
|
|
1779
1919
|
createEvent,
|
|
1920
|
+
decodeToolArgumentsText,
|
|
1780
1921
|
defaultProjectionChain,
|
|
1781
1922
|
defaultSleep,
|
|
1782
1923
|
defaultThresholdSummary,
|
|
@@ -1792,7 +1933,7 @@ export {
|
|
|
1792
1933
|
foldCompactions,
|
|
1793
1934
|
foldedToolResults,
|
|
1794
1935
|
forkSession,
|
|
1795
|
-
|
|
1936
|
+
inputDrafts,
|
|
1796
1937
|
isCompaction,
|
|
1797
1938
|
isContentPart,
|
|
1798
1939
|
isModelOutput,
|
|
@@ -1826,11 +1967,13 @@ export {
|
|
|
1826
1967
|
statusFromMessage,
|
|
1827
1968
|
subagentPause,
|
|
1828
1969
|
supersededIds,
|
|
1970
|
+
toolCallArgumentsMeta,
|
|
1829
1971
|
toolResultTrust,
|
|
1830
1972
|
toolSpecOf,
|
|
1831
1973
|
toolsBoundDrafts,
|
|
1832
1974
|
untrustedOpenTag,
|
|
1833
1975
|
untrustedSourceOf,
|
|
1976
|
+
unwrapToolArguments,
|
|
1834
1977
|
uuidv7,
|
|
1835
1978
|
validateResume,
|
|
1836
1979
|
verifyRunState,
|