@parcha/agentrun-serve 0.1.0-beta.42 → 0.1.0-beta.43

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.
Files changed (81) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +8 -7
  3. package/dist/console/assets/index-BrcDSBD8.css +1 -0
  4. package/dist/console/assets/{index-DYJ_wj27.js → index-Bz6IWncl.js} +186 -186
  5. package/dist/console/index.html +2 -2
  6. package/dist/decisions.js +0 -4
  7. package/dist/import-sources.js +25 -5
  8. package/dist/learn/audit.d.ts +123 -0
  9. package/dist/learn/audit.js +159 -0
  10. package/dist/learn/compile.d.ts +50 -74
  11. package/dist/learn/compile.js +90 -124
  12. package/dist/learn/folder.d.ts +9 -0
  13. package/dist/learn/folder.js +13 -2
  14. package/dist/learn/promote.d.ts +86 -200
  15. package/dist/learn/promote.js +57 -183
  16. package/dist/learn/replay-calls.d.ts +5 -0
  17. package/dist/learn/replay-calls.js +12 -1
  18. package/dist/learn/secrets.d.ts +8 -0
  19. package/dist/learn/secrets.js +12 -0
  20. package/dist/learn/skills.js +2 -4
  21. package/dist/learn/workflow-nodes.d.ts +1 -2
  22. package/dist/learn/workflow-nodes.js +2 -3
  23. package/dist/learned-nodes.d.ts +9 -34
  24. package/dist/learned-nodes.js +11 -23
  25. package/dist/learned-workflow.d.ts +6 -8
  26. package/dist/learned-workflow.js +18 -57
  27. package/dist/learning-batch.d.ts +13 -5
  28. package/dist/learning-batch.js +34 -8
  29. package/dist/learning-cost.d.ts +11 -4
  30. package/dist/learning-cost.js +4 -2
  31. package/dist/learning-routes.js +1 -1
  32. package/dist/learning-setting.d.ts +16 -1
  33. package/dist/learning-setting.js +34 -2
  34. package/dist/openapi.js +95 -55
  35. package/dist/run-launch.d.ts +6 -3
  36. package/dist/run-launch.js +2 -0
  37. package/dist/run-learning-served.d.ts +1 -1
  38. package/dist/runner/adapter-loop.d.ts +4 -0
  39. package/dist/runner/adapter-loop.js +17 -2
  40. package/dist/runner/adapter-run-spec.js +16 -5
  41. package/dist/runner/audit.d.ts +64 -0
  42. package/dist/runner/audit.js +338 -0
  43. package/dist/runner/beside.js +1 -1
  44. package/dist/runner/cli-run-spec.js +15 -5
  45. package/dist/runner/feedback-round.js +1 -4
  46. package/dist/runner/harness-loops.js +1 -15
  47. package/dist/runner/journal-kinds.d.ts +0 -7
  48. package/dist/runner/journal-kinds.js +0 -7
  49. package/dist/runner/learning-dispatch.d.ts +0 -16
  50. package/dist/runner/learning-dispatch.js +4 -47
  51. package/dist/runner/learning-end.d.ts +52 -13
  52. package/dist/runner/learning-end.js +124 -44
  53. package/dist/runner/learning-factory.d.ts +1 -1
  54. package/dist/runner/learning-factory.js +1 -4
  55. package/dist/runner/learning-loop.d.ts +2 -38
  56. package/dist/runner/learning-loop.js +8 -116
  57. package/dist/runner/main.js +1 -1
  58. package/dist/runner/promotion.d.ts +50 -54
  59. package/dist/runner/promotion.js +191 -583
  60. package/dist/runner/reflect-hook.d.ts +10 -0
  61. package/dist/runner/reflect-hook.js +6 -0
  62. package/dist/runner/workflow-first.d.ts +6 -5
  63. package/dist/runner/workflow-first.js +17 -12
  64. package/dist/server.js +61 -16
  65. package/dist/store/sqlite/store.js +1 -0
  66. package/dist/store/store.d.ts +3 -0
  67. package/dist/store-reads/learning.d.ts +17 -6
  68. package/dist/store-reads/learning.js +36 -23
  69. package/dist/store-reads/loop.d.ts +4 -39
  70. package/dist/store-reads/loop.js +10 -79
  71. package/dist/store-view.js +12 -2
  72. package/dist/workspace/run-tools.d.ts +1 -1
  73. package/dist/workspace/run-tools.js +14 -3
  74. package/package.json +9 -9
  75. package/dist/console/assets/index-C3gNPz58.css +0 -1
  76. package/dist/learn/general.d.ts +0 -69
  77. package/dist/learn/general.js +0 -75
  78. package/dist/learn/refit.d.ts +0 -48
  79. package/dist/learn/refit.js +0 -264
  80. package/dist/runner/step-guard.d.ts +0 -62
  81. package/dist/runner/step-guard.js +0 -93
@@ -1,264 +0,0 @@
1
- // Threshold refit: a learned workflow's step guards (runner/step-guard.ts) re-chosen from graded rows, so a guard set too
2
- // high (October's receipt hold: 46 of 54 revisions held) or too low is moved to where the rows say it belongs. Each guarded
3
- // step's threshold becomes the cheapest one (the fewest hand-backs) that keeps the workflow's accuracy over the rows within
4
- // PROMOTE_BAR of the agent's; a `both` guard's fit (logistic over [self, jev], Platt-style) is refit first when the rows
5
- // hold at least FIT_MIN_ROWS with at least FIT_MIN_WRONG wrong, else kept. A guard may also be switched off (OFF: it never
6
- // hands back, and the revision drops it): the cheapest setting of all, so a guard whose p says nothing of right and wrong
7
- // goes. So may an escalate node a replay recorded instead of obeying (the DSL's softEscalates), on the same rule:
8
- // one that stops right drafts is dropped from its chain, one that stops wrong ones stays. Pure: the rows in, the new
9
- // workflow text and what changed out; runner/promotion.ts reads the rows (replays and graded served runs) and writes the
10
- // revision.
11
- import { softEscalates } from "@parcha/agentrun-dsl";
12
- import { agentRight, answerCorrect, PROMOTE_BAR, sameAnswer, SOFT_ESCALATE_THRESHOLD, walkGuards } from "./promote.js";
13
- import { workflowNodes } from "./workflow-nodes.js";
14
- /** A switch set off: the guard or the escalate never hands back. Never a threshold the DSL takes (one is in (0, 1)). */
15
- export const OFF = 0;
16
- export const FIT_MIN_ROWS = 30;
17
- /** The lowest and highest threshold a refit writes: the DSL takes a threshold in (0, 1), exclusive. */
18
- export const THRESHOLD_MIN = 0.001;
19
- export const THRESHOLD_MAX = 0.999;
20
- export const FIT_MIN_WRONG = 5;
21
- /** A replay's rows as the scorer reads them: those its workflow answered or handed back, never one it failed on or skipped
22
- * (no evidence either way: the replay ran without what the graded run had, or stopped at a write it never runs). Answered
23
- * alone only when every guard read a p (record-only, none handed back). */
24
- export const refitRowsOf = (rows) => rows.flatMap((row) => {
25
- if (row.outcome !== "answered" && row.outcome !== "handed_back")
26
- return [];
27
- const answered = row.outcome === "answered" && row.guards.every((guard) => guard.p !== null);
28
- return [{
29
- of: row.of, guards: row.guards, answered, agentCorrect: agentRight(row.recorded) ? 1 : 0,
30
- wfCorrect: answered ? answerCorrect(row.answer, row.recorded) : null, agrees: answered && sameAnswer(row.answer, row.recorded.answer),
31
- }];
32
- });
33
- const sigmoid = (z) => 1 / (1 + Math.exp(-z));
34
- const round = (value, places = 4) => Math.round(value * 10 ** places) / 10 ** places;
35
- /** A logistic fit of y over x (Newton's method with a small ridge, so separable rows stay finite): weights and bias. */
36
- export function fitLogistic(xs, ys, ridge = 1e-2) {
37
- const d = xs[0]?.length ?? 0;
38
- let beta = new Array(d + 1).fill(0);
39
- for (let iter = 0; iter < 50; iter++) {
40
- const grad = new Array(d + 1).fill(0);
41
- const hess = Array.from({ length: d + 1 }, () => new Array(d + 1).fill(0));
42
- xs.forEach((x, i) => {
43
- const row = [1, ...x];
44
- const p = sigmoid(row.reduce((sum, v, j) => sum + v * beta[j], 0));
45
- const err = (ys[i] ? 1 : 0) - p;
46
- for (let j = 0; j <= d; j++) {
47
- grad[j] += err * row[j];
48
- for (let k = 0; k <= d; k++)
49
- hess[j][k] += p * (1 - p) * row[j] * row[k];
50
- }
51
- });
52
- for (let j = 1; j <= d; j++) {
53
- grad[j] -= ridge * beta[j];
54
- hess[j][j] += ridge;
55
- }
56
- const step = solve(hess, grad);
57
- if (!step)
58
- break;
59
- beta = beta.map((v, j) => v + step[j]);
60
- if (Math.max(...step.map(Math.abs)) < 1e-8)
61
- break;
62
- }
63
- return { w: beta.slice(1).map((v) => round(v, 6)), b: round(beta[0], 6) };
64
- }
65
- /** a·x = b by Gaussian elimination with partial pivoting; undefined when singular. */
66
- function solve(a, b) {
67
- const n = b.length;
68
- const m = a.map((row, i) => [...row, b[i]]);
69
- for (let col = 0; col < n; col++) {
70
- let pivot = col;
71
- for (let r = col + 1; r < n; r++)
72
- if (Math.abs(m[r][col]) > Math.abs(m[pivot][col]))
73
- pivot = r;
74
- if (Math.abs(m[pivot][col]) < 1e-12)
75
- return undefined;
76
- [m[col], m[pivot]] = [m[pivot], m[col]];
77
- for (let r = 0; r < n; r++) {
78
- if (r === col)
79
- continue;
80
- const f = m[r][col] / m[col][col];
81
- for (let c = col; c <= n; c++)
82
- m[r][c] -= f * m[col][c];
83
- }
84
- }
85
- return m.map((row, i) => row[n] / row[i]);
86
- }
87
- /** The rows' score, unrounded (scoreRows rounds it; the refit's search compares it as it is), with p read through `pOf`
88
- * and each step held to `thresholds`: a row any guard of hands back on
89
- * takes the agent's answer; one that answered alone, its grade. A row that did not answer alone because a guard handed
90
- * it back (one of its guards escalated) and that no guard would hand back at `thresholds` would have answered with an
91
- * answer nobody read: counted wrong, so a threshold never comes down past hand-backs with no evidence of what the
92
- * workflow says there. One that did not answer for another reason (a step failed, an escalate node) takes the agent's
93
- * answer at every threshold. A switch OFF never hands back, a missing p or not. */
94
- function scoreAt(rows, thresholds, pOf) {
95
- let [wf, agent, handed, agree] = [0, 0, 0, 0];
96
- for (const row of rows) {
97
- agent += row.agentCorrect;
98
- const under = row.guards.some((guard) => {
99
- const at = thresholds.get(guard.node) ?? guard.threshold;
100
- if (at === OFF)
101
- return false;
102
- const p = pOf(guard);
103
- return p === null || p < at;
104
- });
105
- const known = row.answered && row.wfCorrect !== null;
106
- if (under || (!known && !row.guards.some((guard) => guard.escalated))) {
107
- handed += 1;
108
- wf += row.agentCorrect;
109
- continue;
110
- }
111
- if (known && row.wfCorrect)
112
- wf += 1;
113
- if (row.agrees)
114
- agree += 1;
115
- }
116
- const n = rows.length || 1;
117
- return { n: rows.length, agree, wf_acc: wf / n, agent_acc: agent / n, handed_back: handed };
118
- }
119
- /** The one score of a workflow over rows (a replay's, a refit's, a serving check's), each step held to `thresholds` (a step
120
- * not named, its row's own threshold) with p read through `pOf` (the row's p): `n` rows; `agree`, how many it answered
121
- * alone with the agent's recorded answer; `agent_acc`, the agent's accuracy; `wf_acc`, the workflow's, a hand-back
122
- * counting as the agent's answer (scoreAt); `delta` = wf_acc - agent_acc; `handed_back` (it answered n - handed_back
123
- * alone: answersAlone). Accuracies to 1e-4, as the promotion record keeps them. */
124
- export function scoreRows(rows, thresholds, pOf = (row) => row.p) {
125
- const score = scoreAt(rows, thresholds, pOf);
126
- const [agent_acc, wf_acc] = [round(score.agent_acc), round(score.wf_acc)];
127
- return { n: score.n, agree: score.agree, agent_acc, wf_acc, delta: round(wf_acc - agent_acc), handed_back: score.handed_back };
128
- }
129
- /** How good one raise is, compared first to last: any accuracy gained before none; then accuracy per input handed back
130
- * (a gain that hands back nothing first); then the fewest handed back. A raise that gains nothing ranks by its loss. */
131
- const raiseRank = (gain, added) => (gain > 1e-12 ? [1, added > 0 ? gain / added : Number.POSITIVE_INFINITY, -added] : [0, gain, -added]);
132
- const rankAbove = (a, b) => {
133
- for (let i = 0; i < a.length; i++)
134
- if (a[i] !== b[i])
135
- return a[i] > b[i];
136
- return false;
137
- };
138
- /** The escalates of `doc` a refit may switch off: each a replay records (softEscalates) that is a step of a chain with
139
- * a step that is no escalate, so the chain keeps a step once they are dropped. */
140
- function switchableEscalates(doc) {
141
- const soft = softEscalates(doc);
142
- const out = new Set();
143
- for (const { node, prefix } of workflowNodes(doc)) {
144
- if (node.node !== "chain" || !Array.isArray(node.steps))
145
- continue;
146
- const steps = node.steps;
147
- if (!steps.some((step) => step?.node !== "escalate"))
148
- continue;
149
- for (const step of steps)
150
- if (step?.node === "escalate" && soft.has(`${prefix}${step.label}`))
151
- out.add(`${prefix}${step.label}`);
152
- }
153
- return out;
154
- }
155
- /** The workflow `text`'s guards, and the escalates its replay recorded, refit over `rows` (`now`: the fit's fitted_at). A
156
- * guard whose step no row reached keeps what it has, and so does an escalate no row recorded. Nothing changes (no
157
- * `text`) when every guard keeps its threshold and fit and every escalate stays. */
158
- export function refitGuards(text, rows, now) {
159
- let doc;
160
- try {
161
- doc = JSON.parse(text);
162
- }
163
- catch {
164
- return { guards: [], n: rows.length, agree: 0, agent_acc: 0, wf_acc: 0, delta: 0, handed_back: 0 };
165
- }
166
- const guards = [];
167
- walkGuards(doc, (label, guard, node) => guards.push({ label, guard, node }));
168
- const recorded = new Set(rows.flatMap((row) => row.guards.filter((g) => g.signal === "escalate").map((g) => g.node)));
169
- const escalates = [...switchableEscalates(doc)].filter((label) => recorded.has(label));
170
- const fits = new Map();
171
- for (const { label, guard } of guards) {
172
- if (guard.signal !== "both" || fits.has(label))
173
- continue;
174
- const data = rows.flatMap((row) => {
175
- const one = row.guards.find((g) => g.node === label);
176
- return one && typeof one.self === "number" && typeof one.jev === "number" && row.answered && row.wfCorrect !== null ? [{ x: [one.self, one.jev], y: row.wfCorrect }] : [];
177
- });
178
- if (data.length < FIT_MIN_ROWS || data.filter(({ y }) => !y).length < FIT_MIN_WRONG)
179
- continue;
180
- fits.set(label, { ...fitLogistic(data.map(({ x }) => x), data.map(({ y }) => y)), n: data.length, fitted_at: now });
181
- }
182
- // A step's p as the guard would read it with its new fit (the row's own p when no new fit).
183
- const pOf = (row) => {
184
- const fit = fits.get(row.node);
185
- if (!fit)
186
- return row.p;
187
- if (typeof row.self !== "number" || typeof row.jev !== "number")
188
- return null;
189
- return sigmoid(fit.b + fit.w[0] * row.self + fit.w[1] * row.jev);
190
- };
191
- const was = new Map(guards.map(({ label, guard }) => [label, typeof guard.threshold === "number" ? guard.threshold : OFF]));
192
- const thresholds = new Map([...was, ...escalates.map((label) => [label, SOFT_ESCALATE_THRESHOLD])]);
193
- const agentAcc = scoreAt(rows, thresholds, pOf).agent_acc;
194
- const meets = (at) => scoreAt(rows, at, pOf).wf_acc >= agentAcc - PROMOTE_BAR - 1e-9;
195
- // Each guard's candidates: OFF (hands back nothing), THRESHOLD_MIN (nothing but a missing p or one under it), each p its
196
- // rows read within the DSL's range, its own threshold, and THRESHOLD_MAX; a step no row reached keeps its own. Each
197
- // recorded escalate's: off or on.
198
- const candidatesOf = new Map(escalates.map((label) => [label, [OFF, SOFT_ESCALATE_THRESHOLD]]));
199
- for (const [label, own] of was) {
200
- const seen = rows.flatMap((row) => row.guards.filter((g) => g.node === label).map(pOf)).filter((p) => p !== null);
201
- const at = (p) => Math.min(THRESHOLD_MAX, Math.max(THRESHOLD_MIN, round(p, 6)));
202
- if (seen.length)
203
- candidatesOf.set(label, [...new Set([OFF, THRESHOLD_MIN, ...seen.map(at), ...(own > 0 && own < 1 ? [own] : []), THRESHOLD_MAX])].sort((a, b) => a - b));
204
- }
205
- const kept = new Map(thresholds);
206
- // Up from the bottom: while the bar is not met, the one raise (a guard to a higher candidate) that buys the most accuracy
207
- // per input it hands back. Taking the steps in order instead traps the refit: the first step alone meets the bar only by
208
- // handing back every input, and the step whose guard tells right from wrong is then never raised.
209
- for (const [label, candidates] of candidatesOf)
210
- thresholds.set(label, candidates[0]);
211
- for (let now = scoreAt(rows, thresholds, pOf); !meets(thresholds);) {
212
- let best;
213
- for (const [label, candidates] of candidatesOf) {
214
- for (const at of candidates.filter((c) => c > thresholds.get(label))) {
215
- const next = scoreAt(rows, new Map([...thresholds, [label, at]]), pOf);
216
- const rank = raiseRank(next.wf_acc - now.wf_acc, next.handed_back - now.handed_back);
217
- if (!best || rankAbove(rank, best.rank))
218
- best = { label, at, rank, next };
219
- }
220
- }
221
- if (!best)
222
- break;
223
- thresholds.set(best.label, best.at);
224
- now = best.next;
225
- }
226
- if (!meets(thresholds))
227
- for (const [label, at] of kept)
228
- thresholds.set(label, at);
229
- // Then down: each step in turn, twice over, the lowest threshold (the fewest hand-backs) that keeps the bar, the others held.
230
- for (let pass = 0; pass < 2; pass++) {
231
- for (const [label, candidates] of candidatesOf) {
232
- const found = candidates.find((candidate) => candidate <= thresholds.get(label) && meets(new Map([...thresholds, [label, candidate]])));
233
- if (found !== undefined)
234
- thresholds.set(label, found);
235
- }
236
- }
237
- const changed = [];
238
- for (const { label, guard, node } of guards) {
239
- const threshold = thresholds.get(label);
240
- const fit = fits.get(label);
241
- if (threshold === was.get(label) && !fit)
242
- continue;
243
- if (threshold === OFF) {
244
- delete node.guard;
245
- changed.push({ node: label, was: was.get(label), threshold: null });
246
- continue;
247
- }
248
- guard.threshold = threshold;
249
- if (fit)
250
- guard.fit = fit;
251
- if (!changed.some((one) => one.node === label))
252
- changed.push({ node: label, was: was.get(label), threshold, ...(fit ? { fit } : {}) });
253
- }
254
- const off = new Set(escalates.filter((label) => thresholds.get(label) === OFF));
255
- if (off.size) {
256
- for (const { node, prefix } of workflowNodes(doc)) {
257
- if (node.node === "chain" && Array.isArray(node.steps))
258
- node.steps = node.steps.filter((step) => !(step?.node === "escalate" && off.has(`${prefix}${step.label}`)));
259
- }
260
- for (const label of off)
261
- changed.push({ node: label, was: null, threshold: null, escalate: true });
262
- }
263
- return { ...(changed.length ? { text: JSON.stringify(doc) } : {}), guards: changed, ...scoreRows(rows, thresholds, pOf) };
264
- }
@@ -1,62 +0,0 @@
1
- import type { DecisionProvider, GuardStepParams, GuardVerdict, StepGuard, WorkflowDeps } from "@parcha/agentrun-dsl";
2
- import type { GuardRow } from "../learned-nodes.js";
3
- /** The Jev model a guard asks, pinned (https://docs.typesafe.ai/models, read 2026-11-13: jev-1.14.0 is current, and
4
- * jev-latest points to it), by route: TypeSafe's own name, or OpenRouter's. A new Jev is a new pin and a new fit. */
5
- export declare const JEV_GUARD_MODEL: {
6
- readonly typesafe: "jev-1.14.0";
7
- readonly openrouter: "typesafe/jev-1.14";
8
- };
9
- /** The question a jev guard asks when its guard names none. */
10
- export declare const DEFAULT_GUARD_QUESTION = "Is this output correct for this input, as the step's task asks?";
11
- /** The most of a step's task, its input and its output a guard's request holds, each in UTF-16 units of its JSON: a
12
- * longer one goes as its first part, cut as the generality pre-check cuts its state (learn/general.ts cutForJev,
13
- * GENERAL_STATE_CAPS), well within one Jev request's 32k tokens a question. */
14
- export declare const GUARD_STATE_CAPS: Readonly<{
15
- task: 8000;
16
- input: 8000;
17
- output: 8000;
18
- }>;
19
- /** One guard check, as the run keeps it (learned-nodes.ts GuardRow). */
20
- export type { GuardRow };
21
- /** One Jev request as a guard sends it: the step it guards (its label, its execution path, its item in a map), the
22
- * state and its questions; answered with their answers. */
23
- export type GuardJev = (request: {
24
- label: string;
25
- executionPath: string;
26
- item?: {
27
- index: number;
28
- };
29
- state: unknown;
30
- questions: Record<string, unknown>;
31
- signal?: AbortSignal;
32
- }) => Promise<{
33
- answers: Record<string, {
34
- type: string;
35
- noul?: number;
36
- }>;
37
- }>;
38
- /** p from a guard's signals: through its fit when it has one, else the one signal, or the lower of the two for both;
39
- * null when a signal it reads is missing. */
40
- export declare function guardP(guard: Pick<StepGuard, "signal" | "fit">, signals: {
41
- self: number | null;
42
- jev: number | null;
43
- }): number | null;
44
- /** The one Jev request a guard sends, for every node kind: the step's label, what it was asked to do (its task: its
45
- * instructions, its questions or schema; GuardStepParams.task), what it saw and what it wrote, each bounded
46
- * (GUARD_STATE_CAPS); one yes/no question, the guard's own or DEFAULT_GUARD_QUESTION. */
47
- export declare function guardRequestOf(params: Pick<GuardStepParams, "label" | "guard" | "task" | "input" | "output">): {
48
- state: Record<string, unknown>;
49
- questions: Record<string, unknown>;
50
- };
51
- /** A guard's Jev as a decision of the run: `judge` (the learned workflow's own, learned-workflow.ts learnedJudge: held to
52
- * the run's gate on the provider jev, admitted on its one cap, settled at what it charged) asked of Jev, on the pinned
53
- * model of `jev`'s route (its key's: TypeSafe's own, or OpenRouter's), under the step's label and execution path with
54
- * `#guard`, so its receipt is its own. */
55
- export declare function guardJevOn(judge: NonNullable<WorkflowDeps["runJudge"]>, jev: Pick<DecisionProvider, "needs">): GuardJev;
56
- /** The DSL's guardStep for one learned_workflow call: Jev asked (`jev`; none: no Jev signal) only for a guard that reads
57
- * it; p by guardP, NaN (no p, so the step hands back) when a signal it reads is missing. */
58
- export declare function stepGuard(jev: GuardJev | undefined): (params: GuardStepParams) => Promise<GuardVerdict>;
59
- /** A guard.evaluated event's detail as the run's row of it (GuardRow), under the step's label. */
60
- export declare function rowOf(label: string, detail: unknown): GuardRow | undefined;
61
- /** A guard row in words, for the hand-back: what it read and where p fell against its threshold. */
62
- export declare function guardLine(row: GuardRow): string;
@@ -1,93 +0,0 @@
1
- import { JEV_OPENROUTER_KEY_ENV } from "../decisions.js";
2
- import { cutForJev } from "../learn/general.js";
3
- /** The Jev model a guard asks, pinned (https://docs.typesafe.ai/models, read 2026-11-13: jev-1.14.0 is current, and
4
- * jev-latest points to it), by route: TypeSafe's own name, or OpenRouter's. A new Jev is a new pin and a new fit. */
5
- export const JEV_GUARD_MODEL = { typesafe: "jev-1.14.0", openrouter: "typesafe/jev-1.14" };
6
- /** The question a jev guard asks when its guard names none. */
7
- export const DEFAULT_GUARD_QUESTION = "Is this output correct for this input, as the step's task asks?";
8
- /** The most of a step's task, its input and its output a guard's request holds, each in UTF-16 units of its JSON: a
9
- * longer one goes as its first part, cut as the generality pre-check cuts its state (learn/general.ts cutForJev,
10
- * GENERAL_STATE_CAPS), well within one Jev request's 32k tokens a question. */
11
- export const GUARD_STATE_CAPS = Object.freeze({ task: 8_000, input: 8_000, output: 8_000 });
12
- /** What the guard's yes and no mean to Jev. */
13
- const GUARD_CRITERIA = { true: "the output does what the task asks and is right for this input", false: "the output is wrong, incomplete, not what the task asks, or not supported by the input" };
14
- /** The question id a guard's request asks under. */
15
- const GUARD_QUESTION_ID = "right";
16
- const sigmoid = (z) => 1 / (1 + Math.exp(-z));
17
- /** p from a guard's signals: through its fit when it has one, else the one signal, or the lower of the two for both;
18
- * null when a signal it reads is missing. */
19
- export function guardP(guard, signals) {
20
- const x = guard.signal === "self" ? [signals.self] : guard.signal === "jev" ? [signals.jev] : [signals.self, signals.jev];
21
- if (x.some((value) => value === null || !Number.isFinite(value)))
22
- return null;
23
- const read = x;
24
- const fit = guard.fit;
25
- if (fit && Array.isArray(fit.w) && fit.w.length === read.length)
26
- return sigmoid(fit.b + fit.w.reduce((sum, w, i) => sum + w * read[i], 0));
27
- return Math.min(...read);
28
- }
29
- /** A part of what a guard sends: whole while its JSON fits `max`, else that JSON cut (cutForJev). */
30
- function part(value, max) {
31
- const text = JSON.stringify(value ?? null);
32
- return text.length <= max ? value ?? null : cutForJev(text, max);
33
- }
34
- /** The one Jev request a guard sends, for every node kind: the step's label, what it was asked to do (its task: its
35
- * instructions, its questions or schema; GuardStepParams.task), what it saw and what it wrote, each bounded
36
- * (GUARD_STATE_CAPS); one yes/no question, the guard's own or DEFAULT_GUARD_QUESTION. */
37
- export function guardRequestOf(params) {
38
- return {
39
- state: { step: params.label, task: part(params.task, GUARD_STATE_CAPS.task), input: part(params.input, GUARD_STATE_CAPS.input), output: part(params.output, GUARD_STATE_CAPS.output) },
40
- questions: { [GUARD_QUESTION_ID]: { type: "noul", instructions: params.guard.question?.trim() || DEFAULT_GUARD_QUESTION, criteria: GUARD_CRITERIA } },
41
- };
42
- }
43
- /** A guard's Jev as a decision of the run: `judge` (the learned workflow's own, learned-workflow.ts learnedJudge: held to
44
- * the run's gate on the provider jev, admitted on its one cap, settled at what it charged) asked of Jev, on the pinned
45
- * model of `jev`'s route (its key's: TypeSafe's own, or OpenRouter's), under the step's label and execution path with
46
- * `#guard`, so its receipt is its own. */
47
- export function guardJevOn(judge, jev) {
48
- const model = jev.needs.includes(JEV_OPENROUTER_KEY_ENV) ? JEV_GUARD_MODEL.openrouter : JEV_GUARD_MODEL.typesafe;
49
- return async (request) => (await judge({ label: `${request.label} guard`, kind: "judge", provider: "jev", model, state: request.state, questions: request.questions, executionPath: `${request.executionPath}#guard`, ...(request.item ? { item: request.item } : {}), ...(request.signal ? { signal: request.signal } : {}) }));
50
- }
51
- /** The DSL's guardStep for one learned_workflow call: Jev asked (`jev`; none: no Jev signal) only for a guard that reads
52
- * it; p by guardP, NaN (no p, so the step hands back) when a signal it reads is missing. */
53
- export function stepGuard(jev) {
54
- return async (params) => {
55
- const { guard } = params;
56
- let read = null;
57
- if (guard.signal !== "self" && jev) {
58
- try {
59
- const answered = await jev({ label: params.label, executionPath: params.executionPath, ...(params.item ? { item: params.item } : {}), ...guardRequestOf(params), ...(params.signal ? { signal: params.signal } : {}) });
60
- const noul = answered.answers?.[GUARD_QUESTION_ID]?.noul;
61
- read = typeof noul === "number" && Number.isFinite(noul) ? noul : null;
62
- }
63
- catch (error) {
64
- // A stop is the call's stop; any other failure (a refusal of the gate or the cap, Jev's own) leaves no Jev
65
- // signal, so the step hands back.
66
- if (params.signal?.aborted)
67
- throw error;
68
- }
69
- }
70
- const p = guardP(guard, { self: params.self, jev: read });
71
- return { p: p ?? Number.NaN, jev: read };
72
- };
73
- }
74
- /** A guard.evaluated event's detail as the run's row of it (GuardRow), under the step's label. */
75
- export function rowOf(label, detail) {
76
- const d = (detail ?? {});
77
- if (d.signal !== "self" && d.signal !== "jev" && d.signal !== "both")
78
- return undefined;
79
- if (typeof d.threshold !== "number")
80
- return undefined;
81
- const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
82
- const self = num(d.self);
83
- const jev = num(d.jev);
84
- return { node: label, signal: d.signal, ...(self === undefined ? {} : { self }), ...(jev === undefined ? {} : { jev }), p: num(d.p) ?? null, threshold: d.threshold, escalated: d.escalated === true };
85
- }
86
- /** A guard row in words, for the hand-back: what it read and where p fell against its threshold. */
87
- export function guardLine(row) {
88
- if (row.signal === "escalate")
89
- return `escalate "${row.node}" ${row.p === 0 ? "fired" : "did not fire"}; recorded, not obeyed (a replay)`;
90
- const said = (n) => (typeof n === "number" ? n.toFixed(2) : "none");
91
- const read = [row.self !== undefined || row.signal !== "jev" ? `its own confidence ${said(row.self)}` : "", row.signal !== "self" ? `Jev ${said(row.jev)}` : ""].filter(Boolean).join(", ");
92
- return `guard on "${row.node}" (${row.signal}): p ${said(row.p)} against threshold ${row.threshold} (${read}); ${row.escalated ? "handed back" : "passed"}`;
93
- }