@reinsjs/lowering-pi 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -2
- package/README.md +2 -2
- package/dist/index.js +89 -48
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# @reinsjs/lowering-pi
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 14345eb: Every user-facing runtime string is now English. This covers thrown error messages (construction-time validation, store and registry errors, HTTP 4xx bodies), `warn()` output from the brain modules and the server, the text the model sees in error tool results (`Unknown tool: …`, `Tool call blocked: …`, `Invalid arguments: …`, `Approval denied…`, `Approval expired…`), the `note` / `when` fields of every lowering loss matrix and landing, the placeholder text for content a wire protocol cannot carry, the conformance suites exported from `@reinsjs/core/testing`, and the `@reinsjs/eval` report and gate output. Previously these were Chinese while the READMEs and model-facing prompts were English, which left a non-Chinese-speaking host with unreadable diagnostics.
|
|
8
|
+
|
|
9
|
+
Nothing changes structurally: same errors, same codes, same warning points, same landing kinds. Hosts that match on the text of a message or a landing note (rather than on its error code or `landing` value) need to update those matches.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- c16e3ea: README only: point to `@reinsjs/lowering-fetch` as the second lowering layer (the umbrella README's install line and import now show it; `@reinsjs/lowering-pi`'s README links to the side-by-side comparison; `@reinsjs/core`'s module table lists both implementations). No code changes.
|
|
14
|
+
- a082a0c: `tool_reference` content parts (new in `@reinsjs/core`) are rendered as text and tools marked `deferLoading` are not sent — pi-ai's request shaping has no place for Anthropic's `defer_loading`; capabilities report `deferredTools: false`.
|
|
15
|
+
- Updated dependencies [49d5dea]
|
|
16
|
+
- Updated dependencies [c16e3ea]
|
|
17
|
+
- Updated dependencies [14345eb]
|
|
18
|
+
- Updated dependencies [a082a0c]
|
|
19
|
+
- @reinsjs/core@0.2.0
|
|
20
|
+
|
|
21
|
+
## 0.1.1
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- Docs only: the umbrella package is `@reinsjs/agent` (npm refused the bare name `reins` as too similar to `redis`). READMEs and the 0.1.0 changelog text now say so; no code changes.
|
|
26
|
+
- Updated dependencies
|
|
27
|
+
- @reinsjs/core@0.1.1
|
|
28
|
+
|
|
3
29
|
## 0.1.0
|
|
4
30
|
|
|
5
31
|
### Minor Changes
|
|
@@ -8,11 +34,11 @@
|
|
|
8
34
|
|
|
9
35
|
- **Timeline first.** Append-only event log with `schemaVersion` on every event and fail-closed upcast on read; projection decides what the model sees each turn; replay and fork from the log alone.
|
|
10
36
|
- **A loop you can copy.** `runLoop` as an exported async generator: pause/resume is a return value with a small signed state, bounded retry on transient failures only while nothing has been written, tool pipeline `beforeTool → validate → approval → execute → afterTool`, sub-agent pause bubbling (`Interruption { kind: "subagent" }`).
|
|
11
|
-
- **Brain modules** (`@reinsjs/brain`): perception, compact (with folded-result manifest and `recall`; recommended on after measuring 100% recall at lower token cost on two model families), pins, spill, handoff, memory (`memory_20250818` shape, namespace isolation), approval (deny → ask → allow, fail-closed), budget (five limits, sub-agent usage included).
|
|
37
|
+
- **Brain modules** (`@reinsjs/brain`): perception, compact (with folded-result manifest and `recall`; recommended on after measuring 100% recall at lower token cost on two model families), pins, spill, handoff, memory (`memory_20250818` shape, namespace isolation), approval (deny → ask → allow, fail-closed), budget (five limits, sub-agent usage included), skills (Agent Skills with progressive disclosure: menu in the system prompt, `skill_read` to open one).
|
|
12
38
|
- **Lowering** (`@reinsjs/lowering-pi`): Anthropic Messages and OpenAI Responses via pi-ai with a declared loss matrix, trust markers on untrusted content, cache-breakpoint handling.
|
|
13
39
|
- **Serving** (`@reinsjs/server`, `@reinsjs/ui-agui`): Web-standard handler with SSE replay from `lastSeq`, per-session run lock, `authorizeSession` (only `true` allows), AG-UI as the first-class UI protocol.
|
|
14
40
|
- **Stores**: SQLite (`node:sqlite` / `bun:sqlite`) and Postgres (`pg` / PGlite), conformance-tested; configurable memory table for per-role isolation.
|
|
15
|
-
- **Tools**: MCP servers as one socket (`@reinsjs/tools-mcp`, tools bound per run, annotations as defaults not permissions); `asTool(agent)` in
|
|
41
|
+
- **Tools**: MCP servers as one socket (`@reinsjs/tools-mcp`, tools bound per run, annotations as defaults not permissions); `asTool(agent)` in `@reinsjs/agent`.
|
|
16
42
|
- **TanStack AI** middleware (`@reinsjs/adapter-tanstack-ai`): the brain on TanStack's loop with the log as the single source of truth; idempotent client-message import; runtime check for the approval interrupt.
|
|
17
43
|
- **Eval harness** (`@reinsjs/eval`): fixtures from real recordings, recorded tools, arm-vs-arm runner, metrics, the four-rule gate.
|
|
18
44
|
|
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ pnpm add @reinsjs/lowering-pi
|
|
|
8
8
|
|
|
9
9
|
```ts
|
|
10
10
|
import { anthropic, openai } from "@reinsjs/lowering-pi"
|
|
11
|
-
import { createAgent } from "
|
|
11
|
+
import { createAgent } from "@reinsjs/agent"
|
|
12
12
|
|
|
13
13
|
const claude = anthropic("claude-opus-5", { apiKey: process.env.ANTHROPIC_API_KEY! })
|
|
14
14
|
const gpt = openai("gpt-5.5", { apiKey: process.env.OPENAI_API_KEY!, baseUrl: "https://gateway.example/v1" })
|
|
@@ -38,7 +38,7 @@ export const agent = createAgent({ model: claude, store, tools })
|
|
|
38
38
|
|
|
39
39
|
## Runtime footprint
|
|
40
40
|
|
|
41
|
-
pi-ai declares ten dependencies (≈65 MB installed, about 29 MB of which reins never imports). Nothing Node-specific is on the paths used here; the layer is verified on Cloudflare workerd without `nodejs_compat
|
|
41
|
+
pi-ai declares ten dependencies (≈65 MB installed, about 29 MB of which reins never imports). Nothing Node-specific is on the paths used here; the layer is verified on Cloudflare workerd without `nodejs_compat`, and on Bun, Deno and Vercel's `edge-runtime` (`spikes/runtime-matrix`). Two runtime caveats inherited from upstream: pi-ai builds its user-agent from `os.release()`, so Deno needs `--allow-sys=osRelease`; the `openai` SDK's edge branch reads `process.version` unguarded, so an Edge runtime must expose a `process` object (Vercel's deployed Edge runtime does — verified live; the bare `edge-runtime` emulator does not). If install size matters more to you than getting the provider table through pi-ai, use [`@reinsjs/lowering-fetch`](../lowering-fetch/README.md) — the same `Lowering` interface with no dependency but `@reinsjs/core`, three wire protocols (it adds OpenAI Chat Completions), and a request body that is sent exactly as you inspect it. Its README has a side-by-side comparison; timelines written by one layer replay through the other.
|
|
42
42
|
|
|
43
43
|
## Documentation
|
|
44
44
|
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,8 @@ function inferCapabilities(model, requestOptions) {
|
|
|
13
13
|
api: model.api,
|
|
14
14
|
thinkingReplay: model.reasoning,
|
|
15
15
|
parallelTools: true,
|
|
16
|
+
// pi-ai 的请求整形改不了,defer_loading / tool_reference 没有落点(L1):引用段展开成文本、deferLoading 的工具不发
|
|
17
|
+
deferredTools: false,
|
|
16
18
|
images: model.input.includes("image"),
|
|
17
19
|
contextWindow: model.contextWindow,
|
|
18
20
|
maxOutputTokens: model.maxTokens
|
|
@@ -108,7 +110,7 @@ async function* consumeStream(events, ctx = {}) {
|
|
|
108
110
|
return {
|
|
109
111
|
stopReason: "error",
|
|
110
112
|
usage: { input: 0, output: 0 },
|
|
111
|
-
errorMessage: "pi-ai
|
|
113
|
+
errorMessage: "the pi-ai stream ended before done / error"
|
|
112
114
|
};
|
|
113
115
|
}
|
|
114
116
|
|
|
@@ -142,7 +144,7 @@ function resolveModel(ref, extra = []) {
|
|
|
142
144
|
if (!model) {
|
|
143
145
|
throw new LoweringError(
|
|
144
146
|
"unsupported_model",
|
|
145
|
-
|
|
147
|
+
`unknown model ${ref.provider}/${ref.id}; the built-in table covers only anthropic and openai, declare the rest through the models option`,
|
|
146
148
|
{
|
|
147
149
|
provider: ref.provider,
|
|
148
150
|
id: ref.id
|
|
@@ -152,7 +154,7 @@ function resolveModel(ref, extra = []) {
|
|
|
152
154
|
if (!SUPPORTED_APIS.has(model.api)) {
|
|
153
155
|
throw new LoweringError(
|
|
154
156
|
"unsupported_api",
|
|
155
|
-
|
|
157
|
+
`model ${ref.provider}/${ref.id} speaks ${model.api}, but this implementation supports only anthropic-messages and openai-responses`,
|
|
156
158
|
{
|
|
157
159
|
api: model.api
|
|
158
160
|
}
|
|
@@ -287,6 +289,7 @@ import {
|
|
|
287
289
|
markUntrusted,
|
|
288
290
|
markUntrustedText,
|
|
289
291
|
needsUntrustedMark,
|
|
292
|
+
renderToolReference,
|
|
290
293
|
untrustedSourceOf
|
|
291
294
|
} from "@reinsjs/core";
|
|
292
295
|
var ZERO_USAGE = {
|
|
@@ -298,9 +301,11 @@ var ZERO_USAGE = {
|
|
|
298
301
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
299
302
|
};
|
|
300
303
|
function toPiContent(parts) {
|
|
301
|
-
return parts.map(
|
|
302
|
-
(p
|
|
303
|
-
|
|
304
|
+
return parts.map((p) => {
|
|
305
|
+
if (p.type === "text") return { type: "text", text: p.text };
|
|
306
|
+
if (p.type === "tool_reference") return { type: "text", text: renderToolReference(p) };
|
|
307
|
+
return { type: "image", data: p.data, mimeType: p.mime };
|
|
308
|
+
});
|
|
304
309
|
}
|
|
305
310
|
function isPlainObject(v) {
|
|
306
311
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -319,8 +324,8 @@ function sameOrigin(a, b) {
|
|
|
319
324
|
function foreignOrigin(a, target) {
|
|
320
325
|
return a.provider !== target.provider || a.api !== target.api;
|
|
321
326
|
}
|
|
322
|
-
var DEFERRED_NOTE = "
|
|
323
|
-
var ESCAPED_NOTE = "
|
|
327
|
+
var DEFERRED_NOTE = "moved after that batch of tool results (tool results must immediately follow their call)";
|
|
328
|
+
var ESCAPED_NOTE = "an early-closing </untrusted inside untrusted content was escaped";
|
|
324
329
|
function eventsToContext(input) {
|
|
325
330
|
const { model, capabilities } = input;
|
|
326
331
|
const target = { provider: model.provider, api: model.api, model: model.id };
|
|
@@ -400,7 +405,7 @@ function eventsToContext(input) {
|
|
|
400
405
|
event: e,
|
|
401
406
|
kind: "lossy",
|
|
402
407
|
landing: "user",
|
|
403
|
-
note: c.escaped ?
|
|
408
|
+
note: c.escaped ? `the user message sits between a tool call and its results; ${ESCAPED_NOTE}` : "the user message sits between a tool call and its results"
|
|
404
409
|
});
|
|
405
410
|
break;
|
|
406
411
|
}
|
|
@@ -417,20 +422,20 @@ function eventsToContext(input) {
|
|
|
417
422
|
if (r.redacted === true) block.redacted = true;
|
|
418
423
|
assistant(e, origin).content.push(block);
|
|
419
424
|
if (!block.thinkingSignature)
|
|
420
|
-
land(e, "lossy", "text-or-drop", "
|
|
425
|
+
land(e, "lossy", "text-or-drop", "pi-ai downgrades unsigned thinking to text or drops it");
|
|
421
426
|
else if (foreignOrigin(origin, target))
|
|
422
427
|
land(
|
|
423
428
|
e,
|
|
424
429
|
"lossy",
|
|
425
430
|
"provider-dependent",
|
|
426
|
-
|
|
431
|
+
`thinking from ${origin.provider}/${origin.model}, which the provider may ignore or reject`
|
|
427
432
|
);
|
|
428
433
|
else if (origin.model !== target.model)
|
|
429
434
|
land(
|
|
430
435
|
e,
|
|
431
436
|
"exact",
|
|
432
437
|
isAnthropic ? "thinking-block" : "reasoning-item",
|
|
433
|
-
|
|
438
|
+
`the signature comes from ${origin.model}, but this request targets ${target.model}`
|
|
434
439
|
);
|
|
435
440
|
else land(e, "exact", isAnthropic ? "thinking-block" : "reasoning-item");
|
|
436
441
|
break;
|
|
@@ -457,7 +462,7 @@ function eventsToContext(input) {
|
|
|
457
462
|
if (typeof r.thoughtSignature === "string") block.thoughtSignature = r.thoughtSignature;
|
|
458
463
|
if (typeof r.namespace === "string") block.namespace = r.namespace;
|
|
459
464
|
assistant(e, origin).content.push(block);
|
|
460
|
-
if (wrapped) land(e, "lossy", "wrapped-args", "
|
|
465
|
+
if (wrapped) land(e, "lossy", "wrapped-args", "non-object arguments are wrapped as { value }");
|
|
461
466
|
else land(e, "exact", isAnthropic ? "tool_use" : "function_call");
|
|
462
467
|
break;
|
|
463
468
|
}
|
|
@@ -496,7 +501,7 @@ function eventsToContext(input) {
|
|
|
496
501
|
{ role: "user", content: framedSystemNote(e.payload.kind, t.text), timestamp: e.at },
|
|
497
502
|
"lossy",
|
|
498
503
|
"user-role",
|
|
499
|
-
"
|
|
504
|
+
"the model does not support mid-conversation system, so it is wrapped in a <system_note> tag and sent with the user role"
|
|
500
505
|
);
|
|
501
506
|
}
|
|
502
507
|
break;
|
|
@@ -514,7 +519,7 @@ ${t.text}`,
|
|
|
514
519
|
},
|
|
515
520
|
"lossy",
|
|
516
521
|
"user-text",
|
|
517
|
-
"
|
|
522
|
+
"the summary is rendered as user-role text"
|
|
518
523
|
);
|
|
519
524
|
break;
|
|
520
525
|
}
|
|
@@ -526,18 +531,19 @@ ${t.text}`,
|
|
|
526
531
|
case "core.memory_op":
|
|
527
532
|
case "core.handoff":
|
|
528
533
|
case "core.error":
|
|
529
|
-
land(e, "dropped", "none", "
|
|
534
|
+
land(e, "dropped", "none", "operational event, not sent (the default projection already filters it)");
|
|
530
535
|
break;
|
|
531
536
|
default:
|
|
532
|
-
land(raw, "dropped", "none",
|
|
537
|
+
land(raw, "dropped", "none", `no general landing for ${raw.type}`);
|
|
533
538
|
}
|
|
534
539
|
}
|
|
535
540
|
flush();
|
|
536
541
|
settleAwaiting();
|
|
537
542
|
const context = { messages };
|
|
538
543
|
if (input.systemPrompt) context.systemPrompt = input.systemPrompt;
|
|
539
|
-
|
|
540
|
-
|
|
544
|
+
const shownTools = (input.tools ?? []).filter((t) => t.deferLoading !== true);
|
|
545
|
+
if (shownTools.length > 0) {
|
|
546
|
+
context.tools = shownTools.map(
|
|
541
547
|
(t) => ({
|
|
542
548
|
name: t.name,
|
|
543
549
|
description: t.description,
|
|
@@ -589,7 +595,7 @@ var PiAiLowering = class {
|
|
|
589
595
|
const model = resolveModel(req.model, this.extraModels);
|
|
590
596
|
const apiKey = this.opts.apiKey(model.provider);
|
|
591
597
|
if (!apiKey) {
|
|
592
|
-
throw new LoweringError2("missing_api_key",
|
|
598
|
+
throw new LoweringError2("missing_api_key", `no API key configured for ${model.provider}`, {
|
|
593
599
|
provider: model.provider
|
|
594
600
|
});
|
|
595
601
|
}
|
|
@@ -615,7 +621,7 @@ function streamFunctionFor(api) {
|
|
|
615
621
|
case "openai-responses":
|
|
616
622
|
return openaiResponsesStream;
|
|
617
623
|
default:
|
|
618
|
-
throw new LoweringError2("unsupported_api",
|
|
624
|
+
throw new LoweringError2("unsupported_api", `unsupported wire protocol ${api}`, { api });
|
|
619
625
|
}
|
|
620
626
|
}
|
|
621
627
|
function rewritePayload(api, payload, model, opts = {}) {
|
|
@@ -672,73 +678,108 @@ var exact = (landing, note, when) => {
|
|
|
672
678
|
var lossy = (landing, note, when) => when ? { kind: "lossy", landing, note, when } : { kind: "lossy", landing, note };
|
|
673
679
|
var dropped = (landing, note) => ({ kind: "dropped", landing, note });
|
|
674
680
|
var NOT_SENT = {
|
|
675
|
-
"core.approval_request": [
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
"core.
|
|
679
|
-
"core.
|
|
680
|
-
"core.
|
|
681
|
-
"core.
|
|
682
|
-
"core.
|
|
681
|
+
"core.approval_request": [
|
|
682
|
+
dropped("none", "the approval outcome reaches the model through tool_result(isError)")
|
|
683
|
+
],
|
|
684
|
+
"core.approval_decision": [dropped("none", "same as above")],
|
|
685
|
+
"core.run_paused": [dropped("none", "a run record; the perception module distills it into a system_note")],
|
|
686
|
+
"core.run_resumed": [dropped("none", "same as above")],
|
|
687
|
+
"core.budget_usage": [dropped("none", "same as above")],
|
|
688
|
+
"core.memory_op": [
|
|
689
|
+
dropped(
|
|
690
|
+
"none",
|
|
691
|
+
"an audit trail of memory reads and writes; the model already learned of them from the tool result"
|
|
692
|
+
)
|
|
693
|
+
],
|
|
694
|
+
"core.handoff": [
|
|
695
|
+
dropped(
|
|
696
|
+
"none",
|
|
697
|
+
"this session ends at the handoff; the new session's first user message carries the triggerMessage"
|
|
698
|
+
)
|
|
699
|
+
],
|
|
700
|
+
"core.error": [
|
|
701
|
+
dropped(
|
|
702
|
+
"none",
|
|
703
|
+
"provider errors are handled by the loop; tool errors already live in tool_result.isError"
|
|
704
|
+
)
|
|
705
|
+
]
|
|
683
706
|
};
|
|
684
707
|
var THINKING_COMMON = {
|
|
685
708
|
noSignature: lossy(
|
|
686
709
|
"text-or-drop",
|
|
687
|
-
"
|
|
688
|
-
"
|
|
710
|
+
"pi-ai downgrades unsigned thinking to text or drops it",
|
|
711
|
+
"the event's replay has no thinkingSignature"
|
|
689
712
|
),
|
|
690
713
|
foreign: lossy(
|
|
691
714
|
"provider-dependent",
|
|
692
|
-
"
|
|
693
|
-
"replay
|
|
715
|
+
"thinking from another model, which the provider may ignore or reject",
|
|
716
|
+
"the replay's provider/api/model differs from the current one"
|
|
694
717
|
)
|
|
695
718
|
};
|
|
696
|
-
var TOOL_CALL_ARGS = lossy(
|
|
719
|
+
var TOOL_CALL_ARGS = lossy(
|
|
720
|
+
"wrapped-args",
|
|
721
|
+
"non-object arguments are wrapped as { value }",
|
|
722
|
+
"tool_call.args is not an object"
|
|
723
|
+
);
|
|
697
724
|
var USER_DEFERRED = lossy(
|
|
698
725
|
"user",
|
|
699
|
-
"
|
|
700
|
-
"
|
|
726
|
+
"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)",
|
|
727
|
+
"the user speaks up before all tool results are in"
|
|
701
728
|
);
|
|
702
729
|
var LOSS_MATRIX = {
|
|
703
730
|
"anthropic-messages": {
|
|
704
731
|
"core.user_message": [exact("user"), USER_DEFERRED],
|
|
705
732
|
"core.model_text": [exact("assistant-text")],
|
|
706
733
|
"core.model_thinking": [
|
|
707
|
-
exact("thinking-block", "
|
|
734
|
+
exact("thinking-block", "replayed verbatim with its signature"),
|
|
708
735
|
THINKING_COMMON.noSignature,
|
|
709
736
|
THINKING_COMMON.foreign
|
|
710
737
|
],
|
|
711
738
|
"core.tool_call": [exact("tool_use"), TOOL_CALL_ARGS],
|
|
712
|
-
"core.tool_result": [exact("tool_result", "
|
|
739
|
+
"core.tool_result": [exact("tool_result", "in the user message right after the matching tool_use")],
|
|
713
740
|
"core.system_note": [
|
|
714
741
|
exact(
|
|
715
742
|
"system",
|
|
716
|
-
"
|
|
717
|
-
"
|
|
743
|
+
"a mid-conversation system message carrying the text",
|
|
744
|
+
"the model family supports mid-conversation system (Fable 5.x / Mythos 5.x / Opus 5 / Opus 4.8)"
|
|
718
745
|
),
|
|
719
|
-
lossy(
|
|
746
|
+
lossy(
|
|
747
|
+
"user-role",
|
|
748
|
+
"wrapped in a <system_note> tag and sent with the user role",
|
|
749
|
+
"the model family does not support mid-conversation system"
|
|
750
|
+
)
|
|
751
|
+
],
|
|
752
|
+
"core.compaction": [
|
|
753
|
+
lossy(
|
|
754
|
+
"user-text",
|
|
755
|
+
"the summary is rendered as user-role text, so the model cannot tell it apart from the user's own words"
|
|
756
|
+
)
|
|
720
757
|
],
|
|
721
|
-
"core.compaction": [lossy("user-text", "\u6458\u8981\u4EE5 user \u89D2\u8272\u6587\u672C\u5448\u73B0\uFF0C\u6A21\u578B\u65E0\u6CD5\u533A\u5206\u5B83\u4E0E\u7528\u6237\u539F\u8BDD")],
|
|
722
758
|
...NOT_SENT,
|
|
723
|
-
"ext.*": [
|
|
759
|
+
"ext.*": [
|
|
760
|
+
dropped(
|
|
761
|
+
"none",
|
|
762
|
+
"host extension events have no general landing; translate the ones the model must see into core events in the projection layer"
|
|
763
|
+
)
|
|
764
|
+
]
|
|
724
765
|
},
|
|
725
766
|
"openai-responses": {
|
|
726
767
|
"core.user_message": [exact("user"), USER_DEFERRED],
|
|
727
768
|
"core.model_text": [exact("assistant-message")],
|
|
728
769
|
"core.model_thinking": [
|
|
729
|
-
exact("reasoning-item", "encrypted_content
|
|
770
|
+
exact("reasoning-item", "the encrypted_content is replayed verbatim"),
|
|
730
771
|
THINKING_COMMON.noSignature,
|
|
731
772
|
THINKING_COMMON.foreign
|
|
732
773
|
],
|
|
733
774
|
"core.tool_call": [exact("function_call"), TOOL_CALL_ARGS],
|
|
734
775
|
"core.tool_result": [exact("function_call_output")],
|
|
735
776
|
"core.system_note": [
|
|
736
|
-
exact("developer", "reasoning
|
|
737
|
-
exact("system", "
|
|
777
|
+
exact("developer", "reasoning models take the developer role"),
|
|
778
|
+
exact("system", "non-reasoning models take the system role")
|
|
738
779
|
],
|
|
739
|
-
"core.compaction": [lossy("user-text", "
|
|
780
|
+
"core.compaction": [lossy("user-text", "the summary is rendered as user-role text")],
|
|
740
781
|
...NOT_SENT,
|
|
741
|
-
"ext.*": [dropped("none", "
|
|
782
|
+
"ext.*": [dropped("none", "same as Anthropic")]
|
|
742
783
|
}
|
|
743
784
|
};
|
|
744
785
|
function declaredLandings(api, type) {
|
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/factories.ts","../src/loss-matrix.ts"],"sourcesContent":["/**\n * 按模型声明能力(技术方案 §11)。脑子模块只看这些布尔值,不看模型名。\n */\nimport type { LoweringCapabilities } from \"@reinsjs/core\"\nimport type { PiModel } from \"./models.js\"\n\n/**\n * S1 核实:Anthropic 带正文的中途 system 消息支持 Fable 5.1/5、Mythos 5.1/5、Opus 5/4.8;Sonnet 5 及更早不支持。\n * 按 id 前缀匹配,带日期后缀的 id(如 claude-opus-5-20260301)也能命中。\n */\nconst ANTHROPIC_MID_SYSTEM = /^claude-(fable-5|mythos-5|opus-5|opus-4-8)(-|$)/\n\n/** 调研核实:服务端 task budget 仅 Opus 5 与 Fable 5.1(DECISIONS 2026-09-08) */\nconst ANTHROPIC_TASK_BUDGET = /^claude-(opus-5|fable-5-1)(-|$)/\n\n/**\n * OpenAI Responses 只在请求带 reasoningEffort / reasoningSummary 时才开启 reasoning 并返回\n * encrypted_content(pi-ai 0.85.1 buildParams);否则 reasoning 关闭,没有可回放的东西。\n * 所以 thinkingReplay 在这家取决于请求选项,如实声明,脑子模块不必猜。\n */\nfunction openaiReasoningRequested(requestOptions: Record<string, unknown>): boolean {\n return Boolean(requestOptions.reasoningEffort || requestOptions.reasoningSummary)\n}\n\n/** 宿主在 ModelDefinition 里声明的能力,覆盖按 id 的推断 */\nexport interface CapabilityOverrides {\n midConversationSystem?: boolean\n}\n\nexport function capabilitiesOf(\n model: PiModel,\n requestOptions: Record<string, unknown> = {},\n overrides: CapabilityOverrides = {},\n): LoweringCapabilities {\n const caps = inferCapabilities(model, requestOptions)\n return overrides.midConversationSystem === undefined\n ? caps\n : { ...caps, midConversationSystem: overrides.midConversationSystem }\n}\n\nfunction inferCapabilities(model: PiModel, requestOptions: Record<string, unknown>): LoweringCapabilities {\n const base = {\n api: model.api,\n thinkingReplay: model.reasoning,\n parallelTools: true,\n images: model.input.includes(\"image\"),\n contextWindow: model.contextWindow,\n maxOutputTokens: model.maxTokens,\n }\n switch (model.api) {\n case \"anthropic-messages\":\n return {\n ...base,\n midConversationSystem: ANTHROPIC_MID_SYSTEM.test(model.id),\n taskBudget: ANTHROPIC_TASK_BUDGET.test(model.id),\n }\n case \"openai-responses\":\n // Responses 的 input 项允许任意位置的 developer / system 消息\n return {\n ...base,\n thinkingReplay: model.reasoning && openaiReasoningRequested(requestOptions),\n midConversationSystem: true,\n taskBudget: false,\n }\n default:\n return { ...base, midConversationSystem: false, taskBudget: false }\n }\n}\n","/**\n * PiAiLowering:@reinsjs/core 的 Lowering 接口在 pi-ai 上的实现。\n *\n * 只导入 api/<api>(流函数)与 providers/<name>.models(静态模型表)子路径(S4)。\n * pi-ai 的类型不出本包:对外暴露的 payload 用我们自己的结构描述。\n */\nimport type { Api, Context, Model, StreamFunction, StreamOptions } from \"@earendil-works/pi-ai\"\nimport { stream as anthropicStream } from \"@earendil-works/pi-ai/api/anthropic-messages\"\nimport { stream as openaiResponsesStream } from \"@earendil-works/pi-ai/api/openai-responses\"\nimport {\n type CoreEventDraft,\n type LoweredRequest,\n type Lowering,\n type LoweringCapabilities,\n LoweringError,\n type LoweringOutcome,\n type LoweringStreamContext,\n type ModelRef,\n type ToRequestInput,\n} from \"@reinsjs/core\"\nimport { type CapabilityOverrides, capabilitiesOf } from \"./capabilities.js\"\nimport { consumeStream } from \"./from-stream.js\"\nimport { definitionToModel, type ModelDefinition, type PiModel, resolveModel } from \"./models.js\"\nimport {\n type MidSystemCacheBreakpoint,\n type RewriteAnthropicOptions,\n rewriteAnthropicPayload,\n rewriteOpenAIResponsesPayload,\n} from \"./system-note.js\"\nimport { eventsToContext } from \"./to-request.js\"\n\nexport interface PiAiLoweringOptions {\n /** 按 provider 取 key;返回 undefined 视为未配置。本包不读环境变量,由宿主决定来源 */\n apiKey: (provider: string) => string | undefined\n /** 自定义 fetch(测试注入、代理、Workers 绑定);缺省 globalThis.fetch */\n fetch?: typeof globalThis.fetch\n /** 附加请求头;值为 null 表示删掉 pi-ai 的默认头 */\n headers?: Record<string, string | null>\n /** 内置表之外的模型 */\n models?: readonly ModelDefinition[]\n /**\n * 透传给 pi-ai 流函数的额外选项(maxTokens、temperature、Anthropic 的 effort / thinkingEnabled、\n * OpenAI 的 reasoningEffort / reasoningSummary 等),键名以 pi-ai 0.85.1 文档为准。按模型返回,便于分族配置。\n * 注意:OpenAI Responses 不给 reasoningEffort 就不开 reasoning,也就没有 thinking 可回放,capabilities 会如实报 false。\n */\n requestOptions?: (model: ModelRef) => Record<string, unknown>\n /**\n * Anthropic:system_note 殿后时 pi-ai 打在它上面的缓存断点怎么处置(见 system-note.ts)。\n * 缺省 \"automatic\"(去掉块级断点、请求顶层补自动缓存);\"previous-user\" / \"drop\" 供对照或特殊上游。\n */\n midSystemCacheBreakpoint?: MidSystemCacheBreakpoint\n /**\n * trust 标注(技术方案 §14):trust=untrusted 的事件(工具输出、外部内容)翻译时包上\n * `<untrusted source=\"tool:<name>\">…</untrusted>`,事件本身不动。缺省 true;传 false 关掉是宿主自担提示注入风险\n */\n trustMarkers?: boolean\n}\n\n/** 对外暴露的请求体:pi-ai Context 的结构描述,不引用 pi-ai 类型 */\nexport interface PiLoweredPayload {\n api: string\n context: {\n systemPrompt?: string\n messages: readonly unknown[]\n tools?: readonly unknown[]\n }\n}\n\nexport class PiAiLowering implements Lowering<PiLoweredPayload> {\n private readonly extraModels: PiModel[]\n /** 宿主自定义模型声明的能力覆盖,键 provider/id;pi-ai 的 Model 上放不下这些字段 */\n private readonly overrides = new Map<string, CapabilityOverrides>()\n\n constructor(private readonly opts: PiAiLoweringOptions) {\n this.extraModels = (opts.models ?? []).map(definitionToModel)\n for (const def of opts.models ?? []) {\n if (def.midConversationSystem !== undefined) {\n this.overrides.set(`${def.provider}/${def.id}`, { midConversationSystem: def.midConversationSystem })\n }\n }\n }\n\n capabilities(ref: ModelRef): LoweringCapabilities {\n return this.capabilitiesFor(ref, resolveModel(ref, this.extraModels))\n }\n\n private capabilitiesFor(ref: ModelRef, model: PiModel): LoweringCapabilities {\n return capabilitiesOf(model, this.requestOptionsFor(ref), this.overrides.get(`${ref.provider}/${ref.id}`))\n }\n\n private requestOptionsFor(ref: ModelRef): Record<string, unknown> {\n return this.opts.requestOptions?.(ref) ?? {}\n }\n\n toRequest(input: ToRequestInput): LoweredRequest<PiLoweredPayload> {\n const model = resolveModel(input.model, this.extraModels)\n const capabilities = this.capabilitiesFor(input.model, model)\n const { context, landings } = eventsToContext({\n events: input.events,\n model,\n capabilities,\n ...(input.tools ? { tools: input.tools } : {}),\n ...(input.systemPrompt !== undefined ? { systemPrompt: input.systemPrompt } : {}),\n ...(this.opts.trustMarkers !== undefined ? { trustMarkers: this.opts.trustMarkers } : {}),\n })\n return { model: input.model, capabilities, landings, payload: { api: model.api, context } }\n }\n\n async *stream(\n req: LoweredRequest<PiLoweredPayload>,\n ctx: LoweringStreamContext = {},\n ): AsyncGenerator<CoreEventDraft, LoweringOutcome> {\n const model = resolveModel(req.model, this.extraModels)\n const apiKey = this.opts.apiKey(model.provider)\n if (!apiKey) {\n throw new LoweringError(\"missing_api_key\", `未配置 ${model.provider} 的 API key`, {\n provider: model.provider,\n })\n }\n // toRequest 里放进 payload 的就是 pi-ai Context 本体,这里取回\n const context = req.payload.context as Context\n const options: StreamOptions & Record<string, unknown> = {\n ...this.requestOptionsFor(req.model),\n apiKey,\n ...(this.opts.fetch ? { fetch: this.opts.fetch } : {}),\n ...(this.opts.headers ? { headers: this.opts.headers } : {}),\n ...(ctx.signal ? { signal: ctx.signal } : {}),\n onPayload: (payload: unknown, m: Model<Api>) =>\n rewritePayload(model.api, payload, m, {\n ...(this.opts.midSystemCacheBreakpoint\n ? { cacheBreakpoint: this.opts.midSystemCacheBreakpoint }\n : {}),\n }),\n }\n const fn = streamFunctionFor(model.api)\n return yield* consumeStream(fn(model, context, options), ctx)\n }\n}\n\nfunction streamFunctionFor(api: string): StreamFunction<Api, StreamOptions> {\n switch (api) {\n case \"anthropic-messages\":\n return anthropicStream as unknown as StreamFunction<Api, StreamOptions>\n case \"openai-responses\":\n return openaiResponsesStream as unknown as StreamFunction<Api, StreamOptions>\n default:\n throw new LoweringError(\"unsupported_api\", `不支持的线协议 ${api}`, { api })\n }\n}\n\n/** 把带标记的 system_note 改写成各 API 的 system 消息;返回 undefined 表示请求体不变 */\nexport function rewritePayload(\n api: string,\n payload: unknown,\n model: { reasoning: boolean },\n opts: RewriteAnthropicOptions = {},\n): unknown {\n if (api === \"anthropic-messages\") return rewriteAnthropicPayload(payload, opts)\n if (api === \"openai-responses\") return rewriteOpenAIResponsesPayload(payload, model)\n return undefined\n}\n","/**\n * pi-ai 流 → 事件草稿。\n *\n * 只在响应收尾(done / error)时按最终消息的内容块产出草稿:签名类回放数据(Anthropic signature、\n * OpenAI reasoning item)在块结束时才齐,等收尾最稳。增量只通过 onDelta 给 UI。\n * 中断或出错时把已产出的部分内容也交出去 —— 日志要记录\"发生过什么\",是否继续由循环决定。\n */\nimport type { AssistantMessage, AssistantMessageEvent } from \"@earendil-works/pi-ai\"\nimport type { CoreEventDraft, LoweringOutcome, LoweringStreamContext } from \"@reinsjs/core\"\nimport type { ModelOrigin } from \"./to-request.js\"\n\nexport function draftsOf(msg: AssistantMessage): CoreEventDraft[] {\n const origin: ModelOrigin = { provider: msg.provider, api: msg.api, model: msg.model }\n const drafts: CoreEventDraft[] = []\n for (const block of msg.content) {\n if (block.type === \"thinking\") {\n const replay: Record<string, unknown> = { ...origin }\n if (block.thinkingSignature) replay.thinkingSignature = block.thinkingSignature\n if (block.redacted) replay.redacted = true\n drafts.push({ type: \"core.model_thinking\", actor: \"model\", payload: { text: block.thinking }, replay })\n } else if (block.type === \"text\") {\n if (block.text.length === 0) continue\n const replay: Record<string, unknown> = { ...origin }\n if (block.textSignature) replay.textSignature = block.textSignature\n drafts.push({ type: \"core.model_text\", actor: \"model\", payload: { text: block.text }, replay })\n } else if (block.type === \"toolCall\") {\n const replay: Record<string, unknown> = { ...origin }\n if (block.thoughtSignature) replay.thoughtSignature = block.thoughtSignature\n if (block.namespace !== undefined) replay.namespace = block.namespace\n drafts.push({\n type: \"core.tool_call\",\n actor: \"model\",\n payload: { toolCallId: block.id, name: block.name, args: block.arguments },\n replay,\n })\n }\n }\n return drafts\n}\n\nfunction outcomeOf(msg: AssistantMessage, stopReason: LoweringOutcome[\"stopReason\"]): LoweringOutcome {\n const usage: LoweringOutcome[\"usage\"] = { input: msg.usage.input, output: msg.usage.output }\n if (msg.usage.cacheRead) usage.cacheRead = msg.usage.cacheRead\n if (msg.usage.cacheWrite) usage.cacheWrite = msg.usage.cacheWrite\n const out: LoweringOutcome = { stopReason, usage, costUsd: msg.usage.cost.total }\n if (msg.errorMessage) out.errorMessage = msg.errorMessage\n if (msg.responseModel) out.responseModel = msg.responseModel\n return out\n}\n\nexport async function* consumeStream(\n events: AsyncIterable<AssistantMessageEvent>,\n ctx: LoweringStreamContext = {},\n): AsyncGenerator<CoreEventDraft, LoweringOutcome> {\n for await (const ev of events) {\n switch (ev.type) {\n case \"text_delta\":\n ctx.onDelta?.({ kind: \"text\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"thinking_delta\":\n ctx.onDelta?.({ kind: \"thinking\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"toolcall_delta\":\n ctx.onDelta?.({ kind: \"tool_args\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"done\": {\n yield* draftsOf(ev.message)\n // pi-ai 的 \"deferred\" 是异步批处理句柄,第一版不支持,按 stop 收尾并保留 rawStopReason 给排查\n const reason = ev.reason === \"deferred\" ? \"stop\" : ev.reason\n return outcomeOf(ev.message, reason)\n }\n case \"error\":\n yield* draftsOf(ev.error)\n return outcomeOf(ev.error, ev.reason)\n default:\n break\n }\n }\n return {\n stopReason: \"error\",\n usage: { input: 0, output: 0 },\n errorMessage: \"pi-ai 流在 done / error 之前就结束了\",\n }\n}\n","/**\n * ModelRef → pi-ai Model。\n *\n * 只从 providers/<name>.models 取静态模型表(S4:不用 providers/all,它会拉进 Bedrock 与 AWS SDK)。\n * 宿主要用表里没有的模型(代理、私有部署、新发布)时,用 ModelDefinition 以我们自己的词汇描述,\n * 这里补齐 pi-ai 需要的其余字段 —— pi-ai 的 Model 类型不出本包。\n */\nimport type { Api, Model } from \"@earendil-works/pi-ai\"\nimport { ANTHROPIC_MODELS } from \"@earendil-works/pi-ai/providers/anthropic.models\"\nimport { OPENAI_MODELS } from \"@earendil-works/pi-ai/providers/openai.models\"\nimport { LoweringError, type ModelRef } from \"@reinsjs/core\"\n\n/** 本包内部使用的 pi-ai 模型类型 */\nexport type PiModel = Model<Api>\n\n/** 第一版支持的线协议 */\nexport const SUPPORTED_APIS: ReadonlySet<string> = new Set([\"anthropic-messages\", \"openai-responses\"])\n\n/** 宿主自定义模型:用我们的词汇描述,字段与 LoweringCapabilities 对齐 */\nexport interface ModelDefinition {\n provider: string\n id: string\n /** \"anthropic-messages\" | \"openai-responses\" */\n api: string\n baseUrl: string\n /** 支持 thinking / reasoning */\n reasoning: boolean\n contextWindow: number\n maxOutputTokens: number\n images?: boolean\n name?: string\n /** 每百万 token 美元价;缺省全 0(成本算不出但能跑) */\n cost?: { input: number; output: number; cacheRead: number; cacheWrite: number }\n /** 额外请求头,如私有网关的鉴权 */\n headers?: Record<string, string>\n /**\n * 是否接受 messages 里的中途 `role:\"system\"` 消息(system_note 的 exact 落点)。内置 Anthropic 模型按 id 判定;\n * 第三方 Anthropic 协议上游(如 DeepSeek 的兼容端口,2026-09-08 实测接受)由宿主在此声明,缺省按不支持处理。\n */\n midConversationSystem?: boolean\n}\n\nconst BUILTIN: Readonly<Record<string, Readonly<Record<string, PiModel>>>> = {\n anthropic: ANTHROPIC_MODELS as unknown as Record<string, PiModel>,\n openai: OPENAI_MODELS as unknown as Record<string, PiModel>,\n}\n\nexport function definitionToModel(def: ModelDefinition): PiModel {\n const model: PiModel = {\n id: def.id,\n name: def.name ?? def.id,\n api: def.api,\n provider: def.provider,\n baseUrl: def.baseUrl,\n reasoning: def.reasoning,\n input: def.images ? [\"text\", \"image\"] : [\"text\"],\n cost: def.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: def.contextWindow,\n maxTokens: def.maxOutputTokens,\n }\n if (def.headers) model.headers = def.headers\n return model\n}\n\nexport function resolveModel(ref: ModelRef, extra: readonly PiModel[] = []): PiModel {\n const model =\n extra.find((m) => m.provider === ref.provider && m.id === ref.id) ?? BUILTIN[ref.provider]?.[ref.id]\n if (!model) {\n throw new LoweringError(\n \"unsupported_model\",\n `找不到模型 ${ref.provider}/${ref.id};内置表只含 anthropic 与 openai,其余请通过 models 选项声明`,\n {\n provider: ref.provider,\n id: ref.id,\n },\n )\n }\n if (!SUPPORTED_APIS.has(model.api)) {\n throw new LoweringError(\n \"unsupported_api\",\n `模型 ${ref.provider}/${ref.id} 走 ${model.api},本实现只支持 anthropic-messages 与 openai-responses`,\n {\n api: model.api,\n },\n )\n }\n return model\n}\n","/**\n * system_note 的落点(S1 结论)。\n *\n * pi-ai 的 Message 没有 system 角色,所以:\n * - 模型支持中途 system 时:先当 user 消息放进 Context,文本前加内部标记;在 pi-ai 的 onPayload 钩子里\n * 把带标记的消息改写成线协议的 system 消息并归位。标记只在本文件生产与消费,不会送到线上。\n * - 不支持时:以 <system_note> 标签包住、仍走 user 角色,有损矩阵记为 lossy(user-role)。\n *\n * Anthropic 摆放规则(官方,违反即 400):不能是首条;必须紧跟 user 轮(含 tool_result 的 user);\n * 后接 assistant 或收尾;连续多条 system 视为一组。\n * OpenAI Responses:input 项里 developer / system 消息可出现在任意位置,无归位需求。\n */\nimport type { SystemNotePayload } from \"@reinsjs/core\"\n\nexport const SYSTEM_NOTE_MARK = \"[[reins:system_note]]\"\n\nexport function markSystemNote(text: string): string {\n return `${SYSTEM_NOTE_MARK}${text}`\n}\n\n/** 不支持中途 system 的模型:用标签框住,让模型知道这不是用户说的 */\nexport function framedSystemNote(kind: SystemNotePayload[\"kind\"], text: string): string {\n return `<system_note kind=\"${kind}\">\\n${text}\\n</system_note>`\n}\n\ninterface WireMessage {\n role: string\n content: unknown\n [k: string]: unknown\n}\n\ninterface MarkedNote {\n text: string\n /** pi-ai 打在这条消息上的缓存断点(它是最后一条 user 时才有),改写后要搬走而不是丢掉 */\n cacheControl?: unknown\n}\n\n/** 取出带标记的正文;不是标记消息返回 null */\nfunction markedNote(m: WireMessage, textType: string): MarkedNote | null {\n if (m.role !== \"user\") return null\n let text: string | null = null\n let cacheControl: unknown\n if (typeof m.content === \"string\") text = m.content\n else if (Array.isArray(m.content) && m.content.length === 1) {\n const only = m.content[0] as { type?: string; text?: string; cache_control?: unknown }\n if (only.type === textType && typeof only.text === \"string\") {\n text = only.text\n cacheControl = only.cache_control\n }\n }\n if (text === null || !text.startsWith(SYSTEM_NOTE_MARK)) return null\n return {\n text: text.slice(SYSTEM_NOTE_MARK.length),\n ...(cacheControl !== undefined ? { cacheControl } : {}),\n }\n}\n\n/**\n * Anthropic Messages 请求体改写:标记消息 → {role:\"system\", content:[text]},并按摆放规则归位。\n * 归位算法:每条 system 放到\"它之后的第一条 assistant\"之前(此时前一条必是 user);后面没有 assistant 就放到\n * 消息列表末尾(紧跟最后一条 user 收尾)。pi-ai 在部分模型上会在末尾追加 content 为空的 effort 专用 system 消息,\n * 我们的 system 与它相邻成组,符合规则。\n *\n * 缓存断点(B1,prompt cache 约束 4):pi-ai 把 cache_control 打在\"最后一条 user 消息\"上;感知等 system_note\n * 追加在时间线末尾时,那条最后的 user 正是我们的标记消息,改写成 system 后断点会跟着消失,而官方规则是\n * \"最后一个断点之后的内容一律不缓存\" —— 整段对话历史都会按原价计费。处置由 `cacheBreakpoint` 选:\n * - \"automatic\"(缺省):去掉这个块级断点,在请求顶层补 `cache_control`(Anthropic 的自动缓存:断点自动落在最后一个\n * 可缓存块上,与显式断点兼容、占 4 个槽位中的 1 个)。B1 实测(spikes/b1-perception-cache)命中率与不注入持平。\n * - \"previous-user\":搬到紧邻的前一条 user 消息末块(真正的最新 user / tool_result)。实测比不注入低 3~6 个点。\n * - \"drop\":丢掉。只在上游自己会补自动缓存(如某些网关)时才不吃亏。\n * 把断点留在改写后的 system 消息上实测会让整段提示每次重写、几乎零命中,所以不提供这个选项。\n */\nexport type MidSystemCacheBreakpoint = \"automatic\" | \"previous-user\" | \"drop\"\n\nexport interface RewriteAnthropicOptions {\n cacheBreakpoint?: MidSystemCacheBreakpoint\n}\n\n/** Anthropic 每个请求最多 4 个断点(含顶层自动缓存那一个),超出即 400 */\nconst MAX_ANTHROPIC_BREAKPOINTS = 4\n\nexport function rewriteAnthropicPayload(payload: unknown, opts: RewriteAnthropicOptions = {}): unknown {\n const breakpoint = opts.cacheBreakpoint ?? \"automatic\"\n const p = payload as {\n messages?: WireMessage[]\n system?: unknown\n tools?: unknown\n cache_control?: unknown\n }\n if (!Array.isArray(p.messages)) return undefined\n const body: WireMessage[] = []\n const pending: (MarkedNote & { afterIndex: number })[] = []\n for (const m of p.messages) {\n const note = markedNote(m, \"text\")\n if (note !== null) pending.push({ ...note, afterIndex: body.length })\n else body.push(m)\n }\n if (pending.length === 0) return undefined\n\n // 每条说明在**原始** body 里的落点(都算完再拼,而不是边算边 splice:边 splice 会让同一落点的多条说明前后颠倒)\n const placeOf = (note: (typeof pending)[number]): number => {\n let at = body.findIndex((m, idx) => idx >= note.afterIndex && m.role === \"assistant\")\n if (at === -1) {\n // 收尾:跳过 pi-ai 追加的 effort 专用空 system,保持\"紧跟最后一条 user\"\n at = body.length\n while (at > 0 && body[at - 1]?.role === \"system\" && isEmptyContent(body[at - 1]?.content)) at--\n }\n // 不能是首条:前面没有任何消息时挪到第一条 user 之后\n if (at === 0) {\n const firstUser = body.findIndex((m) => m.role === \"user\")\n at = firstUser === -1 ? body.length : firstUser + 1\n }\n return at\n }\n // 同一落点的说明按原顺序成组(相邻的多条 system 视为一组,Anthropic 允许)\n const groups = new Map<number, MarkedNote[]>()\n for (const note of pending) {\n const at = placeOf(note)\n const bucket = groups.get(at)\n if (bucket) bucket.push(note)\n else groups.set(at, [note])\n }\n\n let lostBreakpoint: unknown\n const messages: WireMessage[] = []\n for (let i = 0; i <= body.length; i++) {\n const notes = groups.get(i)\n if (notes) {\n for (const note of notes) {\n if (note.cacheControl !== undefined && breakpoint === \"previous-user\") {\n // 搬到紧邻的前一条 user 消息末块(此时它已在 messages 末尾)\n const prev = messages[messages.length - 1]\n if (prev) messages[messages.length - 1] = withCacheControl(prev, note.cacheControl)\n }\n if (note.cacheControl !== undefined && breakpoint === \"automatic\") lostBreakpoint = note.cacheControl\n messages.push({ role: \"system\", content: [{ type: \"text\", text: note.text }] })\n }\n }\n const m = body[i]\n if (m) messages.push(m)\n }\n const out = { ...p, messages }\n if (lostBreakpoint !== undefined && out.cache_control === undefined) {\n // 顶层自动缓存也占一个槽位;块级断点已满就只能放弃,不能让请求 400\n if (countBlockBreakpoints(out) < MAX_ANTHROPIC_BREAKPOINTS) out.cache_control = lostBreakpoint\n }\n return out\n}\n\n/** 数请求里块级 cache_control 的个数:system 数组、tools 数组、messages 的内容块 */\nfunction countBlockBreakpoints(p: { system?: unknown; tools?: unknown; messages: WireMessage[] }): number {\n const has = (b: unknown) => typeof b === \"object\" && b !== null && \"cache_control\" in b\n let n = 0\n if (Array.isArray(p.system)) n += p.system.filter(has).length\n if (Array.isArray(p.tools)) n += p.tools.filter(has).length\n for (const m of p.messages) if (Array.isArray(m.content)) n += m.content.filter(has).length\n return n\n}\n\n/**\n * 把缓存断点打到某条 user 消息的最后一个内容块上(Anthropic 允许 text / image / tool_result 块带 cache_control)。\n * 归位规则保证 system 前面必是 user;万一不是,宁可丢断点也不把 cache_control 放到厂商不认的位置上。\n * 返回新对象,不改动传入的请求体。\n */\nfunction withCacheControl(m: WireMessage, cacheControl: unknown): WireMessage {\n if (m.role !== \"user\") return m\n if (typeof m.content === \"string\") {\n return { ...m, content: [{ type: \"text\", text: m.content, cache_control: cacheControl }] }\n }\n if (Array.isArray(m.content) && m.content.length > 0) {\n const blocks = [...(m.content as Record<string, unknown>[])]\n const last = blocks[blocks.length - 1] as Record<string, unknown>\n blocks[blocks.length - 1] = { ...last, cache_control: cacheControl }\n return { ...m, content: blocks }\n }\n return m\n}\n\nfunction isEmptyContent(content: unknown): boolean {\n return Array.isArray(content) && content.length === 0\n}\n\n/**\n * OpenAI Responses 请求体改写:标记消息 → {role: developer|system, content:[input_text]}。\n * reasoning 模型用 developer(与 pi-ai 放 systemPrompt 的选择一致),其余用 system。\n */\nexport function rewriteOpenAIResponsesPayload(payload: unknown, model: { reasoning: boolean }): unknown {\n const p = payload as { input?: unknown }\n if (!Array.isArray(p.input)) return undefined\n let changed = false\n const role = model.reasoning ? \"developer\" : \"system\"\n const input = (p.input as WireMessage[]).map((m) => {\n const note = markedNote(m, \"input_text\")\n if (note === null) return m\n changed = true\n return { role, content: [{ type: \"input_text\", text: note.text }] }\n })\n return changed ? { ...p, input } : undefined\n}\n","/**\n * 事件 → pi-ai Context(三角色 Message[] + tools + systemPrompt),并逐条记录落点。\n *\n * 分组规则:连续的 model 事件(thinking / text / tool_call)合成一条 AssistantMessage,\n * 遇到任何非 model 事件就收口。AssistantMessage 需要 api/provider/model 才能让 pi-ai 判断\n * \"这段 thinking 是不是本模型产的、能不能回放\",这些信息在事件产出时记在 replay 里。\n */\nimport type {\n AssistantMessage,\n Context,\n Message,\n TextContent,\n ThinkingContent,\n Tool,\n ToolCall,\n} from \"@earendil-works/pi-ai\"\nimport {\n type ContentPart,\n type CoreEvent,\n type Event,\n type LandingRecord,\n type LoweringCapabilities,\n markUntrusted,\n markUntrustedText,\n needsUntrustedMark,\n type ToolSpec,\n untrustedSourceOf,\n} from \"@reinsjs/core\"\nimport type { PiModel } from \"./models.js\"\nimport { framedSystemNote, markSystemNote } from \"./system-note.js\"\n\n/** 模型事件 replay 里记录的来源,产出与回放两头共用 */\nexport interface ModelOrigin {\n provider: string\n api: string\n model: string\n}\n\nexport interface ThinkingReplay extends Partial<ModelOrigin> {\n thinkingSignature?: string\n redacted?: boolean\n}\nexport interface TextReplay extends Partial<ModelOrigin> {\n textSignature?: string\n}\nexport interface ToolCallReplay extends Partial<ModelOrigin> {\n thoughtSignature?: string\n namespace?: string\n}\n\nconst ZERO_USAGE: AssistantMessage[\"usage\"] = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n}\n\nfunction toPiContent(\n parts: readonly ContentPart[],\n): (TextContent | { type: \"image\"; data: string; mimeType: string })[] {\n return parts.map((p) =>\n p.type === \"text\" ? { type: \"text\", text: p.text } : { type: \"image\", data: p.data, mimeType: p.mime },\n )\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction originOf(replay: Record<string, unknown> | undefined, fallback: PiModel): ModelOrigin {\n const r = (replay ?? {}) as Partial<ModelOrigin>\n return {\n provider: typeof r.provider === \"string\" ? r.provider : fallback.provider,\n api: typeof r.api === \"string\" ? r.api : fallback.api,\n model: typeof r.model === \"string\" ? r.model : fallback.id,\n }\n}\n\nfunction sameOrigin(a: ModelOrigin, b: ModelOrigin): boolean {\n return a.provider === b.provider && a.api === b.api && a.model === b.model\n}\n\n/**\n * 是否来自别家:只比 provider 与 api。响应里报告的模型 id 常与请求的不同(带日期后缀、别名、网关改名),\n * 同家同协议下签名仍可回放,不算有损,只在落点备注里留痕。\n */\nfunction foreignOrigin(a: ModelOrigin, target: ModelOrigin): boolean {\n return a.provider !== target.provider || a.api !== target.api\n}\n\nconst DEFERRED_NOTE = \"已后移到同批工具结果之后(工具结果必须紧跟调用)\"\nconst ESCAPED_NOTE = \"不可信内容里含提前闭合的 </untrusted,已转义\"\n\nexport interface ToContextInput {\n events: readonly Event[]\n tools?: readonly ToolSpec[]\n model: PiModel\n capabilities: LoweringCapabilities\n systemPrompt?: string\n /** trust=untrusted 的内容(工具输出、外部内容)以 <untrusted source=…> 包裹(§14)。缺省 true;关掉是宿主自担风险 */\n trustMarkers?: boolean\n}\n\nexport function eventsToContext(input: ToContextInput): { context: Context; landings: LandingRecord[] } {\n const { model, capabilities } = input\n const target: ModelOrigin = { provider: model.provider, api: model.api, model: model.id }\n const isAnthropic = model.api === \"anthropic-messages\"\n const trustMarkers = input.trustMarkers !== false\n const messages: Message[] = []\n const landings: LandingRecord[] = []\n\n let group: { origin: ModelOrigin; content: AssistantMessage[\"content\"]; at: number } | null = null\n /**\n * 已下发 tool_call、结果还没到的调用 id。Anthropic 要求同一批 tool_result 紧跟在 tool_use 所在的 assistant 之后、\n * 连成一条 user,中间不能插别的消息;而日志里 pin / memory 留痕的说明、感知说明都可能落在两条 tool_result 之间\n * (并行工具时 ctx.emit 的草稿排在各自结果之前),用户也可能在结果回来之前插话(续跑带新 input、进程死亡后再发消息)。\n * 所以结果没到齐时,说明、摘要与用户消息先攒着,到齐后再放出(落点备注说明后移)。时间线本身如实保留插话的位置。\n */\n const awaiting = new Set<string>()\n const deferred: {\n msg: Message\n event: Event\n kind: LandingRecord[\"kind\"]\n landing: string\n note?: string\n }[] = []\n const land = (e: Event, kind: LandingRecord[\"kind\"], landing: string, note?: string) => {\n landings.push(\n note\n ? { eventId: e.id, type: e.type, kind, landing, note }\n : { eventId: e.id, type: e.type, kind, landing },\n )\n }\n const releaseDeferred = () => {\n for (const d of deferred) {\n messages.push(d.msg)\n land(d.event, d.kind, d.landing, d.note ? `${d.note};${DEFERRED_NOTE}` : DEFERRED_NOTE)\n }\n deferred.length = 0\n }\n /**\n * trust 标注(§14):untrusted 的内容包上 <untrusted source=…>,事件本身不动。\n * 返回翻译后的片段与\"是否因转义而有损\"——内容里出现提前闭合的标签时被转义,落点要记 lossy。\n */\n const content = (e: Event, parts: readonly ContentPart[]): { parts: ContentPart[]; escaped: boolean } => {\n if (!trustMarkers || !needsUntrustedMark(e)) return { parts: [...parts], escaped: false }\n return markUntrusted(parts, untrustedSourceOf(e))\n }\n const text = (e: Event, s: string): { text: string; escaped: boolean } => {\n if (!trustMarkers || !needsUntrustedMark(e)) return { text: s, escaped: false }\n return markUntrustedText(s, untrustedSourceOf(e))\n }\n /** 说明 / 摘要类消息:工具结果还没到齐就先攒着 */\n const note = (e: Event, msg: Message, kind: LandingRecord[\"kind\"], landing: string, why?: string) => {\n if (awaiting.size > 0) {\n deferred.push({ msg, event: e, kind, landing, ...(why !== undefined ? { note: why } : {}) })\n return\n }\n messages.push(msg)\n land(e, kind, landing, why)\n }\n /** 新的模型输出到来:这批调用的结果不会再来了(视图被切在了结果之前),后移的一切放出 */\n const settleAwaiting = () => {\n awaiting.clear()\n releaseDeferred()\n }\n const flush = () => {\n if (!group) return\n const hasTool = group.content.some((c) => c.type === \"toolCall\")\n messages.push({\n role: \"assistant\",\n content: group.content,\n api: group.origin.api,\n provider: group.origin.provider,\n model: group.origin.model,\n usage: ZERO_USAGE,\n stopReason: hasTool ? \"toolUse\" : \"stop\",\n timestamp: group.at,\n })\n for (const c of group.content) if (c.type === \"toolCall\") awaiting.add(c.id)\n group = null\n }\n const assistant = (e: Event, origin: ModelOrigin) => {\n if (group && !sameOrigin(group.origin, origin)) flush()\n if (!group) {\n settleAwaiting()\n group = { origin, content: [], at: e.at }\n }\n return group\n }\n\n for (const raw of input.events) {\n const e = raw as CoreEvent\n switch (e.type) {\n case \"core.user_message\": {\n flush()\n const c = content(e, e.payload.content)\n const msg: Message = { role: \"user\", content: toPiContent(c.parts), timestamp: e.at }\n // 工具结果还没到齐就来了用户消息:后移到同批结果之后,否则 tool_use 后面紧跟的不是 tool_result,厂商 400。\n // 顺序变了所以记 lossy;日志里它仍在原位\n if (awaiting.size > 0) {\n deferred.push({\n msg,\n event: e,\n kind: \"lossy\",\n landing: \"user\",\n note: c.escaped\n ? `用户消息落在工具调用与结果之间;${ESCAPED_NOTE}`\n : \"用户消息落在工具调用与结果之间\",\n })\n break\n }\n messages.push(msg)\n if (c.escaped) land(e, \"lossy\", \"user\", ESCAPED_NOTE)\n else land(e, \"exact\", \"user\")\n break\n }\n\n case \"core.model_thinking\": {\n const origin = originOf(e.replay, model)\n const r = (e.replay ?? {}) as ThinkingReplay\n const block: ThinkingContent = { type: \"thinking\", thinking: e.payload.text }\n if (typeof r.thinkingSignature === \"string\") block.thinkingSignature = r.thinkingSignature\n if (r.redacted === true) block.redacted = true\n assistant(e, origin).content.push(block)\n if (!block.thinkingSignature)\n land(e, \"lossy\", \"text-or-drop\", \"无签名的 thinking 由 pi-ai 降为文本或丢弃\")\n else if (foreignOrigin(origin, target))\n land(\n e,\n \"lossy\",\n \"provider-dependent\",\n `来自 ${origin.provider}/${origin.model} 的 thinking,厂商可能忽略或拒收`,\n )\n else if (origin.model !== target.model)\n land(\n e,\n \"exact\",\n isAnthropic ? \"thinking-block\" : \"reasoning-item\",\n `签名来自 ${origin.model},当前请求 ${target.model}`,\n )\n else land(e, \"exact\", isAnthropic ? \"thinking-block\" : \"reasoning-item\")\n break\n }\n\n case \"core.model_text\": {\n const origin = originOf(e.replay, model)\n const r = (e.replay ?? {}) as TextReplay\n const block: TextContent = { type: \"text\", text: e.payload.text }\n if (typeof r.textSignature === \"string\") block.textSignature = r.textSignature\n assistant(e, origin).content.push(block)\n land(e, \"exact\", isAnthropic ? \"assistant-text\" : \"assistant-message\")\n break\n }\n\n case \"core.tool_call\": {\n const origin = originOf(e.replay, model)\n const r = (e.replay ?? {}) as ToolCallReplay\n const wrapped = !isPlainObject(e.payload.args)\n const block: ToolCall = {\n type: \"toolCall\",\n id: e.payload.toolCallId,\n name: e.payload.name,\n arguments: wrapped ? { value: e.payload.args } : (e.payload.args as Record<string, unknown>),\n }\n if (typeof r.thoughtSignature === \"string\") block.thoughtSignature = r.thoughtSignature\n if (typeof r.namespace === \"string\") block.namespace = r.namespace\n assistant(e, origin).content.push(block)\n if (wrapped) land(e, \"lossy\", \"wrapped-args\", \"非对象入参包成 { value }\")\n else land(e, \"exact\", isAnthropic ? \"tool_use\" : \"function_call\")\n break\n }\n\n case \"core.tool_result\": {\n flush()\n const c = content(e, e.payload.content)\n messages.push({\n role: \"toolResult\",\n toolCallId: e.payload.toolCallId,\n toolName: e.payload.name,\n content: toPiContent(c.parts),\n isError: e.payload.isError,\n timestamp: e.at,\n })\n const landing = isAnthropic ? \"tool_result\" : \"function_call_output\"\n if (c.escaped) land(e, \"lossy\", landing, ESCAPED_NOTE)\n else land(e, \"exact\", landing)\n awaiting.delete(e.payload.toolCallId)\n if (awaiting.size === 0) releaseDeferred()\n break\n }\n\n case \"core.system_note\": {\n flush()\n // 宿主注入的外部内容可能把 system_note 标成 untrusted(如抓取的网页),同样包裹\n const t = text(e, e.payload.text)\n if (capabilities.midConversationSystem) {\n note(\n e,\n { role: \"user\", content: markSystemNote(t.text), timestamp: e.at },\n t.escaped ? \"lossy\" : \"exact\",\n isAnthropic ? \"system\" : model.reasoning ? \"developer\" : \"system\",\n t.escaped ? ESCAPED_NOTE : undefined,\n )\n } else {\n note(\n e,\n { role: \"user\", content: framedSystemNote(e.payload.kind, t.text), timestamp: e.at },\n \"lossy\",\n \"user-role\",\n \"模型不支持中途 system,以 <system_note> 标签包住走 user 角色\",\n )\n }\n break\n }\n\n case \"core.compaction\": {\n flush()\n const t = text(e, e.payload.summary)\n note(\n e,\n {\n role: \"user\",\n content: `[Summary of earlier conversation]\\n${t.text}`,\n timestamp: e.at,\n },\n \"lossy\",\n \"user-text\",\n \"摘要以 user 角色文本呈现\",\n )\n break\n }\n\n case \"core.approval_request\":\n case \"core.approval_decision\":\n case \"core.run_paused\":\n case \"core.run_resumed\":\n case \"core.budget_usage\":\n case \"core.memory_op\":\n case \"core.handoff\":\n case \"core.error\":\n land(e, \"dropped\", \"none\", \"运维事件不下发(投影默认已过滤)\")\n break\n\n default:\n land(raw, \"dropped\", \"none\", `无通用落点:${raw.type}`)\n }\n }\n flush()\n settleAwaiting()\n\n const context: Context = { messages }\n if (input.systemPrompt) context.systemPrompt = input.systemPrompt\n if (input.tools && input.tools.length > 0) {\n // pi-ai 的 parameters 是 typebox TSchema,运行时就是 JSON Schema 对象,直接透传\n context.tools = input.tools.map(\n (t): Tool => ({\n name: t.name,\n description: t.description,\n parameters: t.inputSchema as Tool[\"parameters\"],\n }),\n )\n }\n return { context, landings }\n}\n","/**\n * 一行拿到\"模型 + 降级层\":`anthropic(\"claude-opus-5\", { apiKey })`、`openai(\"gpt-5.5\", { apiKey })`。\n * 返回 BoundModel,直接给 `createAgent({ model })`;要更多控制(多模型共享一个降级层、自定义 fetch)就自己 new PiAiLowering。\n *\n * 本包不读环境变量(T7 决策),apiKey 必填、由宿主决定来源。\n * 带 baseUrl 即走代理 / 网关:此时按 ModelDefinition 登记,能力字段给了缺省值,可用 contextWindow 等覆盖。\n */\nimport type { BoundModel } from \"@reinsjs/core\"\nimport type { ModelDefinition } from \"./models.js\"\nimport { PiAiLowering, type PiAiLoweringOptions } from \"./pi-lowering.js\"\n\nexport interface BoundModelOptions {\n apiKey: string\n /** 代理或网关地址。Anthropic 在其后接 /v1/messages,OpenAI 接 /responses(网关请给到 …/v1) */\n baseUrl?: string\n /** 透传给 pi-ai 的请求选项(thinkingEnabled、reasoningEffort、maxTokens…) */\n requestOptions?: Record<string, unknown>\n /** 仅 baseUrl 模式下需要:模型能力。缺省 200k 窗口、16k 输出、支持推理与图片 */\n contextWindow?: number\n maxOutputTokens?: number\n reasoning?: boolean\n images?: boolean\n /** 仅 baseUrl 模式:上游是否接受中途 `role:\"system\"`(system_note 的 exact 落点)。第三方 Anthropic 兼容端口(如 DeepSeek)实测接受时置 true;缺省按不支持、以标签走 user */\n midConversationSystem?: boolean\n fetch?: typeof globalThis.fetch\n headers?: Record<string, string | null>\n /** trust 标注(§14):untrusted 内容包 <untrusted> 标记。缺省开;关掉是宿主自担风险 */\n trustMarkers?: boolean\n}\n\nfunction bound(\n provider: \"anthropic\" | \"openai\",\n api: string,\n id: string,\n opts: BoundModelOptions,\n): BoundModel {\n const models: ModelDefinition[] = opts.baseUrl\n ? [\n {\n provider,\n id,\n api,\n baseUrl: opts.baseUrl,\n reasoning: opts.reasoning ?? true,\n contextWindow: opts.contextWindow ?? 200_000,\n maxOutputTokens: opts.maxOutputTokens ?? 16_000,\n images: opts.images ?? true,\n ...(opts.midConversationSystem !== undefined\n ? { midConversationSystem: opts.midConversationSystem }\n : {}),\n },\n ]\n : []\n const loweringOpts: PiAiLoweringOptions = {\n apiKey: (p) => (p === provider ? opts.apiKey : undefined),\n models,\n ...(opts.requestOptions ? { requestOptions: () => opts.requestOptions ?? {} } : {}),\n ...(opts.fetch ? { fetch: opts.fetch } : {}),\n ...(opts.headers ? { headers: opts.headers } : {}),\n ...(opts.trustMarkers !== undefined ? { trustMarkers: opts.trustMarkers } : {}),\n }\n return { model: { provider, id }, lowering: new PiAiLowering(loweringOpts) }\n}\n\n/** Anthropic Messages。缺省开 thinking(模型不支持时 pi-ai 会忽略) */\nexport function anthropic(id: string, opts: BoundModelOptions): BoundModel {\n return bound(\"anthropic\", \"anthropic-messages\", id, {\n requestOptions: { thinkingEnabled: true },\n ...opts,\n })\n}\n\n/** OpenAI Responses。缺省 reasoningEffort=medium,这样才有可回放的 reasoning(见 T7 决策) */\nexport function openai(id: string, opts: BoundModelOptions): BoundModel {\n return bound(\"openai\", \"openai-responses\", id, {\n requestOptions: { reasoningEffort: \"medium\" },\n ...opts,\n })\n}\n","/**\n * 有损矩阵(P7:有损必声明)。api → 事件 type → 可能落点。\n *\n * 这是\"合同\":toRequest 对每条事件实际记录的落点必须是这里声明过的一种(T8 测试逐项断言)。\n * 新增事件类型或新 API 而不补这张表,测试就红 —— 宁可编译期/测试期吵,不要线上静默丢。\n */\nimport type { LandingSpec, LossMatrix } from \"@reinsjs/core\"\n\nconst exact = (landing: string, note?: string, when?: string): LandingSpec => {\n const spec: LandingSpec = { kind: \"exact\", landing }\n if (note) spec.note = note\n if (when) spec.when = when\n return spec\n}\nconst lossy = (landing: string, note: string, when?: string): LandingSpec =>\n when ? { kind: \"lossy\", landing, note, when } : { kind: \"lossy\", landing, note }\nconst dropped = (landing: string, note: string): LandingSpec => ({ kind: \"dropped\", landing, note })\n\n/** 两家共同的\"不下发\"事件:它们服务宿主与审计,信息由别的事件承载;投影默认已过滤,这里是第二道声明 */\nconst NOT_SENT: Readonly<Record<string, readonly LandingSpec[]>> = {\n \"core.approval_request\": [dropped(\"none\", \"审批结果由 tool_result(isError) 告知模型\")],\n \"core.approval_decision\": [dropped(\"none\", \"同上\")],\n \"core.run_paused\": [dropped(\"none\", \"运行记录;感知模块会提炼进 system_note\")],\n \"core.run_resumed\": [dropped(\"none\", \"同上\")],\n \"core.budget_usage\": [dropped(\"none\", \"同上\")],\n \"core.memory_op\": [dropped(\"none\", \"记忆读写留痕,模型已通过工具结果知晓\")],\n \"core.handoff\": [dropped(\"none\", \"交接后本会话结束;新会话首条 user 承载 triggerMessage\")],\n \"core.error\": [dropped(\"none\", \"provider 错误由循环处理;工具错误已在 tool_result.isError\")],\n}\n\nconst THINKING_COMMON = {\n noSignature: lossy(\n \"text-or-drop\",\n \"无签名的 thinking 由 pi-ai 降为文本或丢弃\",\n \"事件 replay 缺 thinkingSignature\",\n ),\n foreign: lossy(\n \"provider-dependent\",\n \"来自其它模型的 thinking,厂商可能忽略或拒收\",\n \"replay 的 provider/api/model 与当前不同\",\n ),\n}\n\nconst TOOL_CALL_ARGS = lossy(\"wrapped-args\", \"非对象入参包成 { value }\", \"tool_call.args 不是对象\")\n\n/** 用户在工具结果回来之前插话(续跑带新 input、进程死亡后再发消息):消息后移到同批结果之后,顺序有变 */\nconst USER_DEFERRED = lossy(\n \"user\",\n \"落在 tool_call 与 tool_result 之间的用户消息后移到同批结果之后(工具结果必须紧跟调用)\",\n \"工具结果没到齐时用户插话\",\n)\n\nexport const LOSS_MATRIX: LossMatrix = {\n \"anthropic-messages\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED],\n \"core.model_text\": [exact(\"assistant-text\")],\n \"core.model_thinking\": [\n exact(\"thinking-block\", \"带 signature 原样回放\"),\n THINKING_COMMON.noSignature,\n THINKING_COMMON.foreign,\n ],\n \"core.tool_call\": [exact(\"tool_use\"), TOOL_CALL_ARGS],\n \"core.tool_result\": [exact(\"tool_result\", \"紧跟对应 tool_use 的下一条 user\")],\n \"core.system_note\": [\n exact(\n \"system\",\n \"带正文的中途 system 消息\",\n \"模型族支持中途 system(Fable 5.x / Mythos 5.x / Opus 5 / Opus 4.8)\",\n ),\n lossy(\"user-role\", \"以 <system_note> 标签包住走 user 角色\", \"模型族不支持中途 system\"),\n ],\n \"core.compaction\": [lossy(\"user-text\", \"摘要以 user 角色文本呈现,模型无法区分它与用户原话\")],\n ...NOT_SENT,\n \"ext.*\": [dropped(\"none\", \"宿主扩展事件无通用落点;需要模型看见的应在投影层翻译成 core 事件\")],\n },\n \"openai-responses\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED],\n \"core.model_text\": [exact(\"assistant-message\")],\n \"core.model_thinking\": [\n exact(\"reasoning-item\", \"encrypted_content 原样回放\"),\n THINKING_COMMON.noSignature,\n THINKING_COMMON.foreign,\n ],\n \"core.tool_call\": [exact(\"function_call\"), TOOL_CALL_ARGS],\n \"core.tool_result\": [exact(\"function_call_output\")],\n \"core.system_note\": [\n exact(\"developer\", \"reasoning 模型用 developer 角色\"),\n exact(\"system\", \"非 reasoning 模型用 system 角色\"),\n ],\n \"core.compaction\": [lossy(\"user-text\", \"摘要以 user 角色文本呈现\")],\n ...NOT_SENT,\n \"ext.*\": [dropped(\"none\", \"同 Anthropic\")],\n },\n}\n\n/** 查某 api 下某事件 type 的声明落点;ext.* 归到通配项 */\nexport function declaredLandings(api: string, type: string): readonly LandingSpec[] {\n const table = LOSS_MATRIX[api]\n if (!table) return []\n return table[type] ?? (type.startsWith(\"ext.\") ? (table[\"ext.*\"] ?? []) : [])\n}\n"],"mappings":";AAUA,IAAM,uBAAuB;AAG7B,IAAM,wBAAwB;AAO9B,SAAS,yBAAyB,gBAAkD;AAClF,SAAO,QAAQ,eAAe,mBAAmB,eAAe,gBAAgB;AAClF;AAOO,SAAS,eACd,OACA,iBAA0C,CAAC,GAC3C,YAAiC,CAAC,GACZ;AACtB,QAAM,OAAO,kBAAkB,OAAO,cAAc;AACpD,SAAO,UAAU,0BAA0B,SACvC,OACA,EAAE,GAAG,MAAM,uBAAuB,UAAU,sBAAsB;AACxE;AAEA,SAAS,kBAAkB,OAAgB,gBAA+D;AACxG,QAAM,OAAO;AAAA,IACX,KAAK,MAAM;AAAA,IACX,gBAAgB,MAAM;AAAA,IACtB,eAAe;AAAA,IACf,QAAQ,MAAM,MAAM,SAAS,OAAO;AAAA,IACpC,eAAe,MAAM;AAAA,IACrB,iBAAiB,MAAM;AAAA,EACzB;AACA,UAAQ,MAAM,KAAK;AAAA,IACjB,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,uBAAuB,qBAAqB,KAAK,MAAM,EAAE;AAAA,QACzD,YAAY,sBAAsB,KA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A,EACA,oBAAoB;AAAA,IAClB,qBAAqB,CAAC,MAAM,MAAM,GAAG,aAAa;AAAA,IAClD,mBAAmB,CAAC,MAAM,mBAAmB,CAAC;AAAA,IAC9C,uBAAuB;AAAA,MACrB,MAAM,kBAAkB,4CAAwB;AAAA,MAChD,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,IACA,kBAAkB,CAAC,MAAM,eAAe,GAAG,cAAc;AAAA,IACzD,oBAAoB,CAAC,MAAM,sBAAsB,CAAC;AAAA,IAClD,oBAAoB;AAAA,MAClB,MAAM,aAAa,qDAA4B;AAAA,MAC/C,MAAM,UAAU,yDAA2B;AAAA,IAC7C;AAAA,IACA,mBAAmB,CAAC,MAAM,aAAa,8DAAiB,CAAC;AAAA,IACzD,GAAG;AAAA,IACH,SAAS,CAAC,QAAQ,QAAQ,kBAAa,CAAC;AAAA,EAC1C;AACF;AAGO,SAAS,iBAAiB,KAAa,MAAsC;AAClF,QAAM,QAAQ,YAAY,GAAG;AAC7B,MAAI,CAAC,MAAO,QAAO,CAAC;AACpB,SAAO,MAAM,IAAI,MAAM,KAAK,WAAW,MAAM,IAAK,MAAM,OAAO,KAAK,CAAC,IAAK,CAAC;AAC7E;","names":["LoweringError","note","LoweringError"]}
|
|
1
|
+
{"version":3,"sources":["../src/capabilities.ts","../src/pi-lowering.ts","../src/from-stream.ts","../src/models.ts","../src/system-note.ts","../src/to-request.ts","../src/factories.ts","../src/loss-matrix.ts"],"sourcesContent":["/**\n * 按模型声明能力(技术方案 §11)。脑子模块只看这些布尔值,不看模型名。\n */\nimport type { LoweringCapabilities } from \"@reinsjs/core\"\nimport type { PiModel } from \"./models.js\"\n\n/**\n * S1 核实:Anthropic 带正文的中途 system 消息支持 Fable 5.1/5、Mythos 5.1/5、Opus 5/4.8;Sonnet 5 及更早不支持。\n * 按 id 前缀匹配,带日期后缀的 id(如 claude-opus-5-20260301)也能命中。\n */\nconst ANTHROPIC_MID_SYSTEM = /^claude-(fable-5|mythos-5|opus-5|opus-4-8)(-|$)/\n\n/** 调研核实:服务端 task budget 仅 Opus 5 与 Fable 5.1(DECISIONS 2026-09-08) */\nconst ANTHROPIC_TASK_BUDGET = /^claude-(opus-5|fable-5-1)(-|$)/\n\n/**\n * OpenAI Responses 只在请求带 reasoningEffort / reasoningSummary 时才开启 reasoning 并返回\n * encrypted_content(pi-ai 0.85.1 buildParams);否则 reasoning 关闭,没有可回放的东西。\n * 所以 thinkingReplay 在这家取决于请求选项,如实声明,脑子模块不必猜。\n */\nfunction openaiReasoningRequested(requestOptions: Record<string, unknown>): boolean {\n return Boolean(requestOptions.reasoningEffort || requestOptions.reasoningSummary)\n}\n\n/** 宿主在 ModelDefinition 里声明的能力,覆盖按 id 的推断 */\nexport interface CapabilityOverrides {\n midConversationSystem?: boolean\n}\n\nexport function capabilitiesOf(\n model: PiModel,\n requestOptions: Record<string, unknown> = {},\n overrides: CapabilityOverrides = {},\n): LoweringCapabilities {\n const caps = inferCapabilities(model, requestOptions)\n return overrides.midConversationSystem === undefined\n ? caps\n : { ...caps, midConversationSystem: overrides.midConversationSystem }\n}\n\nfunction inferCapabilities(model: PiModel, requestOptions: Record<string, unknown>): LoweringCapabilities {\n const base = {\n api: model.api,\n thinkingReplay: model.reasoning,\n parallelTools: true,\n // 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 type { CoreEventDraft, LoweringOutcome, LoweringStreamContext } from \"@reinsjs/core\"\nimport type { ModelOrigin } from \"./to-request.js\"\n\nexport function draftsOf(msg: AssistantMessage): CoreEventDraft[] {\n const origin: ModelOrigin = { provider: msg.provider, api: msg.api, model: msg.model }\n const drafts: CoreEventDraft[] = []\n for (const block of msg.content) {\n if (block.type === \"thinking\") {\n const replay: Record<string, unknown> = { ...origin }\n if (block.thinkingSignature) replay.thinkingSignature = block.thinkingSignature\n if (block.redacted) replay.redacted = true\n drafts.push({ type: \"core.model_thinking\", actor: \"model\", payload: { text: block.thinking }, replay })\n } else if (block.type === \"text\") {\n if (block.text.length === 0) continue\n const replay: Record<string, unknown> = { ...origin }\n if (block.textSignature) replay.textSignature = block.textSignature\n drafts.push({ type: \"core.model_text\", actor: \"model\", payload: { text: block.text }, replay })\n } else if (block.type === \"toolCall\") {\n const replay: Record<string, unknown> = { ...origin }\n if (block.thoughtSignature) replay.thoughtSignature = block.thoughtSignature\n if (block.namespace !== undefined) replay.namespace = block.namespace\n drafts.push({\n type: \"core.tool_call\",\n actor: \"model\",\n payload: { toolCallId: block.id, name: block.name, args: block.arguments },\n replay,\n })\n }\n }\n return drafts\n}\n\nfunction outcomeOf(msg: AssistantMessage, stopReason: LoweringOutcome[\"stopReason\"]): LoweringOutcome {\n const usage: LoweringOutcome[\"usage\"] = { input: msg.usage.input, output: msg.usage.output }\n if (msg.usage.cacheRead) usage.cacheRead = msg.usage.cacheRead\n if (msg.usage.cacheWrite) usage.cacheWrite = msg.usage.cacheWrite\n const out: LoweringOutcome = { stopReason, usage, costUsd: msg.usage.cost.total }\n if (msg.errorMessage) out.errorMessage = msg.errorMessage\n if (msg.responseModel) out.responseModel = msg.responseModel\n return out\n}\n\nexport async function* consumeStream(\n events: AsyncIterable<AssistantMessageEvent>,\n ctx: LoweringStreamContext = {},\n): AsyncGenerator<CoreEventDraft, LoweringOutcome> {\n for await (const ev of events) {\n switch (ev.type) {\n case \"text_delta\":\n ctx.onDelta?.({ kind: \"text\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"thinking_delta\":\n ctx.onDelta?.({ kind: \"thinking\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"toolcall_delta\":\n ctx.onDelta?.({ kind: \"tool_args\", index: ev.contentIndex, delta: ev.delta })\n break\n case \"done\": {\n yield* draftsOf(ev.message)\n // pi-ai 的 \"deferred\" 是异步批处理句柄,第一版不支持,按 stop 收尾并保留 rawStopReason 给排查\n const reason = ev.reason === \"deferred\" ? \"stop\" : ev.reason\n return outcomeOf(ev.message, reason)\n }\n case \"error\":\n yield* draftsOf(ev.error)\n return outcomeOf(ev.error, ev.reason)\n default:\n break\n }\n }\n return {\n stopReason: \"error\",\n usage: { input: 0, output: 0 },\n errorMessage: \"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 type { PiModel } from \"./models.js\"\nimport { framedSystemNote, markSystemNote } from \"./system-note.js\"\n\n/** 模型事件 replay 里记录的来源,产出与回放两头共用 */\nexport interface ModelOrigin {\n provider: string\n api: string\n model: string\n}\n\nexport interface ThinkingReplay extends Partial<ModelOrigin> {\n thinkingSignature?: string\n redacted?: boolean\n}\nexport interface TextReplay extends Partial<ModelOrigin> {\n textSignature?: string\n}\nexport interface ToolCallReplay extends Partial<ModelOrigin> {\n thoughtSignature?: string\n namespace?: string\n}\n\nconst ZERO_USAGE: AssistantMessage[\"usage\"] = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n}\n\nfunction toPiContent(\n parts: readonly ContentPart[],\n): (TextContent | { type: \"image\"; data: string; mimeType: string })[] {\n return parts.map((p) => {\n if (p.type === \"text\") return { type: \"text\", text: p.text }\n // 工具引用段(L1):pi-ai 的请求整形改不了,没有 defer_loading 落点,展开成文本\n if (p.type === \"tool_reference\") return { type: \"text\", text: renderToolReference(p) }\n return { type: \"image\", data: p.data, mimeType: p.mime }\n })\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction originOf(replay: Record<string, unknown> | undefined, fallback: PiModel): ModelOrigin {\n const r = (replay ?? {}) as Partial<ModelOrigin>\n return {\n provider: typeof r.provider === \"string\" ? r.provider : fallback.provider,\n api: typeof r.api === \"string\" ? r.api : fallback.api,\n model: typeof r.model === \"string\" ? r.model : fallback.id,\n }\n}\n\nfunction sameOrigin(a: ModelOrigin, b: ModelOrigin): boolean {\n return a.provider === b.provider && a.api === b.api && a.model === b.model\n}\n\n/**\n * 是否来自别家:只比 provider 与 api。响应里报告的模型 id 常与请求的不同(带日期后缀、别名、网关改名),\n * 同家同协议下签名仍可回放,不算有损,只在落点备注里留痕。\n */\nfunction foreignOrigin(a: ModelOrigin, target: ModelOrigin): boolean {\n return a.provider !== target.provider || a.api !== target.api\n}\n\nconst DEFERRED_NOTE =\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 msg: Message = { role: \"user\", content: toPiContent(c.parts), timestamp: e.at }\n // 工具结果还没到齐就来了用户消息:后移到同批结果之后,否则 tool_use 后面紧跟的不是 tool_result,厂商 400。\n // 顺序变了所以记 lossy;日志里它仍在原位\n if (awaiting.size > 0) {\n deferred.push({\n msg,\n event: e,\n kind: \"lossy\",\n landing: \"user\",\n note: c.escaped\n ? `the user message sits between a tool call and its results; ${ESCAPED_NOTE}`\n : \"the user message sits between a tool call and its results\",\n })\n break\n }\n messages.push(msg)\n if (c.escaped) land(e, \"lossy\", \"user\", ESCAPED_NOTE)\n else land(e, \"exact\", \"user\")\n break\n }\n\n case \"core.model_thinking\": {\n const origin = originOf(e.replay, model)\n const r = (e.replay ?? {}) as ThinkingReplay\n const block: ThinkingContent = { type: \"thinking\", thinking: e.payload.text }\n if (typeof r.thinkingSignature === \"string\") block.thinkingSignature = r.thinkingSignature\n if (r.redacted === true) block.redacted = true\n assistant(e, origin).content.push(block)\n if (!block.thinkingSignature)\n land(e, \"lossy\", \"text-or-drop\", \"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 messages.push({\n role: \"toolResult\",\n toolCallId: e.payload.toolCallId,\n toolName: e.payload.name,\n content: toPiContent(c.parts),\n isError: e.payload.isError,\n timestamp: e.at,\n })\n const landing = isAnthropic ? \"tool_result\" : \"function_call_output\"\n if (c.escaped) land(e, \"lossy\", landing, ESCAPED_NOTE)\n else land(e, \"exact\", landing)\n awaiting.delete(e.payload.toolCallId)\n if (awaiting.size === 0) releaseDeferred()\n break\n }\n\n case \"core.system_note\": {\n flush()\n // 宿主注入的外部内容可能把 system_note 标成 untrusted(如抓取的网页),同样包裹\n const t = text(e, e.payload.text)\n if (capabilities.midConversationSystem) {\n note(\n e,\n { role: \"user\", content: markSystemNote(t.text), timestamp: e.at },\n t.escaped ? \"lossy\" : \"exact\",\n isAnthropic ? \"system\" : model.reasoning ? \"developer\" : \"system\",\n t.escaped ? ESCAPED_NOTE : undefined,\n )\n } else {\n note(\n e,\n { role: \"user\", content: framedSystemNote(e.payload.kind, t.text), timestamp: e.at },\n \"lossy\",\n \"user-role\",\n \"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.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 * 一行拿到\"模型 + 降级层\":`anthropic(\"claude-opus-5\", { apiKey })`、`openai(\"gpt-5.5\", { apiKey })`。\n * 返回 BoundModel,直接给 `createAgent({ model })`;要更多控制(多模型共享一个降级层、自定义 fetch)就自己 new PiAiLowering。\n *\n * 本包不读环境变量(T7 决策),apiKey 必填、由宿主决定来源。\n * 带 baseUrl 即走代理 / 网关:此时按 ModelDefinition 登记,能力字段给了缺省值,可用 contextWindow 等覆盖。\n */\nimport type { BoundModel } from \"@reinsjs/core\"\nimport type { ModelDefinition } from \"./models.js\"\nimport { PiAiLowering, type PiAiLoweringOptions } from \"./pi-lowering.js\"\n\nexport interface BoundModelOptions {\n apiKey: string\n /** 代理或网关地址。Anthropic 在其后接 /v1/messages,OpenAI 接 /responses(网关请给到 …/v1) */\n baseUrl?: string\n /** 透传给 pi-ai 的请求选项(thinkingEnabled、reasoningEffort、maxTokens…) */\n requestOptions?: Record<string, unknown>\n /** 仅 baseUrl 模式下需要:模型能力。缺省 200k 窗口、16k 输出、支持推理与图片 */\n contextWindow?: number\n maxOutputTokens?: number\n reasoning?: boolean\n images?: boolean\n /** 仅 baseUrl 模式:上游是否接受中途 `role:\"system\"`(system_note 的 exact 落点)。第三方 Anthropic 兼容端口(如 DeepSeek)实测接受时置 true;缺省按不支持、以标签走 user */\n midConversationSystem?: boolean\n fetch?: typeof globalThis.fetch\n headers?: Record<string, string | null>\n /** trust 标注(§14):untrusted 内容包 <untrusted> 标记。缺省开;关掉是宿主自担风险 */\n trustMarkers?: boolean\n}\n\nfunction bound(\n provider: \"anthropic\" | \"openai\",\n api: string,\n id: string,\n opts: BoundModelOptions,\n): BoundModel {\n const models: ModelDefinition[] = opts.baseUrl\n ? [\n {\n provider,\n id,\n api,\n baseUrl: opts.baseUrl,\n reasoning: opts.reasoning ?? true,\n contextWindow: opts.contextWindow ?? 200_000,\n maxOutputTokens: opts.maxOutputTokens ?? 16_000,\n images: opts.images ?? true,\n ...(opts.midConversationSystem !== undefined\n ? { midConversationSystem: opts.midConversationSystem }\n : {}),\n },\n ]\n : []\n const loweringOpts: PiAiLoweringOptions = {\n apiKey: (p) => (p === provider ? opts.apiKey : undefined),\n models,\n ...(opts.requestOptions ? { requestOptions: () => opts.requestOptions ?? {} } : {}),\n ...(opts.fetch ? { fetch: opts.fetch } : {}),\n ...(opts.headers ? { headers: opts.headers } : {}),\n ...(opts.trustMarkers !== undefined ? { trustMarkers: opts.trustMarkers } : {}),\n }\n return { model: { provider, id }, lowering: new PiAiLowering(loweringOpts) }\n}\n\n/** Anthropic Messages。缺省开 thinking(模型不支持时 pi-ai 会忽略) */\nexport function anthropic(id: string, opts: BoundModelOptions): BoundModel {\n return bound(\"anthropic\", \"anthropic-messages\", id, {\n requestOptions: { thinkingEnabled: true },\n ...opts,\n })\n}\n\n/** OpenAI Responses。缺省 reasoningEffort=medium,这样才有可回放的 reasoning(见 T7 决策) */\nexport function openai(id: string, opts: BoundModelOptions): BoundModel {\n return bound(\"openai\", \"openai-responses\", id, {\n requestOptions: { reasoningEffort: \"medium\" },\n ...opts,\n })\n}\n","/**\n * 有损矩阵(P7:有损必声明)。api → 事件 type → 可能落点。\n *\n * 这是\"合同\":toRequest 对每条事件实际记录的落点必须是这里声明过的一种(T8 测试逐项断言)。\n * 新增事件类型或新 API 而不补这张表,测试就红 —— 宁可编译期/测试期吵,不要线上静默丢。\n */\nimport type { LandingSpec, LossMatrix } from \"@reinsjs/core\"\n\nconst exact = (landing: string, note?: string, when?: string): LandingSpec => {\n const spec: LandingSpec = { kind: \"exact\", landing }\n if (note) spec.note = note\n if (when) spec.when = when\n return spec\n}\nconst lossy = (landing: string, note: string, when?: string): LandingSpec =>\n when ? { kind: \"lossy\", landing, note, when } : { kind: \"lossy\", landing, note }\nconst dropped = (landing: string, note: string): LandingSpec => ({ kind: \"dropped\", landing, note })\n\n/** 两家共同的\"不下发\"事件:它们服务宿主与审计,信息由别的事件承载;投影默认已过滤,这里是第二道声明 */\nconst NOT_SENT: Readonly<Record<string, readonly LandingSpec[]>> = {\n \"core.approval_request\": [\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.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\nexport const LOSS_MATRIX: LossMatrix = {\n \"anthropic-messages\": {\n \"core.user_message\": [exact(\"user\"), USER_DEFERRED],\n \"core.model_text\": [exact(\"assistant-text\")],\n \"core.model_thinking\": [\n exact(\"thinking-block\", \"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\": [exact(\"tool_result\", \"in the user message right after the matching tool_use\")],\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\",\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],\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\": [exact(\"function_call_output\")],\n \"core.system_note\": [\n exact(\"developer\", \"reasoning models take the developer role\"),\n exact(\"system\", \"non-reasoning models take the system role\"),\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"],"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,GA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,2CAA2C;AAAA,IAC7D;AAAA,IACA,mBAAmB,CAAC,MAAM,aAAa,2CAA2C,CAAC;AAAA,IACnF,GAAG;AAAA,IACH,SAAS,CAAC,QAAQ,QAAQ,mBAAmB,CAAC;AAAA,EAChD;AACF;AAGO,SAAS,iBAAiB,KAAa,MAAsC;AAClF,QAAM,QAAQ,YAAY,GAAG;AAC7B,MAAI,CAAC,MAAO,QAAO,CAAC;AACpB,SAAO,MAAM,IAAI,MAAM,KAAK,WAAW,MAAM,IAAK,MAAM,OAAO,KAAK,CAAC,IAAK,CAAC;AAC7E;","names":["LoweringError","note","LoweringError"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reinsjs/lowering-pi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "reins — lowering layer on pi-ai: events ⇄ provider wire protocols (Anthropic Messages, OpenAI Responses)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|
|
@@ -31,14 +31,14 @@
|
|
|
31
31
|
"dist",
|
|
32
32
|
"CHANGELOG.md"
|
|
33
33
|
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "tsup"
|
|
36
|
+
},
|
|
34
37
|
"dependencies": {
|
|
35
38
|
"@earendil-works/pi-ai": "0.85.1",
|
|
36
|
-
"@reinsjs/core": "
|
|
39
|
+
"@reinsjs/core": "workspace:*"
|
|
37
40
|
},
|
|
38
41
|
"engines": {
|
|
39
42
|
"node": ">=22"
|
|
40
|
-
},
|
|
41
|
-
"scripts": {
|
|
42
|
-
"build": "tsup"
|
|
43
43
|
}
|
|
44
|
-
}
|
|
44
|
+
}
|