@reinsjs/adapter-tanstack-ai 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +52 -0
- package/dist/index.d.ts +339 -0
- package/dist/index.js +1365 -0
- package/dist/index.js.map +1 -0
- package/package.json +50 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @reinsjs/adapter-tanstack-ai
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- First public release.
|
|
8
|
+
|
|
9
|
+
- **Timeline first.** Append-only event log with `schemaVersion` on every event and fail-closed upcast on read; projection decides what the model sees each turn; replay and fork from the log alone.
|
|
10
|
+
- **A loop you can copy.** `runLoop` as an exported async generator: pause/resume is a return value with a small signed state, bounded retry on transient failures only while nothing has been written, tool pipeline `beforeTool → validate → approval → execute → afterTool`, sub-agent pause bubbling (`Interruption { kind: "subagent" }`).
|
|
11
|
+
- **Brain modules** (`@reinsjs/brain`): perception, compact (with folded-result manifest and `recall`; recommended on after measuring 100% recall at lower token cost on two model families), pins, spill, handoff, memory (`memory_20250818` shape, namespace isolation), approval (deny → ask → allow, fail-closed), budget (five limits, sub-agent usage included).
|
|
12
|
+
- **Lowering** (`@reinsjs/lowering-pi`): Anthropic Messages and OpenAI Responses via pi-ai with a declared loss matrix, trust markers on untrusted content, cache-breakpoint handling.
|
|
13
|
+
- **Serving** (`@reinsjs/server`, `@reinsjs/ui-agui`): Web-standard handler with SSE replay from `lastSeq`, per-session run lock, `authorizeSession` (only `true` allows), AG-UI as the first-class UI protocol.
|
|
14
|
+
- **Stores**: SQLite (`node:sqlite` / `bun:sqlite`) and Postgres (`pg` / PGlite), conformance-tested; configurable memory table for per-role isolation.
|
|
15
|
+
- **Tools**: MCP servers as one socket (`@reinsjs/tools-mcp`, tools bound per run, annotations as defaults not permissions); `asTool(agent)` in `reins`.
|
|
16
|
+
- **TanStack AI** middleware (`@reinsjs/adapter-tanstack-ai`): the brain on TanStack's loop with the log as the single source of truth; idempotent client-message import; runtime check for the approval interrupt.
|
|
17
|
+
- **Eval harness** (`@reinsjs/eval`): fixtures from real recordings, recorded tools, arm-vs-arm runner, metrics, the four-rule gate.
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- Updated dependencies
|
|
22
|
+
- @reinsjs/core@0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NewRate Limited
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# @reinsjs/adapter-tanstack-ai
|
|
2
|
+
|
|
3
|
+
Run the [reins](../../README.md) brain inside [TanStack AI](https://tanstack.com/ai)'s `chat()` as a middleware. TanStack drives the loop, executes tools and handles interrupts; reins keeps the event log as the single source of truth, projects it into what the model sees on every turn, and runs its brain modules (compaction, pins, spill, memory, approval, budget, perception) on TanStack's hooks.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add @reinsjs/adapter-tanstack-ai @tanstack/ai@0.53.0
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { reinsApprovalInterrupt, reinsMiddleware } from "@reinsjs/adapter-tanstack-ai"
|
|
11
|
+
import { approval, compact, perception, spill } from "@reinsjs/brain"
|
|
12
|
+
import { chat } from "@tanstack/ai"
|
|
13
|
+
|
|
14
|
+
const stream = chat({
|
|
15
|
+
adapter,
|
|
16
|
+
messages,
|
|
17
|
+
tools,
|
|
18
|
+
systemPrompts: ["You are…"],
|
|
19
|
+
middleware: [
|
|
20
|
+
reinsMiddleware({
|
|
21
|
+
sessionId,
|
|
22
|
+
log: store.log,
|
|
23
|
+
blobs: store.blobs,
|
|
24
|
+
sockets: [perception(), compact(), spill(), approval({ ask: ["deploy"] })],
|
|
25
|
+
capabilities: { contextWindow: 200_000 }, // TanStack does not tell middleware how big the window is
|
|
26
|
+
}),
|
|
27
|
+
],
|
|
28
|
+
interrupts: [reinsApprovalInterrupt], // required: dynamic approvals are a generic interrupt
|
|
29
|
+
})
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## What the middleware does
|
|
33
|
+
|
|
34
|
+
- **`onConfig(init)`** reads the log (fail-closed on unknown events), merges the brain's static tools and prompt fragment, and imports the client's new user messages. Import is idempotent: a network retry that re-sends the same request does not write the message twice (key = message `id` if present, else its position in the client array, plus exact content).
|
|
35
|
+
- **`onConfig(beforeModel)`** replaces `providerMessages` with the projection of the log — TanStack's own `messages` array only serves the UI.
|
|
36
|
+
- **`onChunk` / `onUsage`** append the model's blocks and a `budget_usage` event.
|
|
37
|
+
- **`onInterruptBoundary(beforeTools)`** runs the socket pipeline for every pending call; a `defer` becomes a `reinsApprovalInterrupt` so the run pauses and the client resumes it with `resume`. `onInterruptResolution` records the answer as `approval_decision`.
|
|
38
|
+
- **`onAfterToolCall` / `onToolPhaseComplete`** append results, including the ones TanStack handled itself (native `needsApproval`, client-side tools).
|
|
39
|
+
|
|
40
|
+
## Boundaries you should know
|
|
41
|
+
|
|
42
|
+
- **Register the interrupt.** If `reinsApprovalInterrupt` is missing from `chat({ interrupts })`, the type layer complains; at run time the middleware also checks the engine's registry, warns once, and treats every call that would need approval as **denied** (an `approval_decision` with `by: "reins"` is left in the log) instead of letting the engine throw mid-run.
|
|
43
|
+
- **`defer` pauses the whole tool batch**, not just the call that needs approval — that is where TanStack's boundary sits.
|
|
44
|
+
- **No `system` role.** `system_note` events travel as a framed `user` message and are declared lossy; thinking is replayed only with a same-provider signature. The complete table is `TANSTACK_LOSS_MATRIX`.
|
|
45
|
+
- **Sub-agent pause bubbling (`asTool`) is not available here.** A tool returning `subagentPause` is reported to the model as an error; the child session stays paused and can be resumed by the host.
|
|
46
|
+
- `@tanstack/ai` is pinned to an exact version because the middleware relies on hook contracts read from its source.
|
|
47
|
+
|
|
48
|
+
## Documentation
|
|
49
|
+
|
|
50
|
+
`docs/模块盘点/adapter-tanstack-ai.md` and `docs/技术方案.md` §2 / §11 — in Chinese, at the repository root.
|
|
51
|
+
|
|
52
|
+
MIT © 2026 NewRate Limited.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { EventDraft, ContentPart as ContentPart$1, LossKind, LandingRecord, ModelRef, Event, EventLog, BlobStore, MemoryStore, Socket, Principal, LoweringCapabilities, EventSchemaRegistry, ProjectionStrategy, TokenEstimator, MaybePromise, TokenUsage as TokenUsage$1, Tool, ToolContext, ToolResult } from '@reinsjs/core';
|
|
2
|
+
import * as _tanstack_ai from '@tanstack/ai';
|
|
3
|
+
import { StreamChunk, ContentPart, ModelMessage, ChatMiddleware, TokenUsage, AnyTool } from '@tanstack/ai';
|
|
4
|
+
import { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 把 TanStack 的流式 AG-UI chunk 拼成完整内容块的事件草稿(对应降级层"草稿只在内容块完整时产出"的约定)。
|
|
8
|
+
*
|
|
9
|
+
* 文本:TEXT_MESSAGE_START/CONTENT/END → model_text(END 时产出)。
|
|
10
|
+
* 思考:REASONING_* 的正文累积,签名可能在 REASONING_ENCRYPTED_VALUE(subtype=message) 或 STEP_FINISHED.signature 里、
|
|
11
|
+
* 且可能排在 REASONING_MESSAGE_END 之后,所以思考块在遇到下一个非思考 chunk(文本 / 工具调用 / 收尾)时才产出。
|
|
12
|
+
* 工具调用:TOOL_CALL_START/ARGS/END → tool_call(END 时产出,入参按 JSON 解析,解析不了原样存字符串);
|
|
13
|
+
* REASONING_ENCRYPTED_VALUE(subtype=tool-call) 是 Gemini 类的 thoughtSignature,写进 replay。
|
|
14
|
+
* replay 记 { provider, api, model }(与 lowering-pi 同字段),回放时据此判断签名能否复用。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
interface AssemblerOrigin {
|
|
18
|
+
provider: string;
|
|
19
|
+
api: string;
|
|
20
|
+
model: string;
|
|
21
|
+
}
|
|
22
|
+
declare class BlockAssembler {
|
|
23
|
+
private readonly origin;
|
|
24
|
+
private text;
|
|
25
|
+
private thinking;
|
|
26
|
+
private readonly calls;
|
|
27
|
+
/** 工具调用结束前先到的 thoughtSignature */
|
|
28
|
+
private readonly callSignatures;
|
|
29
|
+
constructor(origin: AssemblerOrigin);
|
|
30
|
+
/** 新一次模型响应开始前清空半成品(上一轮如有未收尾的块已由 finish 产出) */
|
|
31
|
+
reset(): void;
|
|
32
|
+
/** 喂一个 chunk,返回此刻完整了的块(0 或多条) */
|
|
33
|
+
push(chunk: StreamChunk): EventDraft[];
|
|
34
|
+
/** 收尾:把还没产出的块都产出(没等到 END 的文本、等签名的思考、没等到 END 的工具调用) */
|
|
35
|
+
finish(): EventDraft[];
|
|
36
|
+
private flushText;
|
|
37
|
+
private flushThinking;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 内容片段在 reins 与 TanStack AI 之间的互译。
|
|
42
|
+
*
|
|
43
|
+
* reins 只有两种片段:text(`text` 字段)与 image(base64 `data` + `mime`);TanStack 的 TextPart 用 `content`,
|
|
44
|
+
* 多媒体片段统一是 `{ source: { type: "data" | "url", value, mimeType } }`。能一一对应的逐字翻译,
|
|
45
|
+
* 对不上的(音频、视频、文档、URL 图片)以占位文本代替并在返回值里声明丢了什么(P7:有损必声明)。
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
interface ImportedContent {
|
|
49
|
+
parts: ContentPart$1[];
|
|
50
|
+
/** 无法翻译、只留下占位的片段说明 */
|
|
51
|
+
dropped: string[];
|
|
52
|
+
}
|
|
53
|
+
/** reins → TanStack:给 TanStack 工具结果与消息用 */
|
|
54
|
+
declare function toTanstackParts(parts: readonly ContentPart$1[]): ContentPart[];
|
|
55
|
+
/**
|
|
56
|
+
* reins → TanStack 的消息正文:全是文本时给单个字符串(多段以空行连接,这是 TanStack 消息的自然形态),
|
|
57
|
+
* 含图片时给片段数组。
|
|
58
|
+
*/
|
|
59
|
+
declare function toTanstackContent(parts: readonly ContentPart$1[]): string | ContentPart[];
|
|
60
|
+
/** TanStack → reins:导入客户端发来的消息与 TanStack 记录的工具结果 */
|
|
61
|
+
declare function fromTanstackContent(content: string | null | readonly ContentPart[] | undefined): ImportedContent;
|
|
62
|
+
/**
|
|
63
|
+
* TanStack 工具执行结果(任意值)→ reins 内容片段。TanStack 已把字符串结果尝试 JSON.parse 过,
|
|
64
|
+
* 所以这里拿到的多半是对象;能认出 ContentPart[] 的按片段翻译,其余 JSON 化成文本。
|
|
65
|
+
*/
|
|
66
|
+
declare function fromTanstackToolResult(result: unknown): ContentPart$1[];
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 手写的 Standard Schema(同时满足 StandardSchemaV1 与 StandardJSONSchemaV1)。
|
|
70
|
+
*
|
|
71
|
+
* TanStack 的 `defineInterrupt` 只接受 Standard Schema(zod / valibot / arktype 那类),不接受裸 JSON Schema 对象;
|
|
72
|
+
* 本包不想为两个小形状引入校验库,就按规范把 `~standard` 三件套(version / vendor / jsonSchema + validate)自己写出来。
|
|
73
|
+
* TanStack 用 `jsonSchema.input()` 算定义哈希与下发给客户端的 responseSchema,用 `validate()` 校验客户端回填。
|
|
74
|
+
*/
|
|
75
|
+
|
|
76
|
+
type ReinsSchema<T> = StandardJSONSchemaV1<T, T> & StandardSchemaV1<T, T>;
|
|
77
|
+
interface ReinsSchemaInit<T> {
|
|
78
|
+
jsonSchema: Record<string, unknown>;
|
|
79
|
+
/** 返回问题列表;空数组即通过 */
|
|
80
|
+
check(value: unknown): string[];
|
|
81
|
+
/** 通过后的规范化(缺省原样) */
|
|
82
|
+
parse?(value: unknown): T;
|
|
83
|
+
}
|
|
84
|
+
declare function reinsSchema<T>(init: ReinsSchemaInit<T>): ReinsSchema<T>;
|
|
85
|
+
|
|
86
|
+
declare const REINS_APPROVAL_INTERRUPT_ID = "reins.approval";
|
|
87
|
+
/** 下发给审批方看的内容:与 `approval_request` 事件同源,多带工具名与入参方便渲染 */
|
|
88
|
+
interface ReinsApprovalPayload {
|
|
89
|
+
toolCallId: string;
|
|
90
|
+
name: string;
|
|
91
|
+
args: unknown;
|
|
92
|
+
policyId: string;
|
|
93
|
+
summary: string;
|
|
94
|
+
}
|
|
95
|
+
/** 审批方的答复 */
|
|
96
|
+
interface ReinsApprovalResponse {
|
|
97
|
+
approved: boolean;
|
|
98
|
+
/** 谁批的;缺省记为 "tanstack" */
|
|
99
|
+
by?: string;
|
|
100
|
+
reason?: string;
|
|
101
|
+
}
|
|
102
|
+
declare const reinsApprovalInterrupt: Omit<_tanstack_ai.InterruptDefinition<"reins.approval", ReinsSchema<ReinsApprovalPayload>, ReinsSchema<ReinsApprovalResponse>, ReinsApprovalPayload, ReinsApprovalPayload>, "interrupt"> & {
|
|
103
|
+
interrupt: <TInput>(input: TInput & (TInput extends {
|
|
104
|
+
key: string;
|
|
105
|
+
reason: string;
|
|
106
|
+
message: string;
|
|
107
|
+
expiresAt?: string;
|
|
108
|
+
} & {
|
|
109
|
+
payload?: ReinsApprovalPayload;
|
|
110
|
+
} ? Exclude<keyof TInput, "message" | "reason" | "key" | "expiresAt" | "payload"> extends never ? unknown : { [K in Exclude<keyof TInput, "message" | "reason" | "key" | "expiresAt" | "payload">]: never; } : never)) => {
|
|
111
|
+
readonly definition: _tanstack_ai.InterruptDefinition<"reins.approval", ReinsSchema<ReinsApprovalPayload>, ReinsSchema<ReinsApprovalResponse>, ReinsApprovalPayload, ReinsApprovalPayload>;
|
|
112
|
+
readonly key: string;
|
|
113
|
+
readonly reason: string;
|
|
114
|
+
readonly message: string;
|
|
115
|
+
readonly expiresAt?: string;
|
|
116
|
+
} & {
|
|
117
|
+
readonly payload: ReinsApprovalPayload | undefined;
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
type ReinsApprovalInterrupt = typeof reinsApprovalInterrupt;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* TanStack AI 路径的有损矩阵:每种事件在 `toModelMessages` 里可能的落点(P7:有损必须声明,测试断言实际落点必在其中)。
|
|
124
|
+
* 与 lowering-pi 的 LossMatrix 同形(事件 type → 可能落点列表)。
|
|
125
|
+
*/
|
|
126
|
+
|
|
127
|
+
interface LossEntry {
|
|
128
|
+
kind: LossKind;
|
|
129
|
+
landing: string;
|
|
130
|
+
note?: string;
|
|
131
|
+
}
|
|
132
|
+
declare const TANSTACK_LOSS_MATRIX: Readonly<Record<string, readonly LossEntry[]>>;
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 事件 ⇄ TanStack `ModelMessage` 的翻译(角色只在这里出现 —— 宪法二)。
|
|
136
|
+
*
|
|
137
|
+
* 出口 `toModelMessages`:投影后的事件 → 交给 TanStack 适配器的 `providerMessages`,每条事件记一条落点。
|
|
138
|
+
* TanStack 的 ModelMessage 只有 user / assistant / tool 三种角色、assistant 正文是单个字符串,所以:
|
|
139
|
+
* - system_note 只能以 `<system_note kind=…>` 标签包住走 user 角色(lossy,与 lowering-pi 对不支持中途 system 的模型同一做法)
|
|
140
|
+
* - compaction 摘要走 user 文本(lossy)
|
|
141
|
+
* - 同一响应里多段 model_text 合成一个字符串(lossy,只在多段时)
|
|
142
|
+
* - thinking 只在签名来自同一 provider/model 时回放;无签名或来源不同一律不下发(dropped),
|
|
143
|
+
* 因为多数厂商会拒收无签名的 thinking 块,让适配器崩掉比丢一段思考更糟
|
|
144
|
+
* - 运维事件(审批、预算、暂停等)不下发(投影默认已过滤,这里兜底记 dropped)
|
|
145
|
+
*
|
|
146
|
+
* 入口 `importModelMessages`:客户端发来的 ModelMessage → 事件草稿,首次接入或续接新用户消息时用。
|
|
147
|
+
* 每条草稿的 `provenance.ref` 是幂等键(`importRef`):客户端消息自带 `id` 就用 id,否则用它在客户端数组里的位置;
|
|
148
|
+
* `dedupeImportedUserMessages` 据此把网络重试重发的用户消息挡在日志外(R5)。
|
|
149
|
+
*/
|
|
150
|
+
|
|
151
|
+
interface ToModelMessagesOptions {
|
|
152
|
+
/** 当前请求的模型;thinking 签名只对同一来源回放 */
|
|
153
|
+
model: ModelRef;
|
|
154
|
+
/** trust 标注(§14):untrusted 的内容包 <untrusted source=…>,与 lowering-pi 同一份 core 函数。缺省 true */
|
|
155
|
+
trustMarkers?: boolean;
|
|
156
|
+
}
|
|
157
|
+
interface LoweredMessages {
|
|
158
|
+
messages: ModelMessage[];
|
|
159
|
+
landings: LandingRecord[];
|
|
160
|
+
}
|
|
161
|
+
/** 不支持中途 system 的模型:用标签框住,让模型知道这不是用户说的(与 lowering-pi 的 framedSystemNote 同形) */
|
|
162
|
+
declare function framedSystemNote(kind: string, text: string): string;
|
|
163
|
+
declare const COMPACTION_PREFIX = "[Summary of earlier conversation]\n";
|
|
164
|
+
/** 事件 → TanStack ModelMessage[](纯函数) */
|
|
165
|
+
declare function toModelMessages(events: readonly Event[], opts: ToModelMessagesOptions): LoweredMessages;
|
|
166
|
+
interface ImportOrigin {
|
|
167
|
+
provider: string;
|
|
168
|
+
api: string;
|
|
169
|
+
model: string;
|
|
170
|
+
}
|
|
171
|
+
interface ImportedMessages {
|
|
172
|
+
drafts: EventDraft[];
|
|
173
|
+
/** 未能翻译的片段(类型名),供告警 */
|
|
174
|
+
dropped: string[];
|
|
175
|
+
}
|
|
176
|
+
interface ImportOptions {
|
|
177
|
+
/**
|
|
178
|
+
* `messages[0]` 在客户端完整消息数组里的下标。只导入末尾新消息时必须传,否则位置键会从 0 起算,
|
|
179
|
+
* 与首次整段导入时的键撞上(撞上也只是多比一次内容,不会误删)
|
|
180
|
+
*/
|
|
181
|
+
startIndex?: number;
|
|
182
|
+
}
|
|
183
|
+
/** 导入来源标识(`provenance.source`) */
|
|
184
|
+
declare const IMPORT_SOURCE = "tanstack-ai";
|
|
185
|
+
/**
|
|
186
|
+
* 客户端消息的幂等键(R5),落在草稿的 `provenance.ref`:
|
|
187
|
+
* - 客户端给了稳定 `id`(TanStack 持久化 / 水合会保留)→ `import:id:<id>`
|
|
188
|
+
* - 没给 → `import:<index>`,index 是它在客户端完整消息数组里的位置。客户端每次都把整段历史连同新消息一起发来,
|
|
189
|
+
* 数组只增不减,所以"同一位置 + 同一内容"就是同一条消息;客户端若自行裁剪历史,位置会漂,退化成不去重(今天的行为)
|
|
190
|
+
*/
|
|
191
|
+
declare function importRef(message: ModelMessage, index: number): string;
|
|
192
|
+
/**
|
|
193
|
+
* ModelMessage[] → 事件草稿。assistant 的 thinking 带签名时写进 replay(同 lowering-pi 的字段名),
|
|
194
|
+
* tool 消息的工具名从前面的 toolCalls 反查;解析不了的入参原样存字符串。
|
|
195
|
+
*/
|
|
196
|
+
declare function importModelMessages(messages: readonly ModelMessage[], origin: ImportOrigin, opts?: ImportOptions): ImportedMessages;
|
|
197
|
+
/** 工具入参字符串 → JSON 值;解析失败原样存字符串(日志存模型给的原样,校验在执行前做) */
|
|
198
|
+
declare function parseArgs(raw: string): unknown;
|
|
199
|
+
/**
|
|
200
|
+
* 找出客户端这次新带来的用户消息:末尾连续的 user 消息(最后一条 assistant / tool 之后的)。
|
|
201
|
+
* TanStack 客户端每次把整段历史连同新输入一起发来,历史部分日志里已经有了,只有这一截是新的。
|
|
202
|
+
*/
|
|
203
|
+
declare function trailingUserMessages(messages: readonly ModelMessage[]): ModelMessage[];
|
|
204
|
+
interface DedupedDrafts {
|
|
205
|
+
drafts: EventDraft[];
|
|
206
|
+
/** 被判定为重发而跳过的用户消息条数 */
|
|
207
|
+
skipped: number;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* 导入前去重(R5):草稿里的 `core.user_message` 若在日志里已有同源(`tanstack-ai`)、同幂等键、
|
|
211
|
+
* 且内容逐字相同的一条,就是网络重试 / 客户端重放带来的重发,跳过不入日志。
|
|
212
|
+
*
|
|
213
|
+
* 键相同但内容不同一律当新消息导入——位置键在客户端裁剪历史后会漂到别的消息上,宁可多记一条也不能丢用户说过的话。
|
|
214
|
+
* 内容比对用 `JSON.stringify`:两边都出自同一个翻译函数(键序一致),且 pg 侧刻意用 `json` 不用 `jsonb`(不重排键序),
|
|
215
|
+
* 比不上的后果只是退化成不去重。非 user 草稿(整段接管时的 assistant / tool)原样放行,它们只在日志为空时才会被导入。
|
|
216
|
+
*/
|
|
217
|
+
declare function dedupeImportedUserMessages(drafts: readonly EventDraft[], timeline: readonly Event[]): DedupedDrafts;
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* reins 脑子作为 TanStack AI 的 chat middleware(技术方案 §2"同一插座的三种宿主"、§7、B10)。
|
|
221
|
+
*
|
|
222
|
+
* 循环归 TanStack,日志仍是唯一真源(宪法二)。每个 `chat()` 调用是一次 run,钩子按下面的对应翻译成五个 Socket 方法:
|
|
223
|
+
*
|
|
224
|
+
* onConfig(init) 读日志(fail-closed 升级)→ 静态贡献并入工具表与系统提示 → 导入客户端新带来的用户消息
|
|
225
|
+
* onConfig(beforeModel) 投影 → Socket.beforeModel(emit 的说明本轮可见)→ 事件译成 providerMessages 交给适配器
|
|
226
|
+
* onChunk(modelStream) 流式 chunk 拼成完整块(model_text / model_thinking / tool_call)逐块入日志
|
|
227
|
+
* onUsage 本次请求用量 → budget_usage(带投影估算,供感知校准)
|
|
228
|
+
* onInterruptBoundary afterModel:Socket.afterModel;beforeTools:对每个待执行调用跑 Socket.beforeTool 管线,
|
|
229
|
+
* 结论缓存给 onBeforeToolCall,defer 以通用中断表达(run 暂停等审批)
|
|
230
|
+
* onBeforeToolCall 取缓存结论:block → skip(错误结果)、rewrite → transformArgs
|
|
231
|
+
* onAfterToolCall 结果草稿 → Socket.afterTool(外溢等可替换)→ 留痕先落、结果后落
|
|
232
|
+
* onToolPhaseComplete TanStack 自己处理掉的调用(原生审批拒绝、未知工具、客户端回填)补记结果;原生审批请求入日志
|
|
233
|
+
* onShouldContinue Socket.onTurnEnd:stop / pause / handoff 都让 TanStack 停下
|
|
234
|
+
* onInterruptResolution 审批答复 → approval_decision
|
|
235
|
+
* onAbort / onError run_paused(host) / core.error
|
|
236
|
+
*
|
|
237
|
+
* 与默认循环的已知差异(有损声明,见技术方案 §11 / DECISIONS):
|
|
238
|
+
* - TanStack 消息无 system 角色,system_note 以 <system_note> 标签走 user;thinking 无同源签名不下发
|
|
239
|
+
* - defer 让整轮工具都等审批(TanStack 在边界暂停不执行任何调用);默认循环会先执行不需审批的
|
|
240
|
+
* - onTurnEnd 的 "continue" 只在 TanStack 自己也想继续时生效;pause 表现为 run 正常结束 + run_paused 事件
|
|
241
|
+
* - handoff 只做记录与新会话开头,宿主在下一次请求里改用新 sessionId
|
|
242
|
+
* - 模型看到的是日志投影(providerMessages),TanStack 自己的 messages 数组只给客户端 UI 与它的内部对账用
|
|
243
|
+
*/
|
|
244
|
+
|
|
245
|
+
/** TanStack 原生审批(工具静态 needsApproval)在日志里的策略标识 */
|
|
246
|
+
declare const TANSTACK_APPROVAL_POLICY = "tanstack.needsApproval";
|
|
247
|
+
/** 审批答复者缺省标识 */
|
|
248
|
+
declare const TANSTACK_DECIDER = "tanstack";
|
|
249
|
+
/** 本适配器给 replay.api 与 error.category 用的标识 */
|
|
250
|
+
declare const TANSTACK_API = "tanstack-ai";
|
|
251
|
+
interface ReinsMiddlewareOptions {
|
|
252
|
+
sessionId: string;
|
|
253
|
+
log: EventLog;
|
|
254
|
+
blobs?: BlobStore;
|
|
255
|
+
memory?: MemoryStore;
|
|
256
|
+
sockets?: readonly Socket[];
|
|
257
|
+
principal?: Principal;
|
|
258
|
+
/**
|
|
259
|
+
* 模型能力。TanStack 不告诉中间件上下文窗口有多大,而投影裁剪、感知、预算全靠它,所以 contextWindow 必填;
|
|
260
|
+
* 其余缺省按"只有 user / assistant / tool 三角色"的最保守值填
|
|
261
|
+
*/
|
|
262
|
+
capabilities: Partial<LoweringCapabilities> & {
|
|
263
|
+
contextWindow: number;
|
|
264
|
+
};
|
|
265
|
+
/** 缺省内置 core 注册表;有 ext.* 事件时传自己的 */
|
|
266
|
+
registry?: EventSchemaRegistry;
|
|
267
|
+
projection?: {
|
|
268
|
+
strategies?: readonly ProjectionStrategy[];
|
|
269
|
+
estimate?: TokenEstimator;
|
|
270
|
+
reserveTokens?: number;
|
|
271
|
+
};
|
|
272
|
+
/** 每次请求的落点(有损与丢弃在此可见) */
|
|
273
|
+
onLandings?: (records: LandingRecord[]) => void;
|
|
274
|
+
/** 每条刚 append 的事件(宿主拿去推前端、审计) */
|
|
275
|
+
onEvent?: (event: Event) => void;
|
|
276
|
+
/** 交接后宿主重绑会话(下一次请求用新 sessionId) */
|
|
277
|
+
onHandoff?: (fromSessionId: string, toSessionId: string) => MaybePromise<void>;
|
|
278
|
+
/**
|
|
279
|
+
* 是否把非正文类事件(system_note、compaction、审批、预算、暂停…)作为 AG-UI `CUSTOM` chunk 推进 TanStack 流:
|
|
280
|
+
* name = 事件 type,value = 事件本身(与 @reinsjs/ui-agui 的约定一致)。正文类事件 TanStack 自己已经在流里了。缺省开
|
|
281
|
+
*/
|
|
282
|
+
emitCustomEvents?: boolean;
|
|
283
|
+
/**
|
|
284
|
+
* 告警出口,缺省 console.warn。会告警的降级:审批中断未登记到 `chat({ interrupts })`(需审批的调用按拒绝处理,R7)、
|
|
285
|
+
* 导入客户端消息时有片段翻不动、客户端重发的用户消息被跳过(R5)。缺 BlobStore 由 spill 模块自己告警,不在这里
|
|
286
|
+
*/
|
|
287
|
+
warn?: (message: string) => void;
|
|
288
|
+
/** 工具表与上一次 run 相比有增删时追加模型可见的说明(P1,缺省开);快照事件 `core.tools_bound` 一律记 */
|
|
289
|
+
announceToolChanges?: boolean;
|
|
290
|
+
/** trust 标注(技术方案 §14):untrusted 内容(工具输出)翻译时包 `<untrusted source=…>`。缺省开;关掉是宿主自担提示注入风险 */
|
|
291
|
+
trustMarkers?: boolean;
|
|
292
|
+
/** 测试注入 */
|
|
293
|
+
now?: () => number;
|
|
294
|
+
newId?: (at: number) => string;
|
|
295
|
+
}
|
|
296
|
+
/** 本包给 TanStack 的中间件类型:声明会发出 reins 审批中断,`chat({ interrupts })` 未登记时类型层就会提示 */
|
|
297
|
+
type ReinsChatMiddleware = ChatMiddleware<unknown, ReinsApprovalInterrupt>;
|
|
298
|
+
/** TanStack 用量(promptTokens 含缓存部分)→ reins 用量(input 不含缓存读写,Anthropic 口径) */
|
|
299
|
+
declare function toReinsUsage(u: TokenUsage): TokenUsage$1;
|
|
300
|
+
/**
|
|
301
|
+
* 造一个 reins 中间件。放在宿主其它中间件之后一般最合适:它改 providerMessages / tools / systemPrompts,
|
|
302
|
+
* 后面的中间件看到的就是模型真正收到的。
|
|
303
|
+
*/
|
|
304
|
+
declare function reinsMiddleware(options: ReinsMiddlewareOptions): ReinsChatMiddleware;
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* 工具在两边的桥接。
|
|
308
|
+
*
|
|
309
|
+
* - TanStack 宿主工具 → reins **只读视图**:Socket(审批策略、外溢等)要看工具的名字、schema、风险、是否要审批;
|
|
310
|
+
* 视图不带 execute,执行仍由 TanStack 做。视图打上 NATIVE_TOOL 标记,适配器据此不重复做 TanStack 已经做的事
|
|
311
|
+
* (静态 needsApproval 由 TanStack 自己的审批中断处理)。
|
|
312
|
+
* - reins 工具(脑子模块的 compact / pin / fetch_blob / memory / handoff …)→ TanStack 工具:把 execute 包一层,
|
|
313
|
+
* 造出 reins 的 ToolContext(toolCallId、存储、emit 留痕),结果按 reins 规则归一后存进 bridge.outputs,
|
|
314
|
+
* afterTool 钩子从那里拿到精确的 content / isError,而不是 TanStack JSON 化之后的形态。
|
|
315
|
+
*/
|
|
316
|
+
|
|
317
|
+
/** 视图标记:这是 TanStack 宿主工具在 reins 这边的影子,不由 reins 执行 */
|
|
318
|
+
declare const NATIVE_TOOL: unique symbol;
|
|
319
|
+
type NativeToolView = Tool & {
|
|
320
|
+
[NATIVE_TOOL]: true;
|
|
321
|
+
};
|
|
322
|
+
declare function isNativeToolView(tool: Tool | undefined): tool is NativeToolView;
|
|
323
|
+
/** TanStack 工具 → reins 只读视图 */
|
|
324
|
+
declare function viewOfTanstackTool(tool: AnyTool): NativeToolView;
|
|
325
|
+
/** 包装 reins 工具时需要的运行环境 */
|
|
326
|
+
interface ToolBridge {
|
|
327
|
+
sessionId: string;
|
|
328
|
+
toolContextBase: Omit<ToolContext, "toolCallId" | "signal" | "emit">;
|
|
329
|
+
emit(draft: Parameters<ToolContext["emit"]>[0]): void;
|
|
330
|
+
/** 按 toolCallId 存归一后的结果,供 afterTool 精确取用 */
|
|
331
|
+
outputs: Map<string, ToolResult>;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* reins 工具 → TanStack 工具。`needsApproval` 只透传布尔形态(TanStack 只认布尔);函数形态由适配器在
|
|
335
|
+
* beforeTools 边界按 runLoop 的规则判定(circular:见 middleware 的 beforeTools)。
|
|
336
|
+
*/
|
|
337
|
+
declare function toTanstackTool(tool: Tool, bridge: ToolBridge): AnyTool;
|
|
338
|
+
|
|
339
|
+
export { type AssemblerOrigin, BlockAssembler, COMPACTION_PREFIX, type DedupedDrafts, IMPORT_SOURCE, type ImportOptions, type ImportOrigin, type ImportedMessages, type LossEntry, type LoweredMessages, NATIVE_TOOL, type NativeToolView, REINS_APPROVAL_INTERRUPT_ID, type ReinsApprovalInterrupt, type ReinsApprovalPayload, type ReinsApprovalResponse, type ReinsChatMiddleware, type ReinsMiddlewareOptions, type ReinsSchema, type ReinsSchemaInit, TANSTACK_API, TANSTACK_APPROVAL_POLICY, TANSTACK_DECIDER, TANSTACK_LOSS_MATRIX, type ToModelMessagesOptions, type ToolBridge, dedupeImportedUserMessages, framedSystemNote, fromTanstackContent, fromTanstackToolResult, importModelMessages, importRef, isNativeToolView, parseArgs, reinsApprovalInterrupt, reinsMiddleware, reinsSchema, toModelMessages, toReinsUsage, toTanstackContent, toTanstackParts, toTanstackTool, trailingUserMessages, viewOfTanstackTool };
|