@reinsjs/adapter-tanstack-ai 0.5.1 → 0.6.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 +67 -0
- package/README.md +18 -3
- package/dist/index.d.ts +29 -6
- package/dist/index.js +407 -47
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// src/messages.ts
|
|
2
2
|
import {
|
|
3
|
-
isImageRef as isImageRef2,
|
|
4
3
|
markUntrusted,
|
|
5
4
|
markUntrustedText,
|
|
6
5
|
needsUntrustedMark,
|
|
@@ -8,9 +7,26 @@ import {
|
|
|
8
7
|
} from "@reinsjs/core";
|
|
9
8
|
|
|
10
9
|
// src/content.ts
|
|
11
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
isContentPart,
|
|
12
|
+
isImageRef,
|
|
13
|
+
isSupportedImageMime,
|
|
14
|
+
renderToolReference,
|
|
15
|
+
unsupportedImageText
|
|
16
|
+
} from "@reinsjs/core";
|
|
12
17
|
var IMAGE_REF_PLACEHOLDER = "[image unavailable]";
|
|
13
18
|
var IMAGE_REF_NOTE = "an image stored by reference is not loaded on the TanStack path, so it is replaced with placeholder text";
|
|
19
|
+
function isUnsupportedImage(p) {
|
|
20
|
+
return p.type === "image" && !isImageRef(p) && !isSupportedImageMime(p.mime);
|
|
21
|
+
}
|
|
22
|
+
var IMAGE_UNSUPPORTED_NOTE = "an image of a type outside the supported set (image/jpeg, image/png, image/gif, image/webp; logged before that check existed) would be rejected by the provider, so it is replaced with placeholder text naming its type";
|
|
23
|
+
function placeholderNoteOf(parts) {
|
|
24
|
+
const notes = [
|
|
25
|
+
parts.some(isImageRef) ? IMAGE_REF_NOTE : void 0,
|
|
26
|
+
parts.some(isUnsupportedImage) ? IMAGE_UNSUPPORTED_NOTE : void 0
|
|
27
|
+
].filter(Boolean);
|
|
28
|
+
return notes.length > 0 ? notes.join("; ") : void 0;
|
|
29
|
+
}
|
|
14
30
|
function withoutImageRefs(parts) {
|
|
15
31
|
return parts.map((p) => isImageRef(p) ? { type: "text", text: IMAGE_REF_PLACEHOLDER } : p);
|
|
16
32
|
}
|
|
@@ -26,6 +42,8 @@ function toTanstackParts(parts) {
|
|
|
26
42
|
case "video":
|
|
27
43
|
case "audio":
|
|
28
44
|
if (isImageRef(p)) return { type: "text", content: IMAGE_REF_PLACEHOLDER };
|
|
45
|
+
if (p.type === "image" && !isSupportedImageMime(p.mime))
|
|
46
|
+
return { type: "text", content: unsupportedImageText(p.mime) };
|
|
29
47
|
return { type: p.type, source: { type: "data", value: p.data, mimeType: p.mime } };
|
|
30
48
|
default: {
|
|
31
49
|
const _exhaustive = p;
|
|
@@ -178,7 +196,7 @@ function toModelMessages(events, opts) {
|
|
|
178
196
|
flush();
|
|
179
197
|
const c = content(e, e.payload.content);
|
|
180
198
|
const msg = { role: "user", content: toTanstackContent(c.parts) };
|
|
181
|
-
const refNote = c.parts
|
|
199
|
+
const refNote = placeholderNoteOf(c.parts);
|
|
182
200
|
if (awaiting.size > 0) {
|
|
183
201
|
deferred.push({
|
|
184
202
|
msg,
|
|
@@ -235,7 +253,7 @@ function toModelMessages(events, opts) {
|
|
|
235
253
|
case "core.tool_result": {
|
|
236
254
|
flush();
|
|
237
255
|
const c = content(e, e.payload.content);
|
|
238
|
-
const refNote = c.parts
|
|
256
|
+
const refNote = placeholderNoteOf(c.parts);
|
|
239
257
|
const msg = {
|
|
240
258
|
role: "tool",
|
|
241
259
|
toolCallId: e.payload.toolCallId,
|
|
@@ -288,6 +306,7 @@ function toModelMessages(events, opts) {
|
|
|
288
306
|
case "core.memory_op":
|
|
289
307
|
case "core.handoff":
|
|
290
308
|
case "core.tool_started":
|
|
309
|
+
case "core.tools_bound":
|
|
291
310
|
case "core.run_ended":
|
|
292
311
|
case "core.error":
|
|
293
312
|
land(e, "dropped", "none", "operational event, not sent (the default projection already filters it)");
|
|
@@ -647,7 +666,7 @@ var TANSTACK_LOSS_MATRIX = {
|
|
|
647
666
|
exact("user"),
|
|
648
667
|
lossy(
|
|
649
668
|
"user",
|
|
650
|
-
"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), untrusted content is escaped, or an image stored by reference is replaced with placeholder text (the TanStack path does not load blobs)"
|
|
669
|
+
"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), untrusted content is escaped, or an image stored by reference is replaced with placeholder text (the TanStack path does not load blobs), or an image whose type is outside image/jpeg, png, gif, webp (logged before that check existed) is replaced with placeholder text naming its type"
|
|
651
670
|
)
|
|
652
671
|
],
|
|
653
672
|
"core.model_text": [
|
|
@@ -663,7 +682,7 @@ var TANSTACK_LOSS_MATRIX = {
|
|
|
663
682
|
exact("tool"),
|
|
664
683
|
lossy(
|
|
665
684
|
"tool",
|
|
666
|
-
"untrusted content is escaped, or an image stored by reference is replaced with placeholder text (the TanStack path does not load blobs)"
|
|
685
|
+
"untrusted content is escaped, or an image stored by reference is replaced with placeholder text (the TanStack path does not load blobs), or an image whose type is outside image/jpeg, png, gif, webp (logged before that check existed) is replaced with placeholder text naming its type"
|
|
667
686
|
),
|
|
668
687
|
lossy(
|
|
669
688
|
"tool-error-field",
|
|
@@ -685,32 +704,48 @@ var TANSTACK_LOSS_MATRIX = {
|
|
|
685
704
|
"core.memory_op": [OPS],
|
|
686
705
|
"core.handoff": [OPS],
|
|
687
706
|
"core.tool_started": [OPS],
|
|
707
|
+
"core.tools_bound": [OPS],
|
|
688
708
|
"core.run_ended": [OPS],
|
|
689
|
-
"core.error": [OPS]
|
|
709
|
+
"core.error": [OPS],
|
|
710
|
+
"ext.*": [
|
|
711
|
+
dropped(
|
|
712
|
+
"host extension events have no general landing; translate the ones the model must see into core events in the projection layer"
|
|
713
|
+
)
|
|
714
|
+
]
|
|
690
715
|
};
|
|
691
716
|
|
|
692
717
|
// src/middleware.ts
|
|
693
718
|
import {
|
|
719
|
+
assertDecisionsAwaitApproval,
|
|
720
|
+
awaitingOf,
|
|
694
721
|
BUILTIN_APPROVAL_POLICY,
|
|
695
722
|
computeConfigHash,
|
|
696
723
|
createCoreRegistry,
|
|
697
724
|
createEvent,
|
|
698
|
-
DEFAULT_MODEL_INVISIBLE_TYPES,
|
|
699
725
|
errorMessageOf as errorMessageOf2,
|
|
726
|
+
estimateTotal,
|
|
727
|
+
handoffOpeningDrafts,
|
|
728
|
+
isModelInvisibleByDefault,
|
|
700
729
|
isReplayable,
|
|
701
730
|
outcomeUnknownText,
|
|
702
731
|
pauseDetailOf,
|
|
703
732
|
pendingToolCalls,
|
|
704
733
|
project,
|
|
734
|
+
RunStateError,
|
|
705
735
|
readTimeline,
|
|
736
|
+
resolveReserveTokens,
|
|
706
737
|
resolveSocketContributions,
|
|
707
738
|
resolveSocketPause,
|
|
739
|
+
roughTokenEstimate,
|
|
708
740
|
toolBatchOf,
|
|
709
741
|
toolResultTrust,
|
|
710
742
|
toolStartedAt,
|
|
711
743
|
toolsBoundDrafts,
|
|
712
744
|
uuidv7
|
|
713
745
|
} from "@reinsjs/core";
|
|
746
|
+
import {
|
|
747
|
+
DISCOVERY_TOOL_NAME as DISCOVERY_TOOL_NAME2
|
|
748
|
+
} from "@tanstack/ai";
|
|
714
749
|
import { GenericInterruptDefinitionRegistryCapability } from "@tanstack/ai/adapter-internals";
|
|
715
750
|
|
|
716
751
|
// src/tools.ts
|
|
@@ -719,12 +754,14 @@ import {
|
|
|
719
754
|
isSubagentPause,
|
|
720
755
|
normalizeToolOutput
|
|
721
756
|
} from "@reinsjs/core";
|
|
722
|
-
import { convertSchemaToJsonSchema } from "@tanstack/ai";
|
|
757
|
+
import { convertSchemaToJsonSchema, DISCOVERY_TOOL_NAME } from "@tanstack/ai";
|
|
723
758
|
var NATIVE_TOOL = /* @__PURE__ */ Symbol("reins.tanstack.nativeTool");
|
|
724
759
|
function isNativeToolView(tool) {
|
|
725
760
|
return tool !== void 0 && tool[NATIVE_TOOL] === true;
|
|
726
761
|
}
|
|
727
|
-
|
|
762
|
+
var RISKS = /* @__PURE__ */ new Set(["low", "medium", "high"]);
|
|
763
|
+
function viewOfTanstackTool(tool, options = {}) {
|
|
764
|
+
const warn = typeof options === "object" && options !== null ? options.warn : void 0;
|
|
728
765
|
const view = {
|
|
729
766
|
[NATIVE_TOOL]: true,
|
|
730
767
|
name: tool.name,
|
|
@@ -735,6 +772,21 @@ function viewOfTanstackTool(tool) {
|
|
|
735
772
|
side: tool.execute ? "server" : "client"
|
|
736
773
|
};
|
|
737
774
|
if (tool.needsApproval === true) view.needsApproval = true;
|
|
775
|
+
if (tool.name === DISCOVERY_TOOL_NAME) view.risk = "low";
|
|
776
|
+
const declared = tool.metadata?.reins;
|
|
777
|
+
if (typeof declared === "object" && declared !== null) {
|
|
778
|
+
const { risk, replayable } = declared;
|
|
779
|
+
if (RISKS.has(risk)) view.risk = risk;
|
|
780
|
+
else if (risk !== void 0)
|
|
781
|
+
warn?.(
|
|
782
|
+
`tool ${tool.name}: metadata.reins.risk must be "low", "medium" or "high", got ${JSON.stringify(risk)}; treated as undeclared`
|
|
783
|
+
);
|
|
784
|
+
if (typeof replayable === "boolean") view.replayable = replayable;
|
|
785
|
+
else if (replayable !== void 0)
|
|
786
|
+
warn?.(
|
|
787
|
+
`tool ${tool.name}: metadata.reins.replayable must be a boolean, got ${JSON.stringify(replayable)}; treated as undeclared`
|
|
788
|
+
);
|
|
789
|
+
}
|
|
738
790
|
return view;
|
|
739
791
|
}
|
|
740
792
|
function toTanstackTool(tool, bridge) {
|
|
@@ -742,9 +794,9 @@ function toTanstackTool(tool, bridge) {
|
|
|
742
794
|
name: tool.name,
|
|
743
795
|
description: tool.description,
|
|
744
796
|
inputSchema: tool.inputSchema,
|
|
797
|
+
// 来源标记:这是 reins 包装出来的工具。与宿主工具上的 `metadata.reins = { risk, … }` 声明同键不同义,见 viewOfTanstackTool
|
|
745
798
|
metadata: { reins: true }
|
|
746
799
|
};
|
|
747
|
-
if (tool.needsApproval === true) out.needsApproval = true;
|
|
748
800
|
const execute = tool.execute?.bind(tool);
|
|
749
801
|
if (execute) {
|
|
750
802
|
out.execute = async (args, tctx) => {
|
|
@@ -798,6 +850,45 @@ var CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
|
798
850
|
"core.tool_call",
|
|
799
851
|
"core.tool_result"
|
|
800
852
|
]);
|
|
853
|
+
var NATIVE_APPROVAL_PREFIX = "approval_";
|
|
854
|
+
function nativeResolutionOf(value) {
|
|
855
|
+
if (typeof value === "boolean") return { approved: value };
|
|
856
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
857
|
+
const v = value;
|
|
858
|
+
if (typeof v.approved !== "boolean") return void 0;
|
|
859
|
+
return v.approved && v.editedArgs !== void 0 ? { approved: true, editedArgs: v.editedArgs } : { approved: v.approved };
|
|
860
|
+
}
|
|
861
|
+
function nativeResolutionsOf(config) {
|
|
862
|
+
const out = /* @__PURE__ */ new Map();
|
|
863
|
+
for (const [key, value] of config.resumeToolState?.approvals ?? []) {
|
|
864
|
+
const r = nativeResolutionOf(value);
|
|
865
|
+
if (r) out.set(key.startsWith(NATIVE_APPROVAL_PREFIX) ? key.slice(NATIVE_APPROVAL_PREFIX.length) : key, r);
|
|
866
|
+
}
|
|
867
|
+
for (const item of config.resume ?? []) {
|
|
868
|
+
if (item.status !== "resolved" || !item.interruptId.startsWith(NATIVE_APPROVAL_PREFIX)) continue;
|
|
869
|
+
const r = nativeResolutionOf(item.payload);
|
|
870
|
+
if (r) out.set(item.interruptId.slice(NATIVE_APPROVAL_PREFIX.length), r);
|
|
871
|
+
}
|
|
872
|
+
return out;
|
|
873
|
+
}
|
|
874
|
+
function engineCancelledOf(config) {
|
|
875
|
+
const ids = config.resumeToolState?.cancelledToolCallIds;
|
|
876
|
+
return ids instanceof Set ? ids : void 0;
|
|
877
|
+
}
|
|
878
|
+
function isEngineCancelled(r) {
|
|
879
|
+
return r.result?.error === "Tool execution cancelled";
|
|
880
|
+
}
|
|
881
|
+
function sameArgs(a, b) {
|
|
882
|
+
const canonical = (v) => {
|
|
883
|
+
if (Array.isArray(v)) return v.map(canonical);
|
|
884
|
+
if (typeof v === "object" && v !== null)
|
|
885
|
+
return Object.fromEntries(
|
|
886
|
+
Object.keys(v).sort().map((k) => [k, canonical(v[k])])
|
|
887
|
+
);
|
|
888
|
+
return v;
|
|
889
|
+
};
|
|
890
|
+
return JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
|
|
891
|
+
}
|
|
801
892
|
function defaultCapabilities(partial) {
|
|
802
893
|
return {
|
|
803
894
|
api: TANSTACK_API,
|
|
@@ -834,10 +925,20 @@ function toReinsUsage(u) {
|
|
|
834
925
|
}
|
|
835
926
|
function reinsMiddleware(options) {
|
|
836
927
|
const { sessionId, log, sockets = [] } = options;
|
|
928
|
+
resolveReserveTokens({
|
|
929
|
+
contextLimit: options.capabilities.contextWindow,
|
|
930
|
+
...options.projection?.reserveTokens !== void 0 ? { reserveTokens: options.projection.reserveTokens } : {}
|
|
931
|
+
});
|
|
837
932
|
const registry = options.registry ?? createCoreRegistry();
|
|
838
933
|
const now = options.now ?? (() => Date.now());
|
|
839
934
|
const newId = options.newId ?? uuidv7;
|
|
840
935
|
const warn = options.warn ?? ((m) => console.warn(`[reins/adapter-tanstack-ai] ${m}`));
|
|
936
|
+
const warned = /* @__PURE__ */ new Set();
|
|
937
|
+
const warnOnce = (m) => {
|
|
938
|
+
if (warned.has(m)) return;
|
|
939
|
+
warned.add(m);
|
|
940
|
+
warn(m);
|
|
941
|
+
};
|
|
841
942
|
const emitCustom = options.emitCustomEvents ?? true;
|
|
842
943
|
const states = /* @__PURE__ */ new WeakMap();
|
|
843
944
|
const append = async (ctx, s, drafts) => {
|
|
@@ -900,7 +1001,7 @@ function reinsMiddleware(options) {
|
|
|
900
1001
|
const timeline = await timelineOf();
|
|
901
1002
|
const hostTools = /* @__PURE__ */ new Map();
|
|
902
1003
|
for (const t of config.tools) hostTools.set(t.name, t);
|
|
903
|
-
const hostViews = config.tools.map(viewOfTanstackTool);
|
|
1004
|
+
const hostViews = config.tools.map((t) => viewOfTanstackTool(t, { warn: warnOnce }));
|
|
904
1005
|
const setupCfg = {
|
|
905
1006
|
log,
|
|
906
1007
|
model,
|
|
@@ -936,10 +1037,21 @@ function reinsMiddleware(options) {
|
|
|
936
1037
|
callEventIds: /* @__PURE__ */ new Map(),
|
|
937
1038
|
assembler: new BlockAssembler({ provider: model.provider, api: TANSTACK_API, model: model.id }),
|
|
938
1039
|
wrapped: /* @__PURE__ */ new Map(),
|
|
1040
|
+
lastTools: [],
|
|
939
1041
|
approvalInterruptRegistered: approvalInterruptRegistered(ctx),
|
|
1042
|
+
nativeResolutions: nativeResolutionsOf(config),
|
|
1043
|
+
editRefused: /* @__PURE__ */ new Map(),
|
|
1044
|
+
callArgs: /* @__PURE__ */ new Map(),
|
|
1045
|
+
cancelledByReins: /* @__PURE__ */ new Set(),
|
|
1046
|
+
resumed: false,
|
|
940
1047
|
ended: false
|
|
941
1048
|
};
|
|
942
1049
|
states.set(ctx, s);
|
|
1050
|
+
for (const call of pendingToolCalls(timeline)) {
|
|
1051
|
+
const r = s.nativeResolutions.get(call.payload.toolCallId);
|
|
1052
|
+
if (r?.editedArgs === void 0 || !onNativeCard(s, call.payload.name)) continue;
|
|
1053
|
+
if (!sameArgs(r.editedArgs, call.payload.args)) s.editRefused.set(call.payload.toolCallId, r.editedArgs);
|
|
1054
|
+
}
|
|
943
1055
|
s.bridge.toolContextBase.spend = (usage) => {
|
|
944
1056
|
s.tokensSpent += usage.input + usage.output;
|
|
945
1057
|
if (s.turn) s.turn.ctx.budget.tokensSpent = s.tokensSpent;
|
|
@@ -1040,7 +1152,35 @@ function reinsMiddleware(options) {
|
|
|
1040
1152
|
modelEvents: []
|
|
1041
1153
|
};
|
|
1042
1154
|
};
|
|
1043
|
-
const
|
|
1155
|
+
const syncHostTools = (s, engineTools) => {
|
|
1156
|
+
if (engineTools.length === s.lastTools.length && engineTools.every((t, i) => t === s.lastTools[i])) return;
|
|
1157
|
+
const wrapped = new Set(s.wrapped.values());
|
|
1158
|
+
const taken = new Set(s.baseTools.map((t) => t.name));
|
|
1159
|
+
const added = [];
|
|
1160
|
+
for (const t of engineTools) {
|
|
1161
|
+
if (wrapped.has(t) || s.hostTools.get(t.name) === t) continue;
|
|
1162
|
+
if (taken.has(t.name)) {
|
|
1163
|
+
warnOnce(
|
|
1164
|
+
`host tool ${t.name} appeared during the run but a tool with that name is already bound; it was not added`
|
|
1165
|
+
);
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
s.hostTools.set(t.name, t);
|
|
1169
|
+
added.push(viewOfTanstackTool(t, { warn: warnOnce }));
|
|
1170
|
+
taken.add(t.name);
|
|
1171
|
+
}
|
|
1172
|
+
const dropDiscovery = s.hostTools.has(DISCOVERY_TOOL_NAME2) && !engineTools.some((t) => t.name === DISCOVERY_TOOL_NAME2);
|
|
1173
|
+
if (added.length === 0 && !dropDiscovery) return;
|
|
1174
|
+
if (dropDiscovery) s.hostTools.delete(DISCOVERY_TOOL_NAME2);
|
|
1175
|
+
const kept = dropDiscovery ? s.baseTools.filter((t) => !(isNativeToolView(t) && t.name === DISCOVERY_TOOL_NAME2)) : s.baseTools;
|
|
1176
|
+
let at = 0;
|
|
1177
|
+
kept.forEach((t, i) => {
|
|
1178
|
+
if (isNativeToolView(t)) at = i + 1;
|
|
1179
|
+
});
|
|
1180
|
+
s.baseTools = [...kept.slice(0, at), ...added, ...kept.slice(at)];
|
|
1181
|
+
};
|
|
1182
|
+
const beforeModel = async (ctx, s, config) => {
|
|
1183
|
+
syncHostTools(s, config.tools);
|
|
1044
1184
|
const timeline = await timelineOf();
|
|
1045
1185
|
s.turns++;
|
|
1046
1186
|
const turn = await buildTurn(ctx, s, timeline);
|
|
@@ -1058,9 +1198,10 @@ function reinsMiddleware(options) {
|
|
|
1058
1198
|
tctx.tools = tools;
|
|
1059
1199
|
}
|
|
1060
1200
|
const injected = await flush(ctx, s);
|
|
1061
|
-
visible = [...visible, ...injected.filter((e) => !
|
|
1201
|
+
visible = [...visible, ...injected.filter((e) => !isModelInvisibleByDefault(e.type))];
|
|
1062
1202
|
tctx.events = visible;
|
|
1063
1203
|
tctx.tools = tools;
|
|
1204
|
+
turn.estimate = estimateTotal(visible, options.projection?.estimate ?? roughTokenEstimate);
|
|
1064
1205
|
s.turn = turn;
|
|
1065
1206
|
s.assembler.reset();
|
|
1066
1207
|
const { messages, landings } = toModelMessages(visible, {
|
|
@@ -1068,14 +1209,99 @@ function reinsMiddleware(options) {
|
|
|
1068
1209
|
...options.trustMarkers !== void 0 ? { trustMarkers: options.trustMarkers } : {}
|
|
1069
1210
|
});
|
|
1070
1211
|
options.onLandings?.(landings.filter((l) => l.kind !== "exact"));
|
|
1212
|
+
s.lastTools = tanstackToolsOf(s, tools);
|
|
1071
1213
|
return {
|
|
1072
1214
|
providerMessages: messages,
|
|
1073
|
-
tools:
|
|
1215
|
+
tools: s.lastTools,
|
|
1074
1216
|
systemPrompts: systemPrompt !== void 0 ? [systemPrompt] : s.systemPrompts
|
|
1075
1217
|
};
|
|
1076
1218
|
};
|
|
1077
|
-
const
|
|
1219
|
+
const markResumed = async (ctx, s, by) => {
|
|
1220
|
+
if (s.resumed) return;
|
|
1221
|
+
s.resumed = true;
|
|
1222
|
+
await append(ctx, s, [
|
|
1223
|
+
{ type: "core.run_resumed", actor: "host", payload: by !== void 0 ? { by } : {} }
|
|
1224
|
+
]);
|
|
1225
|
+
};
|
|
1226
|
+
const rerunForBlock = async (ctx, s, toolCallId, tool) => {
|
|
1078
1227
|
const timeline = await timelineOf();
|
|
1228
|
+
const call = pendingToolCalls(timeline).find((c) => c.payload.toolCallId === toolCallId);
|
|
1229
|
+
if (!call || !s.turn) return void 0;
|
|
1230
|
+
const tctx = s.turn.ctx;
|
|
1231
|
+
tctx.timeline = timeline;
|
|
1232
|
+
let seen = call;
|
|
1233
|
+
let refused;
|
|
1234
|
+
for (const sock of sockets) {
|
|
1235
|
+
const d = await sock.beforeTool?.(tctx, seen, tool);
|
|
1236
|
+
if (d === void 0 || d === "proceed") continue;
|
|
1237
|
+
if ("rewrite" in d) {
|
|
1238
|
+
seen = { ...seen, payload: { ...seen.payload, args: d.rewrite } };
|
|
1239
|
+
continue;
|
|
1240
|
+
}
|
|
1241
|
+
if ("block" in d) {
|
|
1242
|
+
refused = d.block;
|
|
1243
|
+
break;
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
await flush(ctx, s);
|
|
1247
|
+
return refused;
|
|
1248
|
+
};
|
|
1249
|
+
const passVerdict = (s, name, rewritten, args) => {
|
|
1250
|
+
if (!rewritten) return { kind: "proceed" };
|
|
1251
|
+
if (onNativeCard(s, name))
|
|
1252
|
+
return {
|
|
1253
|
+
kind: "block",
|
|
1254
|
+
text: "the arguments were rewritten by a socket, but TanStack's native approval card shows the arguments the model wrote, so the call was not executed"
|
|
1255
|
+
};
|
|
1256
|
+
return { kind: "rewrite", args };
|
|
1257
|
+
};
|
|
1258
|
+
const onNativeCard = (s, name) => s.hostTools.get(name)?.needsApproval === true;
|
|
1259
|
+
const isClientTool = (s, name) => {
|
|
1260
|
+
const t = s.hostTools.get(name) ?? s.wrapped.get(name);
|
|
1261
|
+
return t !== void 0 && typeof t.execute !== "function";
|
|
1262
|
+
};
|
|
1263
|
+
const recordNativeResolutions = async (ctx, s, timeline) => {
|
|
1264
|
+
if (s.nativeResolutions.size === 0) return false;
|
|
1265
|
+
const resolutions = s.nativeResolutions;
|
|
1266
|
+
s.nativeResolutions = /* @__PURE__ */ new Map();
|
|
1267
|
+
const pending = pendingToolCalls(timeline);
|
|
1268
|
+
const awaiting = new Set(
|
|
1269
|
+
awaitingOf({ timeline, pending, tools: [], interruptions: [] }).filter((a) => a.kind === "approval").map((a) => a.toolCallId)
|
|
1270
|
+
);
|
|
1271
|
+
const drafts = [];
|
|
1272
|
+
for (const call of pending) {
|
|
1273
|
+
const { toolCallId, name } = call.payload;
|
|
1274
|
+
const r = resolutions.get(toolCallId);
|
|
1275
|
+
if (!r || !awaiting.has(toolCallId) || !onNativeCard(s, name)) continue;
|
|
1276
|
+
drafts.push({
|
|
1277
|
+
type: "core.approval_decision",
|
|
1278
|
+
actor: "host",
|
|
1279
|
+
parentId: call.id,
|
|
1280
|
+
payload: { toolCallId, approved: r.approved, by: TANSTACK_DECIDER }
|
|
1281
|
+
});
|
|
1282
|
+
const edited = s.editRefused.get(toolCallId);
|
|
1283
|
+
if (edited !== void 0) {
|
|
1284
|
+
drafts.push({
|
|
1285
|
+
type: "core.approval_decision",
|
|
1286
|
+
actor: "system",
|
|
1287
|
+
parentId: call.id,
|
|
1288
|
+
payload: {
|
|
1289
|
+
toolCallId,
|
|
1290
|
+
approved: false,
|
|
1291
|
+
by: "reins",
|
|
1292
|
+
reason: `the approver edited the arguments to ${JSON.stringify(edited)}; edited arguments cannot be recorded in the timeline, so the call was not executed. Make the call again with the arguments you intend to use`
|
|
1293
|
+
}
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
if (drafts.length === 0) return false;
|
|
1298
|
+
await markResumed(ctx, s, TANSTACK_DECIDER);
|
|
1299
|
+
await append(ctx, s, drafts);
|
|
1300
|
+
return true;
|
|
1301
|
+
};
|
|
1302
|
+
const beforeTools = async (ctx, s) => {
|
|
1303
|
+
let timeline = await timelineOf();
|
|
1304
|
+
if (await recordNativeResolutions(ctx, s, timeline)) timeline = await timelineOf();
|
|
1079
1305
|
const pending = pendingToolCalls(timeline);
|
|
1080
1306
|
if (pending.length === 0) return void 0;
|
|
1081
1307
|
if (!s.turn) {
|
|
@@ -1098,6 +1324,7 @@ function reinsMiddleware(options) {
|
|
|
1098
1324
|
for (const call of pending) {
|
|
1099
1325
|
const { toolCallId, name } = call.payload;
|
|
1100
1326
|
s.callEventIds.set(toolCallId, call.id);
|
|
1327
|
+
s.callArgs.set(toolCallId, call.payload.args);
|
|
1101
1328
|
const tool = tctx.tools.find((t) => t.name === name);
|
|
1102
1329
|
if (started.has(toolCallId) && (tool === void 0 || !isReplayable(tool))) {
|
|
1103
1330
|
s.verdicts.set(toolCallId, {
|
|
@@ -1145,11 +1372,30 @@ function reinsMiddleware(options) {
|
|
|
1145
1372
|
valid = false;
|
|
1146
1373
|
}
|
|
1147
1374
|
if (valid) {
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1375
|
+
let need;
|
|
1376
|
+
try {
|
|
1377
|
+
need = typeof tool.needsApproval === "function" ? await tool.needsApproval(input, {
|
|
1378
|
+
...toolContextBase(),
|
|
1379
|
+
toolCallId,
|
|
1380
|
+
emit: (d) => s.emitted.push(d)
|
|
1381
|
+
}) : tool.needsApproval;
|
|
1382
|
+
} catch (err) {
|
|
1383
|
+
s.emitted.push({
|
|
1384
|
+
type: "core.error",
|
|
1385
|
+
actor: "system",
|
|
1386
|
+
payload: {
|
|
1387
|
+
category: "host",
|
|
1388
|
+
message: `needsApproval of ${name} threw: ${errorMessageOf2(err)}`,
|
|
1389
|
+
retryable: false,
|
|
1390
|
+
detail: { phase: "needsApproval", toolCallId }
|
|
1391
|
+
}
|
|
1392
|
+
});
|
|
1393
|
+
s.verdicts.set(toolCallId, {
|
|
1394
|
+
kind: "unknown",
|
|
1395
|
+
text: `Approval check failed: ${errorMessageOf2(err)}`
|
|
1396
|
+
});
|
|
1397
|
+
continue;
|
|
1398
|
+
}
|
|
1153
1399
|
if (need)
|
|
1154
1400
|
approval = {
|
|
1155
1401
|
policyId: BUILTIN_APPROVAL_POLICY,
|
|
@@ -1158,6 +1404,18 @@ function reinsMiddleware(options) {
|
|
|
1158
1404
|
}
|
|
1159
1405
|
}
|
|
1160
1406
|
if (approval && !decided?.approved) {
|
|
1407
|
+
if (tool && isNativeToolView(tool) && tool.needsApproval === true) {
|
|
1408
|
+
if (!requested.has(toolCallId)) {
|
|
1409
|
+
s.emitted.push({
|
|
1410
|
+
type: "core.approval_request",
|
|
1411
|
+
actor: "system",
|
|
1412
|
+
parentId: call.id,
|
|
1413
|
+
payload: { toolCallId, policyId: approval.policyId, summary: approval.summary }
|
|
1414
|
+
});
|
|
1415
|
+
}
|
|
1416
|
+
s.verdicts.set(toolCallId, passVerdict(s, name, rewritten, args));
|
|
1417
|
+
continue;
|
|
1418
|
+
}
|
|
1161
1419
|
if (!requested.has(toolCallId)) {
|
|
1162
1420
|
s.emitted.push({
|
|
1163
1421
|
type: "core.approval_request",
|
|
@@ -1188,7 +1446,15 @@ function reinsMiddleware(options) {
|
|
|
1188
1446
|
s.verdicts.set(toolCallId, { kind: "await" });
|
|
1189
1447
|
continue;
|
|
1190
1448
|
}
|
|
1191
|
-
s.verdicts.set(toolCallId,
|
|
1449
|
+
s.verdicts.set(toolCallId, passVerdict(s, name, rewritten, args));
|
|
1450
|
+
}
|
|
1451
|
+
for (const call of pending) {
|
|
1452
|
+
const { toolCallId, name } = call.payload;
|
|
1453
|
+
const kind = s.verdicts.get(toolCallId)?.kind;
|
|
1454
|
+
if ((kind === "block" || kind === "unknown") && isClientTool(s, name) && s.engineCancelled) {
|
|
1455
|
+
s.engineCancelled.add(toolCallId);
|
|
1456
|
+
s.cancelledByReins.add(toolCallId);
|
|
1457
|
+
}
|
|
1192
1458
|
}
|
|
1193
1459
|
await flush(ctx, s);
|
|
1194
1460
|
if (interrupts.length === 0) return void 0;
|
|
@@ -1245,11 +1511,16 @@ function reinsMiddleware(options) {
|
|
|
1245
1511
|
const answered = /* @__PURE__ */ new Set();
|
|
1246
1512
|
const requested = /* @__PURE__ */ new Set();
|
|
1247
1513
|
const decided = /* @__PURE__ */ new Set();
|
|
1514
|
+
const nativeDenied = /* @__PURE__ */ new Set();
|
|
1248
1515
|
for (const raw of timeline) {
|
|
1249
1516
|
const e = raw;
|
|
1250
1517
|
if (e.type === "core.tool_result") answered.add(e.payload.toolCallId);
|
|
1251
1518
|
if (e.type === "core.approval_request") requested.add(e.payload.toolCallId);
|
|
1252
|
-
if (e.type === "core.approval_decision")
|
|
1519
|
+
if (e.type === "core.approval_decision") {
|
|
1520
|
+
decided.add(e.payload.toolCallId);
|
|
1521
|
+
if (e.payload.by === TANSTACK_DECIDER && !e.payload.approved) nativeDenied.add(e.payload.toolCallId);
|
|
1522
|
+
else if (e.payload.by === TANSTACK_DECIDER) nativeDenied.delete(e.payload.toolCallId);
|
|
1523
|
+
}
|
|
1253
1524
|
}
|
|
1254
1525
|
const pending = pendingToolCalls(timeline);
|
|
1255
1526
|
for (const r of info.results) {
|
|
@@ -1263,12 +1534,25 @@ function reinsMiddleware(options) {
|
|
|
1263
1534
|
payload: { toolCallId: r.toolCallId, approved: !isError, by: TANSTACK_DECIDER }
|
|
1264
1535
|
});
|
|
1265
1536
|
}
|
|
1266
|
-
const
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
)
|
|
1537
|
+
const verdict = s.verdicts.get(r.toolCallId);
|
|
1538
|
+
const blocked = verdict?.kind === "block" || verdict?.kind === "unknown";
|
|
1539
|
+
const enforced = !isClientTool(s, r.toolName) || (s.cancelledByReins.has(r.toolCallId) || s.editRefused.has(r.toolCallId)) && isEngineCancelled(r) || nativeDenied.has(r.toolCallId);
|
|
1540
|
+
const result = blocked && enforced ? errorResult(verdict.kind === "block" ? `Tool call blocked: ${verdict.text}` : verdict.text) : { content: fromTanstackToolResult(r.result), isError };
|
|
1541
|
+
await settle(ctx, s, resultDraft(call, r.toolCallId, r.toolName, result, toolNamed(s, r.toolName)));
|
|
1542
|
+
if (blocked && !enforced) {
|
|
1543
|
+
await append(ctx, s, [
|
|
1544
|
+
{
|
|
1545
|
+
type: "core.error",
|
|
1546
|
+
actor: "system",
|
|
1547
|
+
payload: {
|
|
1548
|
+
category: TANSTACK_API,
|
|
1549
|
+
message: `A socket blocked client tool call ${r.toolCallId} (${r.toolName}), but the block was not enforced: TanStack handed the call to the client, which ran it. The real result is recorded`,
|
|
1550
|
+
retryable: false,
|
|
1551
|
+
detail: { toolCallId: r.toolCallId, name: r.toolName, verdict: verdict.text }
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
]);
|
|
1555
|
+
}
|
|
1272
1556
|
answered.add(r.toolCallId);
|
|
1273
1557
|
}
|
|
1274
1558
|
for (const a of info.needsApproval) {
|
|
@@ -1293,7 +1577,7 @@ function reinsMiddleware(options) {
|
|
|
1293
1577
|
};
|
|
1294
1578
|
const doHandoff = async (ctx, s, intent) => {
|
|
1295
1579
|
const toSessionId = intent.toSessionId ?? newId(now());
|
|
1296
|
-
await append(ctx, s, [
|
|
1580
|
+
const [handoffEvent] = await append(ctx, s, [
|
|
1297
1581
|
{
|
|
1298
1582
|
type: "core.handoff",
|
|
1299
1583
|
actor: intent.by ?? "model",
|
|
@@ -1306,21 +1590,11 @@ function reinsMiddleware(options) {
|
|
|
1306
1590
|
}
|
|
1307
1591
|
]);
|
|
1308
1592
|
const at = now();
|
|
1309
|
-
const opening =
|
|
1310
|
-
{ type: "core.system_note", actor: "host", payload: { kind: "host", text: intent.summary } },
|
|
1311
|
-
...intent.opening ?? []
|
|
1312
|
-
];
|
|
1313
|
-
if (intent.triggerMessage !== void 0)
|
|
1314
|
-
opening.push({
|
|
1315
|
-
type: "core.user_message",
|
|
1316
|
-
actor: "user",
|
|
1317
|
-
payload: { content: [{ type: "text", text: intent.triggerMessage }] }
|
|
1318
|
-
});
|
|
1593
|
+
const opening = handoffOpeningDrafts(intent, handoffEvent, await timelineOf());
|
|
1319
1594
|
const events = opening.map(
|
|
1320
1595
|
(d, i) => createEvent(registry, { ...d, sessionId: toSessionId, seq: i + 1, at, id: newId(at) })
|
|
1321
1596
|
);
|
|
1322
1597
|
await log.append(events);
|
|
1323
|
-
for (const e of events) options.onEvent?.(e);
|
|
1324
1598
|
await append(ctx, s, [
|
|
1325
1599
|
{ type: "core.run_ended", actor: "system", payload: { status: "handoff", toSessionId } }
|
|
1326
1600
|
]);
|
|
@@ -1331,11 +1605,27 @@ function reinsMiddleware(options) {
|
|
|
1331
1605
|
async onConfig(ctx, config) {
|
|
1332
1606
|
if (ctx.phase === "init") {
|
|
1333
1607
|
const s2 = await initRun(ctx, config);
|
|
1334
|
-
|
|
1608
|
+
const cancelled2 = engineCancelledOf(config);
|
|
1609
|
+
if (cancelled2) s2.engineCancelled = cancelled2;
|
|
1610
|
+
s2.lastTools = tanstackToolsOf(s2, s2.baseTools);
|
|
1611
|
+
if (s2.editRefused.size === 0) return { tools: s2.lastTools, systemPrompts: s2.systemPrompts };
|
|
1612
|
+
return {
|
|
1613
|
+
tools: s2.lastTools,
|
|
1614
|
+
systemPrompts: s2.systemPrompts,
|
|
1615
|
+
resumeToolState: {
|
|
1616
|
+
...config.resumeToolState,
|
|
1617
|
+
cancelledToolCallIds: /* @__PURE__ */ new Set([
|
|
1618
|
+
...config.resumeToolState?.cancelledToolCallIds ?? [],
|
|
1619
|
+
...s2.editRefused.keys()
|
|
1620
|
+
])
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1335
1623
|
}
|
|
1336
1624
|
const s = states.get(ctx);
|
|
1337
1625
|
if (!s) return void 0;
|
|
1338
|
-
|
|
1626
|
+
const cancelled = engineCancelledOf(config);
|
|
1627
|
+
if (cancelled) s.engineCancelled = cancelled;
|
|
1628
|
+
if (ctx.phase === "beforeModel" || ctx.phase === "structuredOutput") return beforeModel(ctx, s, config);
|
|
1339
1629
|
return void 0;
|
|
1340
1630
|
},
|
|
1341
1631
|
async onChunk(ctx, chunk) {
|
|
@@ -1390,18 +1680,46 @@ function reinsMiddleware(options) {
|
|
|
1390
1680
|
async onInterruptResolution(ctx, resolutions) {
|
|
1391
1681
|
const s = states.get(ctx);
|
|
1392
1682
|
if (!s) return void 0;
|
|
1683
|
+
const timeline = await timelineOf();
|
|
1684
|
+
const pending = pendingToolCalls(timeline);
|
|
1685
|
+
const accepted = [];
|
|
1686
|
+
const drafts = [];
|
|
1393
1687
|
for (const r of resolutions.for(reinsApprovalInterrupt)) {
|
|
1394
1688
|
const approved = r.status === "resolved" && r.response.approved === true;
|
|
1395
1689
|
const by = r.status === "resolved" && r.response.by ? r.response.by : TANSTACK_DECIDER;
|
|
1396
1690
|
const reason = r.status === "resolved" ? r.response.reason : "Approval was cancelled";
|
|
1397
|
-
|
|
1691
|
+
const decision = {
|
|
1692
|
+
toolCallId: r.request.key,
|
|
1693
|
+
approved,
|
|
1694
|
+
by,
|
|
1695
|
+
...reason !== void 0 ? { reason } : {}
|
|
1696
|
+
};
|
|
1697
|
+
try {
|
|
1698
|
+
assertDecisionsAwaitApproval({ sessionId, timeline, decisions: [...accepted, decision] });
|
|
1699
|
+
} catch (err) {
|
|
1700
|
+
if (!(err instanceof RunStateError)) throw err;
|
|
1701
|
+
warn(`ignored an approval answer from the client: ${err.message}`);
|
|
1702
|
+
continue;
|
|
1703
|
+
}
|
|
1704
|
+
const call = pending.find((c) => c.payload.toolCallId === decision.toolCallId);
|
|
1705
|
+
if (call && onNativeCard(s, call.payload.name)) {
|
|
1706
|
+
warn(
|
|
1707
|
+
`ignored an approval answer from the client: call ${decision.toolCallId} is approved through TanStack's native approval, never through reinsApprovalInterrupt`
|
|
1708
|
+
);
|
|
1709
|
+
continue;
|
|
1710
|
+
}
|
|
1711
|
+
accepted.push(decision);
|
|
1712
|
+
drafts.push({
|
|
1398
1713
|
type: "core.approval_decision",
|
|
1399
1714
|
actor: "host",
|
|
1400
|
-
|
|
1715
|
+
...call ? { parentId: call.id } : {},
|
|
1716
|
+
payload: decision
|
|
1401
1717
|
});
|
|
1402
1718
|
}
|
|
1403
|
-
|
|
1404
|
-
|
|
1719
|
+
if (drafts.length > 0) {
|
|
1720
|
+
await markResumed(ctx, s, accepted[0]?.by);
|
|
1721
|
+
await append(ctx, s, drafts);
|
|
1722
|
+
}
|
|
1405
1723
|
return { toolResume: "continue" };
|
|
1406
1724
|
},
|
|
1407
1725
|
async onBeforeToolCall(ctx, hookCtx) {
|
|
@@ -1410,7 +1728,49 @@ function reinsMiddleware(options) {
|
|
|
1410
1728
|
if (!s || !v) return void 0;
|
|
1411
1729
|
if (v.kind === "block") return { type: "skip", result: { error: `Tool call blocked: ${v.text}` } };
|
|
1412
1730
|
if (v.kind === "unknown") return { type: "skip", result: { error: v.text } };
|
|
1731
|
+
const block = (text) => {
|
|
1732
|
+
s.verdicts.set(hookCtx.toolCallId, { kind: "block", text });
|
|
1733
|
+
return { type: "skip", result: { error: `Tool call blocked: ${text}` } };
|
|
1734
|
+
};
|
|
1735
|
+
if (s.callArgs.has(hookCtx.toolCallId)) {
|
|
1736
|
+
const logged = s.callArgs.get(hookCtx.toolCallId);
|
|
1737
|
+
const expected = typeof logged === "object" && logged !== null ? logged : {};
|
|
1738
|
+
let actual;
|
|
1739
|
+
try {
|
|
1740
|
+
const parsed = JSON.parse(hookCtx.toolCall.function.arguments.trim() || "{}");
|
|
1741
|
+
actual = typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
1742
|
+
} catch {
|
|
1743
|
+
actual = void 0;
|
|
1744
|
+
}
|
|
1745
|
+
if (actual === void 0 || !sameArgs(actual, expected))
|
|
1746
|
+
return block(
|
|
1747
|
+
`the call about to run (${hookCtx.toolCall.function.arguments}) differs from the call in the timeline, so it was not executed. Make the call again if you still need it`
|
|
1748
|
+
);
|
|
1749
|
+
}
|
|
1413
1750
|
const tool = toolNamed(s, hookCtx.toolName);
|
|
1751
|
+
if (tool && isNativeToolView(tool) && tool.needsApproval === true) {
|
|
1752
|
+
const timeline = await timelineOf();
|
|
1753
|
+
const awaiting = awaitingOf({
|
|
1754
|
+
timeline,
|
|
1755
|
+
pending: pendingToolCalls(timeline),
|
|
1756
|
+
tools: [],
|
|
1757
|
+
interruptions: []
|
|
1758
|
+
}).some((a) => a.kind === "approval" && a.toolCallId === hookCtx.toolCallId);
|
|
1759
|
+
if (awaiting) {
|
|
1760
|
+
const parentId = s.callEventIds.get(hookCtx.toolCallId);
|
|
1761
|
+
await markResumed(ctx, s, TANSTACK_DECIDER);
|
|
1762
|
+
await append(ctx, s, [
|
|
1763
|
+
{
|
|
1764
|
+
type: "core.approval_decision",
|
|
1765
|
+
actor: "host",
|
|
1766
|
+
...parentId !== void 0 ? { parentId } : {},
|
|
1767
|
+
payload: { toolCallId: hookCtx.toolCallId, approved: true, by: TANSTACK_DECIDER }
|
|
1768
|
+
}
|
|
1769
|
+
]);
|
|
1770
|
+
const refused = await rerunForBlock(ctx, s, hookCtx.toolCallId, tool);
|
|
1771
|
+
if (refused !== void 0) return block(refused);
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1414
1774
|
if (v.kind !== "await" && (tool === void 0 || !isReplayable(tool))) {
|
|
1415
1775
|
const parentId = s.callEventIds.get(hookCtx.toolCallId);
|
|
1416
1776
|
await append(ctx, s, [
|