@reinsjs/lowering-pi 0.1.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 ADDED
@@ -0,0 +1,22 @@
1
+ # @reinsjs/lowering-pi
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - First public release.
8
+
9
+ - **Timeline first.** Append-only event log with `schemaVersion` on every event and fail-closed upcast on read; projection decides what the model sees each turn; replay and fork from the log alone.
10
+ - **A loop you can copy.** `runLoop` as an exported async generator: pause/resume is a return value with a small signed state, bounded retry on transient failures only while nothing has been written, tool pipeline `beforeTool → validate → approval → execute → afterTool`, sub-agent pause bubbling (`Interruption { kind: "subagent" }`).
11
+ - **Brain modules** (`@reinsjs/brain`): perception, compact (with folded-result manifest and `recall`; recommended on after measuring 100% recall at lower token cost on two model families), pins, spill, handoff, memory (`memory_20250818` shape, namespace isolation), approval (deny → ask → allow, fail-closed), budget (five limits, sub-agent usage included).
12
+ - **Lowering** (`@reinsjs/lowering-pi`): Anthropic Messages and OpenAI Responses via pi-ai with a declared loss matrix, trust markers on untrusted content, cache-breakpoint handling.
13
+ - **Serving** (`@reinsjs/server`, `@reinsjs/ui-agui`): Web-standard handler with SSE replay from `lastSeq`, per-session run lock, `authorizeSession` (only `true` allows), AG-UI as the first-class UI protocol.
14
+ - **Stores**: SQLite (`node:sqlite` / `bun:sqlite`) and Postgres (`pg` / PGlite), conformance-tested; configurable memory table for per-role isolation.
15
+ - **Tools**: MCP servers as one socket (`@reinsjs/tools-mcp`, tools bound per run, annotations as defaults not permissions); `asTool(agent)` in `reins`.
16
+ - **TanStack AI** middleware (`@reinsjs/adapter-tanstack-ai`): the brain on TanStack's loop with the log as the single source of truth; idempotent client-message import; runtime check for the approval interrupt.
17
+ - **Eval harness** (`@reinsjs/eval`): fixtures from real recordings, recorded tools, arm-vs-arm runner, metrics, the four-rule gate.
18
+
19
+ ### Patch Changes
20
+
21
+ - Updated dependencies
22
+ - @reinsjs/core@0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NewRate Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # @reinsjs/lowering-pi
2
+
3
+ The lowering layer for [reins](../../README.md) built on [pi-ai](https://github.com/badlogic/pi-mono): timeline events → provider messages → Anthropic Messages or OpenAI Responses wire protocol, and streaming responses → event drafts. Every event type has a declared landing per API (`LOSS_MATRIX`: exact, lossy, dropped); nothing is dropped silently.
4
+
5
+ ```bash
6
+ pnpm add @reinsjs/lowering-pi
7
+ ```
8
+
9
+ ```ts
10
+ import { anthropic, openai } from "@reinsjs/lowering-pi"
11
+ import { createAgent } from "reins"
12
+
13
+ const claude = anthropic("claude-opus-5", { apiKey: process.env.ANTHROPIC_API_KEY! })
14
+ const gpt = openai("gpt-5.5", { apiKey: process.env.OPENAI_API_KEY!, baseUrl: "https://gateway.example/v1" })
15
+
16
+ export const agent = createAgent({ model: claude, store, tools })
17
+ ```
18
+
19
+ `anthropic()` / `openai()` return a `BoundModel = { model, lowering }` — the only thing `createAgent` needs. The `apiKey` is a required option, never read from the environment, so the same code runs where there is no `process.env`.
20
+
21
+ ## Options
22
+
23
+ | option | meaning |
24
+ | --- | --- |
25
+ | `apiKey` | required |
26
+ | `baseUrl` | gateway or proxy; both factories accept any endpoint speaking the respective protocol (DeepSeek's Anthropic-compatible endpoint is tested) |
27
+ | `requestOptions` | passed to pi-ai **as a whole, not merged** — if you set it on `openai()`, include `reasoningEffort` yourself or reasoning turns off |
28
+ | `contextWindow`, `maxOutputTokens`, `reasoning`, `images`, `midConversationSystem` | override the capability table (`capabilitiesOf`) for models the table does not know |
29
+ | `trustMarkers` | default on: tool output is wrapped in `<untrusted source="tool:…">` in the request (the log keeps the original) |
30
+
31
+ ## How events land
32
+
33
+ - Model roles exist only here. `system_note` events become `system` blocks where the API allows mid-conversation system content, otherwise a framed `user` message (declared lossy).
34
+ - A user message that arrives while tool results are still pending is moved after them on the wire (Anthropic requires `tool_result` right after `tool_use`) and recorded as `lossy(user)`; the log order is untouched.
35
+ - Thinking blocks are replayed only with a signature from the same provider and model.
36
+ - Anthropic cache breakpoints: at most four block-level breakpoints are set; when they are exhausted the top-level breakpoint is silently skipped rather than producing a 400.
37
+ - pi-ai 0.85.1 has no `system` role for injected content; the layer rewrites the payload in pi-ai's `onPayload` hook. The `LoweredRequest.payload` you can inspect shows the pre-rewrite shape — remember that when debugging a 400.
38
+
39
+ ## Runtime footprint
40
+
41
+ pi-ai declares ten dependencies (≈65 MB installed, about 29 MB of which reins never imports). Nothing Node-specific is on the paths used here; the layer is verified on Cloudflare workerd without `nodejs_compat`. A zero-dependency lowering layer is on the roadmap for hosts that care about install size more than provider coverage.
42
+
43
+ ## Documentation
44
+
45
+ `docs/技术方案.md` §11 (loss matrix and landings), `docs/模块盘点/lowering-pi.md`, `spikes/` (upstream behaviour probes) — in Chinese, at the repository root.
46
+
47
+ MIT © 2026 NewRate Limited.
@@ -0,0 +1,246 @@
1
+ import { ModelRef, LoweringCapabilities, BoundModel, LoweringStreamContext, CoreEventDraft, LoweringOutcome, LossMatrix, LandingSpec, SystemNotePayload, Lowering, ToRequestInput, LoweredRequest, Event, ToolSpec, LandingRecord } from '@reinsjs/core';
2
+ import { Model, Api, AssistantMessageEvent, AssistantMessage, Context } from '@earendil-works/pi-ai';
3
+
4
+ /**
5
+ * ModelRef → pi-ai Model。
6
+ *
7
+ * 只从 providers/<name>.models 取静态模型表(S4:不用 providers/all,它会拉进 Bedrock 与 AWS SDK)。
8
+ * 宿主要用表里没有的模型(代理、私有部署、新发布)时,用 ModelDefinition 以我们自己的词汇描述,
9
+ * 这里补齐 pi-ai 需要的其余字段 —— pi-ai 的 Model 类型不出本包。
10
+ */
11
+
12
+ /** 本包内部使用的 pi-ai 模型类型 */
13
+ type PiModel = Model<Api>;
14
+ /** 第一版支持的线协议 */
15
+ declare const SUPPORTED_APIS: ReadonlySet<string>;
16
+ /** 宿主自定义模型:用我们的词汇描述,字段与 LoweringCapabilities 对齐 */
17
+ interface ModelDefinition {
18
+ provider: string;
19
+ id: string;
20
+ /** "anthropic-messages" | "openai-responses" */
21
+ api: string;
22
+ baseUrl: string;
23
+ /** 支持 thinking / reasoning */
24
+ reasoning: boolean;
25
+ contextWindow: number;
26
+ maxOutputTokens: number;
27
+ images?: boolean;
28
+ name?: string;
29
+ /** 每百万 token 美元价;缺省全 0(成本算不出但能跑) */
30
+ cost?: {
31
+ input: number;
32
+ output: number;
33
+ cacheRead: number;
34
+ cacheWrite: number;
35
+ };
36
+ /** 额外请求头,如私有网关的鉴权 */
37
+ headers?: Record<string, string>;
38
+ /**
39
+ * 是否接受 messages 里的中途 `role:"system"` 消息(system_note 的 exact 落点)。内置 Anthropic 模型按 id 判定;
40
+ * 第三方 Anthropic 协议上游(如 DeepSeek 的兼容端口,2026-09-08 实测接受)由宿主在此声明,缺省按不支持处理。
41
+ */
42
+ midConversationSystem?: boolean;
43
+ }
44
+ declare function definitionToModel(def: ModelDefinition): PiModel;
45
+ declare function resolveModel(ref: ModelRef, extra?: readonly PiModel[]): PiModel;
46
+
47
+ /**
48
+ * 按模型声明能力(技术方案 §11)。脑子模块只看这些布尔值,不看模型名。
49
+ */
50
+
51
+ /** 宿主在 ModelDefinition 里声明的能力,覆盖按 id 的推断 */
52
+ interface CapabilityOverrides {
53
+ midConversationSystem?: boolean;
54
+ }
55
+ declare function capabilitiesOf(model: PiModel, requestOptions?: Record<string, unknown>, overrides?: CapabilityOverrides): LoweringCapabilities;
56
+
57
+ /**
58
+ * 一行拿到"模型 + 降级层":`anthropic("claude-opus-5", { apiKey })`、`openai("gpt-5.5", { apiKey })`。
59
+ * 返回 BoundModel,直接给 `createAgent({ model })`;要更多控制(多模型共享一个降级层、自定义 fetch)就自己 new PiAiLowering。
60
+ *
61
+ * 本包不读环境变量(T7 决策),apiKey 必填、由宿主决定来源。
62
+ * 带 baseUrl 即走代理 / 网关:此时按 ModelDefinition 登记,能力字段给了缺省值,可用 contextWindow 等覆盖。
63
+ */
64
+
65
+ interface BoundModelOptions {
66
+ apiKey: string;
67
+ /** 代理或网关地址。Anthropic 在其后接 /v1/messages,OpenAI 接 /responses(网关请给到 …/v1) */
68
+ baseUrl?: string;
69
+ /** 透传给 pi-ai 的请求选项(thinkingEnabled、reasoningEffort、maxTokens…) */
70
+ requestOptions?: Record<string, unknown>;
71
+ /** 仅 baseUrl 模式下需要:模型能力。缺省 200k 窗口、16k 输出、支持推理与图片 */
72
+ contextWindow?: number;
73
+ maxOutputTokens?: number;
74
+ reasoning?: boolean;
75
+ images?: boolean;
76
+ /** 仅 baseUrl 模式:上游是否接受中途 `role:"system"`(system_note 的 exact 落点)。第三方 Anthropic 兼容端口(如 DeepSeek)实测接受时置 true;缺省按不支持、以标签走 user */
77
+ midConversationSystem?: boolean;
78
+ fetch?: typeof globalThis.fetch;
79
+ headers?: Record<string, string | null>;
80
+ /** trust 标注(§14):untrusted 内容包 <untrusted> 标记。缺省开;关掉是宿主自担风险 */
81
+ trustMarkers?: boolean;
82
+ }
83
+ /** Anthropic Messages。缺省开 thinking(模型不支持时 pi-ai 会忽略) */
84
+ declare function anthropic(id: string, opts: BoundModelOptions): BoundModel;
85
+ /** OpenAI Responses。缺省 reasoningEffort=medium,这样才有可回放的 reasoning(见 T7 决策) */
86
+ declare function openai(id: string, opts: BoundModelOptions): BoundModel;
87
+
88
+ /**
89
+ * pi-ai 流 → 事件草稿。
90
+ *
91
+ * 只在响应收尾(done / error)时按最终消息的内容块产出草稿:签名类回放数据(Anthropic signature、
92
+ * OpenAI reasoning item)在块结束时才齐,等收尾最稳。增量只通过 onDelta 给 UI。
93
+ * 中断或出错时把已产出的部分内容也交出去 —— 日志要记录"发生过什么",是否继续由循环决定。
94
+ */
95
+
96
+ declare function draftsOf(msg: AssistantMessage): CoreEventDraft[];
97
+ declare function consumeStream(events: AsyncIterable<AssistantMessageEvent>, ctx?: LoweringStreamContext): AsyncGenerator<CoreEventDraft, LoweringOutcome>;
98
+
99
+ /**
100
+ * 有损矩阵(P7:有损必声明)。api → 事件 type → 可能落点。
101
+ *
102
+ * 这是"合同":toRequest 对每条事件实际记录的落点必须是这里声明过的一种(T8 测试逐项断言)。
103
+ * 新增事件类型或新 API 而不补这张表,测试就红 —— 宁可编译期/测试期吵,不要线上静默丢。
104
+ */
105
+
106
+ declare const LOSS_MATRIX: LossMatrix;
107
+ /** 查某 api 下某事件 type 的声明落点;ext.* 归到通配项 */
108
+ declare function declaredLandings(api: string, type: string): readonly LandingSpec[];
109
+
110
+ /**
111
+ * system_note 的落点(S1 结论)。
112
+ *
113
+ * pi-ai 的 Message 没有 system 角色,所以:
114
+ * - 模型支持中途 system 时:先当 user 消息放进 Context,文本前加内部标记;在 pi-ai 的 onPayload 钩子里
115
+ * 把带标记的消息改写成线协议的 system 消息并归位。标记只在本文件生产与消费,不会送到线上。
116
+ * - 不支持时:以 <system_note> 标签包住、仍走 user 角色,有损矩阵记为 lossy(user-role)。
117
+ *
118
+ * Anthropic 摆放规则(官方,违反即 400):不能是首条;必须紧跟 user 轮(含 tool_result 的 user);
119
+ * 后接 assistant 或收尾;连续多条 system 视为一组。
120
+ * OpenAI Responses:input 项里 developer / system 消息可出现在任意位置,无归位需求。
121
+ */
122
+
123
+ declare const SYSTEM_NOTE_MARK = "[[reins:system_note]]";
124
+ declare function markSystemNote(text: string): string;
125
+ /** 不支持中途 system 的模型:用标签框住,让模型知道这不是用户说的 */
126
+ declare function framedSystemNote(kind: SystemNotePayload["kind"], text: string): string;
127
+ /**
128
+ * Anthropic Messages 请求体改写:标记消息 → {role:"system", content:[text]},并按摆放规则归位。
129
+ * 归位算法:每条 system 放到"它之后的第一条 assistant"之前(此时前一条必是 user);后面没有 assistant 就放到
130
+ * 消息列表末尾(紧跟最后一条 user 收尾)。pi-ai 在部分模型上会在末尾追加 content 为空的 effort 专用 system 消息,
131
+ * 我们的 system 与它相邻成组,符合规则。
132
+ *
133
+ * 缓存断点(B1,prompt cache 约束 4):pi-ai 把 cache_control 打在"最后一条 user 消息"上;感知等 system_note
134
+ * 追加在时间线末尾时,那条最后的 user 正是我们的标记消息,改写成 system 后断点会跟着消失,而官方规则是
135
+ * "最后一个断点之后的内容一律不缓存" —— 整段对话历史都会按原价计费。处置由 `cacheBreakpoint` 选:
136
+ * - "automatic"(缺省):去掉这个块级断点,在请求顶层补 `cache_control`(Anthropic 的自动缓存:断点自动落在最后一个
137
+ * 可缓存块上,与显式断点兼容、占 4 个槽位中的 1 个)。B1 实测(spikes/b1-perception-cache)命中率与不注入持平。
138
+ * - "previous-user":搬到紧邻的前一条 user 消息末块(真正的最新 user / tool_result)。实测比不注入低 3~6 个点。
139
+ * - "drop":丢掉。只在上游自己会补自动缓存(如某些网关)时才不吃亏。
140
+ * 把断点留在改写后的 system 消息上实测会让整段提示每次重写、几乎零命中,所以不提供这个选项。
141
+ */
142
+ type MidSystemCacheBreakpoint = "automatic" | "previous-user" | "drop";
143
+ interface RewriteAnthropicOptions {
144
+ cacheBreakpoint?: MidSystemCacheBreakpoint;
145
+ }
146
+ declare function rewriteAnthropicPayload(payload: unknown, opts?: RewriteAnthropicOptions): unknown;
147
+ /**
148
+ * OpenAI Responses 请求体改写:标记消息 → {role: developer|system, content:[input_text]}。
149
+ * reasoning 模型用 developer(与 pi-ai 放 systemPrompt 的选择一致),其余用 system。
150
+ */
151
+ declare function rewriteOpenAIResponsesPayload(payload: unknown, model: {
152
+ reasoning: boolean;
153
+ }): unknown;
154
+
155
+ interface PiAiLoweringOptions {
156
+ /** 按 provider 取 key;返回 undefined 视为未配置。本包不读环境变量,由宿主决定来源 */
157
+ apiKey: (provider: string) => string | undefined;
158
+ /** 自定义 fetch(测试注入、代理、Workers 绑定);缺省 globalThis.fetch */
159
+ fetch?: typeof globalThis.fetch;
160
+ /** 附加请求头;值为 null 表示删掉 pi-ai 的默认头 */
161
+ headers?: Record<string, string | null>;
162
+ /** 内置表之外的模型 */
163
+ models?: readonly ModelDefinition[];
164
+ /**
165
+ * 透传给 pi-ai 流函数的额外选项(maxTokens、temperature、Anthropic 的 effort / thinkingEnabled、
166
+ * OpenAI 的 reasoningEffort / reasoningSummary 等),键名以 pi-ai 0.85.1 文档为准。按模型返回,便于分族配置。
167
+ * 注意:OpenAI Responses 不给 reasoningEffort 就不开 reasoning,也就没有 thinking 可回放,capabilities 会如实报 false。
168
+ */
169
+ requestOptions?: (model: ModelRef) => Record<string, unknown>;
170
+ /**
171
+ * Anthropic:system_note 殿后时 pi-ai 打在它上面的缓存断点怎么处置(见 system-note.ts)。
172
+ * 缺省 "automatic"(去掉块级断点、请求顶层补自动缓存);"previous-user" / "drop" 供对照或特殊上游。
173
+ */
174
+ midSystemCacheBreakpoint?: MidSystemCacheBreakpoint;
175
+ /**
176
+ * trust 标注(技术方案 §14):trust=untrusted 的事件(工具输出、外部内容)翻译时包上
177
+ * `<untrusted source="tool:<name>">…</untrusted>`,事件本身不动。缺省 true;传 false 关掉是宿主自担提示注入风险
178
+ */
179
+ trustMarkers?: boolean;
180
+ }
181
+ /** 对外暴露的请求体:pi-ai Context 的结构描述,不引用 pi-ai 类型 */
182
+ interface PiLoweredPayload {
183
+ api: string;
184
+ context: {
185
+ systemPrompt?: string;
186
+ messages: readonly unknown[];
187
+ tools?: readonly unknown[];
188
+ };
189
+ }
190
+ declare class PiAiLowering implements Lowering<PiLoweredPayload> {
191
+ private readonly opts;
192
+ private readonly extraModels;
193
+ /** 宿主自定义模型声明的能力覆盖,键 provider/id;pi-ai 的 Model 上放不下这些字段 */
194
+ private readonly overrides;
195
+ constructor(opts: PiAiLoweringOptions);
196
+ capabilities(ref: ModelRef): LoweringCapabilities;
197
+ private capabilitiesFor;
198
+ private requestOptionsFor;
199
+ toRequest(input: ToRequestInput): LoweredRequest<PiLoweredPayload>;
200
+ stream(req: LoweredRequest<PiLoweredPayload>, ctx?: LoweringStreamContext): AsyncGenerator<CoreEventDraft, LoweringOutcome>;
201
+ }
202
+ /** 把带标记的 system_note 改写成各 API 的 system 消息;返回 undefined 表示请求体不变 */
203
+ declare function rewritePayload(api: string, payload: unknown, model: {
204
+ reasoning: boolean;
205
+ }, opts?: RewriteAnthropicOptions): unknown;
206
+
207
+ /**
208
+ * 事件 → pi-ai Context(三角色 Message[] + tools + systemPrompt),并逐条记录落点。
209
+ *
210
+ * 分组规则:连续的 model 事件(thinking / text / tool_call)合成一条 AssistantMessage,
211
+ * 遇到任何非 model 事件就收口。AssistantMessage 需要 api/provider/model 才能让 pi-ai 判断
212
+ * "这段 thinking 是不是本模型产的、能不能回放",这些信息在事件产出时记在 replay 里。
213
+ */
214
+
215
+ /** 模型事件 replay 里记录的来源,产出与回放两头共用 */
216
+ interface ModelOrigin {
217
+ provider: string;
218
+ api: string;
219
+ model: string;
220
+ }
221
+ interface ThinkingReplay extends Partial<ModelOrigin> {
222
+ thinkingSignature?: string;
223
+ redacted?: boolean;
224
+ }
225
+ interface TextReplay extends Partial<ModelOrigin> {
226
+ textSignature?: string;
227
+ }
228
+ interface ToolCallReplay extends Partial<ModelOrigin> {
229
+ thoughtSignature?: string;
230
+ namespace?: string;
231
+ }
232
+ interface ToContextInput {
233
+ events: readonly Event[];
234
+ tools?: readonly ToolSpec[];
235
+ model: PiModel;
236
+ capabilities: LoweringCapabilities;
237
+ systemPrompt?: string;
238
+ /** trust=untrusted 的内容(工具输出、外部内容)以 <untrusted source=…> 包裹(§14)。缺省 true;关掉是宿主自担风险 */
239
+ trustMarkers?: boolean;
240
+ }
241
+ declare function eventsToContext(input: ToContextInput): {
242
+ context: Context;
243
+ landings: LandingRecord[];
244
+ };
245
+
246
+ export { type BoundModelOptions, LOSS_MATRIX, type ModelDefinition, type ModelOrigin, PiAiLowering, type PiAiLoweringOptions, type PiLoweredPayload, SUPPORTED_APIS, SYSTEM_NOTE_MARK, type TextReplay, type ThinkingReplay, type ToolCallReplay, anthropic, capabilitiesOf, consumeStream, declaredLandings, definitionToModel, draftsOf, eventsToContext, framedSystemNote, markSystemNote, openai, resolveModel, rewriteAnthropicPayload, rewriteOpenAIResponsesPayload, rewritePayload };
package/dist/index.js ADDED
@@ -0,0 +1,769 @@
1
+ // src/capabilities.ts
2
+ var ANTHROPIC_MID_SYSTEM = /^claude-(fable-5|mythos-5|opus-5|opus-4-8)(-|$)/;
3
+ var ANTHROPIC_TASK_BUDGET = /^claude-(opus-5|fable-5-1)(-|$)/;
4
+ function openaiReasoningRequested(requestOptions) {
5
+ return Boolean(requestOptions.reasoningEffort || requestOptions.reasoningSummary);
6
+ }
7
+ function capabilitiesOf(model, requestOptions = {}, overrides = {}) {
8
+ const caps = inferCapabilities(model, requestOptions);
9
+ return overrides.midConversationSystem === void 0 ? caps : { ...caps, midConversationSystem: overrides.midConversationSystem };
10
+ }
11
+ function inferCapabilities(model, requestOptions) {
12
+ const base = {
13
+ api: model.api,
14
+ thinkingReplay: model.reasoning,
15
+ parallelTools: true,
16
+ images: model.input.includes("image"),
17
+ contextWindow: model.contextWindow,
18
+ maxOutputTokens: model.maxTokens
19
+ };
20
+ switch (model.api) {
21
+ case "anthropic-messages":
22
+ return {
23
+ ...base,
24
+ midConversationSystem: ANTHROPIC_MID_SYSTEM.test(model.id),
25
+ taskBudget: ANTHROPIC_TASK_BUDGET.test(model.id)
26
+ };
27
+ case "openai-responses":
28
+ return {
29
+ ...base,
30
+ thinkingReplay: model.reasoning && openaiReasoningRequested(requestOptions),
31
+ midConversationSystem: true,
32
+ taskBudget: false
33
+ };
34
+ default:
35
+ return { ...base, midConversationSystem: false, taskBudget: false };
36
+ }
37
+ }
38
+
39
+ // src/pi-lowering.ts
40
+ import { stream as anthropicStream } from "@earendil-works/pi-ai/api/anthropic-messages";
41
+ import { stream as openaiResponsesStream } from "@earendil-works/pi-ai/api/openai-responses";
42
+ import {
43
+ LoweringError as LoweringError2
44
+ } from "@reinsjs/core";
45
+
46
+ // src/from-stream.ts
47
+ function draftsOf(msg) {
48
+ const origin = { provider: msg.provider, api: msg.api, model: msg.model };
49
+ const drafts = [];
50
+ for (const block of msg.content) {
51
+ if (block.type === "thinking") {
52
+ const replay = { ...origin };
53
+ if (block.thinkingSignature) replay.thinkingSignature = block.thinkingSignature;
54
+ if (block.redacted) replay.redacted = true;
55
+ drafts.push({ type: "core.model_thinking", actor: "model", payload: { text: block.thinking }, replay });
56
+ } else if (block.type === "text") {
57
+ if (block.text.length === 0) continue;
58
+ const replay = { ...origin };
59
+ if (block.textSignature) replay.textSignature = block.textSignature;
60
+ drafts.push({ type: "core.model_text", actor: "model", payload: { text: block.text }, replay });
61
+ } else if (block.type === "toolCall") {
62
+ const replay = { ...origin };
63
+ if (block.thoughtSignature) replay.thoughtSignature = block.thoughtSignature;
64
+ if (block.namespace !== void 0) replay.namespace = block.namespace;
65
+ drafts.push({
66
+ type: "core.tool_call",
67
+ actor: "model",
68
+ payload: { toolCallId: block.id, name: block.name, args: block.arguments },
69
+ replay
70
+ });
71
+ }
72
+ }
73
+ return drafts;
74
+ }
75
+ function outcomeOf(msg, stopReason) {
76
+ const usage = { input: msg.usage.input, output: msg.usage.output };
77
+ if (msg.usage.cacheRead) usage.cacheRead = msg.usage.cacheRead;
78
+ if (msg.usage.cacheWrite) usage.cacheWrite = msg.usage.cacheWrite;
79
+ const out = { stopReason, usage, costUsd: msg.usage.cost.total };
80
+ if (msg.errorMessage) out.errorMessage = msg.errorMessage;
81
+ if (msg.responseModel) out.responseModel = msg.responseModel;
82
+ return out;
83
+ }
84
+ async function* consumeStream(events, ctx = {}) {
85
+ for await (const ev of events) {
86
+ switch (ev.type) {
87
+ case "text_delta":
88
+ ctx.onDelta?.({ kind: "text", index: ev.contentIndex, delta: ev.delta });
89
+ break;
90
+ case "thinking_delta":
91
+ ctx.onDelta?.({ kind: "thinking", index: ev.contentIndex, delta: ev.delta });
92
+ break;
93
+ case "toolcall_delta":
94
+ ctx.onDelta?.({ kind: "tool_args", index: ev.contentIndex, delta: ev.delta });
95
+ break;
96
+ case "done": {
97
+ yield* draftsOf(ev.message);
98
+ const reason = ev.reason === "deferred" ? "stop" : ev.reason;
99
+ return outcomeOf(ev.message, reason);
100
+ }
101
+ case "error":
102
+ yield* draftsOf(ev.error);
103
+ return outcomeOf(ev.error, ev.reason);
104
+ default:
105
+ break;
106
+ }
107
+ }
108
+ return {
109
+ stopReason: "error",
110
+ usage: { input: 0, output: 0 },
111
+ errorMessage: "pi-ai \u6D41\u5728 done / error \u4E4B\u524D\u5C31\u7ED3\u675F\u4E86"
112
+ };
113
+ }
114
+
115
+ // src/models.ts
116
+ import { ANTHROPIC_MODELS } from "@earendil-works/pi-ai/providers/anthropic.models";
117
+ import { OPENAI_MODELS } from "@earendil-works/pi-ai/providers/openai.models";
118
+ import { LoweringError } from "@reinsjs/core";
119
+ var SUPPORTED_APIS = /* @__PURE__ */ new Set(["anthropic-messages", "openai-responses"]);
120
+ var BUILTIN = {
121
+ anthropic: ANTHROPIC_MODELS,
122
+ openai: OPENAI_MODELS
123
+ };
124
+ function definitionToModel(def) {
125
+ const model = {
126
+ id: def.id,
127
+ name: def.name ?? def.id,
128
+ api: def.api,
129
+ provider: def.provider,
130
+ baseUrl: def.baseUrl,
131
+ reasoning: def.reasoning,
132
+ input: def.images ? ["text", "image"] : ["text"],
133
+ cost: def.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
134
+ contextWindow: def.contextWindow,
135
+ maxTokens: def.maxOutputTokens
136
+ };
137
+ if (def.headers) model.headers = def.headers;
138
+ return model;
139
+ }
140
+ function resolveModel(ref, extra = []) {
141
+ const model = extra.find((m) => m.provider === ref.provider && m.id === ref.id) ?? BUILTIN[ref.provider]?.[ref.id];
142
+ if (!model) {
143
+ throw new LoweringError(
144
+ "unsupported_model",
145
+ `\u627E\u4E0D\u5230\u6A21\u578B ${ref.provider}/${ref.id}\uFF1B\u5185\u7F6E\u8868\u53EA\u542B anthropic \u4E0E openai\uFF0C\u5176\u4F59\u8BF7\u901A\u8FC7 models \u9009\u9879\u58F0\u660E`,
146
+ {
147
+ provider: ref.provider,
148
+ id: ref.id
149
+ }
150
+ );
151
+ }
152
+ if (!SUPPORTED_APIS.has(model.api)) {
153
+ throw new LoweringError(
154
+ "unsupported_api",
155
+ `\u6A21\u578B ${ref.provider}/${ref.id} \u8D70 ${model.api}\uFF0C\u672C\u5B9E\u73B0\u53EA\u652F\u6301 anthropic-messages \u4E0E openai-responses`,
156
+ {
157
+ api: model.api
158
+ }
159
+ );
160
+ }
161
+ return model;
162
+ }
163
+
164
+ // src/system-note.ts
165
+ var SYSTEM_NOTE_MARK = "[[reins:system_note]]";
166
+ function markSystemNote(text) {
167
+ return `${SYSTEM_NOTE_MARK}${text}`;
168
+ }
169
+ function framedSystemNote(kind, text) {
170
+ return `<system_note kind="${kind}">
171
+ ${text}
172
+ </system_note>`;
173
+ }
174
+ function markedNote(m, textType) {
175
+ if (m.role !== "user") return null;
176
+ let text = null;
177
+ let cacheControl;
178
+ if (typeof m.content === "string") text = m.content;
179
+ else if (Array.isArray(m.content) && m.content.length === 1) {
180
+ const only = m.content[0];
181
+ if (only.type === textType && typeof only.text === "string") {
182
+ text = only.text;
183
+ cacheControl = only.cache_control;
184
+ }
185
+ }
186
+ if (text === null || !text.startsWith(SYSTEM_NOTE_MARK)) return null;
187
+ return {
188
+ text: text.slice(SYSTEM_NOTE_MARK.length),
189
+ ...cacheControl !== void 0 ? { cacheControl } : {}
190
+ };
191
+ }
192
+ var MAX_ANTHROPIC_BREAKPOINTS = 4;
193
+ function rewriteAnthropicPayload(payload, opts = {}) {
194
+ const breakpoint = opts.cacheBreakpoint ?? "automatic";
195
+ const p = payload;
196
+ if (!Array.isArray(p.messages)) return void 0;
197
+ const body = [];
198
+ const pending = [];
199
+ for (const m of p.messages) {
200
+ const note = markedNote(m, "text");
201
+ if (note !== null) pending.push({ ...note, afterIndex: body.length });
202
+ else body.push(m);
203
+ }
204
+ if (pending.length === 0) return void 0;
205
+ const placeOf = (note) => {
206
+ let at = body.findIndex((m, idx) => idx >= note.afterIndex && m.role === "assistant");
207
+ if (at === -1) {
208
+ at = body.length;
209
+ while (at > 0 && body[at - 1]?.role === "system" && isEmptyContent(body[at - 1]?.content)) at--;
210
+ }
211
+ if (at === 0) {
212
+ const firstUser = body.findIndex((m) => m.role === "user");
213
+ at = firstUser === -1 ? body.length : firstUser + 1;
214
+ }
215
+ return at;
216
+ };
217
+ const groups = /* @__PURE__ */ new Map();
218
+ for (const note of pending) {
219
+ const at = placeOf(note);
220
+ const bucket = groups.get(at);
221
+ if (bucket) bucket.push(note);
222
+ else groups.set(at, [note]);
223
+ }
224
+ let lostBreakpoint;
225
+ const messages = [];
226
+ for (let i = 0; i <= body.length; i++) {
227
+ const notes = groups.get(i);
228
+ if (notes) {
229
+ for (const note of notes) {
230
+ if (note.cacheControl !== void 0 && breakpoint === "previous-user") {
231
+ const prev = messages[messages.length - 1];
232
+ if (prev) messages[messages.length - 1] = withCacheControl(prev, note.cacheControl);
233
+ }
234
+ if (note.cacheControl !== void 0 && breakpoint === "automatic") lostBreakpoint = note.cacheControl;
235
+ messages.push({ role: "system", content: [{ type: "text", text: note.text }] });
236
+ }
237
+ }
238
+ const m = body[i];
239
+ if (m) messages.push(m);
240
+ }
241
+ const out = { ...p, messages };
242
+ if (lostBreakpoint !== void 0 && out.cache_control === void 0) {
243
+ if (countBlockBreakpoints(out) < MAX_ANTHROPIC_BREAKPOINTS) out.cache_control = lostBreakpoint;
244
+ }
245
+ return out;
246
+ }
247
+ function countBlockBreakpoints(p) {
248
+ const has = (b) => typeof b === "object" && b !== null && "cache_control" in b;
249
+ let n = 0;
250
+ if (Array.isArray(p.system)) n += p.system.filter(has).length;
251
+ if (Array.isArray(p.tools)) n += p.tools.filter(has).length;
252
+ for (const m of p.messages) if (Array.isArray(m.content)) n += m.content.filter(has).length;
253
+ return n;
254
+ }
255
+ function withCacheControl(m, cacheControl) {
256
+ if (m.role !== "user") return m;
257
+ if (typeof m.content === "string") {
258
+ return { ...m, content: [{ type: "text", text: m.content, cache_control: cacheControl }] };
259
+ }
260
+ if (Array.isArray(m.content) && m.content.length > 0) {
261
+ const blocks = [...m.content];
262
+ const last = blocks[blocks.length - 1];
263
+ blocks[blocks.length - 1] = { ...last, cache_control: cacheControl };
264
+ return { ...m, content: blocks };
265
+ }
266
+ return m;
267
+ }
268
+ function isEmptyContent(content) {
269
+ return Array.isArray(content) && content.length === 0;
270
+ }
271
+ function rewriteOpenAIResponsesPayload(payload, model) {
272
+ const p = payload;
273
+ if (!Array.isArray(p.input)) return void 0;
274
+ let changed = false;
275
+ const role = model.reasoning ? "developer" : "system";
276
+ const input = p.input.map((m) => {
277
+ const note = markedNote(m, "input_text");
278
+ if (note === null) return m;
279
+ changed = true;
280
+ return { role, content: [{ type: "input_text", text: note.text }] };
281
+ });
282
+ return changed ? { ...p, input } : void 0;
283
+ }
284
+
285
+ // src/to-request.ts
286
+ import {
287
+ markUntrusted,
288
+ markUntrustedText,
289
+ needsUntrustedMark,
290
+ untrustedSourceOf
291
+ } from "@reinsjs/core";
292
+ var ZERO_USAGE = {
293
+ input: 0,
294
+ output: 0,
295
+ cacheRead: 0,
296
+ cacheWrite: 0,
297
+ totalTokens: 0,
298
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
299
+ };
300
+ function toPiContent(parts) {
301
+ return parts.map(
302
+ (p) => p.type === "text" ? { type: "text", text: p.text } : { type: "image", data: p.data, mimeType: p.mime }
303
+ );
304
+ }
305
+ function isPlainObject(v) {
306
+ return typeof v === "object" && v !== null && !Array.isArray(v);
307
+ }
308
+ function originOf(replay, fallback) {
309
+ const r = replay ?? {};
310
+ return {
311
+ provider: typeof r.provider === "string" ? r.provider : fallback.provider,
312
+ api: typeof r.api === "string" ? r.api : fallback.api,
313
+ model: typeof r.model === "string" ? r.model : fallback.id
314
+ };
315
+ }
316
+ function sameOrigin(a, b) {
317
+ return a.provider === b.provider && a.api === b.api && a.model === b.model;
318
+ }
319
+ function foreignOrigin(a, target) {
320
+ return a.provider !== target.provider || a.api !== target.api;
321
+ }
322
+ var DEFERRED_NOTE = "\u5DF2\u540E\u79FB\u5230\u540C\u6279\u5DE5\u5177\u7ED3\u679C\u4E4B\u540E\uFF08\u5DE5\u5177\u7ED3\u679C\u5FC5\u987B\u7D27\u8DDF\u8C03\u7528\uFF09";
323
+ var ESCAPED_NOTE = "\u4E0D\u53EF\u4FE1\u5185\u5BB9\u91CC\u542B\u63D0\u524D\u95ED\u5408\u7684 </untrusted\uFF0C\u5DF2\u8F6C\u4E49";
324
+ function eventsToContext(input) {
325
+ const { model, capabilities } = input;
326
+ const target = { provider: model.provider, api: model.api, model: model.id };
327
+ const isAnthropic = model.api === "anthropic-messages";
328
+ const trustMarkers = input.trustMarkers !== false;
329
+ const messages = [];
330
+ const landings = [];
331
+ let group = null;
332
+ const awaiting = /* @__PURE__ */ new Set();
333
+ const deferred = [];
334
+ const land = (e, kind, landing, note2) => {
335
+ landings.push(
336
+ note2 ? { eventId: e.id, type: e.type, kind, landing, note: note2 } : { eventId: e.id, type: e.type, kind, landing }
337
+ );
338
+ };
339
+ const releaseDeferred = () => {
340
+ for (const d of deferred) {
341
+ messages.push(d.msg);
342
+ land(d.event, d.kind, d.landing, d.note ? `${d.note}\uFF1B${DEFERRED_NOTE}` : DEFERRED_NOTE);
343
+ }
344
+ deferred.length = 0;
345
+ };
346
+ const content = (e, parts) => {
347
+ if (!trustMarkers || !needsUntrustedMark(e)) return { parts: [...parts], escaped: false };
348
+ return markUntrusted(parts, untrustedSourceOf(e));
349
+ };
350
+ const text = (e, s) => {
351
+ if (!trustMarkers || !needsUntrustedMark(e)) return { text: s, escaped: false };
352
+ return markUntrustedText(s, untrustedSourceOf(e));
353
+ };
354
+ const note = (e, msg, kind, landing, why) => {
355
+ if (awaiting.size > 0) {
356
+ deferred.push({ msg, event: e, kind, landing, ...why !== void 0 ? { note: why } : {} });
357
+ return;
358
+ }
359
+ messages.push(msg);
360
+ land(e, kind, landing, why);
361
+ };
362
+ const settleAwaiting = () => {
363
+ awaiting.clear();
364
+ releaseDeferred();
365
+ };
366
+ const flush = () => {
367
+ if (!group) return;
368
+ const hasTool = group.content.some((c) => c.type === "toolCall");
369
+ messages.push({
370
+ role: "assistant",
371
+ content: group.content,
372
+ api: group.origin.api,
373
+ provider: group.origin.provider,
374
+ model: group.origin.model,
375
+ usage: ZERO_USAGE,
376
+ stopReason: hasTool ? "toolUse" : "stop",
377
+ timestamp: group.at
378
+ });
379
+ for (const c of group.content) if (c.type === "toolCall") awaiting.add(c.id);
380
+ group = null;
381
+ };
382
+ const assistant = (e, origin) => {
383
+ if (group && !sameOrigin(group.origin, origin)) flush();
384
+ if (!group) {
385
+ settleAwaiting();
386
+ group = { origin, content: [], at: e.at };
387
+ }
388
+ return group;
389
+ };
390
+ for (const raw of input.events) {
391
+ const e = raw;
392
+ switch (e.type) {
393
+ case "core.user_message": {
394
+ flush();
395
+ const c = content(e, e.payload.content);
396
+ const msg = { role: "user", content: toPiContent(c.parts), timestamp: e.at };
397
+ if (awaiting.size > 0) {
398
+ deferred.push({
399
+ msg,
400
+ event: e,
401
+ kind: "lossy",
402
+ landing: "user",
403
+ note: c.escaped ? `\u7528\u6237\u6D88\u606F\u843D\u5728\u5DE5\u5177\u8C03\u7528\u4E0E\u7ED3\u679C\u4E4B\u95F4\uFF1B${ESCAPED_NOTE}` : "\u7528\u6237\u6D88\u606F\u843D\u5728\u5DE5\u5177\u8C03\u7528\u4E0E\u7ED3\u679C\u4E4B\u95F4"
404
+ });
405
+ break;
406
+ }
407
+ messages.push(msg);
408
+ if (c.escaped) land(e, "lossy", "user", ESCAPED_NOTE);
409
+ else land(e, "exact", "user");
410
+ break;
411
+ }
412
+ case "core.model_thinking": {
413
+ const origin = originOf(e.replay, model);
414
+ const r = e.replay ?? {};
415
+ const block = { type: "thinking", thinking: e.payload.text };
416
+ if (typeof r.thinkingSignature === "string") block.thinkingSignature = r.thinkingSignature;
417
+ if (r.redacted === true) block.redacted = true;
418
+ assistant(e, origin).content.push(block);
419
+ if (!block.thinkingSignature)
420
+ land(e, "lossy", "text-or-drop", "\u65E0\u7B7E\u540D\u7684 thinking \u7531 pi-ai \u964D\u4E3A\u6587\u672C\u6216\u4E22\u5F03");
421
+ else if (foreignOrigin(origin, target))
422
+ land(
423
+ e,
424
+ "lossy",
425
+ "provider-dependent",
426
+ `\u6765\u81EA ${origin.provider}/${origin.model} \u7684 thinking\uFF0C\u5382\u5546\u53EF\u80FD\u5FFD\u7565\u6216\u62D2\u6536`
427
+ );
428
+ else if (origin.model !== target.model)
429
+ land(
430
+ e,
431
+ "exact",
432
+ isAnthropic ? "thinking-block" : "reasoning-item",
433
+ `\u7B7E\u540D\u6765\u81EA ${origin.model}\uFF0C\u5F53\u524D\u8BF7\u6C42 ${target.model}`
434
+ );
435
+ else land(e, "exact", isAnthropic ? "thinking-block" : "reasoning-item");
436
+ break;
437
+ }
438
+ case "core.model_text": {
439
+ const origin = originOf(e.replay, model);
440
+ const r = e.replay ?? {};
441
+ const block = { type: "text", text: e.payload.text };
442
+ if (typeof r.textSignature === "string") block.textSignature = r.textSignature;
443
+ assistant(e, origin).content.push(block);
444
+ land(e, "exact", isAnthropic ? "assistant-text" : "assistant-message");
445
+ break;
446
+ }
447
+ case "core.tool_call": {
448
+ const origin = originOf(e.replay, model);
449
+ const r = e.replay ?? {};
450
+ const wrapped = !isPlainObject(e.payload.args);
451
+ const block = {
452
+ type: "toolCall",
453
+ id: e.payload.toolCallId,
454
+ name: e.payload.name,
455
+ arguments: wrapped ? { value: e.payload.args } : e.payload.args
456
+ };
457
+ if (typeof r.thoughtSignature === "string") block.thoughtSignature = r.thoughtSignature;
458
+ if (typeof r.namespace === "string") block.namespace = r.namespace;
459
+ assistant(e, origin).content.push(block);
460
+ if (wrapped) land(e, "lossy", "wrapped-args", "\u975E\u5BF9\u8C61\u5165\u53C2\u5305\u6210 { value }");
461
+ else land(e, "exact", isAnthropic ? "tool_use" : "function_call");
462
+ break;
463
+ }
464
+ case "core.tool_result": {
465
+ flush();
466
+ const c = content(e, e.payload.content);
467
+ messages.push({
468
+ role: "toolResult",
469
+ toolCallId: e.payload.toolCallId,
470
+ toolName: e.payload.name,
471
+ content: toPiContent(c.parts),
472
+ isError: e.payload.isError,
473
+ timestamp: e.at
474
+ });
475
+ const landing = isAnthropic ? "tool_result" : "function_call_output";
476
+ if (c.escaped) land(e, "lossy", landing, ESCAPED_NOTE);
477
+ else land(e, "exact", landing);
478
+ awaiting.delete(e.payload.toolCallId);
479
+ if (awaiting.size === 0) releaseDeferred();
480
+ break;
481
+ }
482
+ case "core.system_note": {
483
+ flush();
484
+ const t = text(e, e.payload.text);
485
+ if (capabilities.midConversationSystem) {
486
+ note(
487
+ e,
488
+ { role: "user", content: markSystemNote(t.text), timestamp: e.at },
489
+ t.escaped ? "lossy" : "exact",
490
+ isAnthropic ? "system" : model.reasoning ? "developer" : "system",
491
+ t.escaped ? ESCAPED_NOTE : void 0
492
+ );
493
+ } else {
494
+ note(
495
+ e,
496
+ { role: "user", content: framedSystemNote(e.payload.kind, t.text), timestamp: e.at },
497
+ "lossy",
498
+ "user-role",
499
+ "\u6A21\u578B\u4E0D\u652F\u6301\u4E2D\u9014 system\uFF0C\u4EE5 <system_note> \u6807\u7B7E\u5305\u4F4F\u8D70 user \u89D2\u8272"
500
+ );
501
+ }
502
+ break;
503
+ }
504
+ case "core.compaction": {
505
+ flush();
506
+ const t = text(e, e.payload.summary);
507
+ note(
508
+ e,
509
+ {
510
+ role: "user",
511
+ content: `[Summary of earlier conversation]
512
+ ${t.text}`,
513
+ timestamp: e.at
514
+ },
515
+ "lossy",
516
+ "user-text",
517
+ "\u6458\u8981\u4EE5 user \u89D2\u8272\u6587\u672C\u5448\u73B0"
518
+ );
519
+ break;
520
+ }
521
+ case "core.approval_request":
522
+ case "core.approval_decision":
523
+ case "core.run_paused":
524
+ case "core.run_resumed":
525
+ case "core.budget_usage":
526
+ case "core.memory_op":
527
+ case "core.handoff":
528
+ case "core.error":
529
+ land(e, "dropped", "none", "\u8FD0\u7EF4\u4E8B\u4EF6\u4E0D\u4E0B\u53D1\uFF08\u6295\u5F71\u9ED8\u8BA4\u5DF2\u8FC7\u6EE4\uFF09");
530
+ break;
531
+ default:
532
+ land(raw, "dropped", "none", `\u65E0\u901A\u7528\u843D\u70B9\uFF1A${raw.type}`);
533
+ }
534
+ }
535
+ flush();
536
+ settleAwaiting();
537
+ const context = { messages };
538
+ if (input.systemPrompt) context.systemPrompt = input.systemPrompt;
539
+ if (input.tools && input.tools.length > 0) {
540
+ context.tools = input.tools.map(
541
+ (t) => ({
542
+ name: t.name,
543
+ description: t.description,
544
+ parameters: t.inputSchema
545
+ })
546
+ );
547
+ }
548
+ return { context, landings };
549
+ }
550
+
551
+ // src/pi-lowering.ts
552
+ var PiAiLowering = class {
553
+ constructor(opts) {
554
+ this.opts = opts;
555
+ this.extraModels = (opts.models ?? []).map(definitionToModel);
556
+ for (const def of opts.models ?? []) {
557
+ if (def.midConversationSystem !== void 0) {
558
+ this.overrides.set(`${def.provider}/${def.id}`, { midConversationSystem: def.midConversationSystem });
559
+ }
560
+ }
561
+ }
562
+ opts;
563
+ extraModels;
564
+ /** 宿主自定义模型声明的能力覆盖,键 provider/id;pi-ai 的 Model 上放不下这些字段 */
565
+ overrides = /* @__PURE__ */ new Map();
566
+ capabilities(ref) {
567
+ return this.capabilitiesFor(ref, resolveModel(ref, this.extraModels));
568
+ }
569
+ capabilitiesFor(ref, model) {
570
+ return capabilitiesOf(model, this.requestOptionsFor(ref), this.overrides.get(`${ref.provider}/${ref.id}`));
571
+ }
572
+ requestOptionsFor(ref) {
573
+ return this.opts.requestOptions?.(ref) ?? {};
574
+ }
575
+ toRequest(input) {
576
+ const model = resolveModel(input.model, this.extraModels);
577
+ const capabilities = this.capabilitiesFor(input.model, model);
578
+ const { context, landings } = eventsToContext({
579
+ events: input.events,
580
+ model,
581
+ capabilities,
582
+ ...input.tools ? { tools: input.tools } : {},
583
+ ...input.systemPrompt !== void 0 ? { systemPrompt: input.systemPrompt } : {},
584
+ ...this.opts.trustMarkers !== void 0 ? { trustMarkers: this.opts.trustMarkers } : {}
585
+ });
586
+ return { model: input.model, capabilities, landings, payload: { api: model.api, context } };
587
+ }
588
+ async *stream(req, ctx = {}) {
589
+ const model = resolveModel(req.model, this.extraModels);
590
+ const apiKey = this.opts.apiKey(model.provider);
591
+ if (!apiKey) {
592
+ throw new LoweringError2("missing_api_key", `\u672A\u914D\u7F6E ${model.provider} \u7684 API key`, {
593
+ provider: model.provider
594
+ });
595
+ }
596
+ const context = req.payload.context;
597
+ const options = {
598
+ ...this.requestOptionsFor(req.model),
599
+ apiKey,
600
+ ...this.opts.fetch ? { fetch: this.opts.fetch } : {},
601
+ ...this.opts.headers ? { headers: this.opts.headers } : {},
602
+ ...ctx.signal ? { signal: ctx.signal } : {},
603
+ onPayload: (payload, m) => rewritePayload(model.api, payload, m, {
604
+ ...this.opts.midSystemCacheBreakpoint ? { cacheBreakpoint: this.opts.midSystemCacheBreakpoint } : {}
605
+ })
606
+ };
607
+ const fn = streamFunctionFor(model.api);
608
+ return yield* consumeStream(fn(model, context, options), ctx);
609
+ }
610
+ };
611
+ function streamFunctionFor(api) {
612
+ switch (api) {
613
+ case "anthropic-messages":
614
+ return anthropicStream;
615
+ case "openai-responses":
616
+ return openaiResponsesStream;
617
+ default:
618
+ throw new LoweringError2("unsupported_api", `\u4E0D\u652F\u6301\u7684\u7EBF\u534F\u8BAE ${api}`, { api });
619
+ }
620
+ }
621
+ function rewritePayload(api, payload, model, opts = {}) {
622
+ if (api === "anthropic-messages") return rewriteAnthropicPayload(payload, opts);
623
+ if (api === "openai-responses") return rewriteOpenAIResponsesPayload(payload, model);
624
+ return void 0;
625
+ }
626
+
627
+ // src/factories.ts
628
+ function bound(provider, api, id, opts) {
629
+ const models = opts.baseUrl ? [
630
+ {
631
+ provider,
632
+ id,
633
+ api,
634
+ baseUrl: opts.baseUrl,
635
+ reasoning: opts.reasoning ?? true,
636
+ contextWindow: opts.contextWindow ?? 2e5,
637
+ maxOutputTokens: opts.maxOutputTokens ?? 16e3,
638
+ images: opts.images ?? true,
639
+ ...opts.midConversationSystem !== void 0 ? { midConversationSystem: opts.midConversationSystem } : {}
640
+ }
641
+ ] : [];
642
+ const loweringOpts = {
643
+ apiKey: (p) => p === provider ? opts.apiKey : void 0,
644
+ models,
645
+ ...opts.requestOptions ? { requestOptions: () => opts.requestOptions ?? {} } : {},
646
+ ...opts.fetch ? { fetch: opts.fetch } : {},
647
+ ...opts.headers ? { headers: opts.headers } : {},
648
+ ...opts.trustMarkers !== void 0 ? { trustMarkers: opts.trustMarkers } : {}
649
+ };
650
+ return { model: { provider, id }, lowering: new PiAiLowering(loweringOpts) };
651
+ }
652
+ function anthropic(id, opts) {
653
+ return bound("anthropic", "anthropic-messages", id, {
654
+ requestOptions: { thinkingEnabled: true },
655
+ ...opts
656
+ });
657
+ }
658
+ function openai(id, opts) {
659
+ return bound("openai", "openai-responses", id, {
660
+ requestOptions: { reasoningEffort: "medium" },
661
+ ...opts
662
+ });
663
+ }
664
+
665
+ // src/loss-matrix.ts
666
+ var exact = (landing, note, when) => {
667
+ const spec = { kind: "exact", landing };
668
+ if (note) spec.note = note;
669
+ if (when) spec.when = when;
670
+ return spec;
671
+ };
672
+ var lossy = (landing, note, when) => when ? { kind: "lossy", landing, note, when } : { kind: "lossy", landing, note };
673
+ var dropped = (landing, note) => ({ kind: "dropped", landing, note });
674
+ var NOT_SENT = {
675
+ "core.approval_request": [dropped("none", "\u5BA1\u6279\u7ED3\u679C\u7531 tool_result(isError) \u544A\u77E5\u6A21\u578B")],
676
+ "core.approval_decision": [dropped("none", "\u540C\u4E0A")],
677
+ "core.run_paused": [dropped("none", "\u8FD0\u884C\u8BB0\u5F55\uFF1B\u611F\u77E5\u6A21\u5757\u4F1A\u63D0\u70BC\u8FDB system_note")],
678
+ "core.run_resumed": [dropped("none", "\u540C\u4E0A")],
679
+ "core.budget_usage": [dropped("none", "\u540C\u4E0A")],
680
+ "core.memory_op": [dropped("none", "\u8BB0\u5FC6\u8BFB\u5199\u7559\u75D5\uFF0C\u6A21\u578B\u5DF2\u901A\u8FC7\u5DE5\u5177\u7ED3\u679C\u77E5\u6653")],
681
+ "core.handoff": [dropped("none", "\u4EA4\u63A5\u540E\u672C\u4F1A\u8BDD\u7ED3\u675F\uFF1B\u65B0\u4F1A\u8BDD\u9996\u6761 user \u627F\u8F7D triggerMessage")],
682
+ "core.error": [dropped("none", "provider \u9519\u8BEF\u7531\u5FAA\u73AF\u5904\u7406\uFF1B\u5DE5\u5177\u9519\u8BEF\u5DF2\u5728 tool_result.isError")]
683
+ };
684
+ var THINKING_COMMON = {
685
+ noSignature: lossy(
686
+ "text-or-drop",
687
+ "\u65E0\u7B7E\u540D\u7684 thinking \u7531 pi-ai \u964D\u4E3A\u6587\u672C\u6216\u4E22\u5F03",
688
+ "\u4E8B\u4EF6 replay \u7F3A thinkingSignature"
689
+ ),
690
+ foreign: lossy(
691
+ "provider-dependent",
692
+ "\u6765\u81EA\u5176\u5B83\u6A21\u578B\u7684 thinking\uFF0C\u5382\u5546\u53EF\u80FD\u5FFD\u7565\u6216\u62D2\u6536",
693
+ "replay \u7684 provider/api/model \u4E0E\u5F53\u524D\u4E0D\u540C"
694
+ )
695
+ };
696
+ var TOOL_CALL_ARGS = lossy("wrapped-args", "\u975E\u5BF9\u8C61\u5165\u53C2\u5305\u6210 { value }", "tool_call.args \u4E0D\u662F\u5BF9\u8C61");
697
+ var USER_DEFERRED = lossy(
698
+ "user",
699
+ "\u843D\u5728 tool_call \u4E0E tool_result \u4E4B\u95F4\u7684\u7528\u6237\u6D88\u606F\u540E\u79FB\u5230\u540C\u6279\u7ED3\u679C\u4E4B\u540E\uFF08\u5DE5\u5177\u7ED3\u679C\u5FC5\u987B\u7D27\u8DDF\u8C03\u7528\uFF09",
700
+ "\u5DE5\u5177\u7ED3\u679C\u6CA1\u5230\u9F50\u65F6\u7528\u6237\u63D2\u8BDD"
701
+ );
702
+ var LOSS_MATRIX = {
703
+ "anthropic-messages": {
704
+ "core.user_message": [exact("user"), USER_DEFERRED],
705
+ "core.model_text": [exact("assistant-text")],
706
+ "core.model_thinking": [
707
+ exact("thinking-block", "\u5E26 signature \u539F\u6837\u56DE\u653E"),
708
+ THINKING_COMMON.noSignature,
709
+ THINKING_COMMON.foreign
710
+ ],
711
+ "core.tool_call": [exact("tool_use"), TOOL_CALL_ARGS],
712
+ "core.tool_result": [exact("tool_result", "\u7D27\u8DDF\u5BF9\u5E94 tool_use \u7684\u4E0B\u4E00\u6761 user")],
713
+ "core.system_note": [
714
+ exact(
715
+ "system",
716
+ "\u5E26\u6B63\u6587\u7684\u4E2D\u9014 system \u6D88\u606F",
717
+ "\u6A21\u578B\u65CF\u652F\u6301\u4E2D\u9014 system\uFF08Fable 5.x / Mythos 5.x / Opus 5 / Opus 4.8\uFF09"
718
+ ),
719
+ lossy("user-role", "\u4EE5 <system_note> \u6807\u7B7E\u5305\u4F4F\u8D70 user \u89D2\u8272", "\u6A21\u578B\u65CF\u4E0D\u652F\u6301\u4E2D\u9014 system")
720
+ ],
721
+ "core.compaction": [lossy("user-text", "\u6458\u8981\u4EE5 user \u89D2\u8272\u6587\u672C\u5448\u73B0\uFF0C\u6A21\u578B\u65E0\u6CD5\u533A\u5206\u5B83\u4E0E\u7528\u6237\u539F\u8BDD")],
722
+ ...NOT_SENT,
723
+ "ext.*": [dropped("none", "\u5BBF\u4E3B\u6269\u5C55\u4E8B\u4EF6\u65E0\u901A\u7528\u843D\u70B9\uFF1B\u9700\u8981\u6A21\u578B\u770B\u89C1\u7684\u5E94\u5728\u6295\u5F71\u5C42\u7FFB\u8BD1\u6210 core \u4E8B\u4EF6")]
724
+ },
725
+ "openai-responses": {
726
+ "core.user_message": [exact("user"), USER_DEFERRED],
727
+ "core.model_text": [exact("assistant-message")],
728
+ "core.model_thinking": [
729
+ exact("reasoning-item", "encrypted_content \u539F\u6837\u56DE\u653E"),
730
+ THINKING_COMMON.noSignature,
731
+ THINKING_COMMON.foreign
732
+ ],
733
+ "core.tool_call": [exact("function_call"), TOOL_CALL_ARGS],
734
+ "core.tool_result": [exact("function_call_output")],
735
+ "core.system_note": [
736
+ exact("developer", "reasoning \u6A21\u578B\u7528 developer \u89D2\u8272"),
737
+ exact("system", "\u975E reasoning \u6A21\u578B\u7528 system \u89D2\u8272")
738
+ ],
739
+ "core.compaction": [lossy("user-text", "\u6458\u8981\u4EE5 user \u89D2\u8272\u6587\u672C\u5448\u73B0")],
740
+ ...NOT_SENT,
741
+ "ext.*": [dropped("none", "\u540C Anthropic")]
742
+ }
743
+ };
744
+ function declaredLandings(api, type) {
745
+ const table = LOSS_MATRIX[api];
746
+ if (!table) return [];
747
+ return table[type] ?? (type.startsWith("ext.") ? table["ext.*"] ?? [] : []);
748
+ }
749
+ export {
750
+ LOSS_MATRIX,
751
+ PiAiLowering,
752
+ SUPPORTED_APIS,
753
+ SYSTEM_NOTE_MARK,
754
+ anthropic,
755
+ capabilitiesOf,
756
+ consumeStream,
757
+ declaredLandings,
758
+ definitionToModel,
759
+ draftsOf,
760
+ eventsToContext,
761
+ framedSystemNote,
762
+ markSystemNote,
763
+ openai,
764
+ resolveModel,
765
+ rewriteAnthropicPayload,
766
+ rewriteOpenAIResponsesPayload,
767
+ rewritePayload
768
+ };
769
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/capabilities.ts","../src/pi-lowering.ts","../src/from-stream.ts","../src/models.ts","../src/system-note.ts","../src/to-request.ts","../src/factories.ts","../src/loss-matrix.ts"],"sourcesContent":["/**\n * 按模型声明能力(技术方案 §11)。脑子模块只看这些布尔值,不看模型名。\n */\nimport type { LoweringCapabilities } from \"@reinsjs/core\"\nimport type { PiModel } from \"./models.js\"\n\n/**\n * S1 核实:Anthropic 带正文的中途 system 消息支持 Fable 5.1/5、Mythos 5.1/5、Opus 5/4.8;Sonnet 5 及更早不支持。\n * 按 id 前缀匹配,带日期后缀的 id(如 claude-opus-5-20260301)也能命中。\n */\nconst ANTHROPIC_MID_SYSTEM = /^claude-(fable-5|mythos-5|opus-5|opus-4-8)(-|$)/\n\n/** 调研核实:服务端 task budget 仅 Opus 5 与 Fable 5.1(DECISIONS 2026-09-08) */\nconst ANTHROPIC_TASK_BUDGET = /^claude-(opus-5|fable-5-1)(-|$)/\n\n/**\n * OpenAI Responses 只在请求带 reasoningEffort / reasoningSummary 时才开启 reasoning 并返回\n * encrypted_content(pi-ai 0.85.1 buildParams);否则 reasoning 关闭,没有可回放的东西。\n * 所以 thinkingReplay 在这家取决于请求选项,如实声明,脑子模块不必猜。\n */\nfunction openaiReasoningRequested(requestOptions: Record<string, unknown>): boolean {\n return Boolean(requestOptions.reasoningEffort || requestOptions.reasoningSummary)\n}\n\n/** 宿主在 ModelDefinition 里声明的能力,覆盖按 id 的推断 */\nexport interface CapabilityOverrides {\n midConversationSystem?: boolean\n}\n\nexport function capabilitiesOf(\n model: PiModel,\n requestOptions: Record<string, unknown> = {},\n overrides: CapabilityOverrides = {},\n): LoweringCapabilities {\n const caps = inferCapabilities(model, requestOptions)\n return overrides.midConversationSystem === undefined\n ? caps\n : { ...caps, midConversationSystem: overrides.midConversationSystem }\n}\n\nfunction inferCapabilities(model: PiModel, requestOptions: Record<string, unknown>): LoweringCapabilities {\n const base = {\n api: model.api,\n thinkingReplay: model.reasoning,\n parallelTools: true,\n images: model.input.includes(\"image\"),\n contextWindow: model.contextWindow,\n maxOutputTokens: model.maxTokens,\n }\n switch (model.api) {\n case \"anthropic-messages\":\n return {\n ...base,\n midConversationSystem: ANTHROPIC_MID_SYSTEM.test(model.id),\n taskBudget: ANTHROPIC_TASK_BUDGET.test(model.id),\n }\n case \"openai-responses\":\n // Responses 的 input 项允许任意位置的 developer / system 消息\n return {\n ...base,\n thinkingReplay: model.reasoning && openaiReasoningRequested(requestOptions),\n midConversationSystem: true,\n taskBudget: false,\n }\n default:\n return { ...base, midConversationSystem: false, taskBudget: false }\n }\n}\n","/**\n * PiAiLowering:@reinsjs/core 的 Lowering 接口在 pi-ai 上的实现。\n *\n * 只导入 api/<api>(流函数)与 providers/<name>.models(静态模型表)子路径(S4)。\n * pi-ai 的类型不出本包:对外暴露的 payload 用我们自己的结构描述。\n */\nimport type { Api, Context, Model, StreamFunction, StreamOptions } from \"@earendil-works/pi-ai\"\nimport { stream as anthropicStream } from \"@earendil-works/pi-ai/api/anthropic-messages\"\nimport { stream as openaiResponsesStream } from \"@earendil-works/pi-ai/api/openai-responses\"\nimport {\n type CoreEventDraft,\n type LoweredRequest,\n type Lowering,\n type LoweringCapabilities,\n LoweringError,\n type LoweringOutcome,\n type LoweringStreamContext,\n type ModelRef,\n type ToRequestInput,\n} from \"@reinsjs/core\"\nimport { type CapabilityOverrides, capabilitiesOf } from \"./capabilities.js\"\nimport { consumeStream } from \"./from-stream.js\"\nimport { definitionToModel, type ModelDefinition, type PiModel, resolveModel } from \"./models.js\"\nimport {\n type MidSystemCacheBreakpoint,\n type RewriteAnthropicOptions,\n rewriteAnthropicPayload,\n rewriteOpenAIResponsesPayload,\n} from \"./system-note.js\"\nimport { eventsToContext } from \"./to-request.js\"\n\nexport interface PiAiLoweringOptions {\n /** 按 provider 取 key;返回 undefined 视为未配置。本包不读环境变量,由宿主决定来源 */\n apiKey: (provider: string) => string | undefined\n /** 自定义 fetch(测试注入、代理、Workers 绑定);缺省 globalThis.fetch */\n fetch?: typeof globalThis.fetch\n /** 附加请求头;值为 null 表示删掉 pi-ai 的默认头 */\n headers?: Record<string, string | null>\n /** 内置表之外的模型 */\n models?: readonly ModelDefinition[]\n /**\n * 透传给 pi-ai 流函数的额外选项(maxTokens、temperature、Anthropic 的 effort / thinkingEnabled、\n * OpenAI 的 reasoningEffort / reasoningSummary 等),键名以 pi-ai 0.85.1 文档为准。按模型返回,便于分族配置。\n * 注意:OpenAI Responses 不给 reasoningEffort 就不开 reasoning,也就没有 thinking 可回放,capabilities 会如实报 false。\n */\n requestOptions?: (model: ModelRef) => Record<string, unknown>\n /**\n * Anthropic:system_note 殿后时 pi-ai 打在它上面的缓存断点怎么处置(见 system-note.ts)。\n * 缺省 \"automatic\"(去掉块级断点、请求顶层补自动缓存);\"previous-user\" / \"drop\" 供对照或特殊上游。\n */\n midSystemCacheBreakpoint?: MidSystemCacheBreakpoint\n /**\n * trust 标注(技术方案 §14):trust=untrusted 的事件(工具输出、外部内容)翻译时包上\n * `<untrusted source=\"tool:<name>\">…</untrusted>`,事件本身不动。缺省 true;传 false 关掉是宿主自担提示注入风险\n */\n trustMarkers?: boolean\n}\n\n/** 对外暴露的请求体:pi-ai Context 的结构描述,不引用 pi-ai 类型 */\nexport interface PiLoweredPayload {\n api: string\n context: {\n systemPrompt?: string\n messages: readonly unknown[]\n tools?: readonly unknown[]\n }\n}\n\nexport class PiAiLowering implements Lowering<PiLoweredPayload> {\n private readonly extraModels: PiModel[]\n /** 宿主自定义模型声明的能力覆盖,键 provider/id;pi-ai 的 Model 上放不下这些字段 */\n private readonly overrides = new Map<string, CapabilityOverrides>()\n\n constructor(private readonly opts: PiAiLoweringOptions) {\n this.extraModels = (opts.models ?? []).map(definitionToModel)\n for (const def of opts.models ?? []) {\n if (def.midConversationSystem !== undefined) {\n this.overrides.set(`${def.provider}/${def.id}`, { midConversationSystem: def.midConversationSystem })\n }\n }\n }\n\n capabilities(ref: ModelRef): LoweringCapabilities {\n return this.capabilitiesFor(ref, resolveModel(ref, this.extraModels))\n }\n\n private capabilitiesFor(ref: ModelRef, model: PiModel): LoweringCapabilities {\n return capabilitiesOf(model, this.requestOptionsFor(ref), this.overrides.get(`${ref.provider}/${ref.id}`))\n }\n\n private requestOptionsFor(ref: ModelRef): Record<string, unknown> {\n return this.opts.requestOptions?.(ref) ?? {}\n }\n\n toRequest(input: ToRequestInput): LoweredRequest<PiLoweredPayload> {\n const model = resolveModel(input.model, this.extraModels)\n const capabilities = this.capabilitiesFor(input.model, model)\n const { context, landings } = eventsToContext({\n events: input.events,\n model,\n capabilities,\n ...(input.tools ? { tools: input.tools } : {}),\n ...(input.systemPrompt !== undefined ? { systemPrompt: input.systemPrompt } : {}),\n ...(this.opts.trustMarkers !== undefined ? { trustMarkers: this.opts.trustMarkers } : {}),\n })\n return { model: input.model, capabilities, landings, payload: { api: model.api, context } }\n }\n\n async *stream(\n req: LoweredRequest<PiLoweredPayload>,\n ctx: LoweringStreamContext = {},\n ): AsyncGenerator<CoreEventDraft, LoweringOutcome> {\n const model = resolveModel(req.model, this.extraModels)\n const apiKey = this.opts.apiKey(model.provider)\n if (!apiKey) {\n throw new LoweringError(\"missing_api_key\", `未配置 ${model.provider} 的 API key`, {\n provider: model.provider,\n })\n }\n // toRequest 里放进 payload 的就是 pi-ai Context 本体,这里取回\n const context = req.payload.context as Context\n const options: StreamOptions & Record<string, unknown> = {\n ...this.requestOptionsFor(req.model),\n apiKey,\n ...(this.opts.fetch ? { fetch: this.opts.fetch } : {}),\n ...(this.opts.headers ? { headers: this.opts.headers } : {}),\n ...(ctx.signal ? { signal: ctx.signal } : {}),\n onPayload: (payload: unknown, m: Model<Api>) =>\n rewritePayload(model.api, payload, m, {\n ...(this.opts.midSystemCacheBreakpoint\n ? { cacheBreakpoint: this.opts.midSystemCacheBreakpoint }\n : {}),\n }),\n }\n const fn = streamFunctionFor(model.api)\n return yield* consumeStream(fn(model, context, options), ctx)\n }\n}\n\nfunction streamFunctionFor(api: string): StreamFunction<Api, StreamOptions> {\n switch (api) {\n case \"anthropic-messages\":\n return anthropicStream as unknown as StreamFunction<Api, StreamOptions>\n case \"openai-responses\":\n return openaiResponsesStream as unknown as StreamFunction<Api, StreamOptions>\n default:\n throw new LoweringError(\"unsupported_api\", `不支持的线协议 ${api}`, { api })\n }\n}\n\n/** 把带标记的 system_note 改写成各 API 的 system 消息;返回 undefined 表示请求体不变 */\nexport function rewritePayload(\n api: string,\n payload: unknown,\n model: { reasoning: boolean },\n opts: RewriteAnthropicOptions = {},\n): unknown {\n if (api === \"anthropic-messages\") return rewriteAnthropicPayload(payload, opts)\n if (api === \"openai-responses\") return rewriteOpenAIResponsesPayload(payload, model)\n return undefined\n}\n","/**\n * pi-ai 流 → 事件草稿。\n *\n * 只在响应收尾(done / error)时按最终消息的内容块产出草稿:签名类回放数据(Anthropic signature、\n * OpenAI reasoning item)在块结束时才齐,等收尾最稳。增量只通过 onDelta 给 UI。\n * 中断或出错时把已产出的部分内容也交出去 —— 日志要记录\"发生过什么\",是否继续由循环决定。\n */\nimport type { AssistantMessage, AssistantMessageEvent } from \"@earendil-works/pi-ai\"\nimport type { CoreEventDraft, LoweringOutcome, LoweringStreamContext } from \"@reinsjs/core\"\nimport type { ModelOrigin } from \"./to-request.js\"\n\nexport function draftsOf(msg: AssistantMessage): CoreEventDraft[] {\n const origin: ModelOrigin = { provider: msg.provider, api: msg.api, model: msg.model }\n const drafts: CoreEventDraft[] = []\n for (const block of msg.content) {\n if (block.type === \"thinking\") {\n const replay: Record<string, unknown> = { ...origin }\n if (block.thinkingSignature) replay.thinkingSignature = block.thinkingSignature\n if (block.redacted) replay.redacted = true\n drafts.push({ type: \"core.model_thinking\", actor: \"model\", payload: { text: block.thinking }, replay })\n } else if (block.type === \"text\") {\n if (block.text.length === 0) continue\n const replay: Record<string, unknown> = { ...origin }\n if (block.textSignature) replay.textSignature = block.textSignature\n drafts.push({ type: \"core.model_text\", actor: \"model\", payload: { text: block.text }, replay })\n } else if (block.type === \"toolCall\") {\n const replay: Record<string, unknown> = { ...origin }\n if (block.thoughtSignature) replay.thoughtSignature = block.thoughtSignature\n if (block.namespace !== undefined) replay.namespace = block.namespace\n drafts.push({\n type: \"core.tool_call\",\n actor: \"model\",\n payload: { toolCallId: block.id, name: block.name, args: block.arguments },\n replay,\n })\n }\n }\n return drafts\n}\n\nfunction outcomeOf(msg: AssistantMessage, stopReason: LoweringOutcome[\"stopReason\"]): LoweringOutcome {\n const usage: LoweringOutcome[\"usage\"] = { input: msg.usage.input, output: msg.usage.output }\n if (msg.usage.cacheRead) usage.cacheRead = msg.usage.cacheRead\n if (msg.usage.cacheWrite) usage.cacheWrite = msg.usage.cacheWrite\n const out: LoweringOutcome = { stopReason, usage, costUsd: msg.usage.cost.total }\n if (msg.errorMessage) out.errorMessage = msg.errorMessage\n if (msg.responseModel) out.responseModel = msg.responseModel\n return out\n}\n\nexport async function* consumeStream(\n events: AsyncIterable<AssistantMessageEvent>,\n ctx: LoweringStreamContext = {},\n): AsyncGenerator<CoreEventDraft, LoweringOutcome> {\n for await (const ev of events) {\n switch (ev.type) {\n case \"text_delta\":\n ctx.onDelta?.({ kind: \"text\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"thinking_delta\":\n ctx.onDelta?.({ kind: \"thinking\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"toolcall_delta\":\n ctx.onDelta?.({ kind: \"tool_args\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"done\": {\n yield* draftsOf(ev.message)\n // pi-ai 的 \"deferred\" 是异步批处理句柄,第一版不支持,按 stop 收尾并保留 rawStopReason 给排查\n const reason = ev.reason === \"deferred\" ? \"stop\" : ev.reason\n return outcomeOf(ev.message, reason)\n }\n case \"error\":\n yield* draftsOf(ev.error)\n return outcomeOf(ev.error, ev.reason)\n default:\n break\n }\n }\n return {\n stopReason: \"error\",\n usage: { input: 0, output: 0 },\n errorMessage: \"pi-ai 流在 done / error 之前就结束了\",\n }\n}\n","/**\n * ModelRef → pi-ai Model。\n *\n * 只从 providers/<name>.models 取静态模型表(S4:不用 providers/all,它会拉进 Bedrock 与 AWS SDK)。\n * 宿主要用表里没有的模型(代理、私有部署、新发布)时,用 ModelDefinition 以我们自己的词汇描述,\n * 这里补齐 pi-ai 需要的其余字段 —— pi-ai 的 Model 类型不出本包。\n */\nimport type { Api, Model } from \"@earendil-works/pi-ai\"\nimport { ANTHROPIC_MODELS } from \"@earendil-works/pi-ai/providers/anthropic.models\"\nimport { OPENAI_MODELS } from \"@earendil-works/pi-ai/providers/openai.models\"\nimport { LoweringError, type ModelRef } from \"@reinsjs/core\"\n\n/** 本包内部使用的 pi-ai 模型类型 */\nexport type PiModel = Model<Api>\n\n/** 第一版支持的线协议 */\nexport const SUPPORTED_APIS: ReadonlySet<string> = new Set([\"anthropic-messages\", \"openai-responses\"])\n\n/** 宿主自定义模型:用我们的词汇描述,字段与 LoweringCapabilities 对齐 */\nexport interface ModelDefinition {\n provider: string\n id: string\n /** \"anthropic-messages\" | \"openai-responses\" */\n api: string\n baseUrl: string\n /** 支持 thinking / reasoning */\n reasoning: boolean\n contextWindow: number\n maxOutputTokens: number\n images?: boolean\n name?: string\n /** 每百万 token 美元价;缺省全 0(成本算不出但能跑) */\n cost?: { input: number; output: number; cacheRead: number; cacheWrite: number }\n /** 额外请求头,如私有网关的鉴权 */\n headers?: Record<string, string>\n /**\n * 是否接受 messages 里的中途 `role:\"system\"` 消息(system_note 的 exact 落点)。内置 Anthropic 模型按 id 判定;\n * 第三方 Anthropic 协议上游(如 DeepSeek 的兼容端口,2026-09-08 实测接受)由宿主在此声明,缺省按不支持处理。\n */\n midConversationSystem?: boolean\n}\n\nconst BUILTIN: Readonly<Record<string, Readonly<Record<string, PiModel>>>> = {\n anthropic: ANTHROPIC_MODELS as unknown as Record<string, PiModel>,\n openai: OPENAI_MODELS as unknown as Record<string, PiModel>,\n}\n\nexport function definitionToModel(def: ModelDefinition): PiModel {\n const model: PiModel = {\n id: def.id,\n name: def.name ?? def.id,\n api: def.api,\n provider: def.provider,\n baseUrl: def.baseUrl,\n reasoning: def.reasoning,\n input: def.images ? [\"text\", \"image\"] : [\"text\"],\n cost: def.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: def.contextWindow,\n maxTokens: def.maxOutputTokens,\n }\n if (def.headers) model.headers = def.headers\n return model\n}\n\nexport function resolveModel(ref: ModelRef, extra: readonly PiModel[] = []): PiModel {\n const model =\n extra.find((m) => m.provider === ref.provider && m.id === ref.id) ?? BUILTIN[ref.provider]?.[ref.id]\n if (!model) {\n throw new LoweringError(\n \"unsupported_model\",\n `找不到模型 ${ref.provider}/${ref.id};内置表只含 anthropic 与 openai,其余请通过 models 选项声明`,\n {\n provider: ref.provider,\n id: ref.id,\n },\n )\n }\n if (!SUPPORTED_APIS.has(model.api)) {\n throw new LoweringError(\n \"unsupported_api\",\n `模型 ${ref.provider}/${ref.id} 走 ${model.api},本实现只支持 anthropic-messages 与 openai-responses`,\n {\n api: model.api,\n },\n )\n }\n return model\n}\n","/**\n * system_note 的落点(S1 结论)。\n *\n * pi-ai 的 Message 没有 system 角色,所以:\n * - 模型支持中途 system 时:先当 user 消息放进 Context,文本前加内部标记;在 pi-ai 的 onPayload 钩子里\n * 把带标记的消息改写成线协议的 system 消息并归位。标记只在本文件生产与消费,不会送到线上。\n * - 不支持时:以 <system_note> 标签包住、仍走 user 角色,有损矩阵记为 lossy(user-role)。\n *\n * Anthropic 摆放规则(官方,违反即 400):不能是首条;必须紧跟 user 轮(含 tool_result 的 user);\n * 后接 assistant 或收尾;连续多条 system 视为一组。\n * OpenAI Responses:input 项里 developer / system 消息可出现在任意位置,无归位需求。\n */\nimport type { SystemNotePayload } from \"@reinsjs/core\"\n\nexport const SYSTEM_NOTE_MARK = \"[[reins:system_note]]\"\n\nexport function markSystemNote(text: string): string {\n return `${SYSTEM_NOTE_MARK}${text}`\n}\n\n/** 不支持中途 system 的模型:用标签框住,让模型知道这不是用户说的 */\nexport function framedSystemNote(kind: SystemNotePayload[\"kind\"], text: string): string {\n return `<system_note kind=\"${kind}\">\\n${text}\\n</system_note>`\n}\n\ninterface WireMessage {\n role: string\n content: unknown\n [k: string]: unknown\n}\n\ninterface MarkedNote {\n text: string\n /** pi-ai 打在这条消息上的缓存断点(它是最后一条 user 时才有),改写后要搬走而不是丢掉 */\n cacheControl?: unknown\n}\n\n/** 取出带标记的正文;不是标记消息返回 null */\nfunction markedNote(m: WireMessage, textType: string): MarkedNote | null {\n if (m.role !== \"user\") return null\n let text: string | null = null\n let cacheControl: unknown\n if (typeof m.content === \"string\") text = m.content\n else if (Array.isArray(m.content) && m.content.length === 1) {\n const only = m.content[0] as { type?: string; text?: string; cache_control?: unknown }\n if (only.type === textType && typeof only.text === \"string\") {\n text = only.text\n cacheControl = only.cache_control\n }\n }\n if (text === null || !text.startsWith(SYSTEM_NOTE_MARK)) return null\n return {\n text: text.slice(SYSTEM_NOTE_MARK.length),\n ...(cacheControl !== undefined ? { cacheControl } : {}),\n }\n}\n\n/**\n * Anthropic Messages 请求体改写:标记消息 → {role:\"system\", content:[text]},并按摆放规则归位。\n * 归位算法:每条 system 放到\"它之后的第一条 assistant\"之前(此时前一条必是 user);后面没有 assistant 就放到\n * 消息列表末尾(紧跟最后一条 user 收尾)。pi-ai 在部分模型上会在末尾追加 content 为空的 effort 专用 system 消息,\n * 我们的 system 与它相邻成组,符合规则。\n *\n * 缓存断点(B1,prompt cache 约束 4):pi-ai 把 cache_control 打在\"最后一条 user 消息\"上;感知等 system_note\n * 追加在时间线末尾时,那条最后的 user 正是我们的标记消息,改写成 system 后断点会跟着消失,而官方规则是\n * \"最后一个断点之后的内容一律不缓存\" —— 整段对话历史都会按原价计费。处置由 `cacheBreakpoint` 选:\n * - \"automatic\"(缺省):去掉这个块级断点,在请求顶层补 `cache_control`(Anthropic 的自动缓存:断点自动落在最后一个\n * 可缓存块上,与显式断点兼容、占 4 个槽位中的 1 个)。B1 实测(spikes/b1-perception-cache)命中率与不注入持平。\n * - \"previous-user\":搬到紧邻的前一条 user 消息末块(真正的最新 user / tool_result)。实测比不注入低 3~6 个点。\n * - \"drop\":丢掉。只在上游自己会补自动缓存(如某些网关)时才不吃亏。\n * 把断点留在改写后的 system 消息上实测会让整段提示每次重写、几乎零命中,所以不提供这个选项。\n */\nexport type MidSystemCacheBreakpoint = \"automatic\" | \"previous-user\" | \"drop\"\n\nexport interface RewriteAnthropicOptions {\n cacheBreakpoint?: MidSystemCacheBreakpoint\n}\n\n/** Anthropic 每个请求最多 4 个断点(含顶层自动缓存那一个),超出即 400 */\nconst MAX_ANTHROPIC_BREAKPOINTS = 4\n\nexport function rewriteAnthropicPayload(payload: unknown, opts: RewriteAnthropicOptions = {}): unknown {\n const breakpoint = opts.cacheBreakpoint ?? \"automatic\"\n const p = payload as {\n messages?: WireMessage[]\n system?: unknown\n tools?: unknown\n cache_control?: unknown\n }\n if (!Array.isArray(p.messages)) return undefined\n const body: WireMessage[] = []\n const pending: (MarkedNote & { afterIndex: number })[] = []\n for (const m of p.messages) {\n const note = markedNote(m, \"text\")\n if (note !== null) pending.push({ ...note, afterIndex: body.length })\n else body.push(m)\n }\n if (pending.length === 0) return undefined\n\n // 每条说明在**原始** body 里的落点(都算完再拼,而不是边算边 splice:边 splice 会让同一落点的多条说明前后颠倒)\n const placeOf = (note: (typeof pending)[number]): number => {\n let at = body.findIndex((m, idx) => idx >= note.afterIndex && m.role === \"assistant\")\n if (at === -1) {\n // 收尾:跳过 pi-ai 追加的 effort 专用空 system,保持\"紧跟最后一条 user\"\n at = body.length\n while (at > 0 && body[at - 1]?.role === \"system\" && isEmptyContent(body[at - 1]?.content)) at--\n }\n // 不能是首条:前面没有任何消息时挪到第一条 user 之后\n if (at === 0) {\n const firstUser = body.findIndex((m) => m.role === \"user\")\n at = firstUser === -1 ? body.length : firstUser + 1\n }\n return at\n }\n // 同一落点的说明按原顺序成组(相邻的多条 system 视为一组,Anthropic 允许)\n const groups = new Map<number, MarkedNote[]>()\n for (const note of pending) {\n const at = placeOf(note)\n const bucket = groups.get(at)\n if (bucket) bucket.push(note)\n else groups.set(at, [note])\n }\n\n let lostBreakpoint: unknown\n const messages: WireMessage[] = []\n for (let i = 0; i <= body.length; i++) {\n const notes = groups.get(i)\n if (notes) {\n for (const note of notes) {\n if (note.cacheControl !== undefined && breakpoint === \"previous-user\") {\n // 搬到紧邻的前一条 user 消息末块(此时它已在 messages 末尾)\n const prev = messages[messages.length - 1]\n if (prev) messages[messages.length - 1] = withCacheControl(prev, note.cacheControl)\n }\n if (note.cacheControl !== undefined && breakpoint === \"automatic\") lostBreakpoint = note.cacheControl\n messages.push({ role: \"system\", content: [{ type: \"text\", text: note.text }] })\n }\n }\n const m = body[i]\n if (m) messages.push(m)\n }\n const out = { ...p, messages }\n if (lostBreakpoint !== undefined && out.cache_control === undefined) {\n // 顶层自动缓存也占一个槽位;块级断点已满就只能放弃,不能让请求 400\n if (countBlockBreakpoints(out) < MAX_ANTHROPIC_BREAKPOINTS) out.cache_control = lostBreakpoint\n }\n return out\n}\n\n/** 数请求里块级 cache_control 的个数:system 数组、tools 数组、messages 的内容块 */\nfunction countBlockBreakpoints(p: { system?: unknown; tools?: unknown; messages: WireMessage[] }): number {\n const has = (b: unknown) => typeof b === \"object\" && b !== null && \"cache_control\" in b\n let n = 0\n if (Array.isArray(p.system)) n += p.system.filter(has).length\n if (Array.isArray(p.tools)) n += p.tools.filter(has).length\n for (const m of p.messages) if (Array.isArray(m.content)) n += m.content.filter(has).length\n return n\n}\n\n/**\n * 把缓存断点打到某条 user 消息的最后一个内容块上(Anthropic 允许 text / image / tool_result 块带 cache_control)。\n * 归位规则保证 system 前面必是 user;万一不是,宁可丢断点也不把 cache_control 放到厂商不认的位置上。\n * 返回新对象,不改动传入的请求体。\n */\nfunction withCacheControl(m: WireMessage, cacheControl: unknown): WireMessage {\n if (m.role !== \"user\") return m\n if (typeof m.content === \"string\") {\n return { ...m, content: [{ type: \"text\", text: m.content, cache_control: cacheControl }] }\n }\n if (Array.isArray(m.content) && m.content.length > 0) {\n const blocks = [...(m.content as Record<string, unknown>[])]\n const last = blocks[blocks.length - 1] as Record<string, unknown>\n blocks[blocks.length - 1] = { ...last, cache_control: cacheControl }\n return { ...m, content: blocks }\n }\n return m\n}\n\nfunction isEmptyContent(content: unknown): boolean {\n return Array.isArray(content) && content.length === 0\n}\n\n/**\n * OpenAI Responses 请求体改写:标记消息 → {role: developer|system, content:[input_text]}。\n * reasoning 模型用 developer(与 pi-ai 放 systemPrompt 的选择一致),其余用 system。\n */\nexport function rewriteOpenAIResponsesPayload(payload: unknown, model: { reasoning: boolean }): unknown {\n const p = payload as { input?: unknown }\n if (!Array.isArray(p.input)) return undefined\n let changed = false\n const role = model.reasoning ? \"developer\" : \"system\"\n const input = (p.input as WireMessage[]).map((m) => {\n const note = markedNote(m, \"input_text\")\n if (note === null) return m\n changed = true\n return { role, content: [{ type: \"input_text\", text: note.text }] }\n })\n return changed ? { ...p, input } : undefined\n}\n","/**\n * 事件 → pi-ai Context(三角色 Message[] + tools + systemPrompt),并逐条记录落点。\n *\n * 分组规则:连续的 model 事件(thinking / text / tool_call)合成一条 AssistantMessage,\n * 遇到任何非 model 事件就收口。AssistantMessage 需要 api/provider/model 才能让 pi-ai 判断\n * \"这段 thinking 是不是本模型产的、能不能回放\",这些信息在事件产出时记在 replay 里。\n */\nimport type {\n AssistantMessage,\n Context,\n Message,\n TextContent,\n ThinkingContent,\n Tool,\n ToolCall,\n} from \"@earendil-works/pi-ai\"\nimport {\n type ContentPart,\n type CoreEvent,\n type Event,\n type LandingRecord,\n type LoweringCapabilities,\n markUntrusted,\n markUntrustedText,\n needsUntrustedMark,\n type ToolSpec,\n untrustedSourceOf,\n} from \"@reinsjs/core\"\nimport type { PiModel } from \"./models.js\"\nimport { framedSystemNote, markSystemNote } from \"./system-note.js\"\n\n/** 模型事件 replay 里记录的来源,产出与回放两头共用 */\nexport interface ModelOrigin {\n provider: string\n api: string\n model: string\n}\n\nexport interface ThinkingReplay extends Partial<ModelOrigin> {\n thinkingSignature?: string\n redacted?: boolean\n}\nexport interface TextReplay extends Partial<ModelOrigin> {\n textSignature?: string\n}\nexport interface ToolCallReplay extends Partial<ModelOrigin> {\n thoughtSignature?: string\n namespace?: string\n}\n\nconst ZERO_USAGE: AssistantMessage[\"usage\"] = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n}\n\nfunction toPiContent(\n parts: readonly ContentPart[],\n): (TextContent | { type: \"image\"; data: string; mimeType: string })[] {\n return parts.map((p) =>\n p.type === \"text\" ? { type: \"text\", text: p.text } : { type: \"image\", data: p.data, mimeType: p.mime },\n )\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction originOf(replay: Record<string, unknown> | undefined, fallback: PiModel): ModelOrigin {\n const r = (replay ?? {}) as Partial<ModelOrigin>\n return {\n provider: typeof r.provider === \"string\" ? r.provider : fallback.provider,\n api: typeof r.api === \"string\" ? r.api : fallback.api,\n model: typeof r.model === \"string\" ? r.model : fallback.id,\n }\n}\n\nfunction sameOrigin(a: ModelOrigin, b: ModelOrigin): boolean {\n return a.provider === b.provider && a.api === b.api && a.model === b.model\n}\n\n/**\n * 是否来自别家:只比 provider 与 api。响应里报告的模型 id 常与请求的不同(带日期后缀、别名、网关改名),\n * 同家同协议下签名仍可回放,不算有损,只在落点备注里留痕。\n */\nfunction foreignOrigin(a: ModelOrigin, target: ModelOrigin): boolean {\n return a.provider !== target.provider || a.api !== target.api\n}\n\nconst DEFERRED_NOTE = \"已后移到同批工具结果之后(工具结果必须紧跟调用)\"\nconst ESCAPED_NOTE = \"不可信内容里含提前闭合的 </untrusted,已转义\"\n\nexport interface ToContextInput {\n events: readonly Event[]\n tools?: readonly ToolSpec[]\n model: PiModel\n capabilities: LoweringCapabilities\n systemPrompt?: string\n /** trust=untrusted 的内容(工具输出、外部内容)以 <untrusted source=…> 包裹(§14)。缺省 true;关掉是宿主自担风险 */\n trustMarkers?: boolean\n}\n\nexport function eventsToContext(input: ToContextInput): { context: Context; landings: LandingRecord[] } {\n const { model, capabilities } = input\n const target: ModelOrigin = { provider: model.provider, api: model.api, model: model.id }\n const isAnthropic = model.api === \"anthropic-messages\"\n const trustMarkers = input.trustMarkers !== false\n const messages: Message[] = []\n const landings: LandingRecord[] = []\n\n let group: { origin: ModelOrigin; content: AssistantMessage[\"content\"]; at: number } | null = null\n /**\n * 已下发 tool_call、结果还没到的调用 id。Anthropic 要求同一批 tool_result 紧跟在 tool_use 所在的 assistant 之后、\n * 连成一条 user,中间不能插别的消息;而日志里 pin / memory 留痕的说明、感知说明都可能落在两条 tool_result 之间\n * (并行工具时 ctx.emit 的草稿排在各自结果之前),用户也可能在结果回来之前插话(续跑带新 input、进程死亡后再发消息)。\n * 所以结果没到齐时,说明、摘要与用户消息先攒着,到齐后再放出(落点备注说明后移)。时间线本身如实保留插话的位置。\n */\n const awaiting = new Set<string>()\n const deferred: {\n msg: Message\n event: Event\n kind: LandingRecord[\"kind\"]\n landing: string\n note?: string\n }[] = []\n const land = (e: Event, kind: LandingRecord[\"kind\"], landing: string, note?: string) => {\n landings.push(\n note\n ? { eventId: e.id, type: e.type, kind, landing, note }\n : { eventId: e.id, type: e.type, kind, landing },\n )\n }\n const releaseDeferred = () => {\n for (const d of deferred) {\n messages.push(d.msg)\n land(d.event, d.kind, d.landing, d.note ? `${d.note};${DEFERRED_NOTE}` : DEFERRED_NOTE)\n }\n deferred.length = 0\n }\n /**\n * trust 标注(§14):untrusted 的内容包上 <untrusted source=…>,事件本身不动。\n * 返回翻译后的片段与\"是否因转义而有损\"——内容里出现提前闭合的标签时被转义,落点要记 lossy。\n */\n const content = (e: Event, parts: readonly ContentPart[]): { parts: ContentPart[]; escaped: boolean } => {\n if (!trustMarkers || !needsUntrustedMark(e)) return { parts: [...parts], escaped: false }\n return markUntrusted(parts, untrustedSourceOf(e))\n }\n const text = (e: Event, s: string): { text: string; escaped: boolean } => {\n if (!trustMarkers || !needsUntrustedMark(e)) return { text: s, escaped: false }\n return markUntrustedText(s, untrustedSourceOf(e))\n }\n /** 说明 / 摘要类消息:工具结果还没到齐就先攒着 */\n const note = (e: Event, msg: Message, kind: LandingRecord[\"kind\"], landing: string, why?: string) => {\n if (awaiting.size > 0) {\n deferred.push({ msg, event: e, kind, landing, ...(why !== undefined ? { note: why } : {}) })\n return\n }\n messages.push(msg)\n land(e, kind, landing, why)\n }\n /** 新的模型输出到来:这批调用的结果不会再来了(视图被切在了结果之前),后移的一切放出 */\n const settleAwaiting = () => {\n awaiting.clear()\n releaseDeferred()\n }\n const flush = () => {\n if (!group) return\n const hasTool = group.content.some((c) => c.type === \"toolCall\")\n messages.push({\n role: \"assistant\",\n content: group.content,\n api: group.origin.api,\n provider: group.origin.provider,\n model: group.origin.model,\n usage: ZERO_USAGE,\n stopReason: hasTool ? \"toolUse\" : \"stop\",\n timestamp: group.at,\n })\n for (const c of group.content) if (c.type === \"toolCall\") awaiting.add(c.id)\n group = null\n }\n const assistant = (e: Event, origin: ModelOrigin) => {\n if (group && !sameOrigin(group.origin, origin)) flush()\n if (!group) {\n settleAwaiting()\n group = { origin, content: [], at: e.at }\n }\n return group\n }\n\n for (const raw of input.events) {\n const e = raw as CoreEvent\n switch (e.type) {\n case \"core.user_message\": {\n flush()\n const c = content(e, e.payload.content)\n const msg: Message = { role: \"user\", content: toPiContent(c.parts), timestamp: e.at }\n // 工具结果还没到齐就来了用户消息:后移到同批结果之后,否则 tool_use 后面紧跟的不是 tool_result,厂商 400。\n // 顺序变了所以记 lossy;日志里它仍在原位\n if (awaiting.size > 0) {\n deferred.push({\n msg,\n event: e,\n kind: \"lossy\",\n landing: \"user\",\n note: c.escaped\n ? `用户消息落在工具调用与结果之间;${ESCAPED_NOTE}`\n : \"用户消息落在工具调用与结果之间\",\n })\n break\n }\n messages.push(msg)\n if (c.escaped) land(e, \"lossy\", \"user\", ESCAPED_NOTE)\n else land(e, \"exact\", \"user\")\n break\n }\n\n case \"core.model_thinking\": {\n const origin = originOf(e.replay, model)\n const r = (e.replay ?? {}) as ThinkingReplay\n const block: ThinkingContent = { type: \"thinking\", thinking: e.payload.text }\n if (typeof r.thinkingSignature === \"string\") block.thinkingSignature = r.thinkingSignature\n if (r.redacted === true) block.redacted = true\n assistant(e, origin).content.push(block)\n if (!block.thinkingSignature)\n land(e, \"lossy\", \"text-or-drop\", \"无签名的 thinking 由 pi-ai 降为文本或丢弃\")\n else if (foreignOrigin(origin, target))\n land(\n e,\n \"lossy\",\n \"provider-dependent\",\n `来自 ${origin.provider}/${origin.model} 的 thinking,厂商可能忽略或拒收`,\n )\n else if (origin.model !== target.model)\n land(\n e,\n \"exact\",\n isAnthropic ? \"thinking-block\" : \"reasoning-item\",\n `签名来自 ${origin.model},当前请求 ${target.model}`,\n )\n else land(e, \"exact\", isAnthropic ? \"thinking-block\" : \"reasoning-item\")\n break\n }\n\n case \"core.model_text\": {\n const origin = originOf(e.replay, model)\n const r = (e.replay ?? {}) as TextReplay\n const block: TextContent = { type: \"text\", text: e.payload.text }\n if (typeof r.textSignature === \"string\") block.textSignature = r.textSignature\n assistant(e, origin).content.push(block)\n land(e, \"exact\", isAnthropic ? \"assistant-text\" : \"assistant-message\")\n break\n }\n\n case \"core.tool_call\": {\n const origin = originOf(e.replay, model)\n const r = (e.replay ?? {}) as ToolCallReplay\n const wrapped = !isPlainObject(e.payload.args)\n const block: ToolCall = {\n type: \"toolCall\",\n id: e.payload.toolCallId,\n name: e.payload.name,\n arguments: wrapped ? { value: e.payload.args } : (e.payload.args as Record<string, unknown>),\n }\n if (typeof r.thoughtSignature === \"string\") block.thoughtSignature = r.thoughtSignature\n if (typeof r.namespace === \"string\") block.namespace = r.namespace\n assistant(e, origin).content.push(block)\n if (wrapped) land(e, \"lossy\", \"wrapped-args\", \"非对象入参包成 { value }\")\n else land(e, \"exact\", isAnthropic ? \"tool_use\" : \"function_call\")\n break\n }\n\n case \"core.tool_result\": {\n flush()\n const c = content(e, e.payload.content)\n messages.push({\n role: \"toolResult\",\n toolCallId: e.payload.toolCallId,\n toolName: e.payload.name,\n content: toPiContent(c.parts),\n isError: e.payload.isError,\n timestamp: e.at,\n })\n const landing = isAnthropic ? \"tool_result\" : \"function_call_output\"\n if (c.escaped) land(e, \"lossy\", landing, ESCAPED_NOTE)\n else land(e, \"exact\", landing)\n awaiting.delete(e.payload.toolCallId)\n if (awaiting.size === 0) releaseDeferred()\n break\n }\n\n case \"core.system_note\": {\n flush()\n // 宿主注入的外部内容可能把 system_note 标成 untrusted(如抓取的网页),同样包裹\n const t = text(e, e.payload.text)\n if (capabilities.midConversationSystem) {\n note(\n e,\n { role: \"user\", content: markSystemNote(t.text), timestamp: e.at },\n t.escaped ? \"lossy\" : \"exact\",\n isAnthropic ? \"system\" : model.reasoning ? \"developer\" : \"system\",\n t.escaped ? ESCAPED_NOTE : undefined,\n )\n } else {\n note(\n e,\n { role: \"user\", content: framedSystemNote(e.payload.kind, t.text), timestamp: e.at },\n \"lossy\",\n \"user-role\",\n \"模型不支持中途 system,以 <system_note> 标签包住走 user 角色\",\n )\n }\n break\n }\n\n case \"core.compaction\": {\n flush()\n const t = text(e, e.payload.summary)\n note(\n e,\n {\n role: \"user\",\n content: `[Summary of earlier conversation]\\n${t.text}`,\n timestamp: e.at,\n },\n \"lossy\",\n \"user-text\",\n \"摘要以 user 角色文本呈现\",\n )\n break\n }\n\n case \"core.approval_request\":\n case \"core.approval_decision\":\n case \"core.run_paused\":\n case \"core.run_resumed\":\n case \"core.budget_usage\":\n case \"core.memory_op\":\n case \"core.handoff\":\n case \"core.error\":\n land(e, \"dropped\", \"none\", \"运维事件不下发(投影默认已过滤)\")\n break\n\n default:\n land(raw, \"dropped\", \"none\", `无通用落点:${raw.type}`)\n }\n }\n flush()\n settleAwaiting()\n\n const context: Context = { messages }\n if (input.systemPrompt) context.systemPrompt = input.systemPrompt\n if (input.tools && input.tools.length > 0) {\n // pi-ai 的 parameters 是 typebox TSchema,运行时就是 JSON Schema 对象,直接透传\n context.tools = input.tools.map(\n (t): Tool => ({\n name: t.name,\n description: t.description,\n parameters: t.inputSchema as Tool[\"parameters\"],\n }),\n )\n }\n return { context, landings }\n}\n","/**\n * 一行拿到\"模型 + 降级层\":`anthropic(\"claude-opus-5\", { apiKey })`、`openai(\"gpt-5.5\", { apiKey })`。\n * 返回 BoundModel,直接给 `createAgent({ model })`;要更多控制(多模型共享一个降级层、自定义 fetch)就自己 new PiAiLowering。\n *\n * 本包不读环境变量(T7 决策),apiKey 必填、由宿主决定来源。\n * 带 baseUrl 即走代理 / 网关:此时按 ModelDefinition 登记,能力字段给了缺省值,可用 contextWindow 等覆盖。\n */\nimport type { BoundModel } from \"@reinsjs/core\"\nimport type { ModelDefinition } from \"./models.js\"\nimport { PiAiLowering, type PiAiLoweringOptions } from \"./pi-lowering.js\"\n\nexport interface BoundModelOptions {\n apiKey: string\n /** 代理或网关地址。Anthropic 在其后接 /v1/messages,OpenAI 接 /responses(网关请给到 …/v1) */\n baseUrl?: string\n /** 透传给 pi-ai 的请求选项(thinkingEnabled、reasoningEffort、maxTokens…) */\n requestOptions?: Record<string, unknown>\n /** 仅 baseUrl 模式下需要:模型能力。缺省 200k 窗口、16k 输出、支持推理与图片 */\n contextWindow?: number\n maxOutputTokens?: number\n reasoning?: boolean\n images?: boolean\n /** 仅 baseUrl 模式:上游是否接受中途 `role:\"system\"`(system_note 的 exact 落点)。第三方 Anthropic 兼容端口(如 DeepSeek)实测接受时置 true;缺省按不支持、以标签走 user */\n midConversationSystem?: boolean\n fetch?: typeof globalThis.fetch\n headers?: Record<string, string | null>\n /** trust 标注(§14):untrusted 内容包 <untrusted> 标记。缺省开;关掉是宿主自担风险 */\n trustMarkers?: boolean\n}\n\nfunction bound(\n provider: \"anthropic\" | \"openai\",\n api: string,\n id: string,\n opts: BoundModelOptions,\n): BoundModel {\n const models: ModelDefinition[] = opts.baseUrl\n ? [\n {\n provider,\n id,\n api,\n baseUrl: opts.baseUrl,\n reasoning: opts.reasoning ?? true,\n contextWindow: opts.contextWindow ?? 200_000,\n maxOutputTokens: opts.maxOutputTokens ?? 16_000,\n images: opts.images ?? true,\n ...(opts.midConversationSystem !== undefined\n ? { midConversationSystem: opts.midConversationSystem }\n : {}),\n },\n ]\n : []\n const loweringOpts: PiAiLoweringOptions = {\n apiKey: (p) => (p === provider ? opts.apiKey : undefined),\n models,\n ...(opts.requestOptions ? { requestOptions: () => opts.requestOptions ?? {} } : {}),\n ...(opts.fetch ? { fetch: opts.fetch } : {}),\n ...(opts.headers ? { headers: opts.headers } : {}),\n ...(opts.trustMarkers !== undefined ? { trustMarkers: opts.trustMarkers } : {}),\n }\n return { model: { provider, id }, lowering: new PiAiLowering(loweringOpts) }\n}\n\n/** Anthropic Messages。缺省开 thinking(模型不支持时 pi-ai 会忽略) */\nexport function anthropic(id: string, opts: BoundModelOptions): BoundModel {\n return bound(\"anthropic\", \"anthropic-messages\", id, {\n requestOptions: { thinkingEnabled: true },\n ...opts,\n })\n}\n\n/** OpenAI Responses。缺省 reasoningEffort=medium,这样才有可回放的 reasoning(见 T7 决策) */\nexport function openai(id: string, opts: BoundModelOptions): BoundModel {\n return bound(\"openai\", \"openai-responses\", id, {\n requestOptions: { reasoningEffort: \"medium\" },\n ...opts,\n })\n}\n","/**\n * 有损矩阵(P7:有损必声明)。api → 事件 type → 可能落点。\n *\n * 这是\"合同\":toRequest 对每条事件实际记录的落点必须是这里声明过的一种(T8 测试逐项断言)。\n * 新增事件类型或新 API 而不补这张表,测试就红 —— 宁可编译期/测试期吵,不要线上静默丢。\n */\nimport type { LandingSpec, LossMatrix } from \"@reinsjs/core\"\n\nconst exact = (landing: string, note?: string, when?: string): LandingSpec => {\n const spec: LandingSpec = { kind: \"exact\", landing }\n if (note) spec.note = note\n if (when) spec.when = when\n return spec\n}\nconst lossy = (landing: string, note: string, when?: string): LandingSpec =>\n when ? { kind: \"lossy\", landing, note, when } : { kind: \"lossy\", landing, note }\nconst dropped = (landing: string, note: string): LandingSpec => ({ kind: \"dropped\", landing, note })\n\n/** 两家共同的\"不下发\"事件:它们服务宿主与审计,信息由别的事件承载;投影默认已过滤,这里是第二道声明 */\nconst NOT_SENT: Readonly<Record<string, readonly LandingSpec[]>> = {\n \"core.approval_request\": [dropped(\"none\", \"审批结果由 tool_result(isError) 告知模型\")],\n \"core.approval_decision\": [dropped(\"none\", \"同上\")],\n \"core.run_paused\": [dropped(\"none\", \"运行记录;感知模块会提炼进 system_note\")],\n \"core.run_resumed\": [dropped(\"none\", \"同上\")],\n \"core.budget_usage\": [dropped(\"none\", \"同上\")],\n \"core.memory_op\": [dropped(\"none\", \"记忆读写留痕,模型已通过工具结果知晓\")],\n \"core.handoff\": [dropped(\"none\", \"交接后本会话结束;新会话首条 user 承载 triggerMessage\")],\n \"core.error\": [dropped(\"none\", \"provider 错误由循环处理;工具错误已在 tool_result.isError\")],\n}\n\nconst THINKING_COMMON = {\n noSignature: lossy(\n \"text-or-drop\",\n \"无签名的 thinking 由 pi-ai 降为文本或丢弃\",\n \"事件 replay 缺 thinkingSignature\",\n ),\n foreign: lossy(\n \"provider-dependent\",\n \"来自其它模型的 thinking,厂商可能忽略或拒收\",\n \"replay 的 provider/api/model 与当前不同\",\n ),\n}\n\nconst TOOL_CALL_ARGS = lossy(\"wrapped-args\", \"非对象入参包成 { value }\", \"tool_call.args 不是对象\")\n\n/** 用户在工具结果回来之前插话(续跑带新 input、进程死亡后再发消息):消息后移到同批结果之后,顺序有变 */\nconst USER_DEFERRED = lossy(\n \"user\",\n \"落在 tool_call 与 tool_result 之间的用户消息后移到同批结果之后(工具结果必须紧跟调用)\",\n \"工具结果没到齐时用户插话\",\n)\n\nexport const LOSS_MATRIX: LossMatrix = {\n \"anthropic-messages\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED],\n \"core.model_text\": [exact(\"assistant-text\")],\n \"core.model_thinking\": [\n exact(\"thinking-block\", \"带 signature 原样回放\"),\n THINKING_COMMON.noSignature,\n THINKING_COMMON.foreign,\n ],\n \"core.tool_call\": [exact(\"tool_use\"), TOOL_CALL_ARGS],\n \"core.tool_result\": [exact(\"tool_result\", \"紧跟对应 tool_use 的下一条 user\")],\n \"core.system_note\": [\n exact(\n \"system\",\n \"带正文的中途 system 消息\",\n \"模型族支持中途 system(Fable 5.x / Mythos 5.x / Opus 5 / Opus 4.8)\",\n ),\n lossy(\"user-role\", \"以 <system_note> 标签包住走 user 角色\", \"模型族不支持中途 system\"),\n ],\n \"core.compaction\": [lossy(\"user-text\", \"摘要以 user 角色文本呈现,模型无法区分它与用户原话\")],\n ...NOT_SENT,\n \"ext.*\": [dropped(\"none\", \"宿主扩展事件无通用落点;需要模型看见的应在投影层翻译成 core 事件\")],\n },\n \"openai-responses\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED],\n \"core.model_text\": [exact(\"assistant-message\")],\n \"core.model_thinking\": [\n exact(\"reasoning-item\", \"encrypted_content 原样回放\"),\n THINKING_COMMON.noSignature,\n THINKING_COMMON.foreign,\n ],\n \"core.tool_call\": [exact(\"function_call\"), TOOL_CALL_ARGS],\n \"core.tool_result\": [exact(\"function_call_output\")],\n \"core.system_note\": [\n exact(\"developer\", \"reasoning 模型用 developer 角色\"),\n exact(\"system\", \"非 reasoning 模型用 system 角色\"),\n ],\n \"core.compaction\": [lossy(\"user-text\", \"摘要以 user 角色文本呈现\")],\n ...NOT_SENT,\n \"ext.*\": [dropped(\"none\", \"同 Anthropic\")],\n },\n}\n\n/** 查某 api 下某事件 type 的声明落点;ext.* 归到通配项 */\nexport function declaredLandings(api: string, type: string): readonly LandingSpec[] {\n const table = LOSS_MATRIX[api]\n if (!table) return []\n return table[type] ?? (type.startsWith(\"ext.\") ? (table[\"ext.*\"] ?? []) : [])\n}\n"],"mappings":";AAUA,IAAM,uBAAuB;AAG7B,IAAM,wBAAwB;AAO9B,SAAS,yBAAyB,gBAAkD;AAClF,SAAO,QAAQ,eAAe,mBAAmB,eAAe,gBAAgB;AAClF;AAOO,SAAS,eACd,OACA,iBAA0C,CAAC,GAC3C,YAAiC,CAAC,GACZ;AACtB,QAAM,OAAO,kBAAkB,OAAO,cAAc;AACpD,SAAO,UAAU,0BAA0B,SACvC,OACA,EAAE,GAAG,MAAM,uBAAuB,UAAU,sBAAsB;AACxE;AAEA,SAAS,kBAAkB,OAAgB,gBAA+D;AACxG,QAAM,OAAO;AAAA,IACX,KAAK,MAAM;AAAA,IACX,gBAAgB,MAAM;AAAA,IACtB,eAAe;AAAA,IACf,QAAQ,MAAM,MAAM,SAAS,OAAO;AAAA,IACpC,eAAe,MAAM;AAAA,IACrB,iBAAiB,MAAM;AAAA,EACzB;AACA,UAAQ,MAAM,KAAK;AAAA,IACjB,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,uBAAuB,qBAAqB,KAAK,MAAM,EAAE;AAAA,QACzD,YAAY,sBAAsB,KAAK,MAAM,EAAE;AAAA,MACjD;AAAA,IACF,KAAK;AAEH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,gBAAgB,MAAM,aAAa,yBAAyB,cAAc;AAAA,QAC1E,uBAAuB;AAAA,QACvB,YAAY;AAAA,MACd;AAAA,IACF;AACE,aAAO,EAAE,GAAG,MAAM,uBAAuB,OAAO,YAAY,MAAM;AAAA,EACtE;AACF;;;AC5DA,SAAS,UAAU,uBAAuB;AAC1C,SAAS,UAAU,6BAA6B;AAChD;AAAA,EAKE,iBAAAA;AAAA,OAKK;;;ACRA,SAAS,SA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AA4B;AAAA,MAC/C,MAAM,UAAU,yDAA2B;AAAA,IAC7C;AAAA,IACA,mBAAmB,CAAC,MAAM,aAAa,8DAAiB,CAAC;AAAA,IACzD,GAAG;AAAA,IACH,SAAS,CAAC,QAAQ,QAAQ,kBAAa,CAAC;AAAA,EAC1C;AACF;AAGO,SAAS,iBAAiB,KAAa,MAAsC;AAClF,QAAM,QAAQ,YAAY,GAAG;AAC7B,MAAI,CAAC,MAAO,QAAO,CAAC;AACpB,SAAO,MAAM,IAAI,MAAM,KAAK,WAAW,MAAM,IAAK,MAAM,OAAO,KAAK,CAAC,IAAK,CAAC;AAC7E;","names":["LoweringError","note","LoweringError"]}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@reinsjs/lowering-pi",
3
+ "version": "0.1.0",
4
+ "description": "reins — lowering layer on pi-ai: events ⇄ provider wire protocols (Anthropic Messages, OpenAI Responses)",
5
+ "keywords": [
6
+ "agent",
7
+ "llm",
8
+ "anthropic",
9
+ "openai",
10
+ "pi-ai",
11
+ "provider-adapter"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "NewRate Limited (https://www.adrate.io)",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/AdRate-io/reins.git",
18
+ "directory": "packages/lowering-pi"
19
+ },
20
+ "homepage": "https://github.com/AdRate-io/reins/tree/main/packages/lowering-pi#readme",
21
+ "bugs": "https://github.com/AdRate-io/reins/issues",
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "CHANGELOG.md"
33
+ ],
34
+ "dependencies": {
35
+ "@earendil-works/pi-ai": "0.85.1",
36
+ "@reinsjs/core": "0.1.0"
37
+ },
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "scripts": {
42
+ "build": "tsup"
43
+ }
44
+ }