@reinsjs/core 0.1.1 → 0.2.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 +22 -0
- package/README.md +2 -2
- package/dist/{chunk-BOJD54XN.js → chunk-63AJKR7J.js} +34 -22
- package/dist/chunk-63AJKR7J.js.map +1 -0
- package/dist/index.d.ts +33 -7
- package/dist/index.js +109 -40
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +9 -2
- package/dist/testing/index.js +209 -92
- package/dist/testing/index.js.map +1 -1
- package/dist/{types-BeGSiC1e.d.ts → types-DJB-13o3.d.ts} +58 -5
- package/package.json +5 -5
- package/dist/chunk-BOJD54XN.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @reinsjs/core
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 49d5dea: New store interface `RunLease` (`acquire` / `renew` / `release`) and optional `Stores.runLease` — a lease table that lets the "one run per session at a time" guard span processes. Expiry is judged by the store's own clock, `acquire` is idempotent for the same owner, and none of the three methods throw on contention (they answer with a boolean). `InMemoryRunLease({ now })` is the reference implementation (not included in `memoryStore()`, which stays single-process), and `runLeaseConformance` joins the other suites in `@reinsjs/core/testing`.
|
|
8
|
+
- 14345eb: Every user-facing runtime string is now English. This covers thrown error messages (construction-time validation, store and registry errors, HTTP 4xx bodies), `warn()` output from the brain modules and the server, the text the model sees in error tool results (`Unknown tool: …`, `Tool call blocked: …`, `Invalid arguments: …`, `Approval denied…`, `Approval expired…`), the `note` / `when` fields of every lowering loss matrix and landing, the placeholder text for content a wire protocol cannot carry, the conformance suites exported from `@reinsjs/core/testing`, and the `@reinsjs/eval` report and gate output. Previously these were Chinese while the READMEs and model-facing prompts were English, which left a non-Chinese-speaking host with unreadable diagnostics.
|
|
9
|
+
|
|
10
|
+
Nothing changes structurally: same errors, same codes, same warning points, same landing kinds. Hosts that match on the text of a message or a landing note (rather than on its error code or `landing` value) need to update those matches.
|
|
11
|
+
|
|
12
|
+
- a082a0c: Deferred tool loading, the provider-native path for `lazyTools()`:
|
|
13
|
+
|
|
14
|
+
- `ContentPart` gains a `tool_reference` member — `{ type: "tool_reference", name, description, inputSchema }`, a tool definition carried as content (with a full snapshot, so the log stays self-contained). `renderToolReference(part)` is the one way to render it as text; `normalizeToolOutput` accepts it in tool results.
|
|
15
|
+
- `ToolSpec.deferLoading?: boolean` — a tool that is declared to the provider but not loaded into the model's context until a `tool_reference` to it appears in the history.
|
|
16
|
+
- `LoweringCapabilities.deferredTools: boolean` (required; every lowering must declare it) — whether the wire protocol has a native place for both of the above.
|
|
17
|
+
- `BeforeModelPatch.deferredTools?: string[]` — a socket names which tools of this turn's table are deferred; `runLoop` translates it through the new `deferredToolSpecOf(tool, deferred)`. `toolSpecOf` keeps its single parameter on purpose (it is commonly passed to `map`).
|
|
18
|
+
|
|
19
|
+
Projection estimates count a reference as its rendered text. Hosts implementing their own `Lowering` must add `deferredTools: false` to their capabilities.
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- c16e3ea: README only: point to `@reinsjs/lowering-fetch` as the second lowering layer (the umbrella README's install line and import now show it; `@reinsjs/lowering-pi`'s README links to the side-by-side comparison; `@reinsjs/core`'s module table lists both implementations). No code changes.
|
|
24
|
+
|
|
3
25
|
## 0.1.1
|
|
4
26
|
|
|
5
27
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @reinsjs/core
|
|
2
2
|
|
|
3
|
-
The kernel of [reins](../../README.md): an append-only event timeline, the projection that decides what the model sees on each turn, a loop of a few hundred lines you can read and copy, a serializable run state for pause/resume across processes, and the `Socket` seam that everything else plugs into. Zero dependencies, zero `node:*` — Web standards only; verified on Node 22
|
|
3
|
+
The kernel of [reins](../../README.md): an append-only event timeline, the projection that decides what the model sees on each turn, a loop of a few hundred lines you can read and copy, a serializable run state for pause/resume across processes, and the `Socket` seam that everything else plugs into. Zero dependencies, zero `node:*` — Web standards only; verified on Node 22, Cloudflare workerd (strictest compat), Bun, Deno and Vercel's Edge Runtime (`spikes/runtime-matrix`).
|
|
4
4
|
|
|
5
5
|
Two principles shape every type in here:
|
|
6
6
|
|
|
@@ -20,7 +20,7 @@ Most applications import the umbrella package `@reinsjs/agent` instead; `@reinsj
|
|
|
20
20
|
| `events/` | `Event`, `EventDraft`, `createCoreRegistry`, `createEvent`, `CoreEvent` types | Event shell + payloads, `schemaVersion` on every type, upcast-on-read (unknown types are rejected, not skipped) |
|
|
21
21
|
| `store/` | `EventLog`, `BlobStore`, `MemoryStore`, `InMemory*`, `memoryStore()`, `readTimeline` | Storage contracts. `EventLog.append` is the only write; `seq` is assigned by the caller and must be contiguous (optimistic concurrency) |
|
|
22
22
|
| `projection/` | `project`, `ProjectionStrategy`, `DEFAULT_MODEL_INVISIBLE_TYPES` | Pure function: timeline → what the model sees this turn (filter → fold → pin → trim to budget). Strategies may create events, but they go through the loop into the log first |
|
|
23
|
-
| `lowering/` | `Lowering`, `LoweredRequest`, `LandingRecord`, `markUntrusted` | Interface to a provider wire protocol plus the loss matrix types;
|
|
23
|
+
| `lowering/` | `Lowering`, `LoweredRequest`, `LandingRecord`, `markUntrusted` | Interface to a provider wire protocol plus the loss matrix types; implementations in `@reinsjs/lowering-fetch` (zero-dependency) and `@reinsjs/lowering-pi` (pi-ai) |
|
|
24
24
|
| `loop/` | `runLoop`, `Socket`, `Tool`, `defineTool`, `RunResult`, `SerializedRunState`, `Interruption`, `subagentPause`, `retry` | The default loop and its seams |
|
|
25
25
|
| `replay/` | `replayTurns` | Recompute what the model saw on every turn from the log alone (audit UIs, eval) |
|
|
26
26
|
| `@reinsjs/core/testing` | `ScriptedLowering`, `callTool`, `say`, `think`, store conformance suites | Deterministic model scripts and a suite any `EventLog` / `BlobStore` / `MemoryStore` implementation should pass |
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
// src/events/base.ts
|
|
2
|
+
function renderToolReference(part) {
|
|
3
|
+
return `### ${part.name}
|
|
4
|
+
${part.description.trim()}
|
|
5
|
+
Input schema: ${JSON.stringify(part.inputSchema)}`;
|
|
6
|
+
}
|
|
2
7
|
var DEFAULT_TRUST = {
|
|
3
8
|
user: "principal",
|
|
4
9
|
system: "system",
|
|
@@ -65,24 +70,30 @@ var EventSchemaRegistry = class {
|
|
|
65
70
|
/** 登记一个 type。重复登记同一 type 视为错误,避免两处定义互相覆盖。 */
|
|
66
71
|
register(schema) {
|
|
67
72
|
if (!schema.type || !/^(core|ext)\.[a-z][a-z0-9_]*$/.test(schema.type)) {
|
|
68
|
-
throw new SchemaError(
|
|
69
|
-
|
|
70
|
-
|
|
73
|
+
throw new SchemaError(
|
|
74
|
+
"invalid_schema",
|
|
75
|
+
`type must look like "core.xxx" or "ext.xxx", got ${schema.type}`,
|
|
76
|
+
{
|
|
77
|
+
type: schema.type
|
|
78
|
+
}
|
|
79
|
+
);
|
|
71
80
|
}
|
|
72
81
|
if (!Number.isInteger(schema.version) || schema.version < 1) {
|
|
73
|
-
throw new SchemaError("invalid_schema", `version
|
|
82
|
+
throw new SchemaError("invalid_schema", `version must be an integer >= 1, got ${schema.version}`, {
|
|
74
83
|
type: schema.type,
|
|
75
84
|
version: schema.version
|
|
76
85
|
});
|
|
77
86
|
}
|
|
78
87
|
if (this.schemas.has(schema.type)) {
|
|
79
|
-
throw new SchemaError("invalid_schema", `type
|
|
88
|
+
throw new SchemaError("invalid_schema", `type already registered: ${schema.type}`, {
|
|
89
|
+
type: schema.type
|
|
90
|
+
});
|
|
80
91
|
}
|
|
81
92
|
for (let v = 1; v < schema.version; v++) {
|
|
82
93
|
if (typeof schema.upcasters?.[v] !== "function") {
|
|
83
94
|
throw new SchemaError(
|
|
84
95
|
"invalid_schema",
|
|
85
|
-
`${schema.type}
|
|
96
|
+
`${schema.type} is at version ${schema.version} but has no v${v} -> v${v + 1} upgrade function`,
|
|
86
97
|
{ type: schema.type, version: v }
|
|
87
98
|
);
|
|
88
99
|
}
|
|
@@ -96,7 +107,7 @@ var EventSchemaRegistry = class {
|
|
|
96
107
|
/** 该 type 当前应写入的版本号;未登记则抛 unknown_type。 */
|
|
97
108
|
currentVersion(type) {
|
|
98
109
|
const s = this.schemas.get(type);
|
|
99
|
-
if (!s) throw new SchemaError("unknown_type",
|
|
110
|
+
if (!s) throw new SchemaError("unknown_type", `unregistered event type: ${type}`, { type });
|
|
100
111
|
return s.version;
|
|
101
112
|
}
|
|
102
113
|
/**
|
|
@@ -108,12 +119,12 @@ var EventSchemaRegistry = class {
|
|
|
108
119
|
const base = assertBase(raw);
|
|
109
120
|
const schema = this.schemas.get(base.type);
|
|
110
121
|
if (!schema) {
|
|
111
|
-
throw new SchemaError("unknown_type",
|
|
122
|
+
throw new SchemaError("unknown_type", `unregistered event type: ${base.type}`, { type: base.type });
|
|
112
123
|
}
|
|
113
124
|
if (base.schemaVersion > schema.version) {
|
|
114
125
|
throw new SchemaError(
|
|
115
126
|
"future_version",
|
|
116
|
-
`${base.type} v${base.schemaVersion}
|
|
127
|
+
`${base.type} v${base.schemaVersion} is newer than the locally known v${schema.version}; upgrade the code`,
|
|
117
128
|
{ type: base.type, version: base.schemaVersion }
|
|
118
129
|
);
|
|
119
130
|
}
|
|
@@ -121,7 +132,7 @@ var EventSchemaRegistry = class {
|
|
|
121
132
|
for (let v = base.schemaVersion; v < schema.version; v++) {
|
|
122
133
|
const up = schema.upcasters?.[v];
|
|
123
134
|
if (!up) {
|
|
124
|
-
throw new SchemaError("missing_upcaster", `${base.type}
|
|
135
|
+
throw new SchemaError("missing_upcaster", `${base.type} has no v${v} -> v${v + 1} upgrade function`, {
|
|
125
136
|
type: base.type,
|
|
126
137
|
version: v
|
|
127
138
|
});
|
|
@@ -131,7 +142,7 @@ var EventSchemaRegistry = class {
|
|
|
131
142
|
} catch (cause) {
|
|
132
143
|
throw new SchemaError(
|
|
133
144
|
"upcaster_failed",
|
|
134
|
-
`${base.type} v${v}
|
|
145
|
+
`${base.type} v${v} -> v${v + 1} upgrade failed: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
135
146
|
{ type: base.type, version: v }
|
|
136
147
|
);
|
|
137
148
|
}
|
|
@@ -141,33 +152,33 @@ var EventSchemaRegistry = class {
|
|
|
141
152
|
};
|
|
142
153
|
function assertBase(raw) {
|
|
143
154
|
if (typeof raw !== "object" || raw === null) {
|
|
144
|
-
throw new SchemaError("malformed_base", "
|
|
155
|
+
throw new SchemaError("malformed_base", "event must be an object");
|
|
145
156
|
}
|
|
146
157
|
const r = raw;
|
|
147
158
|
const fail = (field, expect) => {
|
|
148
159
|
throw new SchemaError(
|
|
149
160
|
"malformed_base",
|
|
150
|
-
|
|
161
|
+
`field ${field} must be ${expect}`,
|
|
151
162
|
typeof r.type === "string" ? { type: r.type } : {}
|
|
152
163
|
);
|
|
153
164
|
};
|
|
154
|
-
if (typeof r.id !== "string" || r.id === "") fail("id", "
|
|
155
|
-
if (typeof r.sessionId !== "string" || r.sessionId === "") fail("sessionId", "
|
|
156
|
-
if (!Number.isInteger(r.seq) || r.seq < 1) fail("seq", "
|
|
157
|
-
if (typeof r.at !== "number" || !Number.isFinite(r.at)) fail("at", "
|
|
158
|
-
if (typeof r.type !== "string" || r.type === "") fail("type", "
|
|
165
|
+
if (typeof r.id !== "string" || r.id === "") fail("id", "a non-empty string");
|
|
166
|
+
if (typeof r.sessionId !== "string" || r.sessionId === "") fail("sessionId", "a non-empty string");
|
|
167
|
+
if (!Number.isInteger(r.seq) || r.seq < 1) fail("seq", "an integer >= 1");
|
|
168
|
+
if (typeof r.at !== "number" || !Number.isFinite(r.at)) fail("at", "a finite number");
|
|
169
|
+
if (typeof r.type !== "string" || r.type === "") fail("type", "a non-empty string");
|
|
159
170
|
if (!Number.isInteger(r.schemaVersion) || r.schemaVersion < 1)
|
|
160
|
-
fail("schemaVersion", "
|
|
171
|
+
fail("schemaVersion", "an integer >= 1");
|
|
161
172
|
if (typeof r.actor !== "string" || !ACTORS.has(r.actor)) fail("actor", "user|model|tool|system|host");
|
|
162
173
|
if (typeof r.trust !== "string" || !TRUSTS.has(r.trust)) fail("trust", "principal|system|model|untrusted");
|
|
163
|
-
if (r.parentId !== void 0 && typeof r.parentId !== "string") fail("parentId", "
|
|
174
|
+
if (r.parentId !== void 0 && typeof r.parentId !== "string") fail("parentId", "a string or undefined");
|
|
164
175
|
if (r.provenance !== void 0) {
|
|
165
176
|
const p = r.provenance;
|
|
166
177
|
if (typeof p !== "object" || p === null || typeof p.source !== "string")
|
|
167
178
|
fail("provenance", "{ source: string }");
|
|
168
179
|
}
|
|
169
180
|
if (r.replay !== void 0 && (typeof r.replay !== "object" || r.replay === null))
|
|
170
|
-
fail("replay", "
|
|
181
|
+
fail("replay", "an object or undefined");
|
|
171
182
|
return r;
|
|
172
183
|
}
|
|
173
184
|
var CORE_SCHEMAS = [
|
|
@@ -193,6 +204,7 @@ function createCoreRegistry(extra = []) {
|
|
|
193
204
|
}
|
|
194
205
|
|
|
195
206
|
export {
|
|
207
|
+
renderToolReference,
|
|
196
208
|
DEFAULT_TRUST,
|
|
197
209
|
uuidv7,
|
|
198
210
|
createEvent,
|
|
@@ -202,4 +214,4 @@ export {
|
|
|
202
214
|
CORE_SCHEMAS,
|
|
203
215
|
createCoreRegistry
|
|
204
216
|
};
|
|
205
|
-
//# sourceMappingURL=chunk-
|
|
217
|
+
//# sourceMappingURL=chunk-63AJKR7J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/events/base.ts","../src/events/id.ts","../src/events/create.ts","../src/events/registry.ts"],"sourcesContent":["/**\n * 事件基础类型(技术方案 §4)。\n *\n * 宪法二:时间线是唯一真源,角色只是翻译。内部只有一种数据 —— 带发起者的事件。\n * 本文件只定义\"所有事件共有的壳\",具体载荷见 ./core.ts(内置 core.*)与宿主自定义的 ext.*。\n */\n\n/** 事件发起者。用户打断、脑子注入、宿主插话都只是不同 actor 的一次 append。 */\nexport type Actor = \"user\" | \"model\" | \"tool\" | \"system\" | \"host\"\n\n/**\n * 信任等级,供投影层与安全网判断\"这段内容能不能当指令\"。\n * - principal:主事人(用户)说的\n * - system:库或宿主注入的\n * - model:模型自己产出的\n * - untrusted:工具输出、外部抓取内容(默认值,防提示注入)\n */\nexport type Trust = \"principal\" | \"system\" | \"model\" | \"untrusted\"\n\n/** 来源:哪个工具、哪个 URL、哪个用户。用于审计与信任判断。 */\nexport interface Provenance {\n source: string\n ref?: string\n}\n\n/**\n * 所有事件的公共字段。\n * 载荷放在 payload 下(而不是平铺),这样 schema 升级函数只碰 payload,壳永远稳定。\n */\nexport interface EventBase {\n /** uuidv7,时间有序;会话内唯一。fork 复制的事件保留原 id,以维持 parentId / pinsKept 等引用 */\n id: string\n sessionId: string\n /** 会话内单调递增,从 1 起;是会话内排序的唯一依据 */\n seq: number\n /** Unix 毫秒 */\n at: number\n /** 命名空间化:内置 \"core.*\",宿主扩展 \"ext.*\" */\n type: string\n /** 该 type 自己的 schema 版本,从 1 起;读时按注册表升级(P9) */\n schemaVersion: number\n actor: Actor\n /** 因果链或分叉点:回答哪条消息、由哪次 tool_call 产生 */\n parentId?: string\n trust: Trust\n provenance?: Provenance\n /** 厂商专有回放数据(thinking signature、encrypted reasoning),不进通用字段 */\n replay?: Record<string, unknown>\n}\n\n/** 带类型载荷的事件。T 为 type 字面量,P 为 payload 形状。 */\nexport type Event<T extends string = string, P = unknown> = EventBase & {\n type: T\n payload: P\n}\n\n/**\n * 内容片段。用户消息、工具结果都由它组成;投影/降级时再翻译成各家 API 的 content block。\n * 文本、图片,以及\"工具定义引用\"(L1);大结果不塞进片段,走 tool_result.spilled 外溢到 BlobStore。\n */\nexport type ContentPart = TextPart | ImagePart | ToolReferencePart\n\nexport interface TextPart {\n type: \"text\"\n text: string\n}\n\nexport interface ImagePart {\n type: \"image\"\n mime: string\n /** base64 编码的图片字节 */\n data: string\n}\n\n/**\n * 工具定义引用(L1,2026-09-15):`tool_find` 这类\"取回工具\"的结果用它表达\"这几件工具从现在起可用\"。\n * 带完整定义快照,日志自足(宪法二:模型可见的一切都在日志里);翻译时按能力分两路——\n * 支持原生延迟加载的线(Anthropic `defer_loading`)只发 `tool_reference` 块、由厂商就地展开、工具表整段不变;\n * 其余线用 `renderToolReference` 展开成文本,信息等价。宿主经 HTTP 送来的用户消息不接受这种段(server 白名单)。\n */\nexport interface ToolReferencePart {\n type: \"tool_reference\"\n name: string\n description: string\n /** JSON Schema 对象,与 Tool.inputSchema 同形 */\n inputSchema: Record<string, unknown>\n}\n\n/** 引用段展开成文本的唯一写法:非原生线的降级层、UI、投影估算都调它,别各自拼 */\nexport function renderToolReference(part: ToolReferencePart): string {\n return `### ${part.name}\\n${part.description.trim()}\\nInput schema: ${JSON.stringify(part.inputSchema)}`\n}\n\n/** 各 actor 的默认信任等级;工厂函数在未显式给出 trust 时使用。 */\nexport const DEFAULT_TRUST: Readonly<Record<Actor, Trust>> = {\n user: \"principal\",\n system: \"system\",\n host: \"system\",\n model: \"model\",\n tool: \"untrusted\",\n}\n","/**\n * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。\n * 只用 Web 标准 crypto.getRandomValues,不引依赖(P5)。\n *\n * 同一毫秒内的多个 id 之间顺序随机 —— 会话内排序以 seq 为准,id 只需全局唯一且大致有序。\n */\nexport function uuidv7(now: number = Date.now()): string {\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n\n // 48 位时间戳,大端写入 bytes[0..5]\n let ts = now\n for (let i = 5; i >= 0; i--) {\n bytes[i] = ts & 0xff\n ts = Math.floor(ts / 256)\n }\n // 版本位:byte6 高 4 位 = 0111\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x70\n // 变体位:byte8 高 2 位 = 10\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80\n\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n","/**\n * 事件工厂:补齐 id / at / schemaVersion / trust,调用方只关心\"谁、在哪个会话、第几条、说了什么\"。\n * seq 由 EventLog 的 append 方决定(T4),这里要求显式传入,不替存储层做主。\n */\nimport { type Actor, DEFAULT_TRUST, type Event, type EventBase, type Provenance, type Trust } from \"./base.js\"\nimport type { CoreEventOf, CoreEventPayloads, CoreEventType } from \"./core.js\"\nimport { uuidv7 } from \"./id.js\"\nimport type { EventSchemaRegistry } from \"./registry.js\"\n\n/**\n * 事件草稿:还没进日志的事件,缺 id / seq / at / sessionId / schemaVersion。\n * 降级层(模型输出)与脑子模块(注入的 system_note)都只产出草稿,由循环补齐后 append ——\n * 谁分配 seq 只有循环知道,草稿不替它做主。\n */\nexport interface EventDraft<T extends string = string, P = unknown> {\n type: T\n payload: P\n actor: Actor\n /** 缺省按 DEFAULT_TRUST[actor] */\n trust?: Trust\n parentId?: string\n provenance?: Provenance\n replay?: Record<string, unknown>\n}\n\n/** 内置事件的草稿联合,type 与 payload 联动 */\nexport type CoreEventDraft = { [T in CoreEventType]: EventDraft<T, CoreEventPayloads[T]> }[CoreEventType]\n\nexport interface CreateEventInput<T extends string, P> extends EventDraft<T, P> {\n sessionId: string\n seq: number\n /** 测试注入用;缺省 Date.now() */\n at?: number\n id?: string\n}\n\n/**\n * 通用工厂。schemaVersion 从注册表取当前版本,所以未登记的 type 会在这里就被拒绝,\n * 而不是写进日志后读不出来。\n */\nexport function createEvent<T extends string, P>(\n registry: EventSchemaRegistry,\n input: CreateEventInput<T, P>,\n): Event<T, P> {\n const at = input.at ?? Date.now()\n const base: EventBase = {\n id: input.id ?? uuidv7(at),\n sessionId: input.sessionId,\n seq: input.seq,\n at,\n type: input.type,\n schemaVersion: registry.currentVersion(input.type),\n actor: input.actor,\n trust: input.trust ?? DEFAULT_TRUST[input.actor],\n }\n // 可选字段只在有值时写入,避免日志里出现一堆 undefined(exactOptionalPropertyTypes 也不允许)\n if (input.parentId !== undefined) base.parentId = input.parentId\n if (input.provenance !== undefined) base.provenance = input.provenance\n if (input.replay !== undefined) base.replay = input.replay\n return { ...base, type: input.type, payload: input.payload }\n}\n\n/** 内置事件的强类型版本:type 与 payload 联动校验。 */\nexport function createCoreEvent<T extends CoreEventType>(\n registry: EventSchemaRegistry,\n input: CreateEventInput<T, CoreEventPayloads[T]>,\n): CoreEventOf<T> {\n return createEvent(registry, input) as CoreEventOf<T>\n}\n","/**\n * 事件 schema 注册表(P9:schema 有版本,读时升级,查不到即拒绝)。\n *\n * 职责:\n * 1. 登记每个 type 的当前版本与逐级升级函数 upcast(v → v+1)\n * 2. read(raw):校验壳字段 → 查 type → 逐级升级到当前版本 → 返回类型化事件\n * 3. 任何一步查不到都抛 SchemaError(fail-closed),绝不静默返回半个事件\n *\n * 日志文件不做原地迁移:存的永远是写入时的版本,读时升级。\n */\nimport type { Actor, Event, EventBase, Trust } from \"./base.js\"\nimport type { CoreEventType } from \"./core.js\"\n\n/** 把 payload 从版本 from 升到 from+1。只碰 payload,壳字段由注册表保证不变。 */\nexport type Upcaster = (payload: unknown) => unknown\n\nexport interface EventSchema {\n type: string\n /** 当前版本;新写入的事件一律打这个版本号 */\n version: number\n /**\n * 升级函数表,键为\"起点版本\":upcasters[1] 把 v1 升到 v2。\n * version 为 n 时必须覆盖 1..n-1 全部键,缺一个即注册失败 —— 宁可启动时报错,不要读到一半才发现。\n */\n upcasters?: Readonly<Record<number, Upcaster>>\n}\n\nexport type SchemaErrorCode =\n | \"malformed_base\" // 壳字段缺失或类型不对\n | \"unknown_type\" // 没登记的 type\n | \"future_version\" // 版本比注册表还新(旧代码读新日志)\n | \"missing_upcaster\" // 升级链断了\n | \"upcaster_failed\" // 升级函数自己抛了\n | \"invalid_schema\" // 登记时的定义不合法\n\nexport class SchemaError extends Error {\n constructor(\n readonly code: SchemaErrorCode,\n message: string,\n readonly context: { type?: string; version?: number } = {},\n ) {\n super(`[${code}] ${message}`)\n this.name = \"SchemaError\"\n }\n}\n\nconst ACTORS: ReadonlySet<string> = new Set<Actor>([\"user\", \"model\", \"tool\", \"system\", \"host\"])\nconst TRUSTS: ReadonlySet<string> = new Set<Trust>([\"principal\", \"system\", \"model\", \"untrusted\"])\n\nexport class EventSchemaRegistry {\n private readonly schemas = new Map<string, EventSchema>()\n\n constructor(schemas: Iterable<EventSchema> = []) {\n for (const s of schemas) this.register(s)\n }\n\n /** 登记一个 type。重复登记同一 type 视为错误,避免两处定义互相覆盖。 */\n register(schema: EventSchema): this {\n if (!schema.type || !/^(core|ext)\\.[a-z][a-z0-9_]*$/.test(schema.type)) {\n throw new SchemaError(\n \"invalid_schema\",\n `type must look like \"core.xxx\" or \"ext.xxx\", got ${schema.type}`,\n {\n type: schema.type,\n },\n )\n }\n if (!Number.isInteger(schema.version) || schema.version < 1) {\n throw new SchemaError(\"invalid_schema\", `version must be an integer >= 1, got ${schema.version}`, {\n type: schema.type,\n version: schema.version,\n })\n }\n if (this.schemas.has(schema.type)) {\n throw new SchemaError(\"invalid_schema\", `type already registered: ${schema.type}`, {\n type: schema.type,\n })\n }\n for (let v = 1; v < schema.version; v++) {\n if (typeof schema.upcasters?.[v] !== \"function\") {\n throw new SchemaError(\n \"invalid_schema\",\n `${schema.type} is at version ${schema.version} but has no v${v} -> v${v + 1} upgrade function`,\n { type: schema.type, version: v },\n )\n }\n }\n this.schemas.set(schema.type, schema)\n return this\n }\n\n has(type: string): boolean {\n return this.schemas.has(type)\n }\n\n /** 该 type 当前应写入的版本号;未登记则抛 unknown_type。 */\n currentVersion(type: string): number {\n const s = this.schemas.get(type)\n if (!s) throw new SchemaError(\"unknown_type\", `unregistered event type: ${type}`, { type })\n return s.version\n }\n\n /**\n * 从存储读出的原始对象 → 当前版本的事件。\n * 泛型只是给调用方的类型提示(如 read<CoreEvent>),运行时校验的是壳与版本,不校验 payload 形状 ——\n * payload 的正确性由写入方与升级函数负责。\n */\n read<E extends Event = Event>(raw: unknown): E {\n const base = assertBase(raw)\n const schema = this.schemas.get(base.type)\n if (!schema) {\n throw new SchemaError(\"unknown_type\", `unregistered event type: ${base.type}`, { type: base.type })\n }\n if (base.schemaVersion > schema.version) {\n throw new SchemaError(\n \"future_version\",\n `${base.type} v${base.schemaVersion} is newer than the locally known v${schema.version}; upgrade the code`,\n { type: base.type, version: base.schemaVersion },\n )\n }\n\n let payload = (raw as { payload?: unknown }).payload\n for (let v = base.schemaVersion; v < schema.version; v++) {\n const up = schema.upcasters?.[v]\n if (!up) {\n // register() 已保证不会走到这里,留作防御\n throw new SchemaError(\"missing_upcaster\", `${base.type} has no v${v} -> v${v + 1} upgrade function`, {\n type: base.type,\n version: v,\n })\n }\n try {\n payload = up(payload)\n } catch (cause) {\n throw new SchemaError(\n \"upcaster_failed\",\n `${base.type} v${v} -> v${v + 1} upgrade failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n { type: base.type, version: v },\n )\n }\n }\n\n return { ...base, schemaVersion: schema.version, payload } as E\n }\n}\n\n/** 校验壳字段。只看公共字段,payload 不管。 */\nfunction assertBase(raw: unknown): EventBase {\n if (typeof raw !== \"object\" || raw === null) {\n throw new SchemaError(\"malformed_base\", \"event must be an object\")\n }\n const r = raw as Record<string, unknown>\n const fail = (field: string, expect: string): never => {\n throw new SchemaError(\n \"malformed_base\",\n `field ${field} must be ${expect}`,\n typeof r.type === \"string\" ? { type: r.type } : {},\n )\n }\n if (typeof r.id !== \"string\" || r.id === \"\") fail(\"id\", \"a non-empty string\")\n if (typeof r.sessionId !== \"string\" || r.sessionId === \"\") fail(\"sessionId\", \"a non-empty string\")\n if (!Number.isInteger(r.seq) || (r.seq as number) < 1) fail(\"seq\", \"an integer >= 1\")\n if (typeof r.at !== \"number\" || !Number.isFinite(r.at)) fail(\"at\", \"a finite number\")\n if (typeof r.type !== \"string\" || r.type === \"\") fail(\"type\", \"a non-empty string\")\n if (!Number.isInteger(r.schemaVersion) || (r.schemaVersion as number) < 1)\n fail(\"schemaVersion\", \"an integer >= 1\")\n if (typeof r.actor !== \"string\" || !ACTORS.has(r.actor)) fail(\"actor\", \"user|model|tool|system|host\")\n if (typeof r.trust !== \"string\" || !TRUSTS.has(r.trust)) fail(\"trust\", \"principal|system|model|untrusted\")\n if (r.parentId !== undefined && typeof r.parentId !== \"string\") fail(\"parentId\", \"a string or undefined\")\n if (r.provenance !== undefined) {\n const p = r.provenance as Record<string, unknown> | null\n if (typeof p !== \"object\" || p === null || typeof p.source !== \"string\")\n fail(\"provenance\", \"{ source: string }\")\n }\n if (r.replay !== undefined && (typeof r.replay !== \"object\" || r.replay === null))\n fail(\"replay\", \"an object or undefined\")\n return r as unknown as EventBase\n}\n\n/** 全部内置事件当前都是 v1。升版本时在此加 upcasters,并在 core.ts 改载荷类型。 */\nexport const CORE_SCHEMAS: readonly EventSchema[] = (\n [\n \"core.user_message\",\n \"core.model_text\",\n \"core.model_thinking\",\n \"core.tool_call\",\n \"core.tool_result\",\n \"core.system_note\",\n \"core.approval_request\",\n \"core.approval_decision\",\n \"core.compaction\",\n \"core.handoff\",\n \"core.memory_op\",\n \"core.budget_usage\",\n \"core.run_paused\",\n \"core.run_resumed\",\n \"core.tools_bound\",\n \"core.error\",\n ] satisfies CoreEventType[]\n).map((type) => ({ type, version: 1 }))\n\n/** 预装了全部 core.* 的注册表。宿主要加 ext.* 时 new 一个并传入 [...CORE_SCHEMAS, ...自己的]。 */\nexport function createCoreRegistry(extra: Iterable<EventSchema> = []): EventSchemaRegistry {\n return new EventSchemaRegistry([...CORE_SCHEMAS, ...extra])\n}\n"],"mappings":";AAyFO,SAAS,oBAAoB,MAAiC;AACnE,SAAO,OAAO,KAAK,IAAI;AAAA,EAAK,KAAK,YAAY,KAAK,CAAC;AAAA,gBAAmB,KAAK,UAAU,KAAK,WAAW,CAAC;AACxG;AAGO,IAAM,gBAAgD;AAAA,EAC3D,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,MA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OAAO,UAAU,EAAE,aAAa,KAAM,EAAE,gBAA2B;AACtE,SAAK,iBAAiB,iBAAiB;AACzC,MAAI,OAAO,EAAE,UAAU,YAAY,CAAC,OAAO,IAAI,EAAE,KAAK,EAAG,MAAK,SAAS,6BAA6B;AACpG,MAAI,OAAO,EAAE,UAAU,YAAY,CAAC,OAAO,IAAI,EAAE,KAAK,EAAG,MAAK,SAAS,kCAAkC;AACzG,MAAI,EAAE,aAAa,UAAa,OAAO,EAAE,aAAa,SAAU,MAAK,YAAY,uBAAuB;AACxG,MAAI,EAAE,eAAe,QAAW;AAC9B,UAAM,IAAI,EAAE;AACZ,QAAI,OAAO,MAAM,YAAY,MAAM,QAAQ,OAAO,EAAE,WAAW;AAC7D,WAAK,cAAc,oBAAoB;AAAA,EAC3C;AACA,MAAI,EAAE,WAAW,WAAc,OAAO,EAAE,WAAW,YAAY,EAAE,WAAW;AAC1E,SAAK,UAAU,wBAAwB;AACzC,SAAO;AACT;AAGO,IAAM,eACX;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,EACA,IAAI,CAAC,UAAU,EAAE,MAAM,SAAS,EAAE,EAAE;AAG/B,SAAS,mBAAmB,QAA+B,CAAC,GAAwB;AACzF,SAAO,IAAI,oBAAoB,CAAC,GAAG,cAAc,GAAG,KAAK,CAAC;AAC5D;","names":[]}
|
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, S as Stores } from './types-
|
|
2
|
-
export {
|
|
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';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
|
|
@@ -234,6 +234,12 @@ interface BeforeModelPatch {
|
|
|
234
234
|
events?: Event[];
|
|
235
235
|
tools?: Tool[];
|
|
236
236
|
systemPrompt?: string;
|
|
237
|
+
/**
|
|
238
|
+
* 本轮工具表里哪些只"向厂商声明、不载入上下文"(按名字;L1)。循环把它翻成 `ToolSpec.deferLoading`,
|
|
239
|
+
* 名字不在最终工具表里的忽略。只在 `ctx.capabilities.deferredTools` 为真时有意义——没有原生落点的降级层会直接不发这些工具。
|
|
240
|
+
* 后一个 Socket 给了就整体替换前一个的;没给就沿用
|
|
241
|
+
*/
|
|
242
|
+
deferredTools?: readonly string[];
|
|
237
243
|
}
|
|
238
244
|
/** 审批请求的规格;toolCallId 由循环填 */
|
|
239
245
|
interface ApprovalRequestSpec {
|
|
@@ -652,8 +658,12 @@ declare function toolResultTrust(tool: Tool | undefined, isError: boolean): Trus
|
|
|
652
658
|
* 返回值却能直接放进 Tool[]。不用它也行,只是 needsApproval 写成函数时 TS 会因参数逆变拒绝放进数组。
|
|
653
659
|
*/
|
|
654
660
|
declare function defineTool<TInput>(tool: Tool<TInput>): Tool;
|
|
655
|
-
/**
|
|
661
|
+
/** 工具声明的模型可见部分(刻意单参:常被 `tools.map(toolSpecOf)` 调用,多一个参数就会吃进下标) */
|
|
656
662
|
declare function toolSpecOf(tool: Tool): ToolSpec;
|
|
663
|
+
/** 带"声明但不载入"标记的规格(L1):runLoop 按 BeforeModelPatch.deferredTools 对本轮工具表逐件调 */
|
|
664
|
+
declare function deferredToolSpecOf(tool: Tool, deferred: boolean): ToolSpec;
|
|
665
|
+
/** 工具返回值里能认出的内容段:文本、图片、工具定义引用(L1)。宿主经 HTTP 送来的用户消息另有白名单(server),不含引用段 */
|
|
666
|
+
declare function isContentPart(x: unknown): x is ContentPart;
|
|
657
667
|
/**
|
|
658
668
|
* execute 的返回值 → 模型看到的内容。规则按直觉:
|
|
659
669
|
* - string → 一段文本
|
|
@@ -1013,7 +1023,7 @@ declare class StoreError extends Error {
|
|
|
1013
1023
|
}
|
|
1014
1024
|
|
|
1015
1025
|
/**
|
|
1016
|
-
*
|
|
1026
|
+
* 四个接口的内存实现:零依赖、进程内、无持久化。用途:
|
|
1017
1027
|
* - 单测与示例
|
|
1018
1028
|
* - 一致性套件的参考实现(其他后端的行为以此为准)
|
|
1019
1029
|
* - 短生命周期的宿主(如一次性脚本)
|
|
@@ -1052,7 +1062,23 @@ declare class InMemoryMemoryStore implements MemoryStore {
|
|
|
1052
1062
|
write(path: string, content: string): Promise<void>;
|
|
1053
1063
|
delete(path: string): Promise<void>;
|
|
1054
1064
|
}
|
|
1055
|
-
/**
|
|
1065
|
+
/**
|
|
1066
|
+
* RunLease 的内存参考实现(D4)。进程内的锁跨不了进程,所以它在生产里没有用处——`memoryStore()` 刻意不带它;
|
|
1067
|
+
* 价值在于:一致性套件的基准、server 租约登记表的单测(`now` 可注入,能不等真时间就让租约过期)。
|
|
1068
|
+
*/
|
|
1069
|
+
declare class InMemoryRunLease implements RunLease {
|
|
1070
|
+
private readonly leases;
|
|
1071
|
+
private readonly now;
|
|
1072
|
+
constructor(opts?: {
|
|
1073
|
+
now?: () => number;
|
|
1074
|
+
});
|
|
1075
|
+
acquire(sessionId: string, owner: string, ttlMs: number): Promise<boolean>;
|
|
1076
|
+
renew(sessionId: string, owner: string, ttlMs: number): Promise<boolean>;
|
|
1077
|
+
release(sessionId: string, owner: string): Promise<void>;
|
|
1078
|
+
/** 测试观察用:当前持有者(不看是否过期) */
|
|
1079
|
+
holderOf(sessionId: string): string | undefined;
|
|
1080
|
+
}
|
|
1081
|
+
/** 一套全内存的存储,五分钟体验与测试用;进程结束即清空。不带 `runLease`:单进程用不上,装了只多一份心跳 */
|
|
1056
1082
|
declare function memoryStore(): Stores;
|
|
1057
1083
|
|
|
1058
1084
|
/**
|
|
@@ -1090,6 +1116,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
|
|
|
1090
1116
|
*/
|
|
1091
1117
|
|
|
1092
1118
|
/** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
|
|
1093
|
-
declare const REINS_VERSION = "0.
|
|
1119
|
+
declare const REINS_VERSION = "0.2.0";
|
|
1094
1120
|
|
|
1095
|
-
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, 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, 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, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDraft, isCompaction, 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 };
|
|
1121
|
+
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 };
|