@reinsjs/lowering-pi 0.4.8 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @reinsjs/lowering-pi
2
2
 
3
+ ## 0.4.10
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [831a50a]
8
+ - @reinsjs/core@0.14.1
9
+
10
+ ## 0.4.9
11
+
12
+ ### Patch Changes
13
+
14
+ - 884c840: Session run status. Every `runLoop` run now starts with `core.tools_bound` (carrying `marksEnd: true`) and ends with exactly one end marker: `core.run_paused` as before, or the new model-invisible `core.run_ended` with `status: "done" | "handoff" | "error"`. `core.run_paused` gains `awaiting` (the pending calls waiting on an approval — with `requestedAt` —, a client tool or a sub-agent) and `stopped: true` for a user stop. A `core.error` the loop retries past, or one recorded for a throwing `pullInput`, gets no `run_ended`; an error that ends the run is written together with its `run_ended`.
15
+
16
+ `runStatusOf({ held, lastMarker })` classifies a session as running / paused / done / handoff / error / interrupted / idle / unknown from a lease flag and `lastRunMarker(timeline)`. `@reinsjs/store-pg` adds `pgRunStates(client, sessionIds)`: one SQL statement reads the leases and each session's last marker, so a session list never sees a gap between "lease released" and "outcome written". "Running" is only known for runs started through the server handler with a lease registry (`createAgent` + `pgStores`).
17
+
18
+ Log shape changes: on a resumed run `core.tools_bound` now comes before `core.run_resumed` / `core.approval_decision`, and `RunResult.lastSeq` of a done or handoff run points at its `run_ended`. Live streams carry one more event (a `CUSTOM` frame in AG-UI). The TanStack adapter writes `run_ended` too, but its `tools_bound` carries no `marksEnd` and its `run_paused` no `awaiting` / `stopped`. Lowerings drop `run_ended` like other operational events.
19
+
20
+ **Rolling upgrade:** `@reinsjs/core` 0.13 and earlier reject sessions that contain `core.run_ended` (unknown event type). Upgrade every instance to the same core version at once, and do not roll back past 0.14 once such sessions exist. Sessions whose last run finished before the upgrade read `unknown`.
21
+
22
+ - Updated dependencies [884c840]
23
+ - @reinsjs/core@0.14.0
24
+
3
25
  ## 0.4.8
4
26
 
5
27
  ### Patch Changes
package/dist/index.js CHANGED
@@ -338,6 +338,9 @@ var NOT_SENT = {
338
338
  "marks that a call began executing, for resume and stop handling; the model learns the outcome from tool_result"
339
339
  )
340
340
  ],
341
+ "core.run_ended": [
342
+ dropped("none", "marks how a run ended, for hosts tracking session status; the model never sees it")
343
+ ],
341
344
  "core.error": [
342
345
  dropped(
343
346
  "none",
@@ -722,6 +725,7 @@ ${t.text}`,
722
725
  case "core.memory_op":
723
726
  case "core.handoff":
724
727
  case "core.tool_started":
728
+ case "core.run_ended":
725
729
  case "core.error":
726
730
  land(e, "dropped", "none", "operational event, not sent (the default projection already filters it)");
727
731
  break;
package/dist/index.js.map CHANGED
@@ -1 +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/loss-matrix.ts","../src/factories.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 // pi-ai 的请求整形改不了,defer_loading / tool_reference 没有落点(L1):引用段展开成文本、deferLoading 的工具不发\n deferredTools: false,\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\", `no API key configured for ${model.provider}`, {\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\", `unsupported wire protocol ${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 {\n type CoreEventDraft,\n type LoweringOutcome,\n type LoweringStreamContext,\n toolCallArgumentsMeta,\n unwrapToolArguments,\n} 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 // pi-ai 的 parseStreamingJson 对二次编码的入参同样只解一层、交出字符串,与 fetch 版同一规则再解一层\n const decoded = unwrapToolArguments(block.arguments)\n drafts.push({\n type: \"core.tool_call\",\n actor: \"model\",\n payload: {\n toolCallId: block.id,\n name: block.name,\n args: decoded.args,\n ...toolCallArgumentsMeta(decoded),\n },\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: \"the pi-ai stream ended before 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 `unknown model ${ref.provider}/${ref.id}; the built-in table covers only anthropic and openai, declare the rest through the models option`,\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 `model ${ref.provider}/${ref.id} speaks ${model.api}, but this implementation supports only anthropic-messages and 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 renderToolReference,\n type ToolSpec,\n untrustedSourceOf,\n} from \"@reinsjs/core\"\nimport { MEDIA_PLACEHOLDER_NOTE } from \"./loss-matrix.js\"\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\n/** pi-ai 0.85.1 没有视频 / 音频内容,这两种片段一律换占位并记 lossy(2026-11-05 视频音频方案) */\nconst MEDIA_NOTE = MEDIA_PLACEHOLDER_NOTE\n\nfunction mediaPlaceholder(p: Extract<ContentPart, { type: \"video\" | \"audio\" }>): string {\n const sec =\n p.durationSec === undefined\n ? \"\"\n : `, ${Number.isInteger(p.durationSec) ? p.durationSec : p.durationSec.toFixed(1)} s`\n return `[${p.type} omitted: this model does not accept ${p.type} (${p.mime}${sec})]`\n}\n\nfunction toPiContent(parts: readonly ContentPart[]): {\n content: (TextContent | { type: \"image\"; data: string; mimeType: string })[]\n mediaDropped: boolean\n} {\n let mediaDropped = false\n const content = parts.map((p): TextContent | { type: \"image\"; data: string; mimeType: string } => {\n switch (p.type) {\n case \"text\":\n return { type: \"text\", text: p.text }\n // 工具引用段(L1):pi-ai 的请求整形改不了,没有 defer_loading 落点,展开成文本\n case \"tool_reference\":\n return { type: \"text\", text: renderToolReference(p) }\n case \"image\":\n return { type: \"image\", data: p.data, mimeType: p.mime }\n case \"video\":\n case \"audio\":\n mediaDropped = true\n return { type: \"text\", text: mediaPlaceholder(p) }\n default: {\n const _exhaustive: never = p\n return _exhaustive\n }\n }\n })\n return { content, mediaDropped }\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 =\n \"moved after that batch of tool results (tool results must immediately follow their call)\"\nconst ESCAPED_NOTE = \"an early-closing </untrusted inside untrusted content was escaped\"\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 pc = toPiContent(c.parts)\n const msg: Message = { role: \"user\", content: pc.content, timestamp: e.at }\n const mediaNote = pc.mediaDropped ? MEDIA_NOTE : undefined\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: [\n \"the user message sits between a tool call and its results\",\n c.escaped ? ESCAPED_NOTE : undefined,\n mediaNote,\n ]\n .filter(Boolean)\n .join(\"; \"),\n })\n break\n }\n messages.push(msg)\n if (c.escaped || mediaNote)\n land(\n e,\n \"lossy\",\n \"user\",\n [c.escaped ? ESCAPED_NOTE : undefined, mediaNote].filter(Boolean).join(\"; \"),\n )\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\", \"pi-ai downgrades unsigned thinking to text or drops it\")\n else if (foreignOrigin(origin, target))\n land(\n e,\n \"lossy\",\n \"provider-dependent\",\n `thinking from ${origin.provider}/${origin.model}, which the provider may ignore or reject`,\n )\n else if (origin.model !== target.model)\n land(\n e,\n \"exact\",\n isAnthropic ? \"thinking-block\" : \"reasoning-item\",\n `the signature comes from ${origin.model}, but this request targets ${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\", \"non-object arguments are wrapped as { 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 const pc = toPiContent(c.parts)\n messages.push({\n role: \"toolResult\",\n toolCallId: e.payload.toolCallId,\n toolName: e.payload.name,\n content: pc.content,\n isError: e.payload.isError,\n timestamp: e.at,\n })\n const landing = isAnthropic ? \"tool_result\" : \"function_call_output\"\n if (c.escaped || pc.mediaDropped)\n land(\n e,\n \"lossy\",\n landing,\n [c.escaped ? ESCAPED_NOTE : undefined, pc.mediaDropped ? MEDIA_NOTE : undefined]\n .filter(Boolean)\n .join(\"; \"),\n )\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 // 指令类说明(directive)不走中途 system:有的上游收下却不执行其中的指令(踩坑 42),一律带标签走 user\n if (capabilities.midConversationSystem && e.payload.directive !== true) {\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 e.payload.directive === true\n ? \"the note is a directive the model must act on, so it is wrapped in a <system_note> tag and sent with the user role\"\n : \"the model does not support mid-conversation system, so it is wrapped in a <system_note> tag and sent with the user role\",\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 \"the summary is rendered as user-role text\",\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.tool_started\":\n case \"core.error\":\n land(e, \"dropped\", \"none\", \"operational event, not sent (the default projection already filters it)\")\n break\n\n default:\n land(raw, \"dropped\", \"none\", `no general landing for ${raw.type}`)\n }\n }\n flush()\n settleAwaiting()\n\n const context: Context = { messages }\n if (input.systemPrompt) context.systemPrompt = input.systemPrompt\n // deferLoading 的工具不发(没有\"声明但不载入\"的落点;L1)\n const shownTools = (input.tools ?? []).filter((t) => t.deferLoading !== true)\n if (shownTools.length > 0) {\n // pi-ai 的 parameters 是 typebox TSchema,运行时就是 JSON Schema 对象,直接透传\n context.tools = shownTools.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 * 有损矩阵(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\": [\n dropped(\"none\", \"the approval outcome reaches the model through tool_result(isError)\"),\n ],\n \"core.approval_decision\": [dropped(\"none\", \"same as above\")],\n \"core.run_paused\": [dropped(\"none\", \"a run record; the perception module distills it into a system_note\")],\n \"core.run_resumed\": [dropped(\"none\", \"same as above\")],\n \"core.budget_usage\": [dropped(\"none\", \"same as above\")],\n \"core.memory_op\": [\n dropped(\n \"none\",\n \"an audit trail of memory reads and writes; the model already learned of them from the tool result\",\n ),\n ],\n \"core.handoff\": [\n dropped(\n \"none\",\n \"this session ends at the handoff; the new session's first user message carries the triggerMessage\",\n ),\n ],\n \"core.tool_started\": [\n dropped(\n \"none\",\n \"marks that a call began executing, for resume and stop handling; the model learns the outcome from tool_result\",\n ),\n ],\n \"core.error\": [\n dropped(\n \"none\",\n \"provider errors are handled by the loop; tool errors already live in tool_result.isError\",\n ),\n ],\n}\n\nconst THINKING_COMMON = {\n noSignature: lossy(\n \"text-or-drop\",\n \"pi-ai downgrades unsigned thinking to text or drops it\",\n \"the event's replay has no thinkingSignature\",\n ),\n foreign: lossy(\n \"provider-dependent\",\n \"thinking from another model, which the provider may ignore or reject\",\n \"the replay's provider/api/model differs from the current one\",\n ),\n}\n\nconst TOOL_CALL_ARGS = lossy(\n \"wrapped-args\",\n \"non-object arguments are wrapped as { value }\",\n \"tool_call.args is not an object\",\n)\n\n/** 用户在工具结果回来之前插话(续跑带新 input、进程死亡后再发消息):消息后移到同批结果之后,顺序有变 */\nconst USER_DEFERRED = lossy(\n \"user\",\n \"a user message sitting between a tool_call and its tool_result is moved after that batch of results (tool results must immediately follow their call)\",\n \"the user speaks up before all tool results are in\",\n)\n\n/** pi-ai 没有视频 / 音频内容:换占位(2026-11-05 视频音频方案);to-request.ts 落点 note 用同一常量 */\nexport const MEDIA_PLACEHOLDER_NOTE = \"pi-ai has no video / audio content; replaced with placeholder text\"\nconst MEDIA_WHEN = \"the content carries video or audio\"\n\nexport const LOSS_MATRIX: LossMatrix = {\n \"anthropic-messages\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED, lossy(\"user\", MEDIA_PLACEHOLDER_NOTE, MEDIA_WHEN)],\n \"core.model_text\": [exact(\"assistant-text\")],\n \"core.model_thinking\": [\n exact(\"thinking-block\", \"replayed verbatim with its signature\"),\n THINKING_COMMON.noSignature,\n THINKING_COMMON.foreign,\n ],\n \"core.tool_call\": [exact(\"tool_use\"), TOOL_CALL_ARGS],\n \"core.tool_result\": [\n exact(\"tool_result\", \"in the user message right after the matching tool_use\"),\n lossy(\"tool_result\", MEDIA_PLACEHOLDER_NOTE, MEDIA_WHEN),\n ],\n \"core.system_note\": [\n exact(\n \"system\",\n \"a mid-conversation system message carrying the text\",\n \"the model family supports mid-conversation system (Fable 5.x / Mythos 5.x / Opus 5 / Opus 4.8)\",\n ),\n lossy(\n \"user-role\",\n \"wrapped in a <system_note> tag and sent with the user role\",\n \"the model family does not support mid-conversation system, or the note is a directive the model must act on (SystemNotePayload.directive)\",\n ),\n ],\n \"core.compaction\": [\n lossy(\n \"user-text\",\n \"the summary is rendered as user-role text, so the model cannot tell it apart from the user's own words\",\n ),\n ],\n ...NOT_SENT,\n \"ext.*\": [\n dropped(\n \"none\",\n \"host extension events have no general landing; translate the ones the model must see into core events in the projection layer\",\n ),\n ],\n },\n \"openai-responses\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED, lossy(\"user\", MEDIA_PLACEHOLDER_NOTE, MEDIA_WHEN)],\n \"core.model_text\": [exact(\"assistant-message\")],\n \"core.model_thinking\": [\n exact(\"reasoning-item\", \"the encrypted_content is replayed verbatim\"),\n THINKING_COMMON.noSignature,\n THINKING_COMMON.foreign,\n ],\n \"core.tool_call\": [exact(\"function_call\"), TOOL_CALL_ARGS],\n \"core.tool_result\": [\n exact(\"function_call_output\"),\n lossy(\"function_call_output\", MEDIA_PLACEHOLDER_NOTE, MEDIA_WHEN),\n ],\n \"core.system_note\": [\n exact(\"developer\", \"reasoning models take the developer role\"),\n exact(\"system\", \"non-reasoning models take the system role\"),\n lossy(\n \"user-role\",\n \"wrapped in a <system_note> tag and sent with the user role\",\n \"the note is a directive the model must act on (SystemNotePayload.directive)\",\n ),\n ],\n \"core.compaction\": [lossy(\"user-text\", \"the summary is rendered as user-role text\")],\n ...NOT_SENT,\n \"ext.*\": [dropped(\"none\", \"same as 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","/**\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-respon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A,CAAC;AACL,QAAM,eAAoC;AAAA,IACxC,QAAQ,CAAC,MAAO,MAAM,WAAW,KAAK,SAAS;AAAA,IAC/C;AAAA,IACA,GAAI,KAAK,iBAAiB,EAAE,gBAAgB,MAAM,KAAK,kBAAkB,CAAC,EAAE,IAAI,CAAC;AAAA,IACjF,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,IAC1C,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,IAChD,GAAI,KAAK,iBAAiB,SAAY,EAAE,cAAc,KAAK,aAAa,IAAI,CAAC;AAAA,EAC/E;AACA,SAAO,EAAE,OAAO,EAAE,UAAU,GAAG,GAAG,UAAU,IAAI,aAAa,YAAY,EAAE;AAC7E;AAGO,SAAS,UAAU,IAAY,MAAqC;AACzE,SAAO,MAAM,aAAa,sBAAsB,IAAI;AAAA,IAClD,gBAAgB,EAAE,iBAAiB,KAAK;AAAA,IACxC,GAAG;AAAA,EACL,CAAC;AACH;AAGO,SAAS,OAAO,IAAY,MAAqC;AACtE,SAAO,MAAM,UAAU,oBAAoB,IAAI;AAAA,IAC7C,gBAAgB,EAAE,iBAAiB,SAAS;AAAA,IAC5C,GAAG;AAAA,EACL,CAAC;AACH;","names":["LoweringError","note","LoweringError"]}
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/loss-matrix.ts","../src/factories.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 // pi-ai 的请求整形改不了,defer_loading / tool_reference 没有落点(L1):引用段展开成文本、deferLoading 的工具不发\n deferredTools: false,\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\", `no API key configured for ${model.provider}`, {\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\", `unsupported wire protocol ${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 {\n type CoreEventDraft,\n type LoweringOutcome,\n type LoweringStreamContext,\n toolCallArgumentsMeta,\n unwrapToolArguments,\n} 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 // pi-ai 的 parseStreamingJson 对二次编码的入参同样只解一层、交出字符串,与 fetch 版同一规则再解一层\n const decoded = unwrapToolArguments(block.arguments)\n drafts.push({\n type: \"core.tool_call\",\n actor: \"model\",\n payload: {\n toolCallId: block.id,\n name: block.name,\n args: decoded.args,\n ...toolCallArgumentsMeta(decoded),\n },\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: \"the pi-ai stream ended before 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 `unknown model ${ref.provider}/${ref.id}; the built-in table covers only anthropic and openai, declare the rest through the models option`,\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 `model ${ref.provider}/${ref.id} speaks ${model.api}, but this implementation supports only anthropic-messages and 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 renderToolReference,\n type ToolSpec,\n untrustedSourceOf,\n} from \"@reinsjs/core\"\nimport { MEDIA_PLACEHOLDER_NOTE } from \"./loss-matrix.js\"\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\n/** pi-ai 0.85.1 没有视频 / 音频内容,这两种片段一律换占位并记 lossy(2026-11-05 视频音频方案) */\nconst MEDIA_NOTE = MEDIA_PLACEHOLDER_NOTE\n\nfunction mediaPlaceholder(p: Extract<ContentPart, { type: \"video\" | \"audio\" }>): string {\n const sec =\n p.durationSec === undefined\n ? \"\"\n : `, ${Number.isInteger(p.durationSec) ? p.durationSec : p.durationSec.toFixed(1)} s`\n return `[${p.type} omitted: this model does not accept ${p.type} (${p.mime}${sec})]`\n}\n\nfunction toPiContent(parts: readonly ContentPart[]): {\n content: (TextContent | { type: \"image\"; data: string; mimeType: string })[]\n mediaDropped: boolean\n} {\n let mediaDropped = false\n const content = parts.map((p): TextContent | { type: \"image\"; data: string; mimeType: string } => {\n switch (p.type) {\n case \"text\":\n return { type: \"text\", text: p.text }\n // 工具引用段(L1):pi-ai 的请求整形改不了,没有 defer_loading 落点,展开成文本\n case \"tool_reference\":\n return { type: \"text\", text: renderToolReference(p) }\n case \"image\":\n return { type: \"image\", data: p.data, mimeType: p.mime }\n case \"video\":\n case \"audio\":\n mediaDropped = true\n return { type: \"text\", text: mediaPlaceholder(p) }\n default: {\n const _exhaustive: never = p\n return _exhaustive\n }\n }\n })\n return { content, mediaDropped }\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 =\n \"moved after that batch of tool results (tool results must immediately follow their call)\"\nconst ESCAPED_NOTE = \"an early-closing </untrusted inside untrusted content was escaped\"\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 pc = toPiContent(c.parts)\n const msg: Message = { role: \"user\", content: pc.content, timestamp: e.at }\n const mediaNote = pc.mediaDropped ? MEDIA_NOTE : undefined\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: [\n \"the user message sits between a tool call and its results\",\n c.escaped ? ESCAPED_NOTE : undefined,\n mediaNote,\n ]\n .filter(Boolean)\n .join(\"; \"),\n })\n break\n }\n messages.push(msg)\n if (c.escaped || mediaNote)\n land(\n e,\n \"lossy\",\n \"user\",\n [c.escaped ? ESCAPED_NOTE : undefined, mediaNote].filter(Boolean).join(\"; \"),\n )\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\", \"pi-ai downgrades unsigned thinking to text or drops it\")\n else if (foreignOrigin(origin, target))\n land(\n e,\n \"lossy\",\n \"provider-dependent\",\n `thinking from ${origin.provider}/${origin.model}, which the provider may ignore or reject`,\n )\n else if (origin.model !== target.model)\n land(\n e,\n \"exact\",\n isAnthropic ? \"thinking-block\" : \"reasoning-item\",\n `the signature comes from ${origin.model}, but this request targets ${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\", \"non-object arguments are wrapped as { 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 const pc = toPiContent(c.parts)\n messages.push({\n role: \"toolResult\",\n toolCallId: e.payload.toolCallId,\n toolName: e.payload.name,\n content: pc.content,\n isError: e.payload.isError,\n timestamp: e.at,\n })\n const landing = isAnthropic ? \"tool_result\" : \"function_call_output\"\n if (c.escaped || pc.mediaDropped)\n land(\n e,\n \"lossy\",\n landing,\n [c.escaped ? ESCAPED_NOTE : undefined, pc.mediaDropped ? MEDIA_NOTE : undefined]\n .filter(Boolean)\n .join(\"; \"),\n )\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 // 指令类说明(directive)不走中途 system:有的上游收下却不执行其中的指令(踩坑 42),一律带标签走 user\n if (capabilities.midConversationSystem && e.payload.directive !== true) {\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 e.payload.directive === true\n ? \"the note is a directive the model must act on, so it is wrapped in a <system_note> tag and sent with the user role\"\n : \"the model does not support mid-conversation system, so it is wrapped in a <system_note> tag and sent with the user role\",\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 \"the summary is rendered as user-role text\",\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.tool_started\":\n case \"core.run_ended\":\n case \"core.error\":\n land(e, \"dropped\", \"none\", \"operational event, not sent (the default projection already filters it)\")\n break\n\n default:\n land(raw, \"dropped\", \"none\", `no general landing for ${raw.type}`)\n }\n }\n flush()\n settleAwaiting()\n\n const context: Context = { messages }\n if (input.systemPrompt) context.systemPrompt = input.systemPrompt\n // deferLoading 的工具不发(没有\"声明但不载入\"的落点;L1)\n const shownTools = (input.tools ?? []).filter((t) => t.deferLoading !== true)\n if (shownTools.length > 0) {\n // pi-ai 的 parameters 是 typebox TSchema,运行时就是 JSON Schema 对象,直接透传\n context.tools = shownTools.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 * 有损矩阵(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\": [\n dropped(\"none\", \"the approval outcome reaches the model through tool_result(isError)\"),\n ],\n \"core.approval_decision\": [dropped(\"none\", \"same as above\")],\n \"core.run_paused\": [dropped(\"none\", \"a run record; the perception module distills it into a system_note\")],\n \"core.run_resumed\": [dropped(\"none\", \"same as above\")],\n \"core.budget_usage\": [dropped(\"none\", \"same as above\")],\n \"core.memory_op\": [\n dropped(\n \"none\",\n \"an audit trail of memory reads and writes; the model already learned of them from the tool result\",\n ),\n ],\n \"core.handoff\": [\n dropped(\n \"none\",\n \"this session ends at the handoff; the new session's first user message carries the triggerMessage\",\n ),\n ],\n \"core.tool_started\": [\n dropped(\n \"none\",\n \"marks that a call began executing, for resume and stop handling; the model learns the outcome from tool_result\",\n ),\n ],\n \"core.run_ended\": [\n dropped(\"none\", \"marks how a run ended, for hosts tracking session status; the model never sees it\"),\n ],\n \"core.error\": [\n dropped(\n \"none\",\n \"provider errors are handled by the loop; tool errors already live in tool_result.isError\",\n ),\n ],\n}\n\nconst THINKING_COMMON = {\n noSignature: lossy(\n \"text-or-drop\",\n \"pi-ai downgrades unsigned thinking to text or drops it\",\n \"the event's replay has no thinkingSignature\",\n ),\n foreign: lossy(\n \"provider-dependent\",\n \"thinking from another model, which the provider may ignore or reject\",\n \"the replay's provider/api/model differs from the current one\",\n ),\n}\n\nconst TOOL_CALL_ARGS = lossy(\n \"wrapped-args\",\n \"non-object arguments are wrapped as { value }\",\n \"tool_call.args is not an object\",\n)\n\n/** 用户在工具结果回来之前插话(续跑带新 input、进程死亡后再发消息):消息后移到同批结果之后,顺序有变 */\nconst USER_DEFERRED = lossy(\n \"user\",\n \"a user message sitting between a tool_call and its tool_result is moved after that batch of results (tool results must immediately follow their call)\",\n \"the user speaks up before all tool results are in\",\n)\n\n/** pi-ai 没有视频 / 音频内容:换占位(2026-11-05 视频音频方案);to-request.ts 落点 note 用同一常量 */\nexport const MEDIA_PLACEHOLDER_NOTE = \"pi-ai has no video / audio content; replaced with placeholder text\"\nconst MEDIA_WHEN = \"the content carries video or audio\"\n\nexport const LOSS_MATRIX: LossMatrix = {\n \"anthropic-messages\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED, lossy(\"user\", MEDIA_PLACEHOLDER_NOTE, MEDIA_WHEN)],\n \"core.model_text\": [exact(\"assistant-text\")],\n \"core.model_thinking\": [\n exact(\"thinking-block\", \"replayed verbatim with its signature\"),\n THINKING_COMMON.noSignature,\n THINKING_COMMON.foreign,\n ],\n \"core.tool_call\": [exact(\"tool_use\"), TOOL_CALL_ARGS],\n \"core.tool_result\": [\n exact(\"tool_result\", \"in the user message right after the matching tool_use\"),\n lossy(\"tool_result\", MEDIA_PLACEHOLDER_NOTE, MEDIA_WHEN),\n ],\n \"core.system_note\": [\n exact(\n \"system\",\n \"a mid-conversation system message carrying the text\",\n \"the model family supports mid-conversation system (Fable 5.x / Mythos 5.x / Opus 5 / Opus 4.8)\",\n ),\n lossy(\n \"user-role\",\n \"wrapped in a <system_note> tag and sent with the user role\",\n \"the model family does not support mid-conversation system, or the note is a directive the model must act on (SystemNotePayload.directive)\",\n ),\n ],\n \"core.compaction\": [\n lossy(\n \"user-text\",\n \"the summary is rendered as user-role text, so the model cannot tell it apart from the user's own words\",\n ),\n ],\n ...NOT_SENT,\n \"ext.*\": [\n dropped(\n \"none\",\n \"host extension events have no general landing; translate the ones the model must see into core events in the projection layer\",\n ),\n ],\n },\n \"openai-responses\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED, lossy(\"user\", MEDIA_PLACEHOLDER_NOTE, MEDIA_WHEN)],\n \"core.model_text\": [exact(\"assistant-message\")],\n \"core.model_thinking\": [\n exact(\"reasoning-item\", \"the encrypted_content is replayed verbatim\"),\n THINKING_COMMON.noSignature,\n THINKING_COMMON.foreign,\n ],\n \"core.tool_call\": [exact(\"function_call\"), TOOL_CALL_ARGS],\n \"core.tool_result\": [\n exact(\"function_call_output\"),\n lossy(\"function_call_output\", MEDIA_PLACEHOLDER_NOTE, MEDIA_WHEN),\n ],\n \"core.system_note\": [\n exact(\"developer\", \"reasoning models take the developer role\"),\n exact(\"system\", \"non-reasoning models take the system role\"),\n lossy(\n \"user-role\",\n \"wrapped in a <system_note> tag and sent with the user role\",\n \"the note is a directive the model must act on (SystemNotePayload.directive)\",\n ),\n ],\n \"core.compaction\": [lossy(\"user-text\", \"the summary is rendered as user-role text\")],\n ...NOT_SENT,\n \"ext.*\": [dropped(\"none\", \"same as 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","/**\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"],"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;AAAA,IAEf,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,aAA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,iBAAiB,SAAS;AAAA,IAC5C,GAAG;AAAA,EACL,CAAC;AACH;","names":["LoweringError","note","LoweringError"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reinsjs/lowering-pi",
3
- "version": "0.4.8",
3
+ "version": "0.4.10",
4
4
  "description": "reins — lowering layer on pi-ai: events ⇄ provider wire protocols (Anthropic Messages, OpenAI Responses)",
5
5
  "keywords": [
6
6
  "agent",
@@ -33,7 +33,7 @@
33
33
  ],
34
34
  "dependencies": {
35
35
  "@earendil-works/pi-ai": "0.85.1",
36
- "@reinsjs/core": "0.13.0"
36
+ "@reinsjs/core": "0.14.1"
37
37
  },
38
38
  "engines": {
39
39
  "node": ">=22"