@parcha/agentrun-serve 0.1.0-beta.42 → 0.1.0-beta.44
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 +126 -0
- package/README.md +221 -31
- package/dist/cli.js +42 -8
- package/dist/composio-preset.d.ts +4 -3
- package/dist/composio-preset.js +12 -4
- package/dist/composio-triggers.d.ts +20 -2
- package/dist/composio-triggers.js +183 -17
- package/dist/computer-lost.d.ts +11 -0
- package/dist/computer-lost.js +19 -0
- package/dist/computer-record.d.ts +10 -2
- package/dist/computer-record.js +50 -18
- package/dist/computer-setting.d.ts +1 -0
- package/dist/computer-setting.js +2 -2
- package/dist/console/assets/index-BUktRvS-.css +1 -0
- package/dist/console/assets/index-nB9kTfIN.js +711 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.js +0 -4
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +3 -0
- package/dist/harness-table.d.ts +51 -3
- package/dist/harness-table.js +101 -13
- package/dist/harness.d.ts +18 -1
- package/dist/harness.js +21 -9
- package/dist/host.d.ts +12 -10
- package/dist/host.js +18 -16
- package/dist/import-sources.js +25 -5
- package/dist/import-worker.d.ts +3 -0
- package/dist/import-worker.js +7 -5
- package/dist/import.d.ts +22 -1
- package/dist/import.js +141 -28
- package/dist/learn/audit.d.ts +123 -0
- package/dist/learn/audit.js +159 -0
- package/dist/learn/check.d.ts +3 -0
- package/dist/learn/check.js +1 -1
- package/dist/learn/compile.d.ts +50 -74
- package/dist/learn/compile.js +90 -124
- package/dist/learn/delete.d.ts +17 -0
- package/dist/learn/delete.js +44 -0
- package/dist/learn/folder.d.ts +9 -0
- package/dist/learn/folder.js +13 -2
- package/dist/learn/promote.d.ts +92 -200
- package/dist/learn/promote.js +65 -187
- package/dist/learn/replay-calls.d.ts +5 -0
- package/dist/learn/replay-calls.js +12 -1
- package/dist/learn/secrets.d.ts +8 -0
- package/dist/learn/secrets.js +12 -0
- package/dist/learn/skills.d.ts +4 -0
- package/dist/learn/skills.js +19 -5
- package/dist/learn/workflow-nodes.d.ts +23 -3
- package/dist/learn/workflow-nodes.js +30 -12
- package/dist/learned-nodes.d.ts +9 -34
- package/dist/learned-nodes.js +11 -23
- package/dist/learned-workflow.d.ts +6 -8
- package/dist/learned-workflow.js +18 -57
- package/dist/learning-batch.d.ts +13 -5
- package/dist/learning-batch.js +34 -8
- package/dist/learning-cost.d.ts +111 -4
- package/dist/learning-cost.js +120 -3
- package/dist/learning-evals.d.ts +2 -0
- package/dist/learning-evals.js +4 -3
- package/dist/learning-routes.d.ts +8 -0
- package/dist/learning-routes.js +18 -1
- package/dist/learning-setting.d.ts +16 -1
- package/dist/learning-setting.js +34 -2
- package/dist/learning.d.ts +1 -1
- package/dist/listen-first.d.ts +30 -0
- package/dist/listen-first.js +115 -0
- package/dist/llms.txt +2 -1
- package/dist/mcp-servers-store.d.ts +12 -12
- package/dist/model.d.ts +8 -4
- package/dist/model.js +16 -8
- package/dist/openapi.js +203 -87
- package/dist/owner.d.ts +8 -0
- package/dist/owner.js +11 -0
- package/dist/paid-calls.d.ts +6 -0
- package/dist/paid-calls.js +11 -1
- package/dist/place.d.ts +8 -3
- package/dist/place.js +13 -9
- package/dist/provider.js +15 -1
- package/dist/run-launch.d.ts +6 -3
- package/dist/run-launch.js +2 -0
- package/dist/run-learning-served.d.ts +1 -1
- package/dist/run-model-key.d.ts +64 -0
- package/dist/run-model-key.js +147 -0
- package/dist/runner/adapter-loop.d.ts +10 -0
- package/dist/runner/adapter-loop.js +26 -4
- package/dist/runner/adapter-run-spec.d.ts +6 -3
- package/dist/runner/adapter-run-spec.js +83 -25
- package/dist/runner/adapters/index.d.ts +4 -2
- package/dist/runner/adapters/index.js +13 -4
- package/dist/runner/audit.d.ts +68 -0
- package/dist/runner/audit.js +349 -0
- package/dist/runner/beside.d.ts +2 -1
- package/dist/runner/beside.js +6 -3
- package/dist/runner/claim-secrets.d.ts +49 -0
- package/dist/runner/claim-secrets.js +110 -1
- package/dist/runner/cli-run-spec.d.ts +2 -1
- package/dist/runner/cli-run-spec.js +44 -15
- package/dist/runner/commands.d.ts +3 -6
- package/dist/runner/feedback-round.d.ts +3 -2
- package/dist/runner/feedback-round.js +8 -7
- package/dist/runner/harness-loops.js +31 -23
- package/dist/runner/journal-kinds.d.ts +5 -7
- package/dist/runner/journal-kinds.js +0 -7
- package/dist/runner/learning-dispatch.d.ts +0 -16
- package/dist/runner/learning-dispatch.js +4 -47
- package/dist/runner/learning-end.d.ts +55 -13
- package/dist/runner/learning-end.js +128 -44
- package/dist/runner/learning-factory.d.ts +1 -1
- package/dist/runner/learning-factory.js +1 -4
- package/dist/runner/learning-loop.d.ts +2 -38
- package/dist/runner/learning-loop.js +8 -116
- package/dist/runner/loop-contract.d.ts +6 -0
- package/dist/runner/loop-contract.js +4 -0
- package/dist/runner/loop.js +6 -2
- package/dist/runner/main.d.ts +1 -0
- package/dist/runner/main.js +25 -8
- package/dist/runner/memory-claim.d.ts +9 -6
- package/dist/runner/memory-claim.js +12 -9
- package/dist/runner/promotion.d.ts +55 -54
- package/dist/runner/promotion.js +232 -585
- package/dist/runner/reflect-hook.d.ts +14 -0
- package/dist/runner/reflect-hook.js +28 -3
- package/dist/runner/runner.js +57 -4
- package/dist/runner/store-secrets.js +9 -5
- package/dist/runner/workflow-first.d.ts +6 -5
- package/dist/runner/workflow-first.js +17 -12
- package/dist/runner/workflow-spec.js +10 -2
- package/dist/runs-over-store.d.ts +5 -4
- package/dist/runs-over-store.js +13 -3
- package/dist/sdk/workflows.d.ts +1 -1
- package/dist/server.d.ts +64 -50
- package/dist/server.js +516 -134
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/seal.d.ts +20 -2
- package/dist/store/seal.js +24 -8
- package/dist/store/sqlite/run-launch.d.ts +4 -1
- package/dist/store/sqlite/run-launch.js +12 -0
- package/dist/store/sqlite/store.d.ts +3 -2
- package/dist/store/sqlite/store.js +119 -16
- package/dist/store/store.d.ts +41 -3
- package/dist/store-reads/analytics.js +11 -1
- package/dist/store-reads/learning.d.ts +57 -7
- package/dist/store-reads/learning.js +194 -28
- package/dist/store-reads/loop.d.ts +4 -39
- package/dist/store-reads/loop.js +10 -79
- package/dist/store-reads/stats.js +13 -3
- package/dist/store-view.d.ts +5 -1
- package/dist/store-view.js +12 -1
- package/dist/telemetry.d.ts +59 -0
- package/dist/telemetry.js +153 -0
- package/dist/tool-keys-store.d.ts +1 -1
- package/dist/tool-keys.d.ts +2 -2
- package/dist/tool-plane.d.ts +12 -12
- package/dist/tools.d.ts +11 -11
- package/dist/tools.js +18 -5
- package/dist/trigger-adapter.d.ts +3 -0
- package/dist/trigger-adapters.d.ts +4 -0
- package/dist/trigger-adapters.js +13 -0
- package/dist/trigger-composio.d.ts +58 -1
- package/dist/trigger-composio.js +160 -6
- package/dist/triggers.d.ts +4 -0
- package/dist/triggers.js +22 -3
- package/dist/validate.d.ts +11 -7
- package/dist/validate.js +8 -7
- package/dist/workspace/computer-for-claim.d.ts +15 -5
- package/dist/workspace/computer-for-claim.js +228 -32
- package/dist/workspace/resolve-computer.d.ts +8 -2
- package/dist/workspace/resolve-computer.js +1 -1
- package/dist/workspace/run-tools.d.ts +1 -1
- package/dist/workspace/run-tools.js +14 -3
- package/package.json +10 -9
- package/dist/console/assets/index-C3gNPz58.css +0 -1
- package/dist/console/assets/index-DYJ_wj27.js +0 -711
- package/dist/learn/general.d.ts +0 -69
- package/dist/learn/general.js +0 -75
- package/dist/learn/refit.d.ts +0 -48
- package/dist/learn/refit.js +0 -264
- package/dist/runner/step-guard.d.ts +0 -62
- package/dist/runner/step-guard.js +0 -93
package/dist/learn/general.d.ts
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import type { DecisionProvider } from "@parcha/agentrun-dsl";
|
|
2
|
-
import type { NoteText } from "./grade.js";
|
|
3
|
-
/** The lowest Jev probability that a note holds beyond its one input at which it goes on to the grader. */
|
|
4
|
-
export declare const GENERAL_THRESHOLD = 0.5;
|
|
5
|
-
/** Where the host reads another threshold: a number from 0 to 1. */
|
|
6
|
-
export declare const GENERAL_THRESHOLD_ENV = "AGENTRUN_SERVE_LEARNING_GENERAL_THRESHOLD";
|
|
7
|
-
/** The most of the job's instructions, the run's input and the note the state holds, in UTF-16 units: well within one
|
|
8
|
-
* Jev request's 32k tokens a question. */
|
|
9
|
-
export declare const GENERAL_STATE_CAPS: Readonly<{
|
|
10
|
-
job: 4000;
|
|
11
|
-
input: 8000;
|
|
12
|
-
note: 8000;
|
|
13
|
-
}>;
|
|
14
|
-
/** How long the check waits for Jev, every note's request included. */
|
|
15
|
-
export declare const GENERAL_DEADLINE_MS = 30000;
|
|
16
|
-
/** The question, as the lead's spec states it. */
|
|
17
|
-
export declare const GENERAL_QUESTION = "Does `note` state a method, source, fact or preference that holds for inputs of this job other than `input`, the one it came from?";
|
|
18
|
-
export declare const GENERAL_CRITERIA: Readonly<{
|
|
19
|
-
true: "It holds for other inputs of this job: a method, a source, a fact about the job or the user's own world, or the user's standing preference.";
|
|
20
|
-
false: "It rests on names, ids, amounts or pages of that one input: it would only help on that same input again.";
|
|
21
|
-
}>;
|
|
22
|
-
/** The threshold `env` names, else GENERAL_THRESHOLD. Any value that is not a number from 0 to 1 is an error. */
|
|
23
|
-
export declare function generalThresholdOf(env: NodeJS.ProcessEnv): number;
|
|
24
|
-
/** What the check reads of the run a note came from: the agent's standing instructions (the job), and the run's input
|
|
25
|
-
* (the first message it was sent, else the first trigger's input). */
|
|
26
|
-
export type GeneralSource = {
|
|
27
|
-
readonly job?: string;
|
|
28
|
-
readonly input?: string;
|
|
29
|
-
};
|
|
30
|
-
/** Text as a Jev request's state holds it: whole up to `max` UTF-16 units, else its first `max` and " [cut]". Every Jev
|
|
31
|
-
* request learning sends cuts its state this way (this check's, a step guard's: runner/step-guard.ts). */
|
|
32
|
-
export declare const cutForJev: (text: string | undefined, max: number) => string;
|
|
33
|
-
/** The one Jev request for `note`: its state (the job, the input, the note without its run's risky mark) and one Noul. */
|
|
34
|
-
export declare function generalRequest(note: NoteText, source: GeneralSource): {
|
|
35
|
-
label: string;
|
|
36
|
-
kind: "judge";
|
|
37
|
-
state: Record<string, string>;
|
|
38
|
-
questions: {
|
|
39
|
-
general: {
|
|
40
|
-
type: "noul";
|
|
41
|
-
instructions: string;
|
|
42
|
-
criteria: {
|
|
43
|
-
true: string;
|
|
44
|
-
false: string;
|
|
45
|
-
};
|
|
46
|
-
};
|
|
47
|
-
};
|
|
48
|
-
};
|
|
49
|
-
/** Each note's probability that it holds beyond its one input, by file, and what the requests cost (null once any is
|
|
50
|
-
* unknown). */
|
|
51
|
-
export type GeneralScores = {
|
|
52
|
-
readonly scores: Readonly<Record<string, number>>;
|
|
53
|
-
readonly usd: number | null;
|
|
54
|
-
};
|
|
55
|
-
/** What a learning run's end says when the check could not run (its provider's error stays in the run's journal and the
|
|
56
|
-
* runner's log, never here). */
|
|
57
|
-
export declare const GENERAL_UNCHECKED = "The generality check could not run, so the grader read every note.";
|
|
58
|
-
/** Why a check was skipped when its learning run's cap had no room for its worst case (learning-loop.ts GeneralOverCap):
|
|
59
|
-
* kept as its `unchecked`, and what a run's learning end says for it. */
|
|
60
|
-
export declare const GENERAL_NO_BUDGET = "no_budget";
|
|
61
|
-
export declare const GENERAL_NO_ROOM = "The generality check had no room under the cap, so the grader read every note.";
|
|
62
|
-
/** Asks `jev` the question of each note, one request a note, all at once. Throws when any request fails or answers out of
|
|
63
|
-
* shape, whatever the others answered: the caller grades every note as it would without the check, never drops one on an
|
|
64
|
-
* error, and books what the check spent as unknown (null), never 0, since a request that failed may still have been
|
|
65
|
-
* charged and the others were. `sending`: told once, before the first request leaves (the learning run marks the check
|
|
66
|
-
* sent there, so a restart never asks again unbooked). */
|
|
67
|
-
export declare function generalScores(jev: DecisionProvider, notes: readonly NoteText[], source: GeneralSource, signal: AbortSignal, run: string, sending?: () => Promise<void>): Promise<GeneralScores>;
|
|
68
|
-
/** The why of a note the check drops, in the host's words (no word of the note's). */
|
|
69
|
-
export declare const ONE_CASE: (p: number, threshold: number) => string;
|
package/dist/learn/general.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
// The generality pre-check: before the grader reads what a run proposes, Jev (TypeSafe's System One, the provider a
|
|
2
|
-
// workflow's decision nodes use when they name none, on the same client and model) is asked one Noul per proposed note:
|
|
3
|
-
// does it hold for inputs of this job other than the one it came from? A note scored below the threshold (default
|
|
4
|
-
// GENERAL_THRESHOLD) rests on one input's names, ids, amounts or pages, and is dropped before the grader, its why said
|
|
5
|
-
// where a grader's drop is (the learning run's verdict items). Offline, on Run B's 388 kept MCC notes, this question
|
|
6
|
-
// agreed with an Opus label 97.4% of the time (kappa 0.95). It calls no model itself: the host passes the provider.
|
|
7
|
-
import { createHash } from "node:crypto";
|
|
8
|
-
import { withoutRiskyMark } from "./notes.js";
|
|
9
|
-
/** The lowest Jev probability that a note holds beyond its one input at which it goes on to the grader. */
|
|
10
|
-
export const GENERAL_THRESHOLD = 0.5;
|
|
11
|
-
/** Where the host reads another threshold: a number from 0 to 1. */
|
|
12
|
-
export const GENERAL_THRESHOLD_ENV = "AGENTRUN_SERVE_LEARNING_GENERAL_THRESHOLD";
|
|
13
|
-
/** The most of the job's instructions, the run's input and the note the state holds, in UTF-16 units: well within one
|
|
14
|
-
* Jev request's 32k tokens a question. */
|
|
15
|
-
export const GENERAL_STATE_CAPS = Object.freeze({ job: 4_000, input: 8_000, note: 8_000 });
|
|
16
|
-
/** How long the check waits for Jev, every note's request included. */
|
|
17
|
-
export const GENERAL_DEADLINE_MS = 30_000;
|
|
18
|
-
/** The question, as the lead's spec states it. */
|
|
19
|
-
export const GENERAL_QUESTION = "Does `note` state a method, source, fact or preference that holds for inputs of this job other than `input`, the one it came from?";
|
|
20
|
-
export const GENERAL_CRITERIA = Object.freeze({
|
|
21
|
-
true: "It holds for other inputs of this job: a method, a source, a fact about the job or the user's own world, or the user's standing preference.",
|
|
22
|
-
false: "It rests on names, ids, amounts or pages of that one input: it would only help on that same input again.",
|
|
23
|
-
});
|
|
24
|
-
/** The threshold `env` names, else GENERAL_THRESHOLD. Any value that is not a number from 0 to 1 is an error. */
|
|
25
|
-
export function generalThresholdOf(env) {
|
|
26
|
-
const named = env[GENERAL_THRESHOLD_ENV]?.trim();
|
|
27
|
-
if (!named)
|
|
28
|
-
return GENERAL_THRESHOLD;
|
|
29
|
-
const value = Number(named);
|
|
30
|
-
if (!/^\d*\.?\d+$/.test(named) || !Number.isFinite(value) || value < 0 || value > 1)
|
|
31
|
-
throw new Error(`${GENERAL_THRESHOLD_ENV} is a number from 0 to 1, not ${named}`);
|
|
32
|
-
return value;
|
|
33
|
-
}
|
|
34
|
-
/** Text as a Jev request's state holds it: whole up to `max` UTF-16 units, else its first `max` and " [cut]". Every Jev
|
|
35
|
-
* request learning sends cuts its state this way (this check's, a step guard's: runner/step-guard.ts). */
|
|
36
|
-
export const cutForJev = (text, max) => (text === undefined ? "" : text.length > max ? `${text.slice(0, max)} [cut]` : text);
|
|
37
|
-
/** The one Jev request for `note`: its state (the job, the input, the note without its run's risky mark) and one Noul. */
|
|
38
|
-
export function generalRequest(note, source) {
|
|
39
|
-
return {
|
|
40
|
-
label: `learning: general ${note.file}`,
|
|
41
|
-
kind: "judge",
|
|
42
|
-
state: { job: cutForJev(source.job, GENERAL_STATE_CAPS.job), input: cutForJev(source.input, GENERAL_STATE_CAPS.input), note: cutForJev(withoutRiskyMark(note.text), GENERAL_STATE_CAPS.note) },
|
|
43
|
-
questions: { general: { type: "noul", instructions: GENERAL_QUESTION, criteria: { ...GENERAL_CRITERIA } } },
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
/** What a learning run's end says when the check could not run (its provider's error stays in the run's journal and the
|
|
47
|
-
* runner's log, never here). */
|
|
48
|
-
export const GENERAL_UNCHECKED = "The generality check could not run, so the grader read every note.";
|
|
49
|
-
/** Why a check was skipped when its learning run's cap had no room for its worst case (learning-loop.ts GeneralOverCap):
|
|
50
|
-
* kept as its `unchecked`, and what a run's learning end says for it. */
|
|
51
|
-
export const GENERAL_NO_BUDGET = "no_budget";
|
|
52
|
-
export const GENERAL_NO_ROOM = "The generality check had no room under the cap, so the grader read every note.";
|
|
53
|
-
/** Asks `jev` the question of each note, one request a note, all at once. Throws when any request fails or answers out of
|
|
54
|
-
* shape, whatever the others answered: the caller grades every note as it would without the check, never drops one on an
|
|
55
|
-
* error, and books what the check spent as unknown (null), never 0, since a request that failed may still have been
|
|
56
|
-
* charged and the others were. `sending`: told once, before the first request leaves (the learning run marks the check
|
|
57
|
-
* sent there, so a restart never asks again unbooked). */
|
|
58
|
-
export async function generalScores(jev, notes, source, signal, run, sending) {
|
|
59
|
-
const bound = AbortSignal.any([signal, AbortSignal.timeout(GENERAL_DEADLINE_MS)]);
|
|
60
|
-
// Paid, and Jev dedupes none (the decision id is not sent): marked sent, durably, before any request leaves.
|
|
61
|
-
await sending?.();
|
|
62
|
-
const answers = await Promise.all(notes.map(async (note) => {
|
|
63
|
-
const request = generalRequest(note, source);
|
|
64
|
-
const decisionId = createHash("sha256").update(`agentrun-learn general ${run} ${note.file} ${note.text}`).digest("hex").slice(0, 32);
|
|
65
|
-
const outcome = await jev.decide(request, { decisionId, signal: bound, deadlineMs: GENERAL_DEADLINE_MS });
|
|
66
|
-
const answer = outcome.answers.general;
|
|
67
|
-
if (answer?.type !== "noul" || typeof answer.noul !== "number" || !Number.isFinite(answer.noul) || answer.noul < 0 || answer.noul > 1)
|
|
68
|
-
throw new Error(`Jev's answer for ${note.file} is no probability`);
|
|
69
|
-
return { file: note.file, p: answer.noul, usd: outcome.cost_usd };
|
|
70
|
-
}));
|
|
71
|
-
const usd = answers.reduce((sum, { usd: one }) => (sum === null || one === null || !Number.isFinite(one) ? null : sum + one), 0);
|
|
72
|
-
return { scores: Object.fromEntries(answers.map(({ file, p }) => [file, p])), usd };
|
|
73
|
-
}
|
|
74
|
-
/** The why of a note the check drops, in the host's words (no word of the note's). */
|
|
75
|
-
export const ONE_CASE = (p, threshold) => `Jev rates it ${p.toFixed(2)} likely to hold for inputs other than the one it came from, under the bar of ${threshold}: it rests on that one input, so it was dropped before the grader.`;
|
package/dist/learn/refit.d.ts
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import type { GuardRow } from "../learned-nodes.js";
|
|
2
|
-
import { type RefitGuard, type ReplayRow, type ReplayScore } from "./promote.js";
|
|
3
|
-
/** A switch set off: the guard or the escalate never hands back. Never a threshold the DSL takes (one is in (0, 1)). */
|
|
4
|
-
export declare const OFF = 0;
|
|
5
|
-
export declare const FIT_MIN_ROWS = 30;
|
|
6
|
-
/** The lowest and highest threshold a refit writes: the DSL takes a threshold in (0, 1), exclusive. */
|
|
7
|
-
export declare const THRESHOLD_MIN = 0.001;
|
|
8
|
-
export declare const THRESHOLD_MAX = 0.999;
|
|
9
|
-
export declare const FIT_MIN_WRONG = 5;
|
|
10
|
-
/** One row the scorer (scoreRows) reads: the guard rows of one input (each step's p known up to where it stopped,
|
|
11
|
-
* `escalated` on the one that handed it back), whether the workflow answered it alone with every guard passing
|
|
12
|
-
* record-only (`answered`), and if so whether that answer was right (`wfCorrect`; null: unknown) and said what the
|
|
13
|
-
* agent's recorded answer said (`agrees`); `agentCorrect`, the chance the agent's answer to it is right (1 or 0 when
|
|
14
|
-
* known: a replayed row's agentRight; the agent's mean accuracy when not); `of`, the graded run a replayed row replays (refitRowsOf; a served
|
|
15
|
-
* run's row has none). */
|
|
16
|
-
export interface RefitRow {
|
|
17
|
-
readonly guards: readonly GuardRow[];
|
|
18
|
-
readonly answered: boolean;
|
|
19
|
-
readonly wfCorrect: boolean | null;
|
|
20
|
-
readonly agrees?: boolean;
|
|
21
|
-
readonly agentCorrect: number;
|
|
22
|
-
readonly of?: string;
|
|
23
|
-
}
|
|
24
|
-
/** What a refit chose: the workflow's new text (undefined when nothing changed), each guard it changed, and the rows'
|
|
25
|
-
* score at the new thresholds (scoreRows). */
|
|
26
|
-
export interface Refit extends ReplayScore {
|
|
27
|
-
readonly text?: string;
|
|
28
|
-
readonly guards: RefitGuard[];
|
|
29
|
-
}
|
|
30
|
-
/** A replay's rows as the scorer reads them: those its workflow answered or handed back, never one it failed on or skipped
|
|
31
|
-
* (no evidence either way: the replay ran without what the graded run had, or stopped at a write it never runs). Answered
|
|
32
|
-
* alone only when every guard read a p (record-only, none handed back). */
|
|
33
|
-
export declare const refitRowsOf: (rows: readonly ReplayRow[]) => RefitRow[];
|
|
34
|
-
/** A logistic fit of y over x (Newton's method with a small ridge, so separable rows stay finite): weights and bias. */
|
|
35
|
-
export declare function fitLogistic(xs: readonly (readonly number[])[], ys: readonly boolean[], ridge?: number): {
|
|
36
|
-
w: number[];
|
|
37
|
-
b: number;
|
|
38
|
-
};
|
|
39
|
-
/** 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
|
|
40
|
-
* not named, its row's own threshold) with p read through `pOf` (the row's p): `n` rows; `agree`, how many it answered
|
|
41
|
-
* alone with the agent's recorded answer; `agent_acc`, the agent's accuracy; `wf_acc`, the workflow's, a hand-back
|
|
42
|
-
* counting as the agent's answer (scoreAt); `delta` = wf_acc - agent_acc; `handed_back` (it answered n - handed_back
|
|
43
|
-
* alone: answersAlone). Accuracies to 1e-4, as the promotion record keeps them. */
|
|
44
|
-
export declare function scoreRows(rows: readonly RefitRow[], thresholds: ReadonlyMap<string, number>, pOf?: (row: GuardRow) => number | null): ReplayScore;
|
|
45
|
-
/** The workflow `text`'s guards, and the escalates its replay recorded, refit over `rows` (`now`: the fit's fitted_at). A
|
|
46
|
-
* guard whose step no row reached keeps what it has, and so does an escalate no row recorded. Nothing changes (no
|
|
47
|
-
* `text`) when every guard keeps its threshold and fit and every escalate stays. */
|
|
48
|
-
export declare function refitGuards(text: string, rows: readonly RefitRow[], now: string): Refit;
|
package/dist/learn/refit.js
DELETED
|
@@ -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
|
-
}
|