toolnexus 0.20.0 → 0.21.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/dist/judge.js ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Simple judgments (SPEC.md §8B "Simple judgments — ask / gate", change `add-judge-adapters`).
3
+ * A thin layer over any `Classifier`: named question builders, a role-carrying `State`,
4
+ * `ask` (answers by name with bands) and `gate` / `Policy` (rules that escalate instead of
5
+ * deciding when unsure). The wire is unchanged — the builders produce exactly the §8B
6
+ * `evaluate(state, questions)` inputs.
7
+ *
8
+ * A gate never authorises; it only declines to decide.
9
+ */
10
+ import { Classifier, noul as noulQ, choice as choiceQ, score as scoreQ, } from "./classifier.js";
11
+ /** `noul` question with a name. Name the state field it judges in `instructions`. */
12
+ export function noul(name, instructions, criteria) {
13
+ return { name, question: noulQ(instructions, criteria) };
14
+ }
15
+ /** `choice` question with a name; `options` maps option -> what picking it MEANS. */
16
+ export function choice(name, instructions, options) {
17
+ return { name, question: choiceQ(instructions, options) };
18
+ }
19
+ /** `score` question with a name; `levels` is the ordered rubric. */
20
+ export function score(name, instructions, levels) {
21
+ return { name, question: scoreQ(instructions, levels) };
22
+ }
23
+ /** Ordered list -> the §8B questions map. A duplicate name is an error naming it. */
24
+ export function questionMap(questions) {
25
+ const out = {};
26
+ for (const { name, question } of questions) {
27
+ if (Object.prototype.hasOwnProperty.call(out, name))
28
+ throw new Error(`duplicate question name ${JSON.stringify(name)}`);
29
+ out[name] = question;
30
+ }
31
+ return out;
32
+ }
33
+ // ---------------------------------------------------------------- state
34
+ /** `role` next to the data's fields; a non-object value goes under `data`. */
35
+ export function State(role, data) {
36
+ if (data !== null && typeof data === "object" && !Array.isArray(data))
37
+ return { role, ...data };
38
+ return { role, data };
39
+ }
40
+ /** Sugar: `{context, message, ...extra}`. */
41
+ export function context(ctx, message, extra = {}) {
42
+ return { context: ctx, message, ...extra };
43
+ }
44
+ /** Default cut-points; exclusive on the confident side. */
45
+ export const DEFAULT_BANDS = Object.freeze({ low: 0.3, high: 0.7 });
46
+ function noulBand(p, b) {
47
+ return p < b.low ? "no" : p > b.high ? "yes" : "uncertain";
48
+ }
49
+ function wrap(a, b) {
50
+ const extra = a.type === "noul"
51
+ ? { band: noulBand(a.noul, b) }
52
+ : { sure: a.confidence > b.high && !(a.type === "choice" && a.nearUniform) };
53
+ const value = () => (a.type === "noul" ? a.noul : a.type === "score" ? a.score : a.confidence);
54
+ const pick = () => (a.type === "choice" ? a.choice : "");
55
+ const out = { ...a, ...extra };
56
+ Object.defineProperty(out, "value", { value, enumerable: false });
57
+ Object.defineProperty(out, "pick", { value: pick, enumerable: false });
58
+ return out;
59
+ }
60
+ /** Band / sure every answer of a decision. */
61
+ export function answersOf(decision, bands = DEFAULT_BANDS) {
62
+ return Object.fromEntries(Object.entries(decision.answers).map(([k, a]) => [k, wrap(a, bands)]));
63
+ }
64
+ /** Evaluate once; answers by name, each with a band (noul) or `sure` (choice/score). */
65
+ export async function ask(classifier, state, questions, bands = DEFAULT_BANDS) {
66
+ return answersOf(await classifier.evaluate(state, questionMap(questions)), bands);
67
+ }
68
+ function unsure(a) {
69
+ return a.type === "noul" ? a.band === "uncertain" : !a.sure;
70
+ }
71
+ function escalate(answers, id, question, reason, prompt) {
72
+ return {
73
+ action: "needs_input",
74
+ target: "",
75
+ escalated: true,
76
+ answers,
77
+ request: { id, kind: "input", prompt, data: { question, reason, answers } },
78
+ };
79
+ }
80
+ function applyRules(answers, rules, skipUncertain) {
81
+ for (const [i, r] of rules.entries()) {
82
+ const a = answers[r.question];
83
+ if (!a || unsure(a)) {
84
+ if (a && skipUncertain)
85
+ continue;
86
+ const reason = `${a ? "uncertain" : "missing"} answer "${r.question}"`;
87
+ return escalate(answers, `gate:${i}:${r.question}`, r.question, reason, `Classifier is unsure about "${r.question}" (${reason}). Decide rule ${i} (${r.action}).`);
88
+ }
89
+ const key = JSON.stringify(r.question);
90
+ let fired = false;
91
+ let misfit = "";
92
+ if (r.is !== undefined) {
93
+ if (a.type === "choice")
94
+ fired = a.choice === r.is;
95
+ else
96
+ misfit = `is-rule on ${a.type} answer ${key}`;
97
+ }
98
+ else if (a.type === "choice") {
99
+ misfit = `numeric rule on choice answer ${key}`;
100
+ }
101
+ else {
102
+ const v = a.type === "noul" ? a.noul : a.score;
103
+ if (r.below !== undefined)
104
+ fired = v < r.below;
105
+ else if (r.at_least !== undefined)
106
+ fired = v >= r.at_least;
107
+ else
108
+ misfit = `rule on ${key} has no below / at_least / is`;
109
+ }
110
+ // A rule that does not fit its answer escalates; it is never skipped.
111
+ if (misfit)
112
+ return escalate(answers, `gate:${i}:${r.question}`, r.question, misfit, `Rule ${i} (${r.action}) does not fit its answer (${misfit}). Decide.`);
113
+ if (fired)
114
+ return { action: r.action, target: r.target ?? "", escalated: false, answers };
115
+ }
116
+ return undefined;
117
+ }
118
+ /** Pure half of `gate`: first-match rules; an unsure or missing answer on rule i escalates and wins. */
119
+ export function applyGate(answers, rules) {
120
+ return applyRules(answers, rules, false) ?? { action: "", target: "", escalated: false, answers };
121
+ }
122
+ /** Pure half of a `Policy`. */
123
+ export function applyPolicy(answers, policy) {
124
+ const hit = applyRules(answers, policy.rules, policy.skipUncertain ?? false);
125
+ if (hit)
126
+ return hit;
127
+ if (policy.default)
128
+ return { action: policy.default, target: "", escalated: false, answers };
129
+ return escalate(answers, "gate:default", "", "no rule fired", "No rule fired. Decide the action.");
130
+ }
131
+ /** Ask, then apply rules; no rule fired -> empty action (use a `Policy` for a declared default). */
132
+ export async function gate(classifier, state, questions, rules, bands = DEFAULT_BANDS) {
133
+ return applyGate(await ask(classifier, state, questions, bands), rules);
134
+ }
135
+ /** Ask, then apply a `Policy` (rules, default, bands, skipUncertain). */
136
+ export async function decide(classifier, state, questions, policy) {
137
+ return applyPolicy(await ask(classifier, state, questions, policy.bands ?? DEFAULT_BANDS), policy);
138
+ }
139
+ // ---------------------------------------------------------------- static + tape
140
+ /** One-line `static` classifier from recorded decisions. */
141
+ export function staticClassifier(decisions, model) {
142
+ return new Classifier({ style: "static", decisions: Array.isArray(decisions) ? decisions : [decisions], model });
143
+ }
144
+ /** The recorded-body form of a Decision, decodable by `static`. */
145
+ function toRaw(d) {
146
+ const answers = {};
147
+ for (const [k, a] of Object.entries(d.answers)) {
148
+ if (a.type === "choice") {
149
+ const { nearUniform: _derived, ...rest } = a;
150
+ answers[k] = rest;
151
+ }
152
+ else
153
+ answers[k] = { ...a };
154
+ }
155
+ const usage = { input_tokens: d.usage.inputTokens, output_tokens: d.usage.outputTokens };
156
+ if (d.usage.cost !== undefined)
157
+ usage.cost = d.usage.cost;
158
+ return { model: d.model, answers, usage, calibrated: d.calibrated };
159
+ }
160
+ /**
161
+ * Records live decisions keyed by a caller-given call name, and replays them with no network.
162
+ * `tape.classifier(name)` returns a Classifier: recording (live given) or replaying (no live).
163
+ */
164
+ export class Tape {
165
+ live;
166
+ entries;
167
+ constructor(live, entries = {}) {
168
+ this.live = live;
169
+ this.entries = { ...entries };
170
+ }
171
+ /** A replay-only tape from saved entries. */
172
+ static replay(entries) {
173
+ return new Tape(undefined, entries);
174
+ }
175
+ classifier(name) {
176
+ const live = this.live;
177
+ if (live) {
178
+ return new Classifier({
179
+ style: "custom",
180
+ evaluate: async (state, questions, signal) => {
181
+ const d = await live.evaluate(state, questions, signal);
182
+ this.entries[name] = { state, questions, response: toRaw(d) };
183
+ return d;
184
+ },
185
+ });
186
+ }
187
+ // Replay: resolved when evaluated (a miss fails then, naming the key, and sends nothing).
188
+ return new Classifier({
189
+ style: "custom",
190
+ evaluate: async (state, questions, signal) => {
191
+ const rec = this.entries[name];
192
+ if (!rec)
193
+ throw new Error(`tape: no recorded decision for call "${name}"`);
194
+ const raw = rec.response;
195
+ return staticClassifier(rec, raw?.model).evaluate(state, questions, signal);
196
+ },
197
+ });
198
+ }
199
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolnexus",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Dynamic MCP servers + agent skills as uniform tools for any LLM (opencode-style).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "scripts": {
19
19
  "build": "tsc -p tsconfig.json",
20
- "test": "npm run build && node --experimental-strip-types --test test/unit.test.ts test/agents.test.ts test/agent-hooks.test.ts test/agent-inprocess.test.ts test/home.test.ts test/compaction.test.ts test/loop.test.ts test/in-process.test.ts test/translate.test.ts test/multimodal.test.ts test/classifier.test.ts test/acp.test.ts test/issues.test.ts test/host-boundary.test.ts",
20
+ "test": "npm run build && node --experimental-strip-types --test test/unit.test.ts test/agents.test.ts test/agent-hooks.test.ts test/agent-inprocess.test.ts test/home.test.ts test/compaction.test.ts test/loop.test.ts test/in-process.test.ts test/translate.test.ts test/multimodal.test.ts test/classifier.test.ts test/acp.test.ts test/issues.test.ts test/host-boundary.test.ts test/judge.test.ts test/batteries.test.ts",
21
21
  "example": "node --experimental-strip-types examples/basic.ts",
22
22
  "example:judge": "node --experimental-strip-types examples/judge.ts",
23
23
  "example:multimodal": "node --experimental-strip-types examples/multimodal.ts"