@parcha/agentrun-dsl 0.1.0-beta.20 → 0.1.0-beta.201
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/NOTICE +2 -0
- package/README.md +141 -21
- package/dist/author-references.d.ts +8 -0
- package/dist/author-references.js +8 -0
- package/dist/author.d.ts +4 -3
- package/dist/author.js +19 -10
- package/dist/authoring.js +4 -3
- package/dist/cli.js +13 -12
- package/dist/code-exec.d.ts +19 -0
- package/dist/code-exec.js +54 -5
- package/dist/decision-provider.d.ts +166 -0
- package/dist/decision-provider.js +238 -0
- package/dist/decision-receipts.d.ts +64 -3
- package/dist/decision-receipts.js +50 -8
- package/dist/dry-run.d.ts +31 -1
- package/dist/dry-run.js +122 -16
- package/dist/edit.d.ts +149 -0
- package/dist/edit.js +1415 -0
- package/dist/evidence.d.ts +19 -0
- package/dist/evidence.js +63 -0
- package/dist/graph.d.ts +91 -5
- package/dist/graph.js +212 -10
- package/dist/index.d.ts +17 -12
- package/dist/index.js +16 -10
- package/dist/inspection.d.ts +5 -0
- package/dist/inspection.js +14 -1
- package/dist/pattern-screen.d.ts +14 -0
- package/dist/pattern-screen.js +451 -0
- package/dist/predicates.d.ts +29 -0
- package/dist/predicates.js +62 -3
- package/dist/record.d.ts +4 -0
- package/dist/record.js +6 -0
- package/dist/recovery/binding.js +2 -1
- package/dist/recovery/call-key.d.ts +0 -4
- package/dist/recovery/call-key.js +0 -7
- package/dist/recovery/driver.d.ts +61 -24
- package/dist/recovery/driver.js +193 -68
- package/dist/recovery/frozen-snapshot.d.ts +33 -3
- package/dist/recovery/frozen-snapshot.js +28 -12
- package/dist/recovery/handoff-receipts.d.ts +0 -35
- package/dist/recovery/handoff-receipts.js +2 -44
- package/dist/recovery/index.d.ts +4 -8
- package/dist/recovery/index.js +4 -7
- package/dist/recovery/with-recovery.d.ts +9 -3
- package/dist/recovery/with-recovery.js +72 -15
- package/dist/submit-envelope.d.ts +9 -0
- package/dist/submit-envelope.js +44 -0
- package/dist/system-one.d.ts +21 -2
- package/dist/system-one.js +96 -18
- package/dist/testing/decision-provider.d.ts +32 -0
- package/dist/testing/decision-provider.js +183 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.js +2 -0
- package/dist/vocabulary.d.ts +11 -3
- package/dist/vocabulary.js +18 -8
- package/dist/workflow-shape.js +34 -7
- package/dist/workflow.d.ts +128 -19
- package/dist/workflow.js +772 -238
- package/dist/zod-json-contract.js +6 -8
- package/package.json +16 -4
- package/schema/workflow.schema.json +352 -1
- package/skills/author/SKILL.md +4 -1
- package/skills/author/references/jev-decisions.md +50 -5
- package/skills/author/references/language.md +17 -12
- package/dist/recovery/effect-failure.d.ts +0 -34
- package/dist/recovery/effect-failure.js +0 -62
- package/dist/recovery/handoff-block.d.ts +0 -36
- package/dist/recovery/handoff-block.js +0 -148
- package/dist/recovery/handoff-digest.d.ts +0 -58
- package/dist/recovery/handoff-digest.js +0 -195
- package/dist/recovery/handoff-files.d.ts +0 -54
- package/dist/recovery/handoff-files.js +0 -162
- package/dist/recovery/handoff-redact.d.ts +0 -12
- package/dist/recovery/handoff-redact.js +0 -44
- package/dist/recovery/handoff.d.ts +0 -44
- package/dist/recovery/handoff.js +0 -46
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { RecoveryError } from "./errors.js";
|
|
1
2
|
import { type PartialSlot, type Sha256, type StateDelta } from "./item-state.js";
|
|
3
|
+
export declare const failure: (code: string, message: string) => RecoveryError;
|
|
2
4
|
export declare const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
|
|
3
5
|
/** The keyed layout: what lies in a map item is kept in that item's record beside the state, and a state the driver
|
|
4
6
|
* references is kept once by its digest, so no record rewritten at a commit grows with a map's items. */
|
|
@@ -33,6 +35,7 @@ export type ItemRecord = {
|
|
|
33
35
|
routes: PathFrame["routes"];
|
|
34
36
|
inputs: PathFrame["inputs"];
|
|
35
37
|
steps: PathFrame["steps"];
|
|
38
|
+
decisions?: PathFrame["decisions"];
|
|
36
39
|
};
|
|
37
40
|
effects: string[];
|
|
38
41
|
clocks: Record<string, number>;
|
|
@@ -55,8 +58,6 @@ export type FrozenSnapshotV4 = Omit<FrozenSnapshot, "schema" | "pin"> & {
|
|
|
55
58
|
};
|
|
56
59
|
maps: Record<string, MapEntry>;
|
|
57
60
|
};
|
|
58
|
-
/** Two values a state holds under one key are the same value. A key an item copied from its base holds the base's own
|
|
59
|
-
* object, or one with the same JSON. */
|
|
60
61
|
/** A map item's state at `path`, rebuilt as the driver rebuilds it (`./item-state.ts`, which imports nothing): the
|
|
61
62
|
* `agentrun.states` value its `base` names, with the item's `set` and `unset` for that path applied, checked against
|
|
62
63
|
* that path's `sha256`. `item` is an `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256. When
|
|
@@ -93,15 +94,37 @@ export type QuestionReceipts = {
|
|
|
93
94
|
* is set in the commit that decides and cleared by the save after the host has written what it keeps of the
|
|
94
95
|
* answer: a resume that finds it set writes them, so a crash between the two never leaves the spend without
|
|
95
96
|
* its receipts. A host that keeps nothing commits null. */
|
|
97
|
+
/** `choice` is null and `refused` true for a refused answer, which took the route's unsure branch. */
|
|
96
98
|
export type RouteDecision = {
|
|
97
99
|
label: string;
|
|
98
100
|
branch: string;
|
|
99
|
-
choice: string;
|
|
101
|
+
choice: string | null;
|
|
100
102
|
unsure: boolean;
|
|
103
|
+
refused?: true;
|
|
101
104
|
request_sha256: string | null;
|
|
102
105
|
result: Record<string, unknown>;
|
|
103
106
|
receipts: QuestionReceipts | null;
|
|
104
107
|
};
|
|
108
|
+
/** A decision's request to the host's judge, as the kernel books a paid request: written and committed before the judge
|
|
109
|
+
* is asked (`requested`), with one outcome after. `answered` and `failed` are written by the process that asked;
|
|
110
|
+
* `interrupted` by a later process that found it still `requested`: the answer, if the provider gave one, was lost with
|
|
111
|
+
* the process, so the decision is never asked again and its cost is unknown (null, never 0). A `failed` request is
|
|
112
|
+
* asked again as its next attempt. */
|
|
113
|
+
export type DecisionRequest = {
|
|
114
|
+
record: "decision.request";
|
|
115
|
+
decision_id: string;
|
|
116
|
+
kind: string;
|
|
117
|
+
label: string;
|
|
118
|
+
/** The model the request named, when it named one. */
|
|
119
|
+
model: string | null;
|
|
120
|
+
/** The digest of what the judge was sent: the kind, the label, the state and the questions. */
|
|
121
|
+
request_sha256: string;
|
|
122
|
+
attempt: number;
|
|
123
|
+
status: "requested" | "answered" | "failed" | "interrupted";
|
|
124
|
+
/** The outcome's spend: absent while requested, null when unknown. */
|
|
125
|
+
cost_usd?: number | null;
|
|
126
|
+
};
|
|
127
|
+
export declare const DECISION_REQUEST = "decision.request";
|
|
105
128
|
/** What one document's run committed, by execution path. `done` is every committed path in commit
|
|
106
129
|
* order; `states` keeps the committed state of the paths a resume may still be answered from (a
|
|
107
130
|
* chain's frontier step, a finished map item or parallel branch whose structure has not committed, a
|
|
@@ -122,6 +145,8 @@ export type PathFrame = {
|
|
|
122
145
|
routes: Record<string, RouteDecision>;
|
|
123
146
|
inputs: Record<string, string>;
|
|
124
147
|
steps: Record<string, StepRecord>;
|
|
148
|
+
/** Each decision node's requests to the judge, by decision id. Absent in a frame written before decisions were kept. */
|
|
149
|
+
decisions?: Record<string, Record<string, DecisionRequest>>;
|
|
125
150
|
/** A map that ended on an item's failure: the finished items' results, keyed by the map's `as`, so
|
|
126
151
|
* the handoff carries the completed child work and a redispatch never loses it. */
|
|
127
152
|
partial?: {
|
|
@@ -153,6 +178,10 @@ export type FrozenSnapshot = {
|
|
|
153
178
|
unknownResponses?: Record<string, unknown>;
|
|
154
179
|
/** Spend by question nodes, which have no session of their own: metered per answer, carried with the frames. */
|
|
155
180
|
questionSpendUsd?: number;
|
|
181
|
+
/** How many question answers came back with no price, so their cost is not in `questionSpendUsd`. A run
|
|
182
|
+
* with any makes its spend read as incomplete, never as a bare total that omits them: an unknown cost is
|
|
183
|
+
* never zero. Carried with the frames and committed in the same save as the spend it stands beside. */
|
|
184
|
+
unpricedQuestionCount?: number;
|
|
156
185
|
/** The durable form of the escalation that ended the run; set once, reused on resume. */
|
|
157
186
|
escalation?: EscalationRow;
|
|
158
187
|
};
|
|
@@ -198,6 +227,7 @@ export type FrozenShape = {
|
|
|
198
227
|
resolves: (path: string) => boolean;
|
|
199
228
|
};
|
|
200
229
|
export declare const emptyPathFrame: () => PathFrame;
|
|
230
|
+
export declare const SHA256: RegExp;
|
|
201
231
|
/** Whether a value is an item's committed failure: three strings, and nothing else. */
|
|
202
232
|
export declare const isItemOutcome: (value: unknown) => value is ItemOutcome;
|
|
203
233
|
/** Refuses a saved snapshot the driver could not have produced for this run. */
|
|
@@ -4,14 +4,13 @@
|
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { RecoveryError } from "./errors.js";
|
|
6
6
|
import { itemState as rebuildItemState, partialResults as readPartialResults } from "./item-state.js";
|
|
7
|
-
|
|
7
|
+
import { isRecord } from "../record.js";
|
|
8
|
+
export const failure = (code, message) => new RecoveryError(message, code);
|
|
8
9
|
export const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
|
|
9
10
|
/** The keyed layout: what lies in a map item is kept in that item's record beside the state, and a state the driver
|
|
10
11
|
* references is kept once by its digest, so no record rewritten at a commit grows with a map's items. */
|
|
11
12
|
export const FROZEN_SNAPSHOT_SCHEMA_V4 = "agentrun.frozen_run.v4";
|
|
12
13
|
export { stateDelta, applyStateDelta, canonicalJson } from "./item-state.js";
|
|
13
|
-
/** Two values a state holds under one key are the same value. A key an item copied from its base holds the base's own
|
|
14
|
-
* object, or one with the same JSON. */
|
|
15
14
|
/** A map item's state at `path`, rebuilt as the driver rebuilds it (`./item-state.ts`, which imports nothing): the
|
|
16
15
|
* `agentrun.states` value its `base` names, with the item's `set` and `unset` for that path applied, checked against
|
|
17
16
|
* that path's `sha256`. `item` is an `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256. When
|
|
@@ -26,11 +25,11 @@ export function itemState(item, states, path, options = {}) {
|
|
|
26
25
|
export function partialResults(partial, states, options = {}) {
|
|
27
26
|
return readPartialResults(partial, states, { sha256: options.sha256 ?? ((text) => createHash("sha256").update(text).digest("hex")) });
|
|
28
27
|
}
|
|
28
|
+
export const DECISION_REQUEST = "decision.request";
|
|
29
29
|
export const emptyPathFrame = () => ({ input: null, done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {} });
|
|
30
|
-
const
|
|
31
|
-
const SHA256 = /^[a-f0-9]{64}$/;
|
|
30
|
+
export const SHA256 = /^[a-f0-9]{64}$/;
|
|
32
31
|
/** `value` as an object whose fields can be read, or null. */
|
|
33
|
-
const fields = (value) =>
|
|
32
|
+
const fields = (value) => isRecord(value) ? value : null;
|
|
34
33
|
const entriesOf = (value) => { const object = fields(value); return object ? Object.entries(object) : null; };
|
|
35
34
|
const isStepFailure = (value) => {
|
|
36
35
|
const at = fields(value);
|
|
@@ -42,6 +41,17 @@ export const isItemOutcome = (value) => {
|
|
|
42
41
|
return Boolean(at && Object.keys(at).length === 3 && typeof at.code === "string" && typeof at.label === "string" && typeof at.message === "string");
|
|
43
42
|
};
|
|
44
43
|
const nonNegativeInt = (value) => Number.isSafeInteger(value) && value >= 0;
|
|
44
|
+
/** Whether `value` is a decision request the driver wrote under `id`: requested with no spend, or ended with its spend or null. */
|
|
45
|
+
const isDecisionRequest = (id, value) => {
|
|
46
|
+
const at = fields(value);
|
|
47
|
+
if (!at || at.record !== DECISION_REQUEST || at.decision_id !== id || typeof at.kind !== "string" || typeof at.label !== "string")
|
|
48
|
+
return false;
|
|
49
|
+
if (!(at.model === null || typeof at.model === "string") || typeof at.request_sha256 !== "string" || !Number.isSafeInteger(at.attempt) || at.attempt < 1)
|
|
50
|
+
return false;
|
|
51
|
+
if (at.status === "requested")
|
|
52
|
+
return at.cost_usd === undefined;
|
|
53
|
+
return ["answered", "failed", "interrupted"].includes(String(at.status)) && (at.cost_usd === null || (typeof at.cost_usd === "number" && Number.isFinite(at.cost_usd) && at.cost_usd >= 0));
|
|
54
|
+
};
|
|
45
55
|
/** Whether a saved frame is one the driver could have written for its document. */
|
|
46
56
|
function validFrame(value, resolves) {
|
|
47
57
|
const frame = fields(value);
|
|
@@ -56,14 +66,19 @@ function validFrame(value, resolves) {
|
|
|
56
66
|
const [states, chains, loops, routes, inputs, steps] = [frame.states, frame.chains, frame.loops, frame.routes, frame.inputs, frame.steps].map(entriesOf);
|
|
57
67
|
const partial = frame.partial === undefined ? undefined : fields(frame.partial);
|
|
58
68
|
const failures = frame.failures === undefined ? [] : entriesOf(frame.failures);
|
|
59
|
-
|
|
69
|
+
const decisions = frame.decisions === undefined ? [] : entriesOf(frame.decisions);
|
|
70
|
+
return Boolean(decisions && decisions.every(([path, requests]) => resolves(path) && (entriesOf(requests)?.every(([id, request]) => isDecisionRequest(id, request)) ?? false))
|
|
71
|
+
&& states && states.every(([path, state]) => done.has(path) && isRecord(state))
|
|
60
72
|
&& failures && failures.every(([item, outcome]) => /\/items\/(?:0|[1-9]\d*)$/.test(item) && resolves(`${item}/body`) && isItemOutcome(outcome))
|
|
61
73
|
&& chains && chains.every(([, head]) => { const at = fields(head); return Boolean(at && nonNegativeInt(at.index) && typeof at.path === "string" && done.has(at.path)); })
|
|
62
74
|
&& loops && loops.every(([loop, count]) => resolves(loop) && nonNegativeInt(count))
|
|
63
75
|
&& routes && routes.every(([route, decision]) => {
|
|
64
76
|
const at = fields(decision);
|
|
65
77
|
const receipts = fields(at?.receipts);
|
|
66
|
-
return Boolean(at && resolves(route) && typeof at.label === "string" && typeof at.branch === "string"
|
|
78
|
+
return Boolean(at && resolves(route) && typeof at.label === "string" && typeof at.branch === "string"
|
|
79
|
+
// A refused route took its unsure branch and chose none: a named branch, a null choice, never "" for either.
|
|
80
|
+
&& (at.refused === undefined ? (typeof at.choice === "string" && typeof at.unsure === "boolean") || (at.choice === undefined && at.unsure === undefined) : at.refused === true && at.branch !== "" && at.choice === null && at.unsure === true)
|
|
81
|
+
&& isRecord(at.result) && (at.request_sha256 === null || typeof at.request_sha256 === "string")
|
|
67
82
|
&& (at.receipts === null || (receipts && typeof receipts.invocation === "string" && nonNegativeInt(receipts.request_bytes) && Number.isFinite(receipts.latency_ms))));
|
|
68
83
|
})
|
|
69
84
|
&& inputs && inputs.every(([path, digest]) => resolves(path) && !done.has(path) && typeof digest === "string" && SHA256.test(digest))
|
|
@@ -78,13 +93,14 @@ function validFrame(value, resolves) {
|
|
|
78
93
|
}
|
|
79
94
|
/** Refuses a saved snapshot the driver could not have produced for this run. */
|
|
80
95
|
export function validateFrozenSnapshot(saved, shape) {
|
|
81
|
-
if (!
|
|
96
|
+
if (!saved || typeof saved !== "object" || Array.isArray(saved) || saved.schema !== FROZEN_SNAPSHOT_SCHEMA || !Number.isFinite(saved.startedAt)
|
|
82
97
|
|| (saved.questionSpendUsd !== undefined && !(Number.isFinite(saved.questionSpendUsd) && saved.questionSpendUsd >= 0))
|
|
98
|
+
|| (saved.unpricedQuestionCount !== undefined && !nonNegativeInt(saved.unpricedQuestionCount))
|
|
83
99
|
|| !["running", "paused", "cancelled"].includes(saved.status)
|
|
84
|
-
|| !
|
|
85
|
-
|| !
|
|
100
|
+
|| !isRecord(saved.clocks) || !Object.values(saved.clocks).every(Number.isFinite)
|
|
101
|
+
|| !isRecord(saved.files) || !Object.values(saved.files).every(value => typeof value === "string" && SHA256.test(value))
|
|
86
102
|
|| !validFrame(saved.pin, shape.resolves)
|
|
87
|
-
|| (saved.escalation !== undefined && (!
|
|
103
|
+
|| (saved.escalation !== undefined && (!isRecord(saved.escalation) || typeof saved.escalation.tail !== "string" || typeof saved.escalation.kind !== "string" || !Number.isSafeInteger(saved.escalation.revision)))
|
|
88
104
|
// A checkpoint that holds a second document's frame is refused: the driver runs one document.
|
|
89
105
|
|| saved.adaptation !== undefined) {
|
|
90
106
|
throw failure("FROZEN_CHECKPOINT_INVALID", "Invalid frozen recovery checkpoint");
|
|
@@ -1,38 +1,3 @@
|
|
|
1
|
-
import type { RecoveryEffect, RecoveryIntent } from "./store.js";
|
|
2
|
-
/** A completed tool effect a continuation may answer an exact repeat from: the external call it paid for, and its value. */
|
|
3
|
-
export type InheritedReceipt = {
|
|
4
|
-
id: string;
|
|
5
|
-
name: string;
|
|
6
|
-
tool: string;
|
|
7
|
-
argsHash: string;
|
|
8
|
-
result: unknown;
|
|
9
|
-
session: string | null;
|
|
10
|
-
};
|
|
11
|
-
/** An effect whose outcome is unknown: its call is never dispatched again. `intent` is the external call it was admitted
|
|
12
|
-
* for, when its journal recorded one. */
|
|
13
|
-
export type InheritedUnknown = {
|
|
14
|
-
id: string;
|
|
15
|
-
name: string;
|
|
16
|
-
argsHash: string;
|
|
17
|
-
session: string | null;
|
|
18
|
-
intent?: RecoveryIntent;
|
|
19
|
-
};
|
|
20
|
-
/** A tool value that is itself a returned failure: an error envelope (`ok: false`, `isError: true`, `outcome: "error"`) as
|
|
21
|
-
* an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
|
|
22
|
-
* never prose. */
|
|
23
|
-
export declare function returnedFailure(value: unknown): boolean;
|
|
24
|
-
/** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
|
|
25
|
-
* effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
|
|
26
|
-
* failure. */
|
|
27
|
-
export declare function inheritableReceipts(effects: readonly RecoveryEffect[]): InheritedReceipt[];
|
|
28
|
-
/** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
|
|
29
|
-
* hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
|
|
30
|
-
* continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
|
|
31
|
-
* already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
|
|
32
|
-
* by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
|
|
33
|
-
* hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
|
|
34
|
-
* has none, and is matched by name and hash only. */
|
|
35
|
-
export declare function inheritableUnknowns(effects: readonly RecoveryEffect[]): InheritedUnknown[];
|
|
36
1
|
/** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
|
|
37
2
|
* wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
|
|
38
3
|
* The same key is computed for an effect from its receipt's intent. */
|
|
@@ -1,53 +1,11 @@
|
|
|
1
1
|
import { canonicalHash } from "./canonical-hash.js";
|
|
2
|
-
|
|
3
|
-
* an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
|
|
4
|
-
* never prose. */
|
|
5
|
-
export function returnedFailure(value) {
|
|
6
|
-
const failed = (parsed) => Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed) && (parsed.ok === false || parsed.isError === true || parsed.outcome === "error"));
|
|
7
|
-
if (typeof value !== "string")
|
|
8
|
-
return failed(value);
|
|
9
|
-
// The envelope may be the whole text (pretty-printed or not) or one line of it with guidance appended; each
|
|
10
|
-
// candidate is parsed structurally, never matched as prose.
|
|
11
|
-
for (const candidate of [value.trim(), ...value.split("\n").map((line) => line.trim())]) {
|
|
12
|
-
if (!candidate.startsWith("{"))
|
|
13
|
-
continue;
|
|
14
|
-
try {
|
|
15
|
-
if (failed(JSON.parse(candidate)))
|
|
16
|
-
return true;
|
|
17
|
-
}
|
|
18
|
-
catch { /* not this candidate */ }
|
|
19
|
-
}
|
|
20
|
-
return false;
|
|
21
|
-
}
|
|
22
|
-
/** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
|
|
23
|
-
* effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
|
|
24
|
-
* failure. */
|
|
25
|
-
export function inheritableReceipts(effects) {
|
|
26
|
-
return effects.filter((e) => e.status === "completed" && e.result && typeof e.result === "object" && e.result.intent && typeof e.result.intent.tool === "string" && !returnedFailure(e.result.value))
|
|
27
|
-
.map((e) => {
|
|
28
|
-
const receipt = e.result;
|
|
29
|
-
// Keyed as a continuation's own call is: a node that reached the gateway through the fetch wrapper paid for the tool the wrapper names.
|
|
30
|
-
const { tool, argsHash } = gatewayIntentOf(receipt.intent.tool, receipt.intent.args ?? {});
|
|
31
|
-
return { id: e.id, name: e.name, tool, argsHash, result: receipt.value, session: e.session };
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
/** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
|
|
35
|
-
* hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
|
|
36
|
-
* continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
|
|
37
|
-
* already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
|
|
38
|
-
* by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
|
|
39
|
-
* hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
|
|
40
|
-
* has none, and is matched by name and hash only. */
|
|
41
|
-
export function inheritableUnknowns(effects) {
|
|
42
|
-
return effects.filter((e) => e.status === "unknown").map((e) => ({ id: e.id, name: e.name, argsHash: e.argsHash, session: e.session,
|
|
43
|
-
...(e.intent ? { intent: { tool: e.intent.tool, argsHash: e.intent.argsHash } } : {}) }));
|
|
44
|
-
}
|
|
2
|
+
import { isRecord } from "../record.js";
|
|
45
3
|
/** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
|
|
46
4
|
* wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
|
|
47
5
|
* The same key is computed for an effect from its receipt's intent. */
|
|
48
6
|
export function gatewayIntentOf(name, args) {
|
|
49
7
|
const a = args;
|
|
50
|
-
if (name === "fetch" && a && typeof a === "object" && typeof a.tool === "string" &&
|
|
8
|
+
if (name === "fetch" && a && typeof a === "object" && typeof a.tool === "string" && isRecord(a.args))
|
|
51
9
|
return { tool: a.tool, argsHash: canonicalHash(a.args) };
|
|
52
10
|
return { tool: name, argsHash: canonicalHash(args ?? {}) };
|
|
53
11
|
}
|
package/dist/recovery/index.d.ts
CHANGED
|
@@ -1,18 +1,14 @@
|
|
|
1
1
|
export type { RecoveryBinding, RecoveryEffect, RecoveryIntent, RecoveryItem, RecoveryJournal, RecoveryNote, RecoveryParts, RecoveryStore } from "./store.js";
|
|
2
2
|
export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles, type RecoveryEffectParams, type RecoveryFiles, type RecoveryOptions, type RecoveryStop } from "./driver.js";
|
|
3
|
-
export {
|
|
3
|
+
export { DECISION_REFUSED } from "../decision-receipts.js";
|
|
4
|
+
export { withRecovery, DECISION_INTERRUPTED, type RecoveryAdapters, type RecoveryDriver, type RecoveryNodeParams, type RecoveryStep, type WithRecoveryOptions } from "./with-recovery.js";
|
|
4
5
|
export { memoryStore } from "./memory-store.js";
|
|
5
6
|
export { fileStore } from "./file-store.js";
|
|
6
7
|
export { openJournal, type JournalBackend, type JournalRecord } from "./journal.js";
|
|
7
8
|
export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
|
|
8
9
|
export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
|
|
9
10
|
export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
|
|
10
|
-
export { callKey,
|
|
11
|
-
export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults,
|
|
11
|
+
export { callKey, CALL_KEY_BYTES } from "./call-key.js";
|
|
12
|
+
export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, frozenStepId, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type DecisionRequest, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
|
|
12
13
|
export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
|
|
13
|
-
export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
|
|
14
14
|
export { effectRetryClass, transportFactOf, type TransportFact } from "./transport-facts.js";
|
|
15
|
-
export { buildHandoff, handoffFirstTurn, type Handoff, type HandoffOptions } from "./handoff.js";
|
|
16
|
-
export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
|
|
17
|
-
export { inputProvenance, judgedRecords, type InputProvenance } from "./handoff-files.js";
|
|
18
|
-
export { type InheritedSession, type InheritedEffect, type TranscriptMessage } from "./handoff-digest.js";
|
package/dist/recovery/index.js
CHANGED
|
@@ -1,16 +1,13 @@
|
|
|
1
1
|
export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles } from "./driver.js";
|
|
2
|
-
export {
|
|
2
|
+
export { DECISION_REFUSED } from "../decision-receipts.js";
|
|
3
|
+
export { withRecovery, DECISION_INTERRUPTED } from "./with-recovery.js";
|
|
3
4
|
export { memoryStore } from "./memory-store.js";
|
|
4
5
|
export { fileStore } from "./file-store.js";
|
|
5
6
|
export { openJournal } from "./journal.js";
|
|
6
7
|
export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
|
|
7
8
|
export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
|
|
8
9
|
export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
|
|
9
|
-
export { callKey,
|
|
10
|
-
export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults,
|
|
10
|
+
export { callKey, CALL_KEY_BYTES } from "./call-key.js";
|
|
11
|
+
export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, frozenStepId, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
|
|
11
12
|
export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
|
|
12
|
-
export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
|
|
13
13
|
export { effectRetryClass, transportFactOf } from "./transport-facts.js";
|
|
14
|
-
export { buildHandoff, handoffFirstTurn } from "./handoff.js";
|
|
15
|
-
export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure } from "./handoff-receipts.js";
|
|
16
|
-
export { inputProvenance, judgedRecords } from "./handoff-files.js";
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type WorkflowDeps } from "../workflow.js";
|
|
2
2
|
import type { openRecovery, RecoveryEffectParams } from "./driver.js";
|
|
3
|
+
import { DECISION_INTERRUPTED } from "../decision-receipts.js";
|
|
4
|
+
export { DECISION_INTERRUPTED };
|
|
3
5
|
/** A recovery driver, as `openRecovery` returns it. */
|
|
4
6
|
export type RecoveryDriver = Awaited<ReturnType<typeof openRecovery>>;
|
|
5
7
|
/** The attempt of an LLM step a node runner is asked to run, as the driver admitted it. One attempt is one session:
|
|
@@ -32,8 +34,12 @@ export type WithRecoveryOptions = {
|
|
|
32
34
|
* things they have no slot for are applied to the host's adapters here:
|
|
33
35
|
* - `runEffect`: each effect is admitted before it is dispatched, a completed one is answered from its receipt, and
|
|
34
36
|
* one admitted and never completed is refused;
|
|
35
|
-
* - `runJudge`:
|
|
36
|
-
*
|
|
37
|
+
* - `runJudge`: each request is committed (`decision.request`) before the judge is asked, and ends with one outcome:
|
|
38
|
+
* answered, or failed in its own process (asked again as its next attempt). A later open that finds it asked and
|
|
39
|
+
* never answered (the process died, or a cancel cut the call) books it once at an unknown cost and ends the run
|
|
40
|
+
* escalated (`decision_interrupted`) instead of asking again. A route's answer is committed as its decision before
|
|
41
|
+
* any branch step runs, and a resume inside the branch follows it without asking again; every answer's spend is
|
|
42
|
+
* committed with the driver's state;
|
|
37
43
|
* - `runNode`: an LLM step's record is committed before the step runs, with two attempts, each handed to the
|
|
38
44
|
* runner as its `step`. A failed attempt is followed at once by the second, unless the runner marked the
|
|
39
45
|
* failure final; a step that spent both is refused at every later open. A process that dies inside a step spends
|
|
@@ -1,10 +1,19 @@
|
|
|
1
|
+
import { chargedCost, DecisionProviderError } from "../decision-provider.js";
|
|
1
2
|
import { validateAnswers } from "../system-one.js";
|
|
3
|
+
import { EscalationSignal } from "../workflow.js";
|
|
4
|
+
import { canonicalHash } from "./canonical-hash.js";
|
|
5
|
+
import { DECISION_INTERRUPTED } from "../decision-receipts.js";
|
|
6
|
+
export { DECISION_INTERRUPTED };
|
|
2
7
|
/** The dependencies to run a workflow with under `driver`. The interpreter's `recovery` hooks cover nodes; three
|
|
3
8
|
* things they have no slot for are applied to the host's adapters here:
|
|
4
9
|
* - `runEffect`: each effect is admitted before it is dispatched, a completed one is answered from its receipt, and
|
|
5
10
|
* one admitted and never completed is refused;
|
|
6
|
-
* - `runJudge`:
|
|
7
|
-
*
|
|
11
|
+
* - `runJudge`: each request is committed (`decision.request`) before the judge is asked, and ends with one outcome:
|
|
12
|
+
* answered, or failed in its own process (asked again as its next attempt). A later open that finds it asked and
|
|
13
|
+
* never answered (the process died, or a cancel cut the call) books it once at an unknown cost and ends the run
|
|
14
|
+
* escalated (`decision_interrupted`) instead of asking again. A route's answer is committed as its decision before
|
|
15
|
+
* any branch step runs, and a resume inside the branch follows it without asking again; every answer's spend is
|
|
16
|
+
* committed with the driver's state;
|
|
8
17
|
* - `runNode`: an LLM step's record is committed before the step runs, with two attempts, each handed to the
|
|
9
18
|
* runner as its `step`. A failed attempt is followed at once by the second, unless the runner marked the
|
|
10
19
|
* failure final; a step that spent both is refused at every later open. A process that dies inside a step spends
|
|
@@ -23,22 +32,70 @@ export function withRecovery(driver, deps, options = {}) {
|
|
|
23
32
|
const decided = params.kind === "route" ? driver.routeDecision(params.executionPath) : undefined;
|
|
24
33
|
if (decided)
|
|
25
34
|
return decided.result;
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
35
|
+
await driver.seam();
|
|
36
|
+
const decisionId = params.decisionId ?? canonicalHash(["decision-request", params.executionPath, params.kind, params.questions, params.state]);
|
|
37
|
+
const open = driver.admitDecision(params.executionPath, { decision_id: decisionId, kind: params.kind, label: params.label, model: params.model ?? null,
|
|
38
|
+
request_sha256: canonicalHash({ kind: params.kind, label: params.label, state: params.state, questions: params.questions }) });
|
|
39
|
+
if (open) {
|
|
40
|
+
// An earlier process asked and its answer never reached a receipt: never asked again, booked once at an unknown
|
|
41
|
+
// cost, and the run goes to review. The unknown cost is counted with the outcome in one commit, the way the
|
|
42
|
+
// answered and failed paths commit theirs, so the run's spend reads incomplete and never omits it.
|
|
43
|
+
if (open.status === "requested")
|
|
44
|
+
driver.decisionEnded(params.executionPath, decisionId, "interrupted", null, () => driver.recordQuestionSpend(null));
|
|
45
|
+
await driver.flush();
|
|
46
|
+
throw new EscalationSignal({ kind: DECISION_INTERRUPTED, stage: "decision", executionPath: params.executionPath, label: params.label, state: driver.lastState(),
|
|
47
|
+
summary: `The decision "${params.label}" was asked by an earlier process and its answer never reached a receipt; it is not asked again.` });
|
|
48
|
+
}
|
|
30
49
|
try {
|
|
31
|
-
|
|
50
|
+
// The request is durable before the judge is asked.
|
|
51
|
+
await driver.flush();
|
|
52
|
+
let result;
|
|
53
|
+
try {
|
|
54
|
+
result = await runJudge(params);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
// A request sent whose outcome was lost may have been answered and billed: it is interrupted, never asked again,
|
|
58
|
+
// and its estimate (or an unknown cost, which makes the spend read incomplete) is booked with that outcome.
|
|
59
|
+
const charge = chargedCost(error);
|
|
60
|
+
if (error instanceof DecisionProviderError && error.code === "outcome_unknown") {
|
|
61
|
+
driver.decisionEnded(params.executionPath, decisionId, "interrupted", charge ?? null, () => driver.recordQuestionSpend(charge ?? null));
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
// An answer rejected after it was paid for failed, and its cost (or an unknown one) is booked with that outcome:
|
|
65
|
+
// the next process asks again.
|
|
66
|
+
if (charge !== undefined) {
|
|
67
|
+
driver.decisionEnded(params.executionPath, decisionId, "failed", charge, () => driver.recordQuestionSpend(charge));
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
// A cut call (a cancel, the run's failure) has no outcome: a later open finds it asked and unanswered. A call
|
|
71
|
+
// that ended on its own failed, and the next process asks again; so does one that never left (`unsent`, a host's
|
|
72
|
+
// refusal before it sent anything), whatever stopped the run meanwhile: nothing went out to answer.
|
|
73
|
+
const unsent = error instanceof DecisionProviderError && error.unsent === true;
|
|
74
|
+
if (unsent || (!driver.signal.aborted && !params.signal?.aborted))
|
|
75
|
+
driver.decisionEnded(params.executionPath, decisionId, "failed", null);
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
const cost = typeof result.cost_usd === "number" && Number.isFinite(result.cost_usd) ? result.cost_usd : null;
|
|
79
|
+
// An answer the interpreter would refuse is spent at its price and is never a decision: the question is
|
|
80
|
+
// asked again by the next process.
|
|
81
|
+
try {
|
|
82
|
+
validateAnswers(params.questions, result.answers);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
driver.decisionEnded(params.executionPath, decisionId, "failed", cost, () => driver.recordQuestionSpend(cost));
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
// The outcome, the spend and a route's decision are one commit.
|
|
89
|
+
driver.decisionEnded(params.executionPath, decisionId, "answered", cost, () => driver.recordQuestionSpend(cost, params.kind === "route"
|
|
90
|
+
? { executionPath: params.executionPath, label: params.label, result: result, receipts: null } : undefined));
|
|
91
|
+
// The decision is durable before the interpreter acts on the answer, and a stop taken meanwhile ends the run here.
|
|
92
|
+
await driver.flush();
|
|
93
|
+
driver.checkStop();
|
|
94
|
+
return result;
|
|
32
95
|
}
|
|
33
|
-
|
|
34
|
-
driver.
|
|
35
|
-
throw error;
|
|
96
|
+
finally {
|
|
97
|
+
driver.decisionSettled();
|
|
36
98
|
}
|
|
37
|
-
driver.recordQuestionSpend(cost, params.kind === "route" ? { executionPath: params.executionPath, label: params.label, result: result, receipts: null } : undefined);
|
|
38
|
-
// The decision is durable before the interpreter acts on the answer, and a stop taken meanwhile ends the run here.
|
|
39
|
-
await driver.flush();
|
|
40
|
-
driver.checkStop();
|
|
41
|
-
return result;
|
|
42
99
|
}),
|
|
43
100
|
runNode: runNode && (async (params) => {
|
|
44
101
|
const admit = () => driver.stepSession(params.executionPath, params.label, { attemptsAllowed: 2 });
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
|
|
2
|
+
* `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
|
|
3
|
+
* is not an object schema), and embedding it moves the document root its local pointers resolve
|
|
4
|
+
* against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
|
|
5
|
+
* that sets its own `$id` is a separate resource: its local references do not move. Every runner that
|
|
6
|
+
* delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
|
|
7
|
+
* every harness. A keyword the host alone reads (`criteria`, any `x-` one) is left out of every schema in it, never a property or
|
|
8
|
+
* definition of that name; the submission is still checked against the node's schema as written. */
|
|
9
|
+
export declare function submitParameters(schema: unknown): Record<string, unknown>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { isRecord } from "./record.js";
|
|
2
|
+
// Keywords that may sit on a schema but are not JSON Schema, read by the host alone: the DSL's `criteria` (System One's
|
|
3
|
+
// question keyword) and every `x-` annotation (AgentRun's `x-carried`, the fields of an agent's answer its next run reads
|
|
4
|
+
// back, which a learned workflow's output node can copy from the agent's output schema). Google's OpenAPI-subset
|
|
5
|
+
// `parameters` refuses a field it does not know. The model never sees them.
|
|
6
|
+
const hostOnlyKeyword = (key) => key === "criteria" || key.startsWith("x-");
|
|
7
|
+
/** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
|
|
8
|
+
* `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
|
|
9
|
+
* is not an object schema), and embedding it moves the document root its local pointers resolve
|
|
10
|
+
* against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
|
|
11
|
+
* that sets its own `$id` is a separate resource: its local references do not move. Every runner that
|
|
12
|
+
* delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
|
|
13
|
+
* every harness. A keyword the host alone reads (`criteria`, any `x-` one) is left out of every schema in it, never a property or
|
|
14
|
+
* definition of that name; the submission is still checked against the node's schema as written. */
|
|
15
|
+
export function submitParameters(schema) {
|
|
16
|
+
const maps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
|
|
17
|
+
const singles = new Set(["additionalProperties", "unevaluatedProperties", "propertyNames", "items", "additionalItems", "contains", "unevaluatedItems", "not", "if", "then", "else", "contentSchema"]);
|
|
18
|
+
const arrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
|
|
19
|
+
const relocate = (node, resourceScope = false) => {
|
|
20
|
+
if (!isRecord(node))
|
|
21
|
+
return structuredClone(node);
|
|
22
|
+
// $id establishes a separate schema resource: its local references do not move.
|
|
23
|
+
resourceScope ||= typeof node.$id === "string" && node.$id !== "";
|
|
24
|
+
const child = (value) => relocate(value, resourceScope);
|
|
25
|
+
return Object.fromEntries(Object.entries(node).filter(([key]) => !hostOnlyKeyword(key)).map(([key, value]) => {
|
|
26
|
+
if (!resourceScope && key === "$ref" && typeof value === "string" && (value === "#" || value.startsWith("#/"))) {
|
|
27
|
+
return [key, `#/properties/value${value.slice(1)}`];
|
|
28
|
+
}
|
|
29
|
+
if (maps.has(key) && isRecord(value)) {
|
|
30
|
+
return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, child(value)]))];
|
|
31
|
+
}
|
|
32
|
+
if (arrays.has(key) && Array.isArray(value))
|
|
33
|
+
return [key, value.map(child)];
|
|
34
|
+
if (singles.has(key))
|
|
35
|
+
return [key, Array.isArray(value) ? value.map(child) : child(value)];
|
|
36
|
+
if (key === "dependencies" && isRecord(value)) {
|
|
37
|
+
return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, Array.isArray(value) ? structuredClone(value) : child(value)]))];
|
|
38
|
+
}
|
|
39
|
+
// Annotations and literal values are data, not schemas (including a literal $ref).
|
|
40
|
+
return [key, structuredClone(value)];
|
|
41
|
+
}));
|
|
42
|
+
};
|
|
43
|
+
return { type: "object", properties: { value: relocate(schema) }, required: ["value"], additionalProperties: false };
|
|
44
|
+
}
|
package/dist/system-one.d.ts
CHANGED
|
@@ -44,6 +44,10 @@ export type SystemOneAnswer = {
|
|
|
44
44
|
type: "box";
|
|
45
45
|
box: SystemOneBox;
|
|
46
46
|
confidence: number | null;
|
|
47
|
+
}
|
|
48
|
+
/** The provider declined to answer this question. It is never decoded as a value. */
|
|
49
|
+
| {
|
|
50
|
+
type: "refusal";
|
|
47
51
|
};
|
|
48
52
|
export type SystemOneResult = {
|
|
49
53
|
answers: Record<string, SystemOneAnswer>;
|
|
@@ -61,7 +65,6 @@ export declare const SYSTEM_ONE_LIMITS: {
|
|
|
61
65
|
readonly minScoreLevels: 2;
|
|
62
66
|
readonly maxScoreLevels: 10;
|
|
63
67
|
};
|
|
64
|
-
export declare const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
|
|
65
68
|
export type CompiledQuestions = Record<string, SystemOneQuestion>;
|
|
66
69
|
export declare function compileQuestions(schema: Record<string, unknown>, definitions?: Record<string, unknown>): {
|
|
67
70
|
ok: true;
|
|
@@ -81,7 +84,7 @@ export type AnswersSidecar = {
|
|
|
81
84
|
export declare function answersSidecar(answers: Record<string, SystemOneAnswer>): AnswersSidecar;
|
|
82
85
|
export declare function synthesizeAnswers(questions: Record<string, SystemOneQuestion>): Record<string, SystemOneAnswer>;
|
|
83
86
|
export type SystemOneRetryClass = "http_429" | "http_5xx" | "connection" | "timeout";
|
|
84
|
-
declare const responseReasons: readonly ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability", "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range"];
|
|
87
|
+
declare const responseReasons: readonly ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability", "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range", "refusal"];
|
|
85
88
|
export type SystemOneResponseReason = typeof responseReasons[number];
|
|
86
89
|
export declare function isSystemOneResponseReason(value: unknown): value is SystemOneResponseReason;
|
|
87
90
|
export declare class SystemOneError extends Error {
|
|
@@ -91,4 +94,20 @@ export declare class SystemOneError extends Error {
|
|
|
91
94
|
constructor(message: string, retryClass: SystemOneRetryClass | null, status?: number | undefined, responseReason?: SystemOneResponseReason);
|
|
92
95
|
}
|
|
93
96
|
export declare function validateAnswers(questions: Record<string, SystemOneQuestion>, answers: unknown): asserts answers is Record<string, SystemOneAnswer>;
|
|
97
|
+
/** The questions whose answer is a refusal, in answer order. */
|
|
98
|
+
export declare function refusedQuestions(answers: Record<string, unknown>): string[];
|
|
99
|
+
/** The confidence TypeSafe documents for Jev (docs.typesafe.ai/confidence), computed from an answer's probabilities: for a
|
|
100
|
+
* choice of n options, (p - 1/n) / (1 - 1/n) for the chosen option's p, floored at 0; for a score of n levels, 1 minus
|
|
101
|
+
* the probability-weighted distance from the most likely level (the lowest, on a tie) over that distance for an even
|
|
102
|
+
* spread, floored at 0. Null when the probabilities are missing or are not a distribution over the answer's options. */
|
|
103
|
+
export declare function deriveConfidence(answer: unknown): number | null;
|
|
104
|
+
/** Where an answer's confidence came from: the provider's response, or derived from its probabilities. */
|
|
105
|
+
export type ConfidenceSource = "provider" | "derived";
|
|
106
|
+
/** The answers with every choice and score carrying a confidence: the provider's own when it gave one in [0, 1], else
|
|
107
|
+
* one derived from the probabilities (deriveConfidence), else 0, which validation then refuses with the probabilities
|
|
108
|
+
* that left nothing to derive from. `confidence_source` names each choice and score answer's source. */
|
|
109
|
+
export declare function completeConfidence(questions: Record<string, SystemOneQuestion>, answers: Record<string, unknown>): {
|
|
110
|
+
answers: Record<string, unknown>;
|
|
111
|
+
confidence_source: Record<string, ConfidenceSource>;
|
|
112
|
+
};
|
|
94
113
|
export {};
|