@reinsjs/brain 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -1
- package/README.md +5 -3
- package/dist/index.d.ts +167 -4
- package/dist/index.js +349 -46
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.js
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
var APPROVAL_RULES = `Tool permissions:
|
|
14
14
|
- Some tool calls require human approval before they run. When that happens the run pauses until a person decides; this is normal, not an error. Do not repeat the call while it is waiting.
|
|
15
15
|
- A call may be denied by policy. A denied call returns an error naming the policy; do not retry it with the same or a disguised input. Explain what you were trying to do and ask the user how to proceed.`;
|
|
16
|
+
var APPROVAL_EXPIRY_RULE = `- An approval can expire if it arrives too late. The call is then not run and the error says so; unlike a policy denial, you may make the same call again to request a fresh approval.`;
|
|
16
17
|
|
|
17
18
|
// src/approval/approval.ts
|
|
18
19
|
var APPROVAL_SOCKET_NAME = "approval";
|
|
@@ -24,9 +25,27 @@ var APPROVAL_POLICY_IDS = {
|
|
|
24
25
|
unmatched: "approval.unmatched",
|
|
25
26
|
/** 三段都没命中、按 risk 兜底:`approval.risk.<low|medium|high|undeclared>` */
|
|
26
27
|
risk: (level) => `approval.risk.${level ?? "undeclared"}`,
|
|
27
|
-
/** 入参没过工具自己的 validate:不问人、放行给循环以"
|
|
28
|
-
invalidArgs: "approval.invalid_args"
|
|
28
|
+
/** 入参没过工具自己的 validate:不问人、放行给循环以"Invalid arguments"拒掉(执行不会发生) */
|
|
29
|
+
invalidArgs: "approval.invalid_args",
|
|
30
|
+
/** 宿主的批准到得太晚(超过 `ttlMs`),按拒绝处理 */
|
|
31
|
+
expired: "approval.expired"
|
|
29
32
|
};
|
|
33
|
+
function findExpiredApproval(timeline, toolCallId, ttlMs) {
|
|
34
|
+
let request;
|
|
35
|
+
let approvedAt;
|
|
36
|
+
for (const raw of timeline) {
|
|
37
|
+
const e = raw;
|
|
38
|
+
if (e.type === "core.approval_request" && e.payload.toolCallId === toolCallId) {
|
|
39
|
+
request = e;
|
|
40
|
+
approvedAt = void 0;
|
|
41
|
+
} else if (e.type === "core.approval_decision" && e.payload.toolCallId === toolCallId && e.payload.approved && request !== void 0) {
|
|
42
|
+
approvedAt = e.at;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (request === void 0 || approvedAt === void 0) return void 0;
|
|
46
|
+
const ageMs = approvedAt - request.at;
|
|
47
|
+
return ageMs > ttlMs ? { requestedAt: request.at, decidedAt: approvedAt, ageMs } : void 0;
|
|
48
|
+
}
|
|
30
49
|
function validatedCall(call) {
|
|
31
50
|
const tool = call.tool;
|
|
32
51
|
if (!tool?.validate) return call;
|
|
@@ -55,18 +74,22 @@ async function evaluatePolicy(call, ctx, stages, opts) {
|
|
|
55
74
|
const denyBy = (rule) => ({
|
|
56
75
|
verdict: "deny",
|
|
57
76
|
policyId: rule.id,
|
|
58
|
-
reason: rule.reason ??
|
|
77
|
+
reason: rule.reason ?? `policy ${rule.id} does not allow calling ${call.name}`
|
|
59
78
|
});
|
|
60
79
|
const failClosed = (rule, err) => {
|
|
61
80
|
opts.onError?.(rule, err);
|
|
62
81
|
return {
|
|
63
82
|
verdict: "deny",
|
|
64
83
|
policyId: rule,
|
|
65
|
-
reason:
|
|
84
|
+
reason: `policy ${rule} threw while being evaluated and is treated as a denial: ${err instanceof Error ? err.message : String(err)}`
|
|
66
85
|
};
|
|
67
86
|
};
|
|
68
87
|
if (!call.tool) {
|
|
69
|
-
return {
|
|
88
|
+
return {
|
|
89
|
+
verdict: "deny",
|
|
90
|
+
policyId: APPROVAL_POLICY_IDS.unknownTool,
|
|
91
|
+
reason: `unknown tool: ${call.name}`
|
|
92
|
+
};
|
|
70
93
|
}
|
|
71
94
|
const tool = call.tool;
|
|
72
95
|
const validated = validatedCall(call);
|
|
@@ -105,7 +128,7 @@ async function evaluatePolicy(call, ctx, stages, opts) {
|
|
|
105
128
|
return {
|
|
106
129
|
verdict: "deny",
|
|
107
130
|
policyId: APPROVAL_POLICY_IDS.unmatched,
|
|
108
|
-
reason:
|
|
131
|
+
reason: `no policy allows calling ${call.name}`
|
|
109
132
|
};
|
|
110
133
|
case "ask":
|
|
111
134
|
return { verdict: "ask", policyId: APPROVAL_POLICY_IDS.unmatched, summary: summaryOf(void 0) };
|
|
@@ -137,7 +160,12 @@ function approval(options = {}) {
|
|
|
137
160
|
const unmatched = options.unmatched ?? "byRisk";
|
|
138
161
|
const maxSummaryChars = options.maxSummaryChars ?? DEFAULT_MAX_SUMMARY_CHARS;
|
|
139
162
|
const warn = options.warn ?? ((message) => console.warn(message));
|
|
140
|
-
const
|
|
163
|
+
const ttlMs = options.ttlMs;
|
|
164
|
+
if (ttlMs !== void 0 && !(Number.isFinite(ttlMs) && ttlMs > 0)) {
|
|
165
|
+
throw new RangeError(`approval.ttlMs must be a positive finite number, got ${String(ttlMs)}`);
|
|
166
|
+
}
|
|
167
|
+
const rules = options.rules === void 0 ? ttlMs === void 0 ? APPROVAL_RULES : `${APPROVAL_RULES}
|
|
168
|
+
${APPROVAL_EXPIRY_RULE}` : options.rules;
|
|
141
169
|
return {
|
|
142
170
|
name: APPROVAL_SOCKET_NAME,
|
|
143
171
|
...rules === false ? {} : { systemPrompt: rules },
|
|
@@ -147,22 +175,33 @@ function approval(options = {}) {
|
|
|
147
175
|
unmatched,
|
|
148
176
|
maxSummaryChars,
|
|
149
177
|
onError: (rule, err) => warn(
|
|
150
|
-
`[reins/approval]
|
|
178
|
+
`[reins/approval] Policy ${rule} threw while being evaluated and was treated as a denial (${name}): ${err instanceof Error ? err.message : String(err)}`
|
|
151
179
|
)
|
|
152
180
|
});
|
|
181
|
+
const deny = (policyId, reason) => {
|
|
182
|
+
ctx.emit({
|
|
183
|
+
type: "core.approval_decision",
|
|
184
|
+
actor: "system",
|
|
185
|
+
parentId: call.id,
|
|
186
|
+
payload: { toolCallId, approved: false, by: policyId, reason }
|
|
187
|
+
});
|
|
188
|
+
return { block: reason };
|
|
189
|
+
};
|
|
153
190
|
switch (outcome.verdict) {
|
|
154
191
|
case "allow":
|
|
155
192
|
return "proceed";
|
|
156
|
-
case "ask":
|
|
193
|
+
case "ask": {
|
|
194
|
+
const expired = ttlMs === void 0 ? void 0 : findExpiredApproval(ctx.timeline, toolCallId, ttlMs);
|
|
195
|
+
if (expired !== void 0) {
|
|
196
|
+
return deny(
|
|
197
|
+
APPROVAL_POLICY_IDS.expired,
|
|
198
|
+
`Approval expired: it arrived ${expired.ageMs} ms after the request, beyond the ${ttlMs} ms lifetime, so the call was not executed. If you still need it, make the call again to request a fresh approval`
|
|
199
|
+
);
|
|
200
|
+
}
|
|
157
201
|
return { defer: { policyId: outcome.policyId, summary: outcome.summary } };
|
|
202
|
+
}
|
|
158
203
|
case "deny":
|
|
159
|
-
|
|
160
|
-
type: "core.approval_decision",
|
|
161
|
-
actor: "system",
|
|
162
|
-
parentId: call.id,
|
|
163
|
-
payload: { toolCallId, approved: false, by: outcome.policyId, reason: outcome.reason }
|
|
164
|
-
});
|
|
165
|
-
return { block: outcome.reason };
|
|
204
|
+
return deny(outcome.policyId, outcome.reason);
|
|
166
205
|
}
|
|
167
206
|
}
|
|
168
207
|
};
|
|
@@ -175,7 +214,9 @@ function assertLimits(limits) {
|
|
|
175
214
|
for (const [dimension, limit] of Object.entries(limits)) {
|
|
176
215
|
if (limit === void 0) continue;
|
|
177
216
|
if (typeof limit !== "number" || !Number.isFinite(limit) || limit <= 0) {
|
|
178
|
-
throw new RangeError(
|
|
217
|
+
throw new RangeError(
|
|
218
|
+
`budget.limits.${dimension} must be a positive finite number, got ${String(limit)}`
|
|
219
|
+
);
|
|
179
220
|
}
|
|
180
221
|
}
|
|
181
222
|
}
|
|
@@ -598,7 +639,7 @@ function receipt(plan, withRecall) {
|
|
|
598
639
|
function compact(opts = {}) {
|
|
599
640
|
const maxConsecutive = opts.maxConsecutive ?? DEFAULT_MAX_CONSECUTIVE_COMPACTIONS;
|
|
600
641
|
if (!Number.isInteger(maxConsecutive) || maxConsecutive < 1) {
|
|
601
|
-
throw new RangeError(`compact.maxConsecutive
|
|
642
|
+
throw new RangeError(`compact.maxConsecutive must be an integer >= 1, got ${String(maxConsecutive)}`);
|
|
602
643
|
}
|
|
603
644
|
const withRecall = opts.recall ?? true;
|
|
604
645
|
const records = /* @__PURE__ */ new WeakMap();
|
|
@@ -872,6 +913,244 @@ function handoff(opts = {}) {
|
|
|
872
913
|
return socket;
|
|
873
914
|
}
|
|
874
915
|
|
|
916
|
+
// src/lazy-tools/lazy-tools.ts
|
|
917
|
+
import {
|
|
918
|
+
estimateTextTokens
|
|
919
|
+
} from "@reinsjs/core";
|
|
920
|
+
|
|
921
|
+
// src/lazy-tools/rules.ts
|
|
922
|
+
import { renderToolReference } from "@reinsjs/core";
|
|
923
|
+
var TOOL_FIND_TOOL_NAME = "tool_find";
|
|
924
|
+
var TOOL_FIND_TOOL_DESCRIPTION = [
|
|
925
|
+
"Load tools from the on-request list so you can call them.",
|
|
926
|
+
'`names` are tool names exactly as listed under "Tools available on request".',
|
|
927
|
+
"The result gives each tool's full description and input schema, and the tools appear in your tool list from your next turn on.",
|
|
928
|
+
"Ask for every listed tool the task will need in one call."
|
|
929
|
+
].join(" ");
|
|
930
|
+
var LAZY_TOOL_RULES = `## Tools available on request
|
|
931
|
+
The tools listed below are bound to this session but not loaded yet: only a name and a one-line summary are shown, and they cannot be called until loaded.
|
|
932
|
+
- Before starting work that needs one of them, call \`${TOOL_FIND_TOOL_NAME}({ names: [...] })\` with every listed tool the task will need, in one call where possible. Each loaded tool then appears in your tool list from the next turn on, with its full input schema.
|
|
933
|
+
- Load only what the task needs. A tool loaded earlier in this conversation stays loaded; do not load it again.
|
|
934
|
+
- Do not guess a listed tool's parameters from its summary; load it first.`;
|
|
935
|
+
function renderLazyToolMenu(entries) {
|
|
936
|
+
const lines = entries.map((e) => `- ${e.name}: ${e.summary}`);
|
|
937
|
+
return `Available on request:
|
|
938
|
+
${lines.join("\n")}`;
|
|
939
|
+
}
|
|
940
|
+
var TOOL_FIND_INPUT_SCHEMA = {
|
|
941
|
+
type: "object",
|
|
942
|
+
properties: {
|
|
943
|
+
names: {
|
|
944
|
+
type: "array",
|
|
945
|
+
items: { type: "string" },
|
|
946
|
+
minItems: 1,
|
|
947
|
+
description: 'Tool names to load, exactly as listed under "Tools available on request".'
|
|
948
|
+
}
|
|
949
|
+
},
|
|
950
|
+
required: ["names"],
|
|
951
|
+
additionalProperties: false
|
|
952
|
+
};
|
|
953
|
+
function toolReferenceOf(tool) {
|
|
954
|
+
return {
|
|
955
|
+
type: "tool_reference",
|
|
956
|
+
name: tool.name,
|
|
957
|
+
description: tool.description,
|
|
958
|
+
inputSchema: tool.inputSchema
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
function renderLoadedTool(tool) {
|
|
962
|
+
return renderToolReference(toolReferenceOf(tool));
|
|
963
|
+
}
|
|
964
|
+
function renderToolFindResult(input) {
|
|
965
|
+
const parts = [];
|
|
966
|
+
if (input.loaded.length > 0) {
|
|
967
|
+
const names = input.loaded.map((t) => t.name).join(", ");
|
|
968
|
+
parts.push({
|
|
969
|
+
type: "text",
|
|
970
|
+
text: `Loaded ${input.loaded.length} tool${input.loaded.length === 1 ? "" : "s"} (${names}); callable from your next turn on.`
|
|
971
|
+
});
|
|
972
|
+
parts.push(...input.loaded.map(toolReferenceOf));
|
|
973
|
+
} else {
|
|
974
|
+
parts.push({ type: "text", text: "Nothing loaded." });
|
|
975
|
+
}
|
|
976
|
+
if (input.notListed.length > 0) {
|
|
977
|
+
parts.push({
|
|
978
|
+
type: "text",
|
|
979
|
+
text: `Not on the on-request list: ${input.notListed.join(", ")}. Check the spelling against the list; if a name is already in your tool list, call it directly.`
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
return parts;
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// src/lazy-tools/lazy-tools.ts
|
|
986
|
+
var LAZY_TOOLS_SOCKET_NAME = "lazy-tools";
|
|
987
|
+
var DEFAULT_LAZY_SUMMARY_CHARS = 160;
|
|
988
|
+
var DEFAULT_TOOL_FIND_MAX = 20;
|
|
989
|
+
function summarizeTool(tool, maxChars = DEFAULT_LAZY_SUMMARY_CHARS) {
|
|
990
|
+
const line = tool.description.split(/\r?\n/).map((s) => s.trim()).find((s) => s.length > 0) ?? tool.name;
|
|
991
|
+
const flat = line.replace(/\s+/g, " ");
|
|
992
|
+
if (flat.length <= maxChars) return flat;
|
|
993
|
+
return `${flat.slice(0, Math.max(0, maxChars - 1)).trimEnd()}\u2026`;
|
|
994
|
+
}
|
|
995
|
+
function lazyMenuOf(hostTools, summarize = (t) => summarizeTool(t)) {
|
|
996
|
+
const tools = hostTools.filter((t) => t.lazy === true).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
997
|
+
const entries = tools.map((t) => ({ name: t.name, summary: summarize(t).replace(/\s*\n\s*/g, " ") }));
|
|
998
|
+
return { tools, entries, byName: new Map(tools.map((t) => [t.name, t])) };
|
|
999
|
+
}
|
|
1000
|
+
function parseToolFindInput(raw, maxPerCall = DEFAULT_TOOL_FIND_MAX) {
|
|
1001
|
+
if (typeof raw !== "object" || raw === null || !Array.isArray(raw.names)) {
|
|
1002
|
+
throw new RangeError(`${TOOL_FIND_TOOL_NAME} expects { names: string[] }`);
|
|
1003
|
+
}
|
|
1004
|
+
const list = raw.names;
|
|
1005
|
+
if (list.length === 0) throw new RangeError("`names` must list at least one tool");
|
|
1006
|
+
const names = [];
|
|
1007
|
+
for (const n of list) {
|
|
1008
|
+
if (typeof n !== "string" || n.trim().length === 0)
|
|
1009
|
+
throw new RangeError("`names` must be non-empty strings");
|
|
1010
|
+
const name = n.trim();
|
|
1011
|
+
if (!names.includes(name)) names.push(name);
|
|
1012
|
+
}
|
|
1013
|
+
if (names.length > maxPerCall) {
|
|
1014
|
+
throw new RangeError(`\`names\` lists ${names.length} tools; load at most ${maxPerCall} per call`);
|
|
1015
|
+
}
|
|
1016
|
+
return { names };
|
|
1017
|
+
}
|
|
1018
|
+
function revealedLazyTools(timeline, menuNames) {
|
|
1019
|
+
const succeeded = /* @__PURE__ */ new Set();
|
|
1020
|
+
for (const e of timeline) {
|
|
1021
|
+
if (e.type !== "core.tool_result") continue;
|
|
1022
|
+
const p = e.payload;
|
|
1023
|
+
if (p.name === TOOL_FIND_TOOL_NAME && p.isError === false && typeof p.toolCallId === "string")
|
|
1024
|
+
succeeded.add(p.toolCallId);
|
|
1025
|
+
}
|
|
1026
|
+
const revealed = /* @__PURE__ */ new Set();
|
|
1027
|
+
if (succeeded.size === 0) return revealed;
|
|
1028
|
+
for (const e of timeline) {
|
|
1029
|
+
if (e.type !== "core.tool_call") continue;
|
|
1030
|
+
const { toolCallId, name, args } = e.payload;
|
|
1031
|
+
if (name !== TOOL_FIND_TOOL_NAME || !succeeded.has(toolCallId)) continue;
|
|
1032
|
+
const list = args?.names;
|
|
1033
|
+
if (!Array.isArray(list)) continue;
|
|
1034
|
+
for (const n of list) {
|
|
1035
|
+
if (typeof n !== "string") continue;
|
|
1036
|
+
const trimmed = n.trim();
|
|
1037
|
+
if (menuNames.has(trimmed)) revealed.add(trimmed);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
return revealed;
|
|
1041
|
+
}
|
|
1042
|
+
function toolFindResultBound(menu, maxPerCall) {
|
|
1043
|
+
const sizes = menu.tools.map((t) => estimateTextTokens(renderLoadedTool(t))).sort((a, b) => b - a);
|
|
1044
|
+
return sizes.slice(0, maxPerCall).reduce((sum, n) => sum + n, 0) + 256;
|
|
1045
|
+
}
|
|
1046
|
+
function lazyTools(opts = {}) {
|
|
1047
|
+
const summaryChars = opts.summaryChars ?? DEFAULT_LAZY_SUMMARY_CHARS;
|
|
1048
|
+
if (!Number.isInteger(summaryChars) || summaryChars < 1) {
|
|
1049
|
+
throw new RangeError(`lazyTools.summaryChars must be an integer >= 1, got ${String(summaryChars)}`);
|
|
1050
|
+
}
|
|
1051
|
+
const maxPerCall = opts.maxPerCall ?? DEFAULT_TOOL_FIND_MAX;
|
|
1052
|
+
if (!Number.isInteger(maxPerCall) || maxPerCall < 1) {
|
|
1053
|
+
throw new RangeError(`lazyTools.maxPerCall must be an integer >= 1, got ${String(maxPerCall)}`);
|
|
1054
|
+
}
|
|
1055
|
+
const summarize = opts.summarize ?? ((t) => summarizeTool(t, summaryChars));
|
|
1056
|
+
const warn = opts.warn ?? ((message) => console.warn(message));
|
|
1057
|
+
const warned = /* @__PURE__ */ new Set();
|
|
1058
|
+
const warnOnce = (key, message) => {
|
|
1059
|
+
if (warned.has(key)) return;
|
|
1060
|
+
warned.add(key);
|
|
1061
|
+
warn(message);
|
|
1062
|
+
};
|
|
1063
|
+
const menuTools = /* @__PURE__ */ new WeakSet();
|
|
1064
|
+
const resolved = /* @__PURE__ */ new WeakMap();
|
|
1065
|
+
const resolveFor = (setup) => {
|
|
1066
|
+
if (resolved.has(setup)) return resolved.get(setup);
|
|
1067
|
+
let out;
|
|
1068
|
+
if (setup.hostTools.some((t) => t.name === TOOL_FIND_TOOL_NAME)) {
|
|
1069
|
+
warnOnce(
|
|
1070
|
+
"host-tool",
|
|
1071
|
+
`[reins/lazy-tools] The host tool table already has a tool named ${TOOL_FIND_TOOL_NAME}, so this module's tool and menu are not registered. Rename the host tool to enable them.`
|
|
1072
|
+
);
|
|
1073
|
+
} else {
|
|
1074
|
+
const menu = lazyMenuOf(setup.hostTools, summarize);
|
|
1075
|
+
if (menu.tools.length === 0) {
|
|
1076
|
+
warnOnce(
|
|
1077
|
+
"no-lazy",
|
|
1078
|
+
"[reins/lazy-tools] No host tool is marked lazy: true, so tool_find and the menu are not registered. Mark the tools you want disclosed on demand with lazy: true to enable them."
|
|
1079
|
+
);
|
|
1080
|
+
} else {
|
|
1081
|
+
for (const t of menu.tools) menuTools.add(t);
|
|
1082
|
+
out = { menu, tool: makeToolFind(menu, maxPerCall) };
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
resolved.set(setup, out);
|
|
1086
|
+
return out;
|
|
1087
|
+
};
|
|
1088
|
+
const hiddenByTurn = /* @__PURE__ */ new WeakMap();
|
|
1089
|
+
const socket = {
|
|
1090
|
+
name: LAZY_TOOLS_SOCKET_NAME,
|
|
1091
|
+
tools: (setup) => {
|
|
1092
|
+
const r = resolveFor(setup);
|
|
1093
|
+
return r ? [r.tool] : void 0;
|
|
1094
|
+
},
|
|
1095
|
+
beforeModel(ctx) {
|
|
1096
|
+
const menuNames = /* @__PURE__ */ new Set();
|
|
1097
|
+
for (const t of ctx.tools) if (t.lazy === true && menuTools.has(t)) menuNames.add(t.name);
|
|
1098
|
+
if (menuNames.size === 0) return void 0;
|
|
1099
|
+
const revealed = revealedLazyTools(ctx.timeline, menuNames);
|
|
1100
|
+
const hidden = /* @__PURE__ */ new Map();
|
|
1101
|
+
for (const t of ctx.tools) if (menuNames.has(t.name) && !revealed.has(t.name)) hidden.set(t.name, t);
|
|
1102
|
+
hiddenByTurn.set(ctx, hidden);
|
|
1103
|
+
if (ctx.capabilities.deferredTools) {
|
|
1104
|
+
const inView = revealedLazyTools(ctx.events, menuNames);
|
|
1105
|
+
const deferred = [...menuNames].filter((n) => !revealed.has(n) || inView.has(n));
|
|
1106
|
+
return deferred.length > 0 ? { deferredTools: deferred } : void 0;
|
|
1107
|
+
}
|
|
1108
|
+
const visible = ctx.tools.filter((t) => !hidden.has(t.name));
|
|
1109
|
+
return hidden.size > 0 ? { tools: visible } : void 0;
|
|
1110
|
+
},
|
|
1111
|
+
beforeTool(ctx, call) {
|
|
1112
|
+
const name = call.payload.name;
|
|
1113
|
+
if (!hiddenByTurn.get(ctx)?.has(name)) return void 0;
|
|
1114
|
+
return {
|
|
1115
|
+
block: `Tool "${name}" is on the on-request list but not loaded yet. Call ${TOOL_FIND_TOOL_NAME}({ names: [${JSON.stringify(name)}] }) first; it becomes callable from your next turn.`
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
if (opts.rules !== false) {
|
|
1120
|
+
const rules = opts.rules ?? LAZY_TOOL_RULES;
|
|
1121
|
+
socket.systemPrompt = (setup) => {
|
|
1122
|
+
const r = resolveFor(setup);
|
|
1123
|
+
return r ? `${rules}
|
|
1124
|
+
|
|
1125
|
+
${renderLazyToolMenu(r.menu.entries)}` : void 0;
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
return socket;
|
|
1129
|
+
}
|
|
1130
|
+
function makeToolFind(menu, maxPerCall) {
|
|
1131
|
+
const tool = {
|
|
1132
|
+
name: TOOL_FIND_TOOL_NAME,
|
|
1133
|
+
description: TOOL_FIND_TOOL_DESCRIPTION,
|
|
1134
|
+
inputSchema: TOOL_FIND_INPUT_SCHEMA,
|
|
1135
|
+
validate: (raw) => parseToolFindInput(raw, maxPerCall),
|
|
1136
|
+
risk: "low",
|
|
1137
|
+
// 工具说明与 schema 是宿主配置,视同系统提示可信(与 skill_read 同理)
|
|
1138
|
+
resultTrust: "system",
|
|
1139
|
+
resultPolicy: { maxTokens: toolFindResultBound(menu, maxPerCall), overflow: "spill" },
|
|
1140
|
+
execute(input) {
|
|
1141
|
+
const loaded = [];
|
|
1142
|
+
const notListed = [];
|
|
1143
|
+
for (const name of input.names) {
|
|
1144
|
+
const t = menu.byName.get(name);
|
|
1145
|
+
if (t) loaded.push(t);
|
|
1146
|
+
else notListed.push(name);
|
|
1147
|
+
}
|
|
1148
|
+
return { content: renderToolFindResult({ loaded, notListed }), isError: loaded.length === 0 };
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
return tool;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
875
1154
|
// src/shared/view.ts
|
|
876
1155
|
var encoder = new TextEncoder();
|
|
877
1156
|
var byteLength = (s) => encoder.encode(s).length;
|
|
@@ -1336,13 +1615,13 @@ function memory(opts = {}) {
|
|
|
1336
1615
|
maxViewChars: opts.maxViewChars ?? DEFAULT_MAX_VIEW_CHARS
|
|
1337
1616
|
};
|
|
1338
1617
|
if (!Number.isInteger(limits.maxFileBytes) || limits.maxFileBytes < 1) {
|
|
1339
|
-
throw new RangeError(`memory.maxFileBytes
|
|
1618
|
+
throw new RangeError(`memory.maxFileBytes must be an integer >= 1, got ${String(limits.maxFileBytes)}`);
|
|
1340
1619
|
}
|
|
1341
1620
|
if (!Number.isInteger(limits.maxViewChars) || limits.maxViewChars < 1) {
|
|
1342
|
-
throw new RangeError(`memory.maxViewChars
|
|
1621
|
+
throw new RangeError(`memory.maxViewChars must be an integer >= 1, got ${String(limits.maxViewChars)}`);
|
|
1343
1622
|
}
|
|
1344
1623
|
if (opts.namespace !== void 0 && typeof opts.namespace !== "function") {
|
|
1345
|
-
throw new RangeError("memory.namespace
|
|
1624
|
+
throw new RangeError("memory.namespace must be a function");
|
|
1346
1625
|
}
|
|
1347
1626
|
const namespace = opts.namespace ?? (() => "");
|
|
1348
1627
|
const warn = opts.warn ?? ((message) => console.warn(message));
|
|
@@ -1380,7 +1659,7 @@ function memory(opts = {}) {
|
|
|
1380
1659
|
if (!warned) {
|
|
1381
1660
|
warned = true;
|
|
1382
1661
|
warn(
|
|
1383
|
-
"[reins/memory]
|
|
1662
|
+
"[reins/memory] No MemoryStore configured, so the memory tool and its rules are not registered. Pass a memory store to runLoop / createAgent to enable them."
|
|
1384
1663
|
);
|
|
1385
1664
|
}
|
|
1386
1665
|
return false;
|
|
@@ -1405,7 +1684,9 @@ function assertAscending(name, bounds) {
|
|
|
1405
1684
|
const cur = bounds[i];
|
|
1406
1685
|
const prev = bounds[i - 1];
|
|
1407
1686
|
if (cur === void 0 || !Number.isFinite(cur) || prev !== void 0 && cur <= prev) {
|
|
1408
|
-
throw new RangeError(
|
|
1687
|
+
throw new RangeError(
|
|
1688
|
+
`the tier bounds of ${name} must be strictly ascending finite numbers, got ${JSON.stringify(bounds)}`
|
|
1689
|
+
);
|
|
1409
1690
|
}
|
|
1410
1691
|
}
|
|
1411
1692
|
}
|
|
@@ -1670,13 +1951,13 @@ function normalizeSpecs(specs) {
|
|
|
1670
1951
|
const names = /* @__PURE__ */ new Set();
|
|
1671
1952
|
for (const spec of specs) {
|
|
1672
1953
|
const n = typeof spec === "string" ? { name: spec, text: spec } : "text" in spec ? { name: spec.name, text: spec.text } : { name: spec.name, extract: spec.extract };
|
|
1673
|
-
if (n.name.trim().length === 0) throw new RangeError("pins
|
|
1674
|
-
if (names.has(n.name)) throw new RangeError(`pins
|
|
1954
|
+
if (n.name.trim().length === 0) throw new RangeError("pins: a spec name must not be empty");
|
|
1955
|
+
if (names.has(n.name)) throw new RangeError(`pins: duplicate spec name ${JSON.stringify(n.name)}`);
|
|
1675
1956
|
if (n.text !== void 0 && n.text.trim().length === 0) {
|
|
1676
|
-
throw new RangeError(`pins
|
|
1957
|
+
throw new RangeError(`pins: the text of static pin ${JSON.stringify(n.name)} must not be empty`);
|
|
1677
1958
|
}
|
|
1678
1959
|
if (n.extract !== void 0 && typeof n.extract !== "function") {
|
|
1679
|
-
throw new RangeError(`pins
|
|
1960
|
+
throw new RangeError(`pins: extract of spec ${JSON.stringify(n.name)} must be a function`);
|
|
1680
1961
|
}
|
|
1681
1962
|
names.add(n.name);
|
|
1682
1963
|
out.push(n);
|
|
@@ -1704,14 +1985,14 @@ function pins(opts = {}) {
|
|
|
1704
1985
|
const withTool = opts.tool ?? true;
|
|
1705
1986
|
const maxTextLength = opts.maxTextLength ?? DEFAULT_MAX_PIN_TEXT_LENGTH;
|
|
1706
1987
|
if (!Number.isInteger(maxTextLength) || maxTextLength < 1) {
|
|
1707
|
-
throw new RangeError(`pins.maxTextLength
|
|
1988
|
+
throw new RangeError(`pins.maxTextLength must be an integer >= 1, got ${String(maxTextLength)}`);
|
|
1708
1989
|
}
|
|
1709
1990
|
const tolerance = opts.overshootTolerance ?? DEFAULT_PIN_OVERSHOOT_TOLERANCE;
|
|
1710
1991
|
if (!(tolerance >= 0 && tolerance < 1)) {
|
|
1711
|
-
throw new RangeError(`pins.overshootTolerance
|
|
1992
|
+
throw new RangeError(`pins.overshootTolerance must be within [0, 1), got ${String(tolerance)}`);
|
|
1712
1993
|
}
|
|
1713
1994
|
if (specs.length === 0 && !withTool) {
|
|
1714
|
-
throw new RangeError("pins
|
|
1995
|
+
throw new RangeError("pins: with neither host pins nor a model-facing tool this socket does nothing");
|
|
1715
1996
|
}
|
|
1716
1997
|
const tool = {
|
|
1717
1998
|
name: PIN_TOOL_NAME,
|
|
@@ -1864,7 +2145,7 @@ function inlineSkills(skills2, opts = {}) {
|
|
|
1864
2145
|
for (const [name, skill] of Object.entries(skills2)) {
|
|
1865
2146
|
if (!SKILL_NAME_RE.test(name)) {
|
|
1866
2147
|
throw new RangeError(
|
|
1867
|
-
`inlineSkills
|
|
2148
|
+
`inlineSkills: skill key ${JSON.stringify(name)} is not a valid skill name (it must match ${SKILL_NAME_RE.source} and equal the name in the SKILL.md front matter)`
|
|
1868
2149
|
);
|
|
1869
2150
|
}
|
|
1870
2151
|
if (typeof skill === "string") {
|
|
@@ -1875,7 +2156,7 @@ function inlineSkills(skills2, opts = {}) {
|
|
|
1875
2156
|
const segments = rel.split("/").filter((s) => s.length > 0);
|
|
1876
2157
|
if (segments.length === 0 || segments.some((s) => s === "." || s === "..")) {
|
|
1877
2158
|
throw new RangeError(
|
|
1878
|
-
`inlineSkills
|
|
2159
|
+
`inlineSkills: file path ${JSON.stringify(rel)} of skill ${name} is invalid (it must be relative and contain no . or .. segments)`
|
|
1879
2160
|
);
|
|
1880
2161
|
}
|
|
1881
2162
|
files.set(`${root}/${name}/${segments.join("/")}`, content);
|
|
@@ -1995,12 +2276,12 @@ function assertSkillsRoot(root) {
|
|
|
1995
2276
|
const bad = !root.startsWith("/") || segments.length < 2 || segments.slice(1).some((s) => s.length === 0 || s === "." || s === ".." || /\s/.test(s));
|
|
1996
2277
|
if (bad) {
|
|
1997
2278
|
throw new RangeError(
|
|
1998
|
-
`skills.root
|
|
2279
|
+
`skills.root must be a canonical path starting with "/", not ending with "/", with no empty, . or .. segments, got ${JSON.stringify(root)}`
|
|
1999
2280
|
);
|
|
2000
2281
|
}
|
|
2001
2282
|
if (root === MEMORY_ROOT || root.startsWith(`${MEMORY_ROOT}/`) || MEMORY_ROOT.startsWith(`${root}/`)) {
|
|
2002
2283
|
throw new RangeError(
|
|
2003
|
-
`skills.root ${JSON.stringify(root)}
|
|
2284
|
+
`skills.root ${JSON.stringify(root)} overlaps the memory root ${MEMORY_ROOT}: whatever the model can write through the memory tool must not become a skill (which is trusted as system)`
|
|
2004
2285
|
);
|
|
2005
2286
|
}
|
|
2006
2287
|
}
|
|
@@ -2009,7 +2290,7 @@ function skills(opts = {}) {
|
|
|
2009
2290
|
assertSkillsRoot(root);
|
|
2010
2291
|
const maxReadChars = opts.maxReadChars ?? DEFAULT_SKILL_READ_CHARS;
|
|
2011
2292
|
if (!Number.isInteger(maxReadChars) || maxReadChars < 1) {
|
|
2012
|
-
throw new RangeError(`skills.maxReadChars
|
|
2293
|
+
throw new RangeError(`skills.maxReadChars must be an integer >= 1, got ${String(maxReadChars)}`);
|
|
2013
2294
|
}
|
|
2014
2295
|
const source = opts.source;
|
|
2015
2296
|
const warn = opts.warn ?? ((message) => console.warn(message));
|
|
@@ -2027,25 +2308,28 @@ function skills(opts = {}) {
|
|
|
2027
2308
|
if (!source) {
|
|
2028
2309
|
warnOnce(
|
|
2029
2310
|
"no-source",
|
|
2030
|
-
"[reins/skills]
|
|
2311
|
+
"[reins/skills] No source given, so the skill_read tool and the skill menu are not registered. Pass skills({ source }) to enable them (any MemoryStore, fsSkillSource or inlineSkills works)."
|
|
2031
2312
|
);
|
|
2032
2313
|
return void 0;
|
|
2033
2314
|
}
|
|
2034
2315
|
if (setup.hostTools.some((t) => t.name === SKILL_READ_TOOL_NAME)) {
|
|
2035
2316
|
warnOnce(
|
|
2036
2317
|
"host-tool",
|
|
2037
|
-
`[reins/skills]
|
|
2318
|
+
`[reins/skills] The host tool table already has a tool named ${SKILL_READ_TOOL_NAME}, so this module's tool and menu are not registered. Rename the host tool to enable them.`
|
|
2038
2319
|
);
|
|
2039
2320
|
return void 0;
|
|
2040
2321
|
}
|
|
2041
2322
|
const menu = await loadSkillMenu(source, root);
|
|
2042
2323
|
for (const r of menu.rejected) {
|
|
2043
|
-
warnOnce(
|
|
2324
|
+
warnOnce(
|
|
2325
|
+
`rejected:${r.path}:${r.reason}`,
|
|
2326
|
+
`[reins/skills] Skipping invalid skill ${r.path}: ${r.reason}`
|
|
2327
|
+
);
|
|
2044
2328
|
}
|
|
2045
2329
|
if (menu.skills.length === 0) {
|
|
2046
2330
|
warnOnce(
|
|
2047
2331
|
"empty",
|
|
2048
|
-
`[reins/skills] source
|
|
2332
|
+
`[reins/skills] The source holds no valid SKILL.md under ${root}/, so the skill_read tool and the skill menu are not registered. Check: (1) the source's root matches skills({ root }) (both default to ${DEFAULT_SKILLS_ROOT}); (2) the layout is <root>/<name>/${SKILL_FILE_NAME} (fsSkillSource resolves dir against process.cwd(), so an absolute path is safer); (3) the name in the front matter equals the directory name.`
|
|
2049
2333
|
);
|
|
2050
2334
|
return void 0;
|
|
2051
2335
|
}
|
|
@@ -2081,7 +2365,7 @@ function skills(opts = {}) {
|
|
|
2081
2365
|
try {
|
|
2082
2366
|
content = await source.read(key);
|
|
2083
2367
|
} catch (err) {
|
|
2084
|
-
warnOnce(`read-failed:${String(err)}`, `[reins/skills]
|
|
2368
|
+
warnOnce(`read-failed:${String(err)}`, `[reins/skills] Failed to read ${key}: ${String(err)}`);
|
|
2085
2369
|
return {
|
|
2086
2370
|
content: [
|
|
2087
2371
|
{ type: "text", text: `Skill file ${input.name}/${input.path} could not be read right now.` }
|
|
@@ -2125,8 +2409,8 @@ function escapeRegExp(s) {
|
|
|
2125
2409
|
}
|
|
2126
2410
|
|
|
2127
2411
|
// src/spill/preview.ts
|
|
2128
|
-
import { estimateTextTokens } from "@reinsjs/core";
|
|
2129
|
-
var defaultTextTokens =
|
|
2412
|
+
import { estimateTextTokens as estimateTextTokens2 } from "@reinsjs/core";
|
|
2413
|
+
var defaultTextTokens = estimateTextTokens2;
|
|
2130
2414
|
function measureText(text, estimate = defaultTextTokens) {
|
|
2131
2415
|
return { chars: text.length, lines: countLines(text), tokens: estimate(text) };
|
|
2132
2416
|
}
|
|
@@ -2256,15 +2540,15 @@ ${preview.tail}`;
|
|
|
2256
2540
|
function spill(opts = {}) {
|
|
2257
2541
|
const maxTokens = opts.maxResultTokens ?? DEFAULT_MAX_RESULT_TOKENS;
|
|
2258
2542
|
if (!Number.isInteger(maxTokens) || maxTokens < 1) {
|
|
2259
|
-
throw new RangeError(`spill.maxResultTokens
|
|
2543
|
+
throw new RangeError(`spill.maxResultTokens must be an integer >= 1, got ${String(maxTokens)}`);
|
|
2260
2544
|
}
|
|
2261
2545
|
const previewLines = opts.previewLines ?? DEFAULT_PREVIEW_LINES;
|
|
2262
2546
|
if (!Number.isInteger(previewLines) || previewLines < 0) {
|
|
2263
|
-
throw new RangeError(`spill.previewLines
|
|
2547
|
+
throw new RangeError(`spill.previewLines must be an integer >= 0, got ${String(previewLines)}`);
|
|
2264
2548
|
}
|
|
2265
2549
|
const previewChars = opts.previewChars ?? Math.min(DEFAULT_PREVIEW_CHARS, Math.floor(maxTokens / 4));
|
|
2266
2550
|
if (!Number.isInteger(previewChars) || previewChars < 0) {
|
|
2267
|
-
throw new RangeError(`spill.previewChars
|
|
2551
|
+
throw new RangeError(`spill.previewChars must be an integer >= 0, got ${String(previewChars)}`);
|
|
2268
2552
|
}
|
|
2269
2553
|
const estimate = opts.estimate ?? defaultTextTokens;
|
|
2270
2554
|
const withTool = opts.tool ?? true;
|
|
@@ -2306,7 +2590,7 @@ ${renderPreview(preview)}` },
|
|
|
2306
2590
|
if (!warnedNoBlobs) {
|
|
2307
2591
|
warnedNoBlobs = true;
|
|
2308
2592
|
warn(
|
|
2309
|
-
`[reins/spill]
|
|
2593
|
+
`[reins/spill] No BlobStore configured, so spilling is off: \`${name}\` returned ${size} and will enter the context as is. Pass blobs to runLoop / createAgent to enable it.`
|
|
2310
2594
|
);
|
|
2311
2595
|
}
|
|
2312
2596
|
return void 0;
|
|
@@ -2383,6 +2667,7 @@ async function loadReferencedBlob(blobs, id) {
|
|
|
2383
2667
|
}
|
|
2384
2668
|
}
|
|
2385
2669
|
export {
|
|
2670
|
+
APPROVAL_EXPIRY_RULE,
|
|
2386
2671
|
APPROVAL_POLICY_IDS,
|
|
2387
2672
|
APPROVAL_RULES,
|
|
2388
2673
|
APPROVAL_SOCKET_NAME,
|
|
@@ -2393,6 +2678,7 @@ export {
|
|
|
2393
2678
|
COMPACT_TOOL_DESCRIPTION,
|
|
2394
2679
|
COMPACT_TOOL_NAME,
|
|
2395
2680
|
DEFAULT_HANDOFF_REASON,
|
|
2681
|
+
DEFAULT_LAZY_SUMMARY_CHARS,
|
|
2396
2682
|
DEFAULT_MAX_CONSECUTIVE_COMPACTIONS,
|
|
2397
2683
|
DEFAULT_MAX_FILE_BYTES,
|
|
2398
2684
|
DEFAULT_MAX_PIN_TEXT_LENGTH,
|
|
@@ -2405,6 +2691,7 @@ export {
|
|
|
2405
2691
|
DEFAULT_PREVIEW_LINES,
|
|
2406
2692
|
DEFAULT_SKILLS_ROOT,
|
|
2407
2693
|
DEFAULT_SKILL_READ_CHARS,
|
|
2694
|
+
DEFAULT_TOOL_FIND_MAX,
|
|
2408
2695
|
FETCH_BLOB_INPUT_SCHEMA,
|
|
2409
2696
|
FETCH_BLOB_TOOL_DESCRIPTION,
|
|
2410
2697
|
FETCH_BLOB_TOOL_NAME,
|
|
@@ -2413,6 +2700,8 @@ export {
|
|
|
2413
2700
|
HANDOFF_SOCKET_NAME,
|
|
2414
2701
|
HANDOFF_TOOL_DESCRIPTION,
|
|
2415
2702
|
HANDOFF_TOOL_NAME,
|
|
2703
|
+
LAZY_TOOLS_SOCKET_NAME,
|
|
2704
|
+
LAZY_TOOL_RULES,
|
|
2416
2705
|
MANIFEST_DEFAULT_EXCLUDE,
|
|
2417
2706
|
MANIFEST_HEADING,
|
|
2418
2707
|
MAX_MEMORY_PATH_LENGTH,
|
|
@@ -2443,6 +2732,9 @@ export {
|
|
|
2443
2732
|
SPILL_BLOB_MIME,
|
|
2444
2733
|
SPILL_RULES,
|
|
2445
2734
|
SPILL_SOCKET_NAME,
|
|
2735
|
+
TOOL_FIND_INPUT_SCHEMA,
|
|
2736
|
+
TOOL_FIND_TOOL_DESCRIPTION,
|
|
2737
|
+
TOOL_FIND_TOOL_NAME,
|
|
2446
2738
|
approval,
|
|
2447
2739
|
assertAscending,
|
|
2448
2740
|
assertLimits,
|
|
@@ -2466,6 +2758,7 @@ export {
|
|
|
2466
2758
|
defaultTextTokens,
|
|
2467
2759
|
evaluatePolicy,
|
|
2468
2760
|
executeMemoryCommand,
|
|
2761
|
+
findExpiredApproval,
|
|
2469
2762
|
findModelPin,
|
|
2470
2763
|
fmt,
|
|
2471
2764
|
globToRegExp,
|
|
@@ -2479,6 +2772,8 @@ export {
|
|
|
2479
2772
|
lastHostPin,
|
|
2480
2773
|
lastVisiblePerceptionNote,
|
|
2481
2774
|
lastVisibleUserMessage,
|
|
2775
|
+
lazyMenuOf,
|
|
2776
|
+
lazyTools,
|
|
2482
2777
|
loadSkillMenu,
|
|
2483
2778
|
measureText,
|
|
2484
2779
|
memory,
|
|
@@ -2491,6 +2786,7 @@ export {
|
|
|
2491
2786
|
parseRecallArgs,
|
|
2492
2787
|
parseSkillMarkdown,
|
|
2493
2788
|
parseSkillReadInput,
|
|
2789
|
+
parseToolFindInput,
|
|
2494
2790
|
percent,
|
|
2495
2791
|
perception,
|
|
2496
2792
|
pinInputSchema,
|
|
@@ -2504,13 +2800,20 @@ export {
|
|
|
2504
2800
|
recallResult,
|
|
2505
2801
|
recallTool,
|
|
2506
2802
|
renderCompactionSummary,
|
|
2803
|
+
renderLazyToolMenu,
|
|
2804
|
+
renderLoadedTool,
|
|
2507
2805
|
renderPerception,
|
|
2508
2806
|
renderSkillMenu,
|
|
2807
|
+
renderToolFindResult,
|
|
2509
2808
|
resolveMemoryPath,
|
|
2809
|
+
revealedLazyTools,
|
|
2510
2810
|
segmentTimelineByTurn,
|
|
2511
2811
|
skills,
|
|
2512
2812
|
spill,
|
|
2513
2813
|
sumSessionTokens,
|
|
2814
|
+
summarizeTool,
|
|
2815
|
+
toolFindResultBound,
|
|
2816
|
+
toolReferenceOf,
|
|
2514
2817
|
trailingCompactionRun,
|
|
2515
2818
|
unfinishedHandoffArgs
|
|
2516
2819
|
};
|