@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/dist/index.js
ADDED
|
@@ -0,0 +1,1365 @@
|
|
|
1
|
+
// src/messages.ts
|
|
2
|
+
import {
|
|
3
|
+
markUntrusted,
|
|
4
|
+
markUntrustedText,
|
|
5
|
+
needsUntrustedMark,
|
|
6
|
+
untrustedSourceOf
|
|
7
|
+
} from "@reinsjs/core";
|
|
8
|
+
|
|
9
|
+
// src/content.ts
|
|
10
|
+
function toTanstackParts(parts) {
|
|
11
|
+
return parts.map((p) => {
|
|
12
|
+
if (p.type === "text") return { type: "text", content: p.text };
|
|
13
|
+
return { type: "image", source: { type: "data", value: p.data, mimeType: p.mime } };
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function toTanstackContent(parts) {
|
|
17
|
+
if (parts.every((p) => p.type === "text"))
|
|
18
|
+
return parts.map((p) => p.type === "text" ? p.text : "").join("\n\n");
|
|
19
|
+
return toTanstackParts(parts);
|
|
20
|
+
}
|
|
21
|
+
function fromTanstackContent(content) {
|
|
22
|
+
if (content === null || content === void 0) return { parts: [], dropped: [] };
|
|
23
|
+
if (typeof content === "string") return { parts: [{ type: "text", text: content }], dropped: [] };
|
|
24
|
+
const parts = [];
|
|
25
|
+
const dropped2 = [];
|
|
26
|
+
for (const p of content) {
|
|
27
|
+
if (p.type === "text") {
|
|
28
|
+
parts.push({ type: "text", text: p.content });
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (p.type === "image" && p.source.type === "data") {
|
|
32
|
+
parts.push({ type: "image", mime: p.source.mimeType, data: p.source.value });
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const what = p.type === "image" ? "image(url)" : p.type;
|
|
36
|
+
dropped2.push(what);
|
|
37
|
+
parts.push({ type: "text", text: `[${what} \u7247\u6BB5\u672A\u80FD\u5BFC\u5165 reins \u65F6\u95F4\u7EBF]` });
|
|
38
|
+
}
|
|
39
|
+
return { parts, dropped: dropped2 };
|
|
40
|
+
}
|
|
41
|
+
function fromTanstackToolResult(result) {
|
|
42
|
+
if (typeof result === "string") return [{ type: "text", text: result }];
|
|
43
|
+
if (result === void 0 || result === null) return [{ type: "text", text: "" }];
|
|
44
|
+
if (Array.isArray(result) && result.length > 0 && result.every(isTanstackPart))
|
|
45
|
+
return fromTanstackContent(result).parts;
|
|
46
|
+
const json = JSON.stringify(result);
|
|
47
|
+
return [{ type: "text", text: typeof json === "string" ? json : String(result) }];
|
|
48
|
+
}
|
|
49
|
+
function isTanstackPart(x) {
|
|
50
|
+
if (typeof x !== "object" || x === null) return false;
|
|
51
|
+
const p = x;
|
|
52
|
+
if (p.type === "text") return typeof p.content === "string";
|
|
53
|
+
return (p.type === "image" || p.type === "audio" || p.type === "video" || p.type === "document") && typeof p.source === "object" && p.source !== null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/messages.ts
|
|
57
|
+
function framedSystemNote(kind, text) {
|
|
58
|
+
return `<system_note kind="${kind}">
|
|
59
|
+
${text}
|
|
60
|
+
</system_note>`;
|
|
61
|
+
}
|
|
62
|
+
var COMPACTION_PREFIX = "[Summary of earlier conversation]\n";
|
|
63
|
+
var DEFERRED_NOTE = "\u5DF2\u540E\u79FB\u5230\u540C\u6279\u5DE5\u5177\u7ED3\u679C\u4E4B\u540E\uFF08\u5DE5\u5177\u7ED3\u679C\u5FC5\u987B\u7D27\u8DDF\u8C03\u7528\uFF09";
|
|
64
|
+
var ESCAPED_NOTE = "\u4E0D\u53EF\u4FE1\u5185\u5BB9\u91CC\u542B\u63D0\u524D\u95ED\u5408\u7684 </untrusted\uFF0C\u5DF2\u8F6C\u4E49";
|
|
65
|
+
function toModelMessages(events, opts) {
|
|
66
|
+
const messages = [];
|
|
67
|
+
const landings = [];
|
|
68
|
+
let group;
|
|
69
|
+
const awaiting = /* @__PURE__ */ new Set();
|
|
70
|
+
const deferred = [];
|
|
71
|
+
const trustMarkers = opts.trustMarkers !== false;
|
|
72
|
+
const content = (e, parts) => trustMarkers && needsUntrustedMark(e) ? markUntrusted(parts, untrustedSourceOf(e)) : { parts, escaped: false };
|
|
73
|
+
const text = (e, s) => trustMarkers && needsUntrustedMark(e) ? markUntrustedText(s, untrustedSourceOf(e)) : { text: s, escaped: false };
|
|
74
|
+
const land = (e, kind, landing, note2) => {
|
|
75
|
+
landings.push(
|
|
76
|
+
note2 ? { eventId: e.id, type: e.type, kind, landing, note: note2 } : { eventId: e.id, type: e.type, kind, landing }
|
|
77
|
+
);
|
|
78
|
+
};
|
|
79
|
+
const releaseDeferred = () => {
|
|
80
|
+
for (const d of deferred) {
|
|
81
|
+
messages.push(d.msg);
|
|
82
|
+
land(d.event, "lossy", d.landing, `${d.note}\uFF1B${DEFERRED_NOTE}`);
|
|
83
|
+
}
|
|
84
|
+
deferred.length = 0;
|
|
85
|
+
};
|
|
86
|
+
const note = (e, msg, landing, why) => {
|
|
87
|
+
if (awaiting.size > 0) {
|
|
88
|
+
deferred.push({ msg, event: e, landing, note: why });
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
messages.push(msg);
|
|
92
|
+
land(e, "lossy", landing, why);
|
|
93
|
+
};
|
|
94
|
+
const settleAwaiting = () => {
|
|
95
|
+
awaiting.clear();
|
|
96
|
+
releaseDeferred();
|
|
97
|
+
};
|
|
98
|
+
const flush = () => {
|
|
99
|
+
if (!group) return;
|
|
100
|
+
const g = group;
|
|
101
|
+
group = void 0;
|
|
102
|
+
if (g.texts.length === 0 && g.thinking.length === 0 && g.toolCalls.length === 0) return;
|
|
103
|
+
const msg = { role: "assistant", content: g.texts.length > 0 ? g.texts.join("\n\n") : null };
|
|
104
|
+
if (g.thinking.length > 0) msg.thinking = g.thinking;
|
|
105
|
+
if (g.toolCalls.length > 0) msg.toolCalls = g.toolCalls;
|
|
106
|
+
messages.push(msg);
|
|
107
|
+
for (const c of g.toolCalls) awaiting.add(c.id);
|
|
108
|
+
if (g.textEvents.length > 1)
|
|
109
|
+
for (const e of g.textEvents) land(e, "lossy", "merged-text", "\u540C\u4E00\u54CD\u5E94\u7684\u591A\u6BB5\u6B63\u6587\u5408\u6210\u4E00\u4E2A\u5B57\u7B26\u4E32");
|
|
110
|
+
else for (const e of g.textEvents) land(e, "exact", "assistant-text");
|
|
111
|
+
};
|
|
112
|
+
const assistant = () => {
|
|
113
|
+
if (!group) {
|
|
114
|
+
settleAwaiting();
|
|
115
|
+
group = { texts: [], thinking: [], toolCalls: [], textEvents: [] };
|
|
116
|
+
}
|
|
117
|
+
return group;
|
|
118
|
+
};
|
|
119
|
+
for (const raw of events) {
|
|
120
|
+
const e = raw;
|
|
121
|
+
switch (e.type) {
|
|
122
|
+
case "core.user_message": {
|
|
123
|
+
flush();
|
|
124
|
+
const c = content(e, e.payload.content);
|
|
125
|
+
const msg = { role: "user", content: toTanstackContent(c.parts) };
|
|
126
|
+
if (awaiting.size > 0) {
|
|
127
|
+
deferred.push({
|
|
128
|
+
msg,
|
|
129
|
+
event: e,
|
|
130
|
+
landing: "user",
|
|
131
|
+
note: c.escaped ? `\u7528\u6237\u6D88\u606F\u843D\u5728\u5DE5\u5177\u8C03\u7528\u4E0E\u7ED3\u679C\u4E4B\u95F4\uFF1B${ESCAPED_NOTE}` : "\u7528\u6237\u6D88\u606F\u843D\u5728\u5DE5\u5177\u8C03\u7528\u4E0E\u7ED3\u679C\u4E4B\u95F4"
|
|
132
|
+
});
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
messages.push(msg);
|
|
136
|
+
if (c.escaped) land(e, "lossy", "user", ESCAPED_NOTE);
|
|
137
|
+
else land(e, "exact", "user");
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
case "core.model_text":
|
|
141
|
+
assistant().texts.push(e.payload.text);
|
|
142
|
+
assistant().textEvents.push(e);
|
|
143
|
+
break;
|
|
144
|
+
case "core.model_thinking": {
|
|
145
|
+
const r = e.replay ?? {};
|
|
146
|
+
const sameOrigin = r.provider === opts.model.provider && r.model === opts.model.id;
|
|
147
|
+
if (typeof r.thinkingSignature === "string" && sameOrigin) {
|
|
148
|
+
assistant().thinking.push({ content: e.payload.text, signature: r.thinkingSignature });
|
|
149
|
+
land(e, "exact", "thinking");
|
|
150
|
+
} else if (typeof r.thinkingSignature === "string") {
|
|
151
|
+
land(
|
|
152
|
+
e,
|
|
153
|
+
"dropped",
|
|
154
|
+
"none",
|
|
155
|
+
`\u7B7E\u540D\u6765\u81EA ${String(r.provider)}/${String(r.model)}\uFF0C\u5F53\u524D\u8BF7\u6C42 ${opts.model.provider}/${opts.model.id}\uFF0C\u4E0D\u56DE\u653E`
|
|
156
|
+
);
|
|
157
|
+
} else {
|
|
158
|
+
land(e, "dropped", "none", "\u65E0\u7B7E\u540D\u7684 thinking \u4E0D\u4E0B\u53D1\uFF08\u5382\u5546\u4F1A\u62D2\u6536\uFF09");
|
|
159
|
+
}
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
case "core.tool_call": {
|
|
163
|
+
const r = e.replay ?? {};
|
|
164
|
+
const call = {
|
|
165
|
+
id: e.payload.toolCallId,
|
|
166
|
+
type: "function",
|
|
167
|
+
function: { name: e.payload.name, arguments: JSON.stringify(e.payload.args ?? {}) }
|
|
168
|
+
};
|
|
169
|
+
if (typeof r.thoughtSignature === "string") call.metadata = { thoughtSignature: r.thoughtSignature };
|
|
170
|
+
assistant().toolCalls.push(call);
|
|
171
|
+
land(e, "exact", "tool-call");
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
case "core.tool_result": {
|
|
175
|
+
flush();
|
|
176
|
+
const c = content(e, e.payload.content);
|
|
177
|
+
const msg = {
|
|
178
|
+
role: "tool",
|
|
179
|
+
toolCallId: e.payload.toolCallId,
|
|
180
|
+
name: e.payload.name,
|
|
181
|
+
content: toTanstackContent(c.parts)
|
|
182
|
+
};
|
|
183
|
+
if (e.payload.isError) {
|
|
184
|
+
msg.error = textOf(c.parts);
|
|
185
|
+
land(
|
|
186
|
+
e,
|
|
187
|
+
"lossy",
|
|
188
|
+
"tool-error-field",
|
|
189
|
+
c.escaped ? `isError \u53EA\u843D\u5728 ModelMessage.error \u5B57\u6BB5\uFF0C\u662F\u5426\u544A\u77E5\u6A21\u578B\u53D6\u51B3\u4E8E\u9002\u914D\u5668\uFF1B${ESCAPED_NOTE}` : "isError \u53EA\u843D\u5728 ModelMessage.error \u5B57\u6BB5\uFF0C\u662F\u5426\u544A\u77E5\u6A21\u578B\u53D6\u51B3\u4E8E\u9002\u914D\u5668"
|
|
190
|
+
);
|
|
191
|
+
} else if (c.escaped) land(e, "lossy", "tool", ESCAPED_NOTE);
|
|
192
|
+
else land(e, "exact", "tool");
|
|
193
|
+
messages.push(msg);
|
|
194
|
+
awaiting.delete(e.payload.toolCallId);
|
|
195
|
+
if (awaiting.size === 0) releaseDeferred();
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
case "core.system_note":
|
|
199
|
+
flush();
|
|
200
|
+
note(
|
|
201
|
+
e,
|
|
202
|
+
{ role: "user", content: framedSystemNote(e.payload.kind, text(e, e.payload.text).text) },
|
|
203
|
+
"user-role",
|
|
204
|
+
"TanStack \u6D88\u606F\u65E0 system \u89D2\u8272\uFF0C\u4EE5 <system_note> \u6807\u7B7E\u5305\u4F4F\u8D70 user"
|
|
205
|
+
);
|
|
206
|
+
break;
|
|
207
|
+
case "core.compaction":
|
|
208
|
+
flush();
|
|
209
|
+
note(
|
|
210
|
+
e,
|
|
211
|
+
{ role: "user", content: `${COMPACTION_PREFIX}${text(e, e.payload.summary).text}` },
|
|
212
|
+
"user-text",
|
|
213
|
+
"\u6458\u8981\u4EE5 user \u89D2\u8272\u6587\u672C\u5448\u73B0"
|
|
214
|
+
);
|
|
215
|
+
break;
|
|
216
|
+
case "core.approval_request":
|
|
217
|
+
case "core.approval_decision":
|
|
218
|
+
case "core.run_paused":
|
|
219
|
+
case "core.run_resumed":
|
|
220
|
+
case "core.budget_usage":
|
|
221
|
+
case "core.memory_op":
|
|
222
|
+
case "core.handoff":
|
|
223
|
+
case "core.error":
|
|
224
|
+
land(e, "dropped", "none", "\u8FD0\u7EF4\u4E8B\u4EF6\u4E0D\u4E0B\u53D1\uFF08\u6295\u5F71\u9ED8\u8BA4\u5DF2\u8FC7\u6EE4\uFF09");
|
|
225
|
+
break;
|
|
226
|
+
default:
|
|
227
|
+
land(raw, "dropped", "none", `\u65E0\u901A\u7528\u843D\u70B9\uFF1A${raw.type}`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
flush();
|
|
231
|
+
releaseDeferred();
|
|
232
|
+
return { messages, landings };
|
|
233
|
+
}
|
|
234
|
+
function textOf(parts) {
|
|
235
|
+
return parts.map((p) => p.type === "text" ? p.text : `[image ${p.mime}]`).join("\n");
|
|
236
|
+
}
|
|
237
|
+
var IMPORT_SOURCE = "tanstack-ai";
|
|
238
|
+
function importRef(message, index) {
|
|
239
|
+
return message.id !== void 0 && message.id !== "" ? `import:id:${message.id}` : `import:${index}`;
|
|
240
|
+
}
|
|
241
|
+
function importModelMessages(messages, origin, opts = {}) {
|
|
242
|
+
const drafts = [];
|
|
243
|
+
const dropped2 = [];
|
|
244
|
+
const names = /* @__PURE__ */ new Map();
|
|
245
|
+
const startIndex = opts.startIndex ?? 0;
|
|
246
|
+
for (const [i, m] of messages.entries()) {
|
|
247
|
+
const provenance = { source: IMPORT_SOURCE, ref: importRef(m, startIndex + i) };
|
|
248
|
+
if (m.role === "user") {
|
|
249
|
+
const c = fromTanstackContent(m.content);
|
|
250
|
+
dropped2.push(...c.dropped);
|
|
251
|
+
drafts.push({ type: "core.user_message", actor: "user", payload: { content: c.parts }, provenance });
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (m.role === "assistant") {
|
|
255
|
+
for (const t of m.thinking ?? []) {
|
|
256
|
+
const replay = { ...origin };
|
|
257
|
+
if (t.signature) replay.thinkingSignature = t.signature;
|
|
258
|
+
drafts.push({
|
|
259
|
+
type: "core.model_thinking",
|
|
260
|
+
actor: "model",
|
|
261
|
+
payload: { text: t.content },
|
|
262
|
+
replay,
|
|
263
|
+
provenance
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
if (typeof m.content === "string" && m.content.length > 0)
|
|
267
|
+
drafts.push({
|
|
268
|
+
type: "core.model_text",
|
|
269
|
+
actor: "model",
|
|
270
|
+
payload: { text: m.content },
|
|
271
|
+
replay: { ...origin },
|
|
272
|
+
provenance
|
|
273
|
+
});
|
|
274
|
+
else if (Array.isArray(m.content)) {
|
|
275
|
+
const c = fromTanstackContent(m.content);
|
|
276
|
+
dropped2.push(...c.dropped);
|
|
277
|
+
const text = c.parts.map((p) => p.type === "text" ? p.text : "").join("\n");
|
|
278
|
+
if (text)
|
|
279
|
+
drafts.push({
|
|
280
|
+
type: "core.model_text",
|
|
281
|
+
actor: "model",
|
|
282
|
+
payload: { text },
|
|
283
|
+
replay: { ...origin },
|
|
284
|
+
provenance
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
for (const call of m.toolCalls ?? []) {
|
|
288
|
+
names.set(call.id, call.function.name);
|
|
289
|
+
const payload = {
|
|
290
|
+
toolCallId: call.id,
|
|
291
|
+
name: call.function.name,
|
|
292
|
+
args: parseArgs(call.function.arguments)
|
|
293
|
+
};
|
|
294
|
+
drafts.push({ type: "core.tool_call", actor: "model", payload, replay: { ...origin }, provenance });
|
|
295
|
+
}
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
if (m.role === "tool" && m.toolCallId) {
|
|
299
|
+
const c = fromTanstackContent(m.content);
|
|
300
|
+
dropped2.push(...c.dropped);
|
|
301
|
+
const name = names.get(m.toolCallId) ?? m.name ?? "unknown";
|
|
302
|
+
drafts.push({
|
|
303
|
+
type: "core.tool_result",
|
|
304
|
+
actor: "tool",
|
|
305
|
+
provenance: { source: name, ref: "tanstack-ai:import" },
|
|
306
|
+
payload: { toolCallId: m.toolCallId, name, content: c.parts, isError: typeof m.error === "string" }
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return { drafts, dropped: dropped2 };
|
|
311
|
+
}
|
|
312
|
+
function parseArgs(raw) {
|
|
313
|
+
const s = raw.trim();
|
|
314
|
+
if (s === "") return {};
|
|
315
|
+
try {
|
|
316
|
+
return JSON.parse(s);
|
|
317
|
+
} catch {
|
|
318
|
+
return raw;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function trailingUserMessages(messages) {
|
|
322
|
+
let i = messages.length;
|
|
323
|
+
while (i > 0 && messages[i - 1]?.role === "user") i--;
|
|
324
|
+
return messages.slice(i);
|
|
325
|
+
}
|
|
326
|
+
function dedupeImportedUserMessages(drafts, timeline) {
|
|
327
|
+
const seen = /* @__PURE__ */ new Map();
|
|
328
|
+
for (const e of timeline) {
|
|
329
|
+
if (e.type !== "core.user_message" || e.provenance?.source !== IMPORT_SOURCE || e.provenance.ref === void 0)
|
|
330
|
+
continue;
|
|
331
|
+
seen.set(e.provenance.ref, JSON.stringify(e.payload.content));
|
|
332
|
+
}
|
|
333
|
+
let skipped = 0;
|
|
334
|
+
const kept = [];
|
|
335
|
+
for (const d of drafts) {
|
|
336
|
+
const ref = d.provenance?.ref;
|
|
337
|
+
if (d.type === "core.user_message" && ref !== void 0) {
|
|
338
|
+
const prior = seen.get(ref);
|
|
339
|
+
if (prior !== void 0 && prior === JSON.stringify(d.payload.content)) {
|
|
340
|
+
skipped++;
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
kept.push(d);
|
|
345
|
+
}
|
|
346
|
+
return { drafts: kept, skipped };
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// src/assembler.ts
|
|
350
|
+
var BlockAssembler = class {
|
|
351
|
+
constructor(origin) {
|
|
352
|
+
this.origin = origin;
|
|
353
|
+
}
|
|
354
|
+
origin;
|
|
355
|
+
text;
|
|
356
|
+
thinking;
|
|
357
|
+
calls = /* @__PURE__ */ new Map();
|
|
358
|
+
/** 工具调用结束前先到的 thoughtSignature */
|
|
359
|
+
callSignatures = /* @__PURE__ */ new Map();
|
|
360
|
+
/** 新一次模型响应开始前清空半成品(上一轮如有未收尾的块已由 finish 产出) */
|
|
361
|
+
reset() {
|
|
362
|
+
this.text = void 0;
|
|
363
|
+
this.thinking = void 0;
|
|
364
|
+
this.calls.clear();
|
|
365
|
+
this.callSignatures.clear();
|
|
366
|
+
}
|
|
367
|
+
/** 喂一个 chunk,返回此刻完整了的块(0 或多条) */
|
|
368
|
+
push(chunk) {
|
|
369
|
+
const out = [];
|
|
370
|
+
const c = chunk;
|
|
371
|
+
switch (chunk.type) {
|
|
372
|
+
case "TEXT_MESSAGE_START":
|
|
373
|
+
this.flushThinking(out);
|
|
374
|
+
this.text = { text: "" };
|
|
375
|
+
break;
|
|
376
|
+
case "TEXT_MESSAGE_CONTENT": {
|
|
377
|
+
if (!this.text) this.text = { text: "" };
|
|
378
|
+
if (typeof c.content === "string" && c.content !== "") this.text.text = c.content;
|
|
379
|
+
else if (typeof c.delta === "string") this.text.text += c.delta;
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
case "TEXT_MESSAGE_END":
|
|
383
|
+
this.flushText(out);
|
|
384
|
+
break;
|
|
385
|
+
case "REASONING_START":
|
|
386
|
+
case "REASONING_MESSAGE_START":
|
|
387
|
+
this.flushThinking(out);
|
|
388
|
+
this.thinking = { text: "" };
|
|
389
|
+
break;
|
|
390
|
+
case "REASONING_MESSAGE_CONTENT":
|
|
391
|
+
if (!this.thinking) this.thinking = { text: "" };
|
|
392
|
+
if (typeof c.delta === "string") this.thinking.text += c.delta;
|
|
393
|
+
break;
|
|
394
|
+
case "REASONING_MESSAGE_END":
|
|
395
|
+
case "REASONING_END":
|
|
396
|
+
break;
|
|
397
|
+
// 等签名
|
|
398
|
+
case "REASONING_ENCRYPTED_VALUE": {
|
|
399
|
+
const value = typeof c.encryptedValue === "string" ? c.encryptedValue : void 0;
|
|
400
|
+
if (value === void 0) break;
|
|
401
|
+
if (c.subtype === "tool-call" && typeof c.entityId === "string") {
|
|
402
|
+
const call = this.calls.get(c.entityId);
|
|
403
|
+
if (call) call.thoughtSignature = value;
|
|
404
|
+
else this.callSignatures.set(c.entityId, value);
|
|
405
|
+
} else {
|
|
406
|
+
if (!this.thinking) this.thinking = { text: "" };
|
|
407
|
+
this.thinking.signature = value;
|
|
408
|
+
}
|
|
409
|
+
break;
|
|
410
|
+
}
|
|
411
|
+
case "STEP_STARTED":
|
|
412
|
+
this.flushThinking(out);
|
|
413
|
+
break;
|
|
414
|
+
case "STEP_FINISHED":
|
|
415
|
+
if (typeof c.signature === "string" && c.signature !== "") {
|
|
416
|
+
if (!this.thinking) this.thinking = { text: "" };
|
|
417
|
+
this.thinking.signature = c.signature;
|
|
418
|
+
}
|
|
419
|
+
break;
|
|
420
|
+
case "TOOL_CALL_START": {
|
|
421
|
+
this.flushThinking(out);
|
|
422
|
+
const id = String(c.toolCallId);
|
|
423
|
+
const name = typeof c.toolCallName === "string" ? c.toolCallName : String(c.toolName ?? "");
|
|
424
|
+
const call = { name, args: "" };
|
|
425
|
+
const sig = this.callSignatures.get(id);
|
|
426
|
+
if (sig !== void 0) {
|
|
427
|
+
call.thoughtSignature = sig;
|
|
428
|
+
this.callSignatures.delete(id);
|
|
429
|
+
}
|
|
430
|
+
const meta = c.metadata;
|
|
431
|
+
if (typeof meta?.thoughtSignature === "string") call.thoughtSignature = meta.thoughtSignature;
|
|
432
|
+
this.calls.set(id, call);
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
case "TOOL_CALL_ARGS": {
|
|
436
|
+
const call = this.calls.get(String(c.toolCallId));
|
|
437
|
+
if (call && typeof c.delta === "string") call.args += c.delta;
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
case "TOOL_CALL_END": {
|
|
441
|
+
const id = String(c.toolCallId);
|
|
442
|
+
const call = this.calls.get(id);
|
|
443
|
+
if (!call) break;
|
|
444
|
+
this.calls.delete(id);
|
|
445
|
+
const args = c.input !== void 0 ? c.input : parseArgs(call.args);
|
|
446
|
+
const replay = { ...this.origin };
|
|
447
|
+
if (call.thoughtSignature !== void 0) replay.thoughtSignature = call.thoughtSignature;
|
|
448
|
+
out.push({
|
|
449
|
+
type: "core.tool_call",
|
|
450
|
+
actor: "model",
|
|
451
|
+
payload: { toolCallId: id, name: call.name, args },
|
|
452
|
+
replay
|
|
453
|
+
});
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
case "RUN_FINISHED":
|
|
457
|
+
case "RUN_ERROR":
|
|
458
|
+
out.push(...this.finish());
|
|
459
|
+
break;
|
|
460
|
+
default:
|
|
461
|
+
break;
|
|
462
|
+
}
|
|
463
|
+
return out;
|
|
464
|
+
}
|
|
465
|
+
/** 收尾:把还没产出的块都产出(没等到 END 的文本、等签名的思考、没等到 END 的工具调用) */
|
|
466
|
+
finish() {
|
|
467
|
+
const out = [];
|
|
468
|
+
this.flushThinking(out);
|
|
469
|
+
this.flushText(out);
|
|
470
|
+
for (const [id, call] of this.calls) {
|
|
471
|
+
const replay = { ...this.origin };
|
|
472
|
+
if (call.thoughtSignature !== void 0) replay.thoughtSignature = call.thoughtSignature;
|
|
473
|
+
out.push({
|
|
474
|
+
type: "core.tool_call",
|
|
475
|
+
actor: "model",
|
|
476
|
+
payload: { toolCallId: id, name: call.name, args: parseArgs(call.args) },
|
|
477
|
+
replay
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
this.calls.clear();
|
|
481
|
+
this.callSignatures.clear();
|
|
482
|
+
return out;
|
|
483
|
+
}
|
|
484
|
+
flushText(out) {
|
|
485
|
+
if (!this.text) return;
|
|
486
|
+
const { text } = this.text;
|
|
487
|
+
this.text = void 0;
|
|
488
|
+
if (text.length === 0) return;
|
|
489
|
+
out.push({ type: "core.model_text", actor: "model", payload: { text }, replay: { ...this.origin } });
|
|
490
|
+
}
|
|
491
|
+
flushThinking(out) {
|
|
492
|
+
if (!this.thinking) return;
|
|
493
|
+
const { text, signature } = this.thinking;
|
|
494
|
+
this.thinking = void 0;
|
|
495
|
+
if (text.length === 0 && signature === void 0) return;
|
|
496
|
+
const replay = { ...this.origin };
|
|
497
|
+
if (signature !== void 0) replay.thinkingSignature = signature;
|
|
498
|
+
out.push({ type: "core.model_thinking", actor: "model", payload: { text }, replay });
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
// src/interrupt.ts
|
|
503
|
+
import { defineInterrupt } from "@tanstack/ai";
|
|
504
|
+
|
|
505
|
+
// src/schema.ts
|
|
506
|
+
function reinsSchema(init) {
|
|
507
|
+
return {
|
|
508
|
+
"~standard": {
|
|
509
|
+
version: 1,
|
|
510
|
+
vendor: "reins",
|
|
511
|
+
jsonSchema: { input: () => init.jsonSchema, output: () => init.jsonSchema },
|
|
512
|
+
validate: (value) => {
|
|
513
|
+
const issues = init.check(value);
|
|
514
|
+
if (issues.length > 0) return { issues: issues.map((message) => ({ message })) };
|
|
515
|
+
return { value: init.parse ? init.parse(value) : value };
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
function isRecord(x) {
|
|
521
|
+
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// src/interrupt.ts
|
|
525
|
+
var REINS_APPROVAL_INTERRUPT_ID = "reins.approval";
|
|
526
|
+
var payloadSchema = reinsSchema({
|
|
527
|
+
jsonSchema: {
|
|
528
|
+
type: "object",
|
|
529
|
+
properties: {
|
|
530
|
+
toolCallId: { type: "string" },
|
|
531
|
+
name: { type: "string" },
|
|
532
|
+
args: {},
|
|
533
|
+
policyId: { type: "string" },
|
|
534
|
+
summary: { type: "string" }
|
|
535
|
+
},
|
|
536
|
+
required: ["toolCallId", "name", "policyId", "summary"]
|
|
537
|
+
},
|
|
538
|
+
check: (v) => {
|
|
539
|
+
if (!isRecord(v)) return ["payload \u5FC5\u987B\u662F\u5BF9\u8C61"];
|
|
540
|
+
const issues = [];
|
|
541
|
+
for (const k of ["toolCallId", "name", "policyId", "summary"])
|
|
542
|
+
if (typeof v[k] !== "string") issues.push(`${k} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`);
|
|
543
|
+
return issues;
|
|
544
|
+
}
|
|
545
|
+
});
|
|
546
|
+
var responseSchema = reinsSchema({
|
|
547
|
+
jsonSchema: {
|
|
548
|
+
type: "object",
|
|
549
|
+
properties: {
|
|
550
|
+
approved: { type: "boolean" },
|
|
551
|
+
by: { type: "string" },
|
|
552
|
+
reason: { type: "string" }
|
|
553
|
+
},
|
|
554
|
+
required: ["approved"]
|
|
555
|
+
},
|
|
556
|
+
check: (v) => {
|
|
557
|
+
if (!isRecord(v)) return ["\u7B54\u590D\u5FC5\u987B\u662F\u5BF9\u8C61"];
|
|
558
|
+
const issues = [];
|
|
559
|
+
if (typeof v.approved !== "boolean") issues.push("approved \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
|
|
560
|
+
if (v.by !== void 0 && typeof v.by !== "string") issues.push("by \u5FC5\u987B\u662F\u5B57\u7B26\u4E32");
|
|
561
|
+
if (v.reason !== void 0 && typeof v.reason !== "string") issues.push("reason \u5FC5\u987B\u662F\u5B57\u7B26\u4E32");
|
|
562
|
+
return issues;
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
var reinsApprovalInterrupt = defineInterrupt({
|
|
566
|
+
id: REINS_APPROVAL_INTERRUPT_ID,
|
|
567
|
+
payloadSchema,
|
|
568
|
+
responseSchema
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
// src/loss-matrix.ts
|
|
572
|
+
var exact = (landing) => ({ kind: "exact", landing });
|
|
573
|
+
var lossy = (landing, note) => ({ kind: "lossy", landing, note });
|
|
574
|
+
var dropped = (note) => ({ kind: "dropped", landing: "none", note });
|
|
575
|
+
var OPS = dropped("\u8FD0\u7EF4\u4E8B\u4EF6\u4E0D\u4E0B\u53D1\uFF08\u6295\u5F71\u9ED8\u8BA4\u5DF2\u8FC7\u6EE4\uFF09");
|
|
576
|
+
var TANSTACK_LOSS_MATRIX = {
|
|
577
|
+
"core.user_message": [
|
|
578
|
+
exact("user"),
|
|
579
|
+
lossy("user", "\u843D\u5728 tool_call \u4E0E tool_result \u4E4B\u95F4\u7684\u7528\u6237\u6D88\u606F\u540E\u79FB\u5230\u540C\u6279\u7ED3\u679C\u4E4B\u540E\uFF08\u5DE5\u5177\u7ED3\u679C\u5FC5\u987B\u7D27\u8DDF\u8C03\u7528\uFF09")
|
|
580
|
+
],
|
|
581
|
+
"core.model_text": [exact("assistant-text"), lossy("merged-text", "\u540C\u4E00\u54CD\u5E94\u7684\u591A\u6BB5\u6B63\u6587\u5408\u6210\u4E00\u4E2A\u5B57\u7B26\u4E32")],
|
|
582
|
+
"core.model_thinking": [exact("thinking"), dropped("\u65E0\u7B7E\u540D\u6216\u6765\u6E90\u4E0D\u540C\u7684 thinking \u4E0D\u4E0B\u53D1\uFF08\u5382\u5546\u4F1A\u62D2\u6536\uFF09")],
|
|
583
|
+
"core.tool_call": [exact("tool-call")],
|
|
584
|
+
"core.tool_result": [
|
|
585
|
+
exact("tool"),
|
|
586
|
+
lossy("tool-error-field", "isError \u53EA\u843D\u5728 ModelMessage.error \u5B57\u6BB5\uFF0C\u662F\u5426\u544A\u77E5\u6A21\u578B\u53D6\u51B3\u4E8E\u9002\u914D\u5668")
|
|
587
|
+
],
|
|
588
|
+
"core.system_note": [lossy("user-role", "TanStack \u6D88\u606F\u65E0 system \u89D2\u8272\uFF0C\u4EE5 <system_note> \u6807\u7B7E\u5305\u4F4F\u8D70 user")],
|
|
589
|
+
"core.compaction": [lossy("user-text", "\u6458\u8981\u4EE5 user \u89D2\u8272\u6587\u672C\u5448\u73B0")],
|
|
590
|
+
"core.approval_request": [OPS],
|
|
591
|
+
"core.approval_decision": [OPS],
|
|
592
|
+
"core.run_paused": [OPS],
|
|
593
|
+
"core.run_resumed": [OPS],
|
|
594
|
+
"core.budget_usage": [OPS],
|
|
595
|
+
"core.memory_op": [OPS],
|
|
596
|
+
"core.handoff": [OPS],
|
|
597
|
+
"core.error": [OPS]
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
// src/middleware.ts
|
|
601
|
+
import {
|
|
602
|
+
BUILTIN_APPROVAL_POLICY,
|
|
603
|
+
computeConfigHash,
|
|
604
|
+
createCoreRegistry,
|
|
605
|
+
createEvent,
|
|
606
|
+
DEFAULT_MODEL_INVISIBLE_TYPES,
|
|
607
|
+
errorMessageOf as errorMessageOf2,
|
|
608
|
+
pendingToolCalls,
|
|
609
|
+
project,
|
|
610
|
+
readTimeline,
|
|
611
|
+
resolveSocketContributions,
|
|
612
|
+
toolResultTrust,
|
|
613
|
+
toolsBoundDrafts,
|
|
614
|
+
uuidv7
|
|
615
|
+
} from "@reinsjs/core";
|
|
616
|
+
import { GenericInterruptDefinitionRegistryCapability } from "@tanstack/ai/adapter-internals";
|
|
617
|
+
|
|
618
|
+
// src/tools.ts
|
|
619
|
+
import {
|
|
620
|
+
errorMessageOf,
|
|
621
|
+
isSubagentPause,
|
|
622
|
+
normalizeToolOutput
|
|
623
|
+
} from "@reinsjs/core";
|
|
624
|
+
import { convertSchemaToJsonSchema } from "@tanstack/ai";
|
|
625
|
+
var NATIVE_TOOL = /* @__PURE__ */ Symbol("reins.tanstack.nativeTool");
|
|
626
|
+
function isNativeToolView(tool) {
|
|
627
|
+
return tool !== void 0 && tool[NATIVE_TOOL] === true;
|
|
628
|
+
}
|
|
629
|
+
function viewOfTanstackTool(tool) {
|
|
630
|
+
const view = {
|
|
631
|
+
[NATIVE_TOOL]: true,
|
|
632
|
+
name: tool.name,
|
|
633
|
+
description: tool.description,
|
|
634
|
+
inputSchema: convertSchemaToJsonSchema(tool.inputSchema) ?? {
|
|
635
|
+
type: "object"
|
|
636
|
+
},
|
|
637
|
+
side: tool.execute ? "server" : "client"
|
|
638
|
+
};
|
|
639
|
+
if (tool.needsApproval === true) view.needsApproval = true;
|
|
640
|
+
return view;
|
|
641
|
+
}
|
|
642
|
+
function toTanstackTool(tool, bridge) {
|
|
643
|
+
const out = {
|
|
644
|
+
name: tool.name,
|
|
645
|
+
description: tool.description,
|
|
646
|
+
inputSchema: tool.inputSchema,
|
|
647
|
+
metadata: { reins: true }
|
|
648
|
+
};
|
|
649
|
+
if (tool.needsApproval === true) out.needsApproval = true;
|
|
650
|
+
const execute = tool.execute?.bind(tool);
|
|
651
|
+
if (execute) {
|
|
652
|
+
out.execute = async (args, tctx) => {
|
|
653
|
+
const toolCallId = tctx?.toolCallId ?? "";
|
|
654
|
+
const ctx = {
|
|
655
|
+
...bridge.toolContextBase,
|
|
656
|
+
toolCallId,
|
|
657
|
+
...tctx?.abortSignal ? { signal: tctx.abortSignal } : {},
|
|
658
|
+
emit: bridge.emit
|
|
659
|
+
};
|
|
660
|
+
let input = args;
|
|
661
|
+
try {
|
|
662
|
+
if (tool.validate) input = tool.validate(input);
|
|
663
|
+
} catch (err) {
|
|
664
|
+
const result2 = {
|
|
665
|
+
content: [{ type: "text", text: `\u5165\u53C2\u4E0D\u5408\u6CD5\uFF1A${errorMessageOf(err)}` }],
|
|
666
|
+
isError: true
|
|
667
|
+
};
|
|
668
|
+
bridge.outputs.set(toolCallId, result2);
|
|
669
|
+
throw new Error(result2.content[0]?.type === "text" ? result2.content[0].text : "\u5165\u53C2\u4E0D\u5408\u6CD5");
|
|
670
|
+
}
|
|
671
|
+
const raw = await execute(input, ctx);
|
|
672
|
+
const result = isSubagentPause(raw) ? {
|
|
673
|
+
content: [
|
|
674
|
+
{
|
|
675
|
+
type: "text",
|
|
676
|
+
text: `\u5B50\u4EE3\u7406\u4F1A\u8BDD ${raw.detail.childSessionId} \u5DF2\u6682\u505C\uFF08${raw.detail.reason}\uFF09\u7B49\u5F85\u5BBF\u4E3B\u5904\u7406\uFF1B\u672C\u8DEF\u5F84\u4E0D\u652F\u6301\u628A\u6682\u505C\u5192\u6CE1\u5230\u7236 run\uFF0C\u8FD9\u6B21\u8C03\u7528\u6309\u672A\u5B8C\u6210\u5904\u7406`
|
|
677
|
+
}
|
|
678
|
+
],
|
|
679
|
+
isError: true
|
|
680
|
+
} : tool.toModelOutput ? { content: tool.toModelOutput(raw) } : normalizeToolOutput(raw);
|
|
681
|
+
bridge.outputs.set(toolCallId, result);
|
|
682
|
+
if (result.isError) throw new Error(textOf2(result));
|
|
683
|
+
return toTanstackContent(result.content);
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
return out;
|
|
687
|
+
}
|
|
688
|
+
function textOf2(result) {
|
|
689
|
+
return result.content.map((p) => p.type === "text" ? p.text : `[image ${p.mime}]`).join("\n");
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// src/middleware.ts
|
|
693
|
+
var TANSTACK_APPROVAL_POLICY = "tanstack.needsApproval";
|
|
694
|
+
var TANSTACK_DECIDER = "tanstack";
|
|
695
|
+
var TANSTACK_API = "tanstack-ai";
|
|
696
|
+
var CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
697
|
+
"core.user_message",
|
|
698
|
+
"core.model_text",
|
|
699
|
+
"core.model_thinking",
|
|
700
|
+
"core.tool_call",
|
|
701
|
+
"core.tool_result"
|
|
702
|
+
]);
|
|
703
|
+
function defaultCapabilities(partial) {
|
|
704
|
+
return {
|
|
705
|
+
api: TANSTACK_API,
|
|
706
|
+
midConversationSystem: false,
|
|
707
|
+
thinkingReplay: true,
|
|
708
|
+
parallelTools: true,
|
|
709
|
+
taskBudget: false,
|
|
710
|
+
images: true,
|
|
711
|
+
maxOutputTokens: 8192,
|
|
712
|
+
...partial
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
function lastBudgetUsage(timeline) {
|
|
716
|
+
for (let i = timeline.length - 1; i >= 0; i--) {
|
|
717
|
+
const e = timeline[i];
|
|
718
|
+
if (e?.type === "core.budget_usage") return e;
|
|
719
|
+
}
|
|
720
|
+
return void 0;
|
|
721
|
+
}
|
|
722
|
+
function toReinsUsage(u) {
|
|
723
|
+
const cacheRead = u.promptTokensDetails?.cachedTokens;
|
|
724
|
+
const cacheWrite = u.promptTokensDetails?.cacheWriteTokens;
|
|
725
|
+
const input = Math.max(0, u.promptTokens - (cacheRead ?? 0) - (cacheWrite ?? 0));
|
|
726
|
+
return {
|
|
727
|
+
input,
|
|
728
|
+
output: u.completionTokens,
|
|
729
|
+
...cacheRead !== void 0 ? { cacheRead } : {},
|
|
730
|
+
...cacheWrite !== void 0 ? { cacheWrite } : {}
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
function reinsMiddleware(options) {
|
|
734
|
+
const { sessionId, log, sockets = [] } = options;
|
|
735
|
+
const registry = options.registry ?? createCoreRegistry();
|
|
736
|
+
const now = options.now ?? (() => Date.now());
|
|
737
|
+
const newId = options.newId ?? uuidv7;
|
|
738
|
+
const warn = options.warn ?? ((m) => console.warn(`[reins/adapter-tanstack-ai] ${m}`));
|
|
739
|
+
const emitCustom = options.emitCustomEvents ?? true;
|
|
740
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
741
|
+
const append = async (ctx, s, drafts) => {
|
|
742
|
+
if (drafts.length === 0) return [];
|
|
743
|
+
const at = now();
|
|
744
|
+
const events = drafts.map(
|
|
745
|
+
(d, i) => createEvent(registry, { ...d, sessionId, seq: s.lastSeq + 1 + i, at, id: newId(at) })
|
|
746
|
+
);
|
|
747
|
+
await log.append(events);
|
|
748
|
+
s.lastSeq += events.length;
|
|
749
|
+
for (const e of events) {
|
|
750
|
+
options.onEvent?.(e);
|
|
751
|
+
if (emitCustom && !CONTENT_TYPES.has(e.type))
|
|
752
|
+
ctx.emitCustomEvent(e.type, e);
|
|
753
|
+
}
|
|
754
|
+
return events;
|
|
755
|
+
};
|
|
756
|
+
const flush = (ctx, s) => append(ctx, s, s.emitted.splice(0));
|
|
757
|
+
const settle = async (ctx, s, draft) => [
|
|
758
|
+
...await flush(ctx, s),
|
|
759
|
+
...await append(ctx, s, [draft])
|
|
760
|
+
];
|
|
761
|
+
const timelineOf = () => readTimeline(log, sessionId, { registry });
|
|
762
|
+
const toolContextBase = () => ({
|
|
763
|
+
sessionId,
|
|
764
|
+
log,
|
|
765
|
+
...options.blobs ? { blobs: options.blobs } : {},
|
|
766
|
+
...options.memory ? { memory: options.memory } : {},
|
|
767
|
+
...options.principal ? { principal: options.principal } : {}
|
|
768
|
+
});
|
|
769
|
+
const tanstackToolsOf = (s, tools) => {
|
|
770
|
+
const out = [];
|
|
771
|
+
for (const t of tools) {
|
|
772
|
+
if (isNativeToolView(t)) {
|
|
773
|
+
const host = s.hostTools.get(t.name);
|
|
774
|
+
if (host) out.push(host);
|
|
775
|
+
continue;
|
|
776
|
+
}
|
|
777
|
+
let w = s.wrapped.get(t.name);
|
|
778
|
+
if (!w) {
|
|
779
|
+
w = toTanstackTool(t, s.bridge);
|
|
780
|
+
s.wrapped.set(t.name, w);
|
|
781
|
+
}
|
|
782
|
+
out.push(w);
|
|
783
|
+
}
|
|
784
|
+
return out;
|
|
785
|
+
};
|
|
786
|
+
const approvalInterruptRegistered = (ctx) => ctx.getOptional(GenericInterruptDefinitionRegistryCapability)?.definitions.get(REINS_APPROVAL_INTERRUPT_ID) === reinsApprovalInterrupt;
|
|
787
|
+
const initRun = async (ctx, config) => {
|
|
788
|
+
const model = { provider: ctx.provider, id: ctx.model };
|
|
789
|
+
const capabilities = defaultCapabilities(options.capabilities);
|
|
790
|
+
const timeline = await timelineOf();
|
|
791
|
+
const hostTools = /* @__PURE__ */ new Map();
|
|
792
|
+
for (const t of config.tools) hostTools.set(t.name, t);
|
|
793
|
+
const hostViews = config.tools.map(viewOfTanstackTool);
|
|
794
|
+
const setupCfg = {
|
|
795
|
+
log,
|
|
796
|
+
model,
|
|
797
|
+
tools: hostViews,
|
|
798
|
+
sockets,
|
|
799
|
+
...options.blobs ? { blobs: options.blobs } : {},
|
|
800
|
+
...options.memory ? { memory: options.memory } : {},
|
|
801
|
+
...options.principal ? { principal: options.principal } : {}
|
|
802
|
+
};
|
|
803
|
+
const { tools: baseTools, systemPrompt: brainPrompt } = await resolveSocketContributions(setupCfg);
|
|
804
|
+
const systemPrompts = [...config.systemPrompts];
|
|
805
|
+
if (brainPrompt !== void 0) systemPrompts.push(brainPrompt);
|
|
806
|
+
const s = {
|
|
807
|
+
model,
|
|
808
|
+
capabilities,
|
|
809
|
+
registry,
|
|
810
|
+
lastSeq: timeline.at(-1)?.seq ?? 0,
|
|
811
|
+
startedAt: now(),
|
|
812
|
+
turns: 0,
|
|
813
|
+
tokensSpent: 0,
|
|
814
|
+
toolCallsTotal: 0,
|
|
815
|
+
hostTools,
|
|
816
|
+
baseTools,
|
|
817
|
+
systemPrompts,
|
|
818
|
+
bridge: {
|
|
819
|
+
sessionId,
|
|
820
|
+
toolContextBase: toolContextBase(),
|
|
821
|
+
emit: (d) => s.emitted.push(d),
|
|
822
|
+
outputs: /* @__PURE__ */ new Map()
|
|
823
|
+
},
|
|
824
|
+
emitted: [],
|
|
825
|
+
verdicts: /* @__PURE__ */ new Map(),
|
|
826
|
+
assembler: new BlockAssembler({ provider: model.provider, api: TANSTACK_API, model: model.id }),
|
|
827
|
+
wrapped: /* @__PURE__ */ new Map(),
|
|
828
|
+
approvalInterruptRegistered: approvalInterruptRegistered(ctx)
|
|
829
|
+
};
|
|
830
|
+
states.set(ctx, s);
|
|
831
|
+
s.bridge.toolContextBase.spend = (usage) => {
|
|
832
|
+
s.tokensSpent += usage.input + usage.output;
|
|
833
|
+
if (s.turn) s.turn.ctx.budget.tokensSpent = s.tokensSpent;
|
|
834
|
+
};
|
|
835
|
+
if (!s.approvalInterruptRegistered)
|
|
836
|
+
warn(
|
|
837
|
+
"reinsApprovalInterrupt \u672A\u767B\u8BB0\u5230 chat({ interrupts })\uFF0C\u672C\u6B21 run \u65E0\u6CD5\u8BF7\u6C42\u4EBA\u5DE5\u5BA1\u6279\uFF1A\u9700\u8981\u5BA1\u6279\u7684\u5DE5\u5177\u8C03\u7528\u4E00\u5F8B\u6309\u62D2\u7EDD\u5904\u7406\uFF08fail-closed\uFF09"
|
|
838
|
+
);
|
|
839
|
+
await append(
|
|
840
|
+
ctx,
|
|
841
|
+
s,
|
|
842
|
+
toolsBoundDrafts({
|
|
843
|
+
timeline,
|
|
844
|
+
toolNames: baseTools.map((t) => t.name),
|
|
845
|
+
configHash: await computeConfigHash({
|
|
846
|
+
model,
|
|
847
|
+
tools: baseTools,
|
|
848
|
+
...brainPrompt !== void 0 ? { systemPrompt: brainPrompt } : {}
|
|
849
|
+
}),
|
|
850
|
+
announce: options.announceToolChanges ?? true
|
|
851
|
+
})
|
|
852
|
+
);
|
|
853
|
+
const origin = { provider: model.provider, api: TANSTACK_API, model: model.id };
|
|
854
|
+
const fresh = timeline.length === 0 ? config.messages : trailingUserMessages(config.messages);
|
|
855
|
+
if (fresh.length > 0) {
|
|
856
|
+
const imported = importModelMessages(fresh, origin, {
|
|
857
|
+
startIndex: config.messages.length - fresh.length
|
|
858
|
+
});
|
|
859
|
+
if (imported.dropped.length > 0) warn(`\u5BFC\u5165\u5BA2\u6237\u7AEF\u6D88\u606F\u65F6\u6709\u7247\u6BB5\u672A\u80FD\u7FFB\u8BD1\uFF1A${imported.dropped.join(", ")}`);
|
|
860
|
+
const { drafts, skipped } = dedupeImportedUserMessages(imported.drafts, timeline);
|
|
861
|
+
if (skipped > 0) warn(`\u5BA2\u6237\u7AEF\u91CD\u53D1\u4E86 ${skipped} \u6761\u5DF2\u5728\u65E5\u5FD7\u91CC\u7684\u7528\u6237\u6D88\u606F\uFF08\u7F51\u7EDC\u91CD\u8BD5\uFF1F\uFF09\uFF0C\u5DF2\u8DF3\u8FC7`);
|
|
862
|
+
await append(ctx, s, drafts);
|
|
863
|
+
}
|
|
864
|
+
return s;
|
|
865
|
+
};
|
|
866
|
+
const buildTurn = async (ctx, s, timeline) => {
|
|
867
|
+
const turnStartedAt = now();
|
|
868
|
+
const projected = project({
|
|
869
|
+
timeline,
|
|
870
|
+
budget: {
|
|
871
|
+
contextLimit: s.capabilities.contextWindow,
|
|
872
|
+
...options.projection?.reserveTokens !== void 0 ? { reserveTokens: options.projection.reserveTokens } : {}
|
|
873
|
+
},
|
|
874
|
+
registry,
|
|
875
|
+
sessionId,
|
|
876
|
+
now: turnStartedAt,
|
|
877
|
+
newId,
|
|
878
|
+
...options.projection?.strategies ? { strategies: options.projection.strategies } : {},
|
|
879
|
+
...options.projection?.estimate ? { estimate: options.projection.estimate } : {}
|
|
880
|
+
});
|
|
881
|
+
if (projected.emitted.length > 0) {
|
|
882
|
+
await log.append(projected.emitted);
|
|
883
|
+
s.lastSeq += projected.emitted.length;
|
|
884
|
+
for (const e of projected.emitted) {
|
|
885
|
+
options.onEvent?.(e);
|
|
886
|
+
if (emitCustom) ctx.emitCustomEvent(e.type, e);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
const lastUsage = lastBudgetUsage(timeline)?.payload.tokens;
|
|
890
|
+
const turnCtx = {
|
|
891
|
+
session: { id: sessionId, turn: s.turns },
|
|
892
|
+
...options.principal ? { principal: options.principal } : {},
|
|
893
|
+
events: projected.events,
|
|
894
|
+
timeline,
|
|
895
|
+
log,
|
|
896
|
+
...options.blobs ? { blobs: options.blobs } : {},
|
|
897
|
+
...options.memory ? { memory: options.memory } : {},
|
|
898
|
+
tools: s.baseTools,
|
|
899
|
+
model: s.model,
|
|
900
|
+
capabilities: s.capabilities,
|
|
901
|
+
budget: {
|
|
902
|
+
contextLimit: s.capabilities.contextWindow,
|
|
903
|
+
targetTokens: projected.stats.targetTokens,
|
|
904
|
+
used: projected.stats.estimatedTokens,
|
|
905
|
+
tokensSpent: s.tokensSpent,
|
|
906
|
+
turns: s.turns,
|
|
907
|
+
toolCalls: s.toolCallsTotal,
|
|
908
|
+
wallMs: turnStartedAt - s.startedAt,
|
|
909
|
+
...lastUsage ? { lastUsage } : {}
|
|
910
|
+
},
|
|
911
|
+
...ctx.signal ? { signal: ctx.signal } : {},
|
|
912
|
+
emit: (d) => s.emitted.push(d)
|
|
913
|
+
};
|
|
914
|
+
return {
|
|
915
|
+
ctx: turnCtx,
|
|
916
|
+
estimate: projected.stats.estimatedTokens,
|
|
917
|
+
startedAt: turnStartedAt,
|
|
918
|
+
toolCalls: 0,
|
|
919
|
+
modelEvents: []
|
|
920
|
+
};
|
|
921
|
+
};
|
|
922
|
+
const beforeModel = async (ctx, s) => {
|
|
923
|
+
const timeline = await timelineOf();
|
|
924
|
+
s.turns++;
|
|
925
|
+
const turn = await buildTurn(ctx, s, timeline);
|
|
926
|
+
const tctx = turn.ctx;
|
|
927
|
+
let visible = tctx.events;
|
|
928
|
+
let tools = s.baseTools;
|
|
929
|
+
let systemPrompt;
|
|
930
|
+
for (const sock of sockets) {
|
|
931
|
+
const patch = await sock.beforeModel?.(tctx);
|
|
932
|
+
if (!patch) continue;
|
|
933
|
+
if (patch.events) visible = patch.events;
|
|
934
|
+
if (patch.tools) tools = patch.tools;
|
|
935
|
+
if (patch.systemPrompt !== void 0) systemPrompt = patch.systemPrompt;
|
|
936
|
+
tctx.events = visible;
|
|
937
|
+
tctx.tools = tools;
|
|
938
|
+
}
|
|
939
|
+
const injected = await flush(ctx, s);
|
|
940
|
+
visible = [...visible, ...injected.filter((e) => !DEFAULT_MODEL_INVISIBLE_TYPES.has(e.type))];
|
|
941
|
+
tctx.events = visible;
|
|
942
|
+
tctx.tools = tools;
|
|
943
|
+
s.turn = turn;
|
|
944
|
+
s.assembler.reset();
|
|
945
|
+
const { messages, landings } = toModelMessages(visible, {
|
|
946
|
+
model: s.model,
|
|
947
|
+
...options.trustMarkers !== void 0 ? { trustMarkers: options.trustMarkers } : {}
|
|
948
|
+
});
|
|
949
|
+
options.onLandings?.(landings.filter((l) => l.kind !== "exact"));
|
|
950
|
+
return {
|
|
951
|
+
providerMessages: messages,
|
|
952
|
+
tools: tanstackToolsOf(s, tools),
|
|
953
|
+
systemPrompts: systemPrompt !== void 0 ? [systemPrompt] : s.systemPrompts
|
|
954
|
+
};
|
|
955
|
+
};
|
|
956
|
+
const beforeTools = async (ctx, s) => {
|
|
957
|
+
const timeline = await timelineOf();
|
|
958
|
+
const pending = pendingToolCalls(timeline);
|
|
959
|
+
if (pending.length === 0) return void 0;
|
|
960
|
+
if (!s.turn) s.turn = await buildTurn(ctx, s, timeline);
|
|
961
|
+
const tctx = s.turn.ctx;
|
|
962
|
+
const decisions = /* @__PURE__ */ new Map();
|
|
963
|
+
const requested = /* @__PURE__ */ new Set();
|
|
964
|
+
for (const raw of timeline) {
|
|
965
|
+
const e = raw;
|
|
966
|
+
if (e.type === "core.approval_decision") decisions.set(e.payload.toolCallId, e.payload);
|
|
967
|
+
if (e.type === "core.approval_request") requested.add(e.payload.toolCallId);
|
|
968
|
+
}
|
|
969
|
+
const interrupts = [];
|
|
970
|
+
for (const call of pending) {
|
|
971
|
+
const { toolCallId, name } = call.payload;
|
|
972
|
+
const tool = tctx.tools.find((t) => t.name === name);
|
|
973
|
+
const decided = decisions.get(toolCallId);
|
|
974
|
+
if (decided && !decided.approved) {
|
|
975
|
+
s.verdicts.set(toolCallId, {
|
|
976
|
+
kind: "block",
|
|
977
|
+
text: `\u5BA1\u6279\u88AB\u62D2\u7EDD${decided.reason ? `\uFF1A${decided.reason}` : ""}`
|
|
978
|
+
});
|
|
979
|
+
continue;
|
|
980
|
+
}
|
|
981
|
+
let args = call.payload.args;
|
|
982
|
+
let rewritten = false;
|
|
983
|
+
let seen = call;
|
|
984
|
+
let verdict = "proceed";
|
|
985
|
+
for (const sock of sockets) {
|
|
986
|
+
const d = await sock.beforeTool?.(tctx, seen, tool);
|
|
987
|
+
if (d === void 0 || d === "proceed") continue;
|
|
988
|
+
if ("rewrite" in d) {
|
|
989
|
+
args = d.rewrite;
|
|
990
|
+
rewritten = true;
|
|
991
|
+
seen = { ...seen, payload: { ...seen.payload, args } };
|
|
992
|
+
continue;
|
|
993
|
+
}
|
|
994
|
+
if ("defer" in d && decided?.approved) continue;
|
|
995
|
+
verdict = d;
|
|
996
|
+
break;
|
|
997
|
+
}
|
|
998
|
+
if (typeof verdict === "object" && "block" in verdict) {
|
|
999
|
+
s.verdicts.set(toolCallId, { kind: "block", text: verdict.block });
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
let approval = typeof verdict === "object" && "defer" in verdict ? verdict.defer : void 0;
|
|
1003
|
+
if (!approval && !decided?.approved && tool && !isNativeToolView(tool) && tool.needsApproval !== void 0) {
|
|
1004
|
+
let input = args;
|
|
1005
|
+
let valid = true;
|
|
1006
|
+
try {
|
|
1007
|
+
if (tool.validate) input = tool.validate(args);
|
|
1008
|
+
} catch {
|
|
1009
|
+
valid = false;
|
|
1010
|
+
}
|
|
1011
|
+
if (valid) {
|
|
1012
|
+
const need = typeof tool.needsApproval === "function" ? await tool.needsApproval(input, {
|
|
1013
|
+
...toolContextBase(),
|
|
1014
|
+
toolCallId,
|
|
1015
|
+
emit: (d) => s.emitted.push(d)
|
|
1016
|
+
}) : tool.needsApproval;
|
|
1017
|
+
if (need)
|
|
1018
|
+
approval = {
|
|
1019
|
+
policyId: BUILTIN_APPROVAL_POLICY,
|
|
1020
|
+
summary: `${name}(${JSON.stringify(input) ?? ""})`
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
if (approval && !decided?.approved) {
|
|
1025
|
+
if (!requested.has(toolCallId)) {
|
|
1026
|
+
s.emitted.push({
|
|
1027
|
+
type: "core.approval_request",
|
|
1028
|
+
actor: "system",
|
|
1029
|
+
parentId: call.id,
|
|
1030
|
+
payload: { toolCallId, policyId: approval.policyId, summary: approval.summary }
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
if (!s.approvalInterruptRegistered) {
|
|
1034
|
+
const reason = "\u5BA1\u6279\u4E2D\u65AD\u672A\u767B\u8BB0\uFF08chat({ interrupts }) \u7F3A reinsApprovalInterrupt\uFF09\uFF0C\u65E0\u6CD5\u8BF7\u6C42\u4EBA\u5DE5\u5BA1\u6279\uFF0C\u6309\u62D2\u7EDD\u5904\u7406";
|
|
1035
|
+
s.emitted.push({
|
|
1036
|
+
type: "core.approval_decision",
|
|
1037
|
+
actor: "system",
|
|
1038
|
+
parentId: call.id,
|
|
1039
|
+
payload: { toolCallId, approved: false, by: "reins", reason }
|
|
1040
|
+
});
|
|
1041
|
+
s.verdicts.set(toolCallId, { kind: "block", text: `\u5BA1\u6279\u88AB\u62D2\u7EDD\uFF1A${reason}` });
|
|
1042
|
+
continue;
|
|
1043
|
+
}
|
|
1044
|
+
interrupts.push(
|
|
1045
|
+
reinsApprovalInterrupt.interrupt({
|
|
1046
|
+
key: toolCallId,
|
|
1047
|
+
reason: "tool_call",
|
|
1048
|
+
message: approval.summary,
|
|
1049
|
+
payload: { toolCallId, name, args, policyId: approval.policyId, summary: approval.summary }
|
|
1050
|
+
})
|
|
1051
|
+
);
|
|
1052
|
+
s.verdicts.set(toolCallId, { kind: "await" });
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
s.verdicts.set(toolCallId, rewritten ? { kind: "rewrite", args } : { kind: "proceed" });
|
|
1056
|
+
}
|
|
1057
|
+
await flush(ctx, s);
|
|
1058
|
+
if (interrupts.length === 0) return void 0;
|
|
1059
|
+
await append(ctx, s, [{ type: "core.run_paused", actor: "system", payload: { reason: "approval" } }]);
|
|
1060
|
+
return { interrupts };
|
|
1061
|
+
};
|
|
1062
|
+
const resultDraft = (call, toolCallId, name, result, tool) => ({
|
|
1063
|
+
type: "core.tool_result",
|
|
1064
|
+
actor: "tool",
|
|
1065
|
+
...call ? { parentId: call.id } : {},
|
|
1066
|
+
provenance: { source: name },
|
|
1067
|
+
// 与 runLoop 同一口径(core 同一个纯函数):工具声明的 resultTrust 只用于成功结果(拦截 / 失败仍是缺省 untrusted)
|
|
1068
|
+
...(() => {
|
|
1069
|
+
const trust = toolResultTrust(tool, result.isError ?? false);
|
|
1070
|
+
return trust === void 0 ? {} : { trust };
|
|
1071
|
+
})(),
|
|
1072
|
+
payload: { toolCallId, name, content: result.content, isError: result.isError ?? false }
|
|
1073
|
+
});
|
|
1074
|
+
const errorResult = (text) => ({ content: [{ type: "text", text }], isError: true });
|
|
1075
|
+
const toolNamed = (s, name) => (s.turn?.ctx.tools ?? s.baseTools).find((t) => t.name === name);
|
|
1076
|
+
const afterTool = async (ctx, s, info) => {
|
|
1077
|
+
const timeline = await timelineOf();
|
|
1078
|
+
const answered = timeline.some(
|
|
1079
|
+
(e) => e.type === "core.tool_result" && e.payload.toolCallId === info.toolCallId
|
|
1080
|
+
);
|
|
1081
|
+
if (answered) return;
|
|
1082
|
+
const call = pendingToolCalls(timeline).find((c) => c.payload.toolCallId === info.toolCallId);
|
|
1083
|
+
const verdict = s.verdicts.get(info.toolCallId);
|
|
1084
|
+
const stored = s.bridge.outputs.get(info.toolCallId);
|
|
1085
|
+
s.bridge.outputs.delete(info.toolCallId);
|
|
1086
|
+
if (verdict?.kind === "block") {
|
|
1087
|
+
await settle(
|
|
1088
|
+
ctx,
|
|
1089
|
+
s,
|
|
1090
|
+
resultDraft(call, info.toolCallId, info.toolName, errorResult(`\u5DE5\u5177\u8C03\u7528\u88AB\u62E6\u622A\uFF1A${verdict.text}`))
|
|
1091
|
+
);
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
let result;
|
|
1095
|
+
if (stored) result = stored;
|
|
1096
|
+
else if (info.ok) result = { content: fromTanstackToolResult(info.result), isError: false };
|
|
1097
|
+
else result = errorResult(`\u5DE5\u5177\u6267\u884C\u5931\u8D25\uFF1A${errorMessageOf2(info.error)}`);
|
|
1098
|
+
s.toolCallsTotal++;
|
|
1099
|
+
if (s.turn) s.turn.ctx.budget.toolCalls = s.toolCallsTotal;
|
|
1100
|
+
let draft = resultDraft(call, info.toolCallId, info.toolName, result, toolNamed(s, info.toolName));
|
|
1101
|
+
if (s.turn && call) {
|
|
1102
|
+
for (const sock of sockets) {
|
|
1103
|
+
const replaced = await sock.afterTool?.(s.turn.ctx, call, draft);
|
|
1104
|
+
if (replaced) draft = replaced;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
await settle(ctx, s, draft);
|
|
1108
|
+
};
|
|
1109
|
+
const toolPhaseComplete = async (ctx, s, info) => {
|
|
1110
|
+
const timeline = await timelineOf();
|
|
1111
|
+
const answered = /* @__PURE__ */ new Set();
|
|
1112
|
+
const requested = /* @__PURE__ */ new Set();
|
|
1113
|
+
const decided = /* @__PURE__ */ new Set();
|
|
1114
|
+
for (const raw of timeline) {
|
|
1115
|
+
const e = raw;
|
|
1116
|
+
if (e.type === "core.tool_result") answered.add(e.payload.toolCallId);
|
|
1117
|
+
if (e.type === "core.approval_request") requested.add(e.payload.toolCallId);
|
|
1118
|
+
if (e.type === "core.approval_decision") decided.add(e.payload.toolCallId);
|
|
1119
|
+
}
|
|
1120
|
+
const pending = pendingToolCalls(timeline);
|
|
1121
|
+
for (const r of info.results) {
|
|
1122
|
+
if (answered.has(r.toolCallId)) continue;
|
|
1123
|
+
const call = pending.find((c) => c.payload.toolCallId === r.toolCallId);
|
|
1124
|
+
const isError = r.state === "output-error";
|
|
1125
|
+
if (requested.has(r.toolCallId) && !decided.has(r.toolCallId)) {
|
|
1126
|
+
s.emitted.push({
|
|
1127
|
+
type: "core.approval_decision",
|
|
1128
|
+
actor: "host",
|
|
1129
|
+
payload: { toolCallId: r.toolCallId, approved: !isError, by: TANSTACK_DECIDER }
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
const content = fromTanstackToolResult(r.result);
|
|
1133
|
+
await settle(
|
|
1134
|
+
ctx,
|
|
1135
|
+
s,
|
|
1136
|
+
resultDraft(call, r.toolCallId, r.toolName, { content, isError }, toolNamed(s, r.toolName))
|
|
1137
|
+
);
|
|
1138
|
+
answered.add(r.toolCallId);
|
|
1139
|
+
}
|
|
1140
|
+
for (const a of info.needsApproval) {
|
|
1141
|
+
if (requested.has(a.toolCallId)) continue;
|
|
1142
|
+
const call = pending.find((c) => c.payload.toolCallId === a.toolCallId);
|
|
1143
|
+
s.emitted.push({
|
|
1144
|
+
type: "core.approval_request",
|
|
1145
|
+
actor: "system",
|
|
1146
|
+
...call ? { parentId: call.id } : {},
|
|
1147
|
+
payload: {
|
|
1148
|
+
toolCallId: a.toolCallId,
|
|
1149
|
+
policyId: TANSTACK_APPROVAL_POLICY,
|
|
1150
|
+
summary: `${a.toolName}(${JSON.stringify(a.input) ?? ""})`
|
|
1151
|
+
}
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
await flush(ctx, s);
|
|
1155
|
+
if (info.needsApproval.length > 0)
|
|
1156
|
+
await append(ctx, s, [{ type: "core.run_paused", actor: "system", payload: { reason: "approval" } }]);
|
|
1157
|
+
else if (info.needsClientExecution.length > 0)
|
|
1158
|
+
await append(ctx, s, [{ type: "core.run_paused", actor: "system", payload: { reason: "host" } }]);
|
|
1159
|
+
};
|
|
1160
|
+
const doHandoff = async (ctx, s, intent) => {
|
|
1161
|
+
const toSessionId = intent.toSessionId ?? newId(now());
|
|
1162
|
+
await append(ctx, s, [
|
|
1163
|
+
{
|
|
1164
|
+
type: "core.handoff",
|
|
1165
|
+
actor: intent.by ?? "model",
|
|
1166
|
+
payload: {
|
|
1167
|
+
toSessionId,
|
|
1168
|
+
summary: intent.summary,
|
|
1169
|
+
reason: intent.reason,
|
|
1170
|
+
...intent.triggerMessage !== void 0 ? { triggerMessage: intent.triggerMessage } : {}
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
]);
|
|
1174
|
+
const at = now();
|
|
1175
|
+
const opening = [
|
|
1176
|
+
{ type: "core.system_note", actor: "host", payload: { kind: "host", text: intent.summary } },
|
|
1177
|
+
...intent.opening ?? []
|
|
1178
|
+
];
|
|
1179
|
+
if (intent.triggerMessage !== void 0)
|
|
1180
|
+
opening.push({
|
|
1181
|
+
type: "core.user_message",
|
|
1182
|
+
actor: "user",
|
|
1183
|
+
payload: { content: [{ type: "text", text: intent.triggerMessage }] }
|
|
1184
|
+
});
|
|
1185
|
+
const events = opening.map(
|
|
1186
|
+
(d, i) => createEvent(registry, { ...d, sessionId: toSessionId, seq: i + 1, at, id: newId(at) })
|
|
1187
|
+
);
|
|
1188
|
+
await log.append(events);
|
|
1189
|
+
for (const e of events) options.onEvent?.(e);
|
|
1190
|
+
await options.onHandoff?.(sessionId, toSessionId);
|
|
1191
|
+
};
|
|
1192
|
+
const middleware = {
|
|
1193
|
+
name: "reins",
|
|
1194
|
+
async onConfig(ctx, config) {
|
|
1195
|
+
if (ctx.phase === "init") {
|
|
1196
|
+
const s2 = await initRun(ctx, config);
|
|
1197
|
+
return { tools: tanstackToolsOf(s2, s2.baseTools), systemPrompts: s2.systemPrompts };
|
|
1198
|
+
}
|
|
1199
|
+
const s = states.get(ctx);
|
|
1200
|
+
if (!s) return void 0;
|
|
1201
|
+
if (ctx.phase === "beforeModel" || ctx.phase === "structuredOutput") return beforeModel(ctx, s);
|
|
1202
|
+
return void 0;
|
|
1203
|
+
},
|
|
1204
|
+
async onChunk(ctx, chunk) {
|
|
1205
|
+
const s = states.get(ctx);
|
|
1206
|
+
if (!s || !(ctx.phase === "modelStream" || ctx.phase === "structuredOutput")) return void 0;
|
|
1207
|
+
const drafts = s.assembler.push(chunk);
|
|
1208
|
+
if (drafts.length === 0) return void 0;
|
|
1209
|
+
const events = await append(ctx, s, drafts);
|
|
1210
|
+
if (s.turn) {
|
|
1211
|
+
s.turn.modelEvents.push(...events);
|
|
1212
|
+
s.turn.toolCalls += events.filter((e) => e.type === "core.tool_call").length;
|
|
1213
|
+
}
|
|
1214
|
+
return void 0;
|
|
1215
|
+
},
|
|
1216
|
+
async onUsage(ctx, usage) {
|
|
1217
|
+
const s = states.get(ctx);
|
|
1218
|
+
if (!s?.turn) return;
|
|
1219
|
+
const tokens = toReinsUsage(usage);
|
|
1220
|
+
s.tokensSpent += tokens.input + tokens.output;
|
|
1221
|
+
const b = s.turn.ctx.budget;
|
|
1222
|
+
b.tokensSpent = s.tokensSpent;
|
|
1223
|
+
b.wallMs = now() - s.startedAt;
|
|
1224
|
+
b.lastUsage = tokens;
|
|
1225
|
+
await append(ctx, s, [
|
|
1226
|
+
{
|
|
1227
|
+
type: "core.budget_usage",
|
|
1228
|
+
actor: "system",
|
|
1229
|
+
payload: {
|
|
1230
|
+
tokens,
|
|
1231
|
+
toolCalls: s.turn.toolCalls,
|
|
1232
|
+
wallMs: now() - s.turn.startedAt,
|
|
1233
|
+
contextEstimate: s.turn.estimate
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
]);
|
|
1237
|
+
},
|
|
1238
|
+
async onInterruptBoundary(ctx) {
|
|
1239
|
+
const s = states.get(ctx);
|
|
1240
|
+
if (!s) return void 0;
|
|
1241
|
+
if (ctx.phase === "afterModel") {
|
|
1242
|
+
if (s.turn) {
|
|
1243
|
+
const leftover = await append(ctx, s, s.assembler.finish());
|
|
1244
|
+
s.turn.modelEvents.push(...leftover);
|
|
1245
|
+
for (const sock of sockets) await sock.afterModel?.(s.turn.ctx, s.turn.modelEvents);
|
|
1246
|
+
await flush(ctx, s);
|
|
1247
|
+
}
|
|
1248
|
+
return void 0;
|
|
1249
|
+
}
|
|
1250
|
+
if (ctx.phase === "beforeTools") return beforeTools(ctx, s);
|
|
1251
|
+
return void 0;
|
|
1252
|
+
},
|
|
1253
|
+
async onInterruptResolution(ctx, resolutions) {
|
|
1254
|
+
const s = states.get(ctx);
|
|
1255
|
+
if (!s) return void 0;
|
|
1256
|
+
for (const r of resolutions.for(reinsApprovalInterrupt)) {
|
|
1257
|
+
const approved = r.status === "resolved" && r.response.approved === true;
|
|
1258
|
+
const by = r.status === "resolved" && r.response.by ? r.response.by : TANSTACK_DECIDER;
|
|
1259
|
+
const reason = r.status === "resolved" ? r.response.reason : "\u5BA1\u6279\u88AB\u53D6\u6D88";
|
|
1260
|
+
s.emitted.push({
|
|
1261
|
+
type: "core.approval_decision",
|
|
1262
|
+
actor: "host",
|
|
1263
|
+
payload: { toolCallId: r.request.key, approved, by, ...reason !== void 0 ? { reason } : {} }
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
const events = await flush(ctx, s);
|
|
1267
|
+
if (events.length > 0) await append(ctx, s, [{ type: "core.run_resumed", actor: "host", payload: {} }]);
|
|
1268
|
+
return { toolResume: "continue" };
|
|
1269
|
+
},
|
|
1270
|
+
onBeforeToolCall(ctx, hookCtx) {
|
|
1271
|
+
const s = states.get(ctx);
|
|
1272
|
+
const v = s?.verdicts.get(hookCtx.toolCallId);
|
|
1273
|
+
if (!v) return void 0;
|
|
1274
|
+
if (v.kind === "block") return { type: "skip", result: { error: `\u5DE5\u5177\u8C03\u7528\u88AB\u62E6\u622A\uFF1A${v.text}` } };
|
|
1275
|
+
if (v.kind === "rewrite") return { type: "transformArgs", args: v.args };
|
|
1276
|
+
return void 0;
|
|
1277
|
+
},
|
|
1278
|
+
async onAfterToolCall(ctx, info) {
|
|
1279
|
+
const s = states.get(ctx);
|
|
1280
|
+
if (!s) return;
|
|
1281
|
+
await afterTool(ctx, s, info);
|
|
1282
|
+
},
|
|
1283
|
+
async onToolPhaseComplete(ctx, info) {
|
|
1284
|
+
const s = states.get(ctx);
|
|
1285
|
+
if (!s) return;
|
|
1286
|
+
await toolPhaseComplete(ctx, s, info);
|
|
1287
|
+
},
|
|
1288
|
+
async onShouldContinue(ctx, state) {
|
|
1289
|
+
const s = states.get(ctx);
|
|
1290
|
+
if (!s?.turn) return void 0;
|
|
1291
|
+
const tctx = s.turn.ctx;
|
|
1292
|
+
tctx.budget.wallMs = now() - s.startedAt;
|
|
1293
|
+
let decision = state.lastTurnToolCallCount > 0 ? "continue" : "stop";
|
|
1294
|
+
for (const sock of sockets) {
|
|
1295
|
+
const d = await sock.onTurnEnd?.(tctx);
|
|
1296
|
+
if (d !== void 0) {
|
|
1297
|
+
decision = d;
|
|
1298
|
+
break;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
await flush(ctx, s);
|
|
1302
|
+
if (decision === "continue") return true;
|
|
1303
|
+
if (decision === "stop") return false;
|
|
1304
|
+
if ("pause" in decision) {
|
|
1305
|
+
await append(ctx, s, [
|
|
1306
|
+
{ type: "core.run_paused", actor: "system", payload: { reason: decision.pause.reason } }
|
|
1307
|
+
]);
|
|
1308
|
+
return false;
|
|
1309
|
+
}
|
|
1310
|
+
await doHandoff(ctx, s, decision.handoff);
|
|
1311
|
+
return false;
|
|
1312
|
+
},
|
|
1313
|
+
async onAbort(ctx) {
|
|
1314
|
+
const s = states.get(ctx);
|
|
1315
|
+
if (!s) return;
|
|
1316
|
+
await append(ctx, s, [
|
|
1317
|
+
...s.assembler.finish(),
|
|
1318
|
+
{ type: "core.run_paused", actor: "system", payload: { reason: "host" } }
|
|
1319
|
+
]);
|
|
1320
|
+
},
|
|
1321
|
+
async onError(ctx, info) {
|
|
1322
|
+
const s = states.get(ctx);
|
|
1323
|
+
if (!s) return;
|
|
1324
|
+
await append(ctx, s, [
|
|
1325
|
+
...s.assembler.finish(),
|
|
1326
|
+
{
|
|
1327
|
+
type: "core.error",
|
|
1328
|
+
actor: "system",
|
|
1329
|
+
payload: { category: TANSTACK_API, message: errorMessageOf2(info.error), retryable: false }
|
|
1330
|
+
}
|
|
1331
|
+
]);
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
return middleware;
|
|
1335
|
+
}
|
|
1336
|
+
export {
|
|
1337
|
+
BlockAssembler,
|
|
1338
|
+
COMPACTION_PREFIX,
|
|
1339
|
+
IMPORT_SOURCE,
|
|
1340
|
+
NATIVE_TOOL,
|
|
1341
|
+
REINS_APPROVAL_INTERRUPT_ID,
|
|
1342
|
+
TANSTACK_API,
|
|
1343
|
+
TANSTACK_APPROVAL_POLICY,
|
|
1344
|
+
TANSTACK_DECIDER,
|
|
1345
|
+
TANSTACK_LOSS_MATRIX,
|
|
1346
|
+
dedupeImportedUserMessages,
|
|
1347
|
+
framedSystemNote,
|
|
1348
|
+
fromTanstackContent,
|
|
1349
|
+
fromTanstackToolResult,
|
|
1350
|
+
importModelMessages,
|
|
1351
|
+
importRef,
|
|
1352
|
+
isNativeToolView,
|
|
1353
|
+
parseArgs,
|
|
1354
|
+
reinsApprovalInterrupt,
|
|
1355
|
+
reinsMiddleware,
|
|
1356
|
+
reinsSchema,
|
|
1357
|
+
toModelMessages,
|
|
1358
|
+
toReinsUsage,
|
|
1359
|
+
toTanstackContent,
|
|
1360
|
+
toTanstackParts,
|
|
1361
|
+
toTanstackTool,
|
|
1362
|
+
trailingUserMessages,
|
|
1363
|
+
viewOfTanstackTool
|
|
1364
|
+
};
|
|
1365
|
+
//# sourceMappingURL=index.js.map
|