@parcha/agentrun-dsl 0.1.0-beta.12 → 0.1.0-beta.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/author.d.ts +9 -2
- package/dist/author.js +6 -3
- package/dist/decision-receipts.d.ts +98 -0
- package/dist/decision-receipts.js +51 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +2 -1
- package/dist/recovery/binding.d.ts +10 -0
- package/dist/recovery/binding.js +43 -0
- package/dist/recovery/call-key.d.ts +13 -0
- package/dist/recovery/call-key.js +24 -0
- package/dist/recovery/canonical-hash.d.ts +7 -0
- package/dist/recovery/canonical-hash.js +22 -0
- package/dist/recovery/driver.d.ts +186 -0
- package/dist/recovery/driver.js +777 -0
- package/dist/recovery/effect-failure.d.ts +34 -0
- package/dist/recovery/effect-failure.js +62 -0
- package/dist/recovery/errors.d.ts +31 -0
- package/dist/recovery/errors.js +51 -0
- package/dist/recovery/execution-path.d.ts +45 -0
- package/dist/recovery/execution-path.js +153 -0
- package/dist/recovery/file-store.d.ts +7 -0
- package/dist/recovery/file-store.js +131 -0
- package/dist/recovery/frozen-snapshot.d.ts +149 -0
- package/dist/recovery/frozen-snapshot.js +136 -0
- package/dist/recovery/handoff-block.d.ts +36 -0
- package/dist/recovery/handoff-block.js +148 -0
- package/dist/recovery/handoff-digest.d.ts +58 -0
- package/dist/recovery/handoff-digest.js +195 -0
- package/dist/recovery/handoff-files.d.ts +54 -0
- package/dist/recovery/handoff-files.js +162 -0
- package/dist/recovery/handoff-receipts.d.ts +42 -0
- package/dist/recovery/handoff-receipts.js +53 -0
- package/dist/recovery/handoff-redact.d.ts +12 -0
- package/dist/recovery/handoff-redact.js +44 -0
- package/dist/recovery/handoff.d.ts +44 -0
- package/dist/recovery/handoff.js +46 -0
- package/dist/recovery/index.d.ts +18 -0
- package/dist/recovery/index.js +16 -0
- package/dist/recovery/journal.d.ts +25 -0
- package/dist/recovery/journal.js +127 -0
- package/dist/recovery/memory-store.d.ts +4 -0
- package/dist/recovery/memory-store.js +20 -0
- package/dist/recovery/store.d.ts +81 -0
- package/dist/recovery/store.js +6 -0
- package/dist/recovery/testing/conformance.d.ts +4 -0
- package/dist/recovery/testing/conformance.js +213 -0
- package/dist/recovery/testing/crash-points.d.ts +18 -0
- package/dist/recovery/testing/crash-points.js +43 -0
- package/dist/recovery/testing/crash-sweep.d.ts +65 -0
- package/dist/recovery/testing/crash-sweep.js +146 -0
- package/dist/recovery/testing/index.d.ts +3 -0
- package/dist/recovery/testing/index.js +4 -0
- package/dist/recovery/testing/preload.d.ts +1 -0
- package/dist/recovery/testing/preload.js +3 -0
- package/dist/recovery/transport-facts.d.ts +23 -0
- package/dist/recovery/transport-facts.js +46 -0
- package/dist/recovery/with-recovery.d.ts +44 -0
- package/dist/recovery/with-recovery.js +84 -0
- package/dist/workflow.d.ts +28 -0
- package/dist/workflow.js +247 -87
- package/package.json +9 -1
package/dist/author.d.ts
CHANGED
|
@@ -47,9 +47,16 @@ export interface CandidatePolicyOptions {
|
|
|
47
47
|
}
|
|
48
48
|
/** Author policy over a candidate, checked before validation so a refused candidate never evaluates code. */
|
|
49
49
|
export declare function candidatePolicyErrors(candidate: unknown, options: CandidatePolicyOptions): string[];
|
|
50
|
+
export interface HostOutputTypeOptions {
|
|
51
|
+
/** The host's name for an authored artifact type: an authored spelling (another case, dashes for underscores,
|
|
52
|
+
* an alias) mapped to one of `host.outputTypes`, or null when it names none; its answer decides, so null leaves even
|
|
53
|
+
* an exact name as authored. Absent, a type is matched exactly. */
|
|
54
|
+
normalizeType?: (type: string) => string | null | undefined;
|
|
55
|
+
}
|
|
50
56
|
/** The interpreter's view of a workflow written in a host's vocabulary: an artifact of a declared prose output
|
|
51
|
-
* type becomes the report writer it is. Validate and run this view; retain and digest the authored bytes.
|
|
52
|
-
|
|
57
|
+
* type becomes the report writer it is. Validate and run this view; retain and digest the authored bytes. With
|
|
58
|
+
* `normalizeType`, an artifact's type is first mapped to the host's name for it. */
|
|
59
|
+
export declare function applyHostOutputTypes(candidate: Workflow, host: AuthorHostAddendum | undefined, options?: HostOutputTypeOptions): Workflow;
|
|
53
60
|
export interface AuthorWorkflowOptions {
|
|
54
61
|
request: string;
|
|
55
62
|
outputDir: string;
|
package/dist/author.js
CHANGED
|
@@ -213,15 +213,18 @@ export function candidatePolicyErrors(candidate, options) {
|
|
|
213
213
|
return errors;
|
|
214
214
|
}
|
|
215
215
|
/** The interpreter's view of a workflow written in a host's vocabulary: an artifact of a declared prose output
|
|
216
|
-
* type becomes the report writer it is. Validate and run this view; retain and digest the authored bytes.
|
|
217
|
-
|
|
216
|
+
* type becomes the report writer it is. Validate and run this view; retain and digest the authored bytes. With
|
|
217
|
+
* `normalizeType`, an artifact's type is first mapped to the host's name for it. */
|
|
218
|
+
export function applyHostOutputTypes(candidate, host, options = {}) {
|
|
218
219
|
const prose = new Set(Object.entries(host?.outputTypes ?? {}).filter(([, spec]) => spec.kind === "prose").map(([type]) => type));
|
|
219
220
|
if (!prose.size)
|
|
220
221
|
return candidate;
|
|
222
|
+
// With a normaliser the host's answer is the name: null or undefined matches no type, the exact one included.
|
|
223
|
+
const nameOf = (type) => typeof type === "string" && options.normalizeType ? options.normalizeType(type) : type;
|
|
221
224
|
const visit = (node) => {
|
|
222
225
|
if (!node || typeof node !== "object")
|
|
223
226
|
return node;
|
|
224
|
-
if (node.node === "artifact" && prose.has(node.type))
|
|
227
|
+
if (node.node === "artifact" && prose.has(nameOf(node.type)))
|
|
225
228
|
return { ...node, type: "report" };
|
|
226
229
|
if (node.node === "chain")
|
|
227
230
|
return { ...node, steps: (node.steps || []).map(visit) };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
|
|
2
|
+
export declare const DECISION_RECEIPT_VERSION = 1;
|
|
3
|
+
/** The typed questions the interpreter asks: the five question nodes and predicates, and a generative
|
|
4
|
+
* node's `verify` clause. */
|
|
5
|
+
export type DecisionKind = "judge" | "pick" | "sift" | "route" | "ask" | "verify";
|
|
6
|
+
/** How answers become the action, with every threshold applied. */
|
|
7
|
+
export type DecisionRule =
|
|
8
|
+
/** judge: each question's decoded value (a choice, a yes/no at 0.5, a rounded score). */
|
|
9
|
+
{
|
|
10
|
+
kind: "judge";
|
|
11
|
+
}
|
|
12
|
+
/** pick: the chosen option names an item by its position, or none. */
|
|
13
|
+
| {
|
|
14
|
+
kind: "pick";
|
|
15
|
+
options: string[];
|
|
16
|
+
none: string | null;
|
|
17
|
+
}
|
|
18
|
+
/** route: the chosen branch, or the unsure branch when the choice's confidence is below `gte`. */
|
|
19
|
+
| {
|
|
20
|
+
kind: "route";
|
|
21
|
+
unsure: {
|
|
22
|
+
gte: number;
|
|
23
|
+
branch: string;
|
|
24
|
+
} | null;
|
|
25
|
+
}
|
|
26
|
+
/** sift: an item of this request is kept when its `keep` measure meets `gte`; every item without a keep
|
|
27
|
+
* rule. `items` counts this request's items; the action names them by their position in the request. */
|
|
28
|
+
| {
|
|
29
|
+
kind: "sift";
|
|
30
|
+
items: number;
|
|
31
|
+
ids: string[];
|
|
32
|
+
keep: {
|
|
33
|
+
id: string;
|
|
34
|
+
measure: "confidence" | "value";
|
|
35
|
+
gte: number;
|
|
36
|
+
} | null;
|
|
37
|
+
}
|
|
38
|
+
/** ask: the predicate holds when the yes-probability meets `gte`. */
|
|
39
|
+
| {
|
|
40
|
+
kind: "ask";
|
|
41
|
+
gte: number;
|
|
42
|
+
}
|
|
43
|
+
/** verify: a yes/no question fails when its yes-probability is below its threshold (null: not judged).
|
|
44
|
+
* A failed question the submission holds is doubted; a failed one it lacks is unmet. */
|
|
45
|
+
| {
|
|
46
|
+
kind: "verify";
|
|
47
|
+
thresholds: Record<string, number | null>;
|
|
48
|
+
present: string[];
|
|
49
|
+
};
|
|
50
|
+
export type DecisionReceipt = {
|
|
51
|
+
v: typeof DECISION_RECEIPT_VERSION;
|
|
52
|
+
/** The request's identity: where it sits in the run (execution path, kind, position among its node's
|
|
53
|
+
* requests) and what it asked (questions and state). The same request asked again has the same id. */
|
|
54
|
+
id: string;
|
|
55
|
+
/** When the receipt was made, ISO 8601. */
|
|
56
|
+
at: string;
|
|
57
|
+
/** The label the request carried, a child workflow's prefix included. */
|
|
58
|
+
node: string;
|
|
59
|
+
kind: DecisionKind;
|
|
60
|
+
/** The map item the request ran for, by index; null outside a map. */
|
|
61
|
+
item: number | null;
|
|
62
|
+
execution_path: string;
|
|
63
|
+
/** This request among the requests its node makes at this path. A sift over the host's limits sends
|
|
64
|
+
* `count` requests, and `items` lists the positions in the sifted list this one covers, in the order it
|
|
65
|
+
* asked about them. A verify clause's nth review has index n - 1 and `count` is the most it may ask.
|
|
66
|
+
* Every other kind asks once. */
|
|
67
|
+
request: {
|
|
68
|
+
index: number;
|
|
69
|
+
count: number;
|
|
70
|
+
items?: number[];
|
|
71
|
+
};
|
|
72
|
+
/** `answered`: the answers came back and decided `action`. `failed`: the judge rejected, or its answers
|
|
73
|
+
* were refused. `cancelled`: the request's signal was aborted before it settled, so whether it was
|
|
74
|
+
* served is not known. */
|
|
75
|
+
status: "answered" | "failed" | "cancelled";
|
|
76
|
+
/** SHA-256 of the canonical JSON of the state the judge was given. */
|
|
77
|
+
state_sha256: string;
|
|
78
|
+
questions: Record<string, SystemOneQuestion>;
|
|
79
|
+
/** What came back, as it came back; empty when nothing did. */
|
|
80
|
+
answers: Record<string, SystemOneAnswer>;
|
|
81
|
+
/** Null unless `status` is `answered`. */
|
|
82
|
+
rule: DecisionRule | null;
|
|
83
|
+
/** What the answers decide under `rule`; null unless `status` is `answered`. */
|
|
84
|
+
action: unknown;
|
|
85
|
+
model: string | null;
|
|
86
|
+
usage: {
|
|
87
|
+
input_tokens: number;
|
|
88
|
+
output_tokens: number;
|
|
89
|
+
} | null;
|
|
90
|
+
cost_usd: number | null;
|
|
91
|
+
request_sha256: string | null;
|
|
92
|
+
/** Wall time of the judge call, in milliseconds. */
|
|
93
|
+
latency_ms: number;
|
|
94
|
+
error?: string;
|
|
95
|
+
};
|
|
96
|
+
/** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
|
|
97
|
+
* receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
|
|
98
|
+
export declare function rederiveDecision(receipt: Pick<DecisionReceipt, "rule" | "answers" | "questions">): unknown;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Decision receipts: one record per typed-question request, holding what was asked, what came back, the
|
|
2
|
+
// rule that turns those answers into an action (its thresholds included) and the action itself. A receipt
|
|
3
|
+
// alone explains a decision: `rederiveDecision` recomputes the action from it without a model call.
|
|
4
|
+
import { answerConfidence, answersToValue } from "./system-one.js";
|
|
5
|
+
export const DECISION_RECEIPT_VERSION = 1;
|
|
6
|
+
/** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
|
|
7
|
+
* receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
|
|
8
|
+
export function rederiveDecision(receipt) {
|
|
9
|
+
const rule = receipt.rule;
|
|
10
|
+
const answers = receipt.answers;
|
|
11
|
+
if (!rule)
|
|
12
|
+
return null;
|
|
13
|
+
switch (rule.kind) {
|
|
14
|
+
case "judge": return answersToValue(receipt.answers, receipt.questions);
|
|
15
|
+
case "pick": {
|
|
16
|
+
const choice = answers.pick?.choice;
|
|
17
|
+
const none = rule.none !== null && choice === rule.none;
|
|
18
|
+
return { index: none ? null : rule.options.indexOf(choice), none };
|
|
19
|
+
}
|
|
20
|
+
case "route": {
|
|
21
|
+
const branch = answers.branch?.choice;
|
|
22
|
+
const unsure = Boolean(rule.unsure && answers.branch.confidence < rule.unsure.gte);
|
|
23
|
+
return { branch, taken: unsure ? rule.unsure.branch : branch, unsure };
|
|
24
|
+
}
|
|
25
|
+
case "sift": {
|
|
26
|
+
const kept = [];
|
|
27
|
+
for (let i = 0; i < rule.items; i += 1) {
|
|
28
|
+
if (!rule.keep) {
|
|
29
|
+
kept.push(i);
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
const answer = answers[`${i}.${rule.keep.id}`];
|
|
33
|
+
const measure = !answer ? NaN : rule.keep.measure === "confidence" ? answerConfidence(answer) : answer.type === "noul" ? answer.noul : answer.type === "score" ? answer.score : NaN;
|
|
34
|
+
if (Number.isFinite(measure) && measure >= rule.keep.gte)
|
|
35
|
+
kept.push(i);
|
|
36
|
+
}
|
|
37
|
+
return { kept };
|
|
38
|
+
}
|
|
39
|
+
case "ask": return { holds: Number(answers.holds?.noul) >= rule.gte };
|
|
40
|
+
case "verify": {
|
|
41
|
+
const doubted = [];
|
|
42
|
+
const unmet = [];
|
|
43
|
+
for (const [id, threshold] of Object.entries(rule.thresholds)) {
|
|
44
|
+
if (threshold === null || !(Number(answers[id]?.noul) < threshold))
|
|
45
|
+
continue;
|
|
46
|
+
(rule.present.includes(id) ? doubted : unmet).push(id);
|
|
47
|
+
}
|
|
48
|
+
return { accepted: doubted.length === 0 && unmet.length === 0, doubted, unmet };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
|
|
2
2
|
export type { StandardJSONSchema, AuthoringSchema, TypedWorkflow, TypedWorkflowRunResult, WorkflowInput, WorkflowOutput, } from "./authoring.js";
|
|
3
|
-
export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, } from "./workflow.js";
|
|
4
|
-
export
|
|
3
|
+
export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, } from "./workflow.js";
|
|
4
|
+
export { DECISION_RECEIPT_VERSION, rederiveDecision } from "./decision-receipts.js";
|
|
5
|
+
export type { DecisionKind, DecisionReceipt, DecisionRule } from "./decision-receipts.js";
|
|
6
|
+
export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, DecisionExchange, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, MechanicalPredicate, Predicate, } from "./workflow.js";
|
|
5
7
|
export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
|
|
6
8
|
export type { DryRunOptions, DryRunResult } from "./dry-run.js";
|
|
7
9
|
export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, } from "./system-one.js";
|
|
@@ -14,6 +16,6 @@ export { resolveSchemaForWorkflow } from "./schema-references.js";
|
|
|
14
16
|
export { getPath, predicateMatches } from "./predicates.js";
|
|
15
17
|
export type { StopPredicate, AcceptPredicate } from "./predicates.js";
|
|
16
18
|
export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
|
|
17
|
-
export type { AuthorHostAddendum, CandidatePolicyOptions, AuthorWorkflowOptions, AuthoredWorkflow } from "./author.js";
|
|
19
|
+
export type { AuthorHostAddendum, CandidatePolicyOptions, AuthorWorkflowOptions, AuthoredWorkflow, HostOutputTypeOptions } from "./author.js";
|
|
18
20
|
export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
|
|
19
21
|
export type { WorkflowNodeKind, WorkflowPredicateName } from "./vocabulary.js";
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
|
|
2
|
-
export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, } from "./workflow.js";
|
|
2
|
+
export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, } from "./workflow.js";
|
|
3
|
+
export { DECISION_RECEIPT_VERSION, rederiveDecision } from "./decision-receipts.js";
|
|
3
4
|
export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
|
|
4
5
|
export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, } from "./system-one.js";
|
|
5
6
|
export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { RecoveryError } from "./errors.js";
|
|
2
|
+
/** The digest of each input a binding covers, named by its path: one entry per key of `parts`, and
|
|
3
|
+
* one per key of a part that is itself an object ("config.question", "binding.budget"). Stored beside
|
|
4
|
+
* the binding, they let a mismatch name the inputs that moved instead of only saying one did. */
|
|
5
|
+
export declare function bindingDigests(parts: Record<string, unknown>): Record<string, string>;
|
|
6
|
+
/** Why a store refuses a binding: the inputs whose digests differ from the ones it was bound with. */
|
|
7
|
+
export declare function bindingMismatch(stored: string | null, given: Record<string, string> | undefined): RecoveryError;
|
|
8
|
+
/** The format of what a run's store holds for a resume. Every binding carries it, so a store written under
|
|
9
|
+
* another format is refused, never resumed as if it held the same record. */
|
|
10
|
+
export declare const LEDGER_FORMAT = 3;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// A run's binding: what a durable record of the run was opened under. A binding is the hash of the host's inputs; its
|
|
2
|
+
// per-input digests let a refused open name the inputs that moved.
|
|
3
|
+
import { canonicalHash } from "./canonical-hash.js";
|
|
4
|
+
import { RecoveryError } from "./errors.js";
|
|
5
|
+
/** The digest of each input a binding covers, named by its path: one entry per key of `parts`, and
|
|
6
|
+
* one per key of a part that is itself an object ("config.question", "binding.budget"). Stored beside
|
|
7
|
+
* the binding, they let a mismatch name the inputs that moved instead of only saying one did. */
|
|
8
|
+
export function bindingDigests(parts) {
|
|
9
|
+
// An omitted input has no digest, as the binding's own JSON omits it: a change between omitted and
|
|
10
|
+
// null is then named as an input that is new or gone.
|
|
11
|
+
const digests = {};
|
|
12
|
+
for (const [name, value] of Object.entries(parts)) {
|
|
13
|
+
if (value === undefined)
|
|
14
|
+
continue;
|
|
15
|
+
if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length) {
|
|
16
|
+
for (const [key, inner] of Object.entries(value))
|
|
17
|
+
if (inner !== undefined)
|
|
18
|
+
digests[`${name}.${key}`] = canonicalHash(inner);
|
|
19
|
+
}
|
|
20
|
+
else
|
|
21
|
+
digests[name] = canonicalHash(value);
|
|
22
|
+
}
|
|
23
|
+
return digests;
|
|
24
|
+
}
|
|
25
|
+
/** Why a store refuses a binding: the inputs whose digests differ from the ones it was bound with. */
|
|
26
|
+
export function bindingMismatch(stored, given) {
|
|
27
|
+
let recorded = null;
|
|
28
|
+
try {
|
|
29
|
+
recorded = stored ? JSON.parse(stored) : null;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
recorded = null;
|
|
33
|
+
}
|
|
34
|
+
if (!recorded || !given) {
|
|
35
|
+
return Object.assign(new RecoveryError(`Run store binding mismatch: ${!recorded ? "the store was bound before its input digests were recorded" : "the opener named no input digests"}, so the input that moved cannot be named`, "RUN_STORE_BINDING_MISMATCH"), { moved: null });
|
|
36
|
+
}
|
|
37
|
+
const moved = [...new Set([...Object.keys(recorded), ...Object.keys(given)])].filter((name) => recorded[name] !== given[name]).sort();
|
|
38
|
+
const described = moved.map((name) => !(name in recorded) ? `${name} (new)` : !(name in given) ? `${name} (gone)` : name);
|
|
39
|
+
return Object.assign(new RecoveryError(`Run store binding mismatch: ${moved.length ? `${described.join(", ")} changed since the run was bound` : "every named input matches, so the change is in how the binding is composed"}`, "RUN_STORE_BINDING_MISMATCH"), { moved });
|
|
40
|
+
}
|
|
41
|
+
/** The format of what a run's store holds for a resume. Every binding carries it, so a store written under
|
|
42
|
+
* another format is refused, never resumed as if it held the same record. */
|
|
43
|
+
export const LEDGER_FORMAT = 3;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The widest provider tool-call id that is keyed as it is. */
|
|
2
|
+
export declare const CALL_KEY_BYTES = 256;
|
|
3
|
+
/** A host's own key for a provider-minted tool-call id. A provider may fold arbitrary data into
|
|
4
|
+
* its call ids (a reasoning signature, for one), so an id's length is the provider's, not ours: an id
|
|
5
|
+
* within `CALL_KEY_BYTES` is its own key, and a wider one is keyed by its leading characters (made
|
|
6
|
+
* identifier-safe) and a SHA-256 prefix of the whole id. The mapping is deterministic, so the same
|
|
7
|
+
* call always has the same key, and two different wide ids share a key only on a digest collision.
|
|
8
|
+
* Only keys use it: what goes back to the provider is always the id it minted. */
|
|
9
|
+
export declare function callKey(callId: string): string;
|
|
10
|
+
/** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
|
|
11
|
+
* ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
|
|
12
|
+
* wide id as it was resumes against its own receipts and never re-runs a recorded call. */
|
|
13
|
+
export declare function heldCallKey(callId: string, holds: (rawKey: string) => boolean): string;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
/** The widest provider tool-call id that is keyed as it is. */
|
|
3
|
+
export const CALL_KEY_BYTES = 256;
|
|
4
|
+
const PREFIX_CHARS = 64;
|
|
5
|
+
const DIGEST_HEX = 32;
|
|
6
|
+
/** A host's own key for a provider-minted tool-call id. A provider may fold arbitrary data into
|
|
7
|
+
* its call ids (a reasoning signature, for one), so an id's length is the provider's, not ours: an id
|
|
8
|
+
* within `CALL_KEY_BYTES` is its own key, and a wider one is keyed by its leading characters (made
|
|
9
|
+
* identifier-safe) and a SHA-256 prefix of the whole id. The mapping is deterministic, so the same
|
|
10
|
+
* call always has the same key, and two different wide ids share a key only on a digest collision.
|
|
11
|
+
* Only keys use it: what goes back to the provider is always the id it minted. */
|
|
12
|
+
export function callKey(callId) {
|
|
13
|
+
if (Buffer.byteLength(callId) <= CALL_KEY_BYTES)
|
|
14
|
+
return callId;
|
|
15
|
+
const prefix = callId.slice(0, PREFIX_CHARS).replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
16
|
+
return `${prefix}~${createHash("sha256").update(callId).digest("hex").slice(0, DIGEST_HEX)}`;
|
|
17
|
+
}
|
|
18
|
+
/** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
|
|
19
|
+
* ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
|
|
20
|
+
* wide id as it was resumes against its own receipts and never re-runs a recorded call. */
|
|
21
|
+
export function heldCallKey(callId, holds) {
|
|
22
|
+
const key = callKey(callId);
|
|
23
|
+
return key !== callId && holds(callId) ? callId : key;
|
|
24
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** SHA-256 of a value's JSON with every object's keys sorted: the identity of a binding, an input,
|
|
2
|
+
* an intent's arguments or a set of file hashes, independent of key order. */
|
|
3
|
+
export declare const canonicalHash: (value: unknown) => string;
|
|
4
|
+
/** SHA-256 of a value serialized with sorted keys: an identity for a contract a host persists. Not interchangeable
|
|
5
|
+
* with canonicalHash: it writes an undefined member as `undefined` and never calls toJSON, and both identities are
|
|
6
|
+
* persisted. */
|
|
7
|
+
export declare function canonicalSha256(value: unknown): string;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
/** SHA-256 of a value's JSON with every object's keys sorted: the identity of a binding, an input,
|
|
3
|
+
* an intent's arguments or a set of file hashes, independent of key order. */
|
|
4
|
+
export const canonicalHash = (value) => createHash("sha256").update(JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item)
|
|
5
|
+
? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item)).digest("hex");
|
|
6
|
+
function canonical(value) {
|
|
7
|
+
if (value === null || typeof value !== "object")
|
|
8
|
+
return JSON.stringify(value);
|
|
9
|
+
if (Array.isArray(value))
|
|
10
|
+
return `[${value.map(canonical).join(",")}]`;
|
|
11
|
+
const object = value;
|
|
12
|
+
return `{${Object.keys(object)
|
|
13
|
+
.sort()
|
|
14
|
+
.map((key) => `${JSON.stringify(key)}:${canonical(object[key])}`)
|
|
15
|
+
.join(",")}}`;
|
|
16
|
+
}
|
|
17
|
+
/** SHA-256 of a value serialized with sorted keys: an identity for a contract a host persists. Not interchangeable
|
|
18
|
+
* with canonicalHash: it writes an undefined member as `undefined` and never calls toJSON, and both identities are
|
|
19
|
+
* persisted. */
|
|
20
|
+
export function canonicalSha256(value) {
|
|
21
|
+
return createHash("sha256").update(canonical(value)).digest("hex");
|
|
22
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import type { RouteNode, Workflow, WorkflowDeps, WorkflowNode } from "../workflow.js";
|
|
2
|
+
import { type RouteDecision, type QuestionReceipts, type StepRecord, type EscalationRow } from "./frozen-snapshot.js";
|
|
3
|
+
import type { RecoveryBinding, RecoveryEffect, RecoveryStore } from "./store.js";
|
|
4
|
+
/** The branch a route runs for its answer, as the interpreter takes it: the node's `unsure` branch when
|
|
5
|
+
* the answer's confidence is below `unsure.gte`, else the choice the answer names. */
|
|
6
|
+
export declare function routeTaken(node: RouteNode, answers: unknown): {
|
|
7
|
+
branch: string;
|
|
8
|
+
choice: string;
|
|
9
|
+
unsure: boolean;
|
|
10
|
+
};
|
|
11
|
+
/** The binding of a run of `workflow` under what the host binds beside it. */
|
|
12
|
+
export declare function recoveryBinding(workflow: Workflow, bind?: Record<string, unknown>): string;
|
|
13
|
+
/** What a store is opened under for a run of `workflow`: its binding, and the digest of each input the binding
|
|
14
|
+
* covers. The driver opens its store under it, and so does an operator who reconciles an effect by hand. */
|
|
15
|
+
export declare function recoveryBound(workflow: Workflow, bind?: Record<string, unknown>): RecoveryBinding;
|
|
16
|
+
/** A host's pause or cancel, and who issued it. */
|
|
17
|
+
export type RecoveryStop = {
|
|
18
|
+
action: "pause" | "cancel";
|
|
19
|
+
source?: string;
|
|
20
|
+
};
|
|
21
|
+
/** How the driver reads the files a workflow declares it writes. */
|
|
22
|
+
export type RecoveryFiles = {
|
|
23
|
+
/** Whether two names are one file. */
|
|
24
|
+
same(a: string, b: string): boolean;
|
|
25
|
+
/** The SHA-256 of each named file, by name. A missing file, or one outside the place files live, is refused
|
|
26
|
+
* with FROZEN_ARTIFACT_INVALID. */
|
|
27
|
+
hashes(names: string[]): Record<string, string>;
|
|
28
|
+
};
|
|
29
|
+
/** The files of a workspace directory: a name is relative to it, and a file that resolves outside it is refused. */
|
|
30
|
+
export declare function workspaceFiles(cwd: string): RecoveryFiles;
|
|
31
|
+
export type RecoveryOptions = {
|
|
32
|
+
/** The run's identity. Its step sessions, its effects' receipts and the continuation of its escalation are named
|
|
33
|
+
* under it, so the same run is opened with the same key in every process. */
|
|
34
|
+
key: string;
|
|
35
|
+
/** What else must not change between two opens of the run, beside the workflow: the host's own inputs. */
|
|
36
|
+
bind?: Record<string, unknown>;
|
|
37
|
+
/** The document the interpreter runs, when the host rewrites the authored one before running it. Execution paths
|
|
38
|
+
* resolve in it; the binding, the labels and the declared files are the authored document's. Absent, the
|
|
39
|
+
* desugared workflow. */
|
|
40
|
+
view?: Workflow;
|
|
41
|
+
/** Files only the host writes. A workflow that declares one of them is refused before any step runs. */
|
|
42
|
+
reservedOutputs?: readonly string[];
|
|
43
|
+
/** The files a workflow declares it writes. Absent, the files of the process's working directory. */
|
|
44
|
+
files?: RecoveryFiles;
|
|
45
|
+
/** Closes the session of an LLM step's attempt that ended without a submission. It runs on the driver's commit
|
|
46
|
+
* chain, before the commit that records the attempt as closed; its failure is the run's. */
|
|
47
|
+
closeStepSession?: (sessionId: string) => Promise<unknown>;
|
|
48
|
+
/** Settles effects a killed process left unknown, through the driver's own open of the run (one generation per process).
|
|
49
|
+
* `openRecovery` calls it once, after the open and before anything resumes, when the journal holds an effect that was
|
|
50
|
+
* admitted and never completed; `unknown` is those effects, with their `intent` and the `args` the call was admitted with (what the host's door is sent; absent on a record written before args were kept). `complete(id, value, receipt)`
|
|
51
|
+
* records `value` as the effect's result, as `journal.complete` does with `{ value, files }`, hashing the files the effect declares (a missing one refuses the settlement); `receipt.intent` names
|
|
52
|
+
* the call the host's door answered, as a handoff reads it. `receipt.calls` are the outside calls the host MADE or FOUND APPLIED
|
|
53
|
+
* while settling it, records of the shape `{ outcome: "applied" | "failed" | "unknown", ... }`, so that the effect's `calls` lists
|
|
54
|
+
* every applied call exactly once. They are kept on the effect before it completes, after the calls an earlier process kept, as a
|
|
55
|
+
* dispatch keeps its own. A re-send is a call of this process. A settle from evidence that the call applied (a provider's own
|
|
56
|
+
* lookup, an answer the host kept) reports `{ outcome: "applied" }` when the calls the effect holds include no applied entry,
|
|
57
|
+
* and adds none when its applied call is already there. A settle that made no call and found none applied reports none. The
|
|
58
|
+
* effect is then answered from that result and not
|
|
59
|
+
* dispatched again. One it leaves unknown is refused at resume (`FROZEN_EFFECT_UNKNOWN`). A throw fails the open with
|
|
60
|
+
* `RECOVERY_RECONCILE_FAILED`, keeping the cause, before any effect is dispatched. */
|
|
61
|
+
reconcile?: (unknown: RecoveryEffect[], complete: (id: string, value: unknown, receipt?: {
|
|
62
|
+
intent?: {
|
|
63
|
+
tool: string;
|
|
64
|
+
args?: unknown;
|
|
65
|
+
};
|
|
66
|
+
calls?: unknown[];
|
|
67
|
+
}) => Promise<void>) => Promise<void>;
|
|
68
|
+
};
|
|
69
|
+
/** What a host's effect adapter receives under the driver: the interpreter's parameters, `call`, which keeps each
|
|
70
|
+
* outside call the effect makes on its record as the call ends, and `effect`, the admitted effect: its journal id and
|
|
71
|
+
* the hash of its arguments, as the journal stores them and the same in every process of the run. A host that keeps
|
|
72
|
+
* what an outside call answered under them can settle an effect whose call was cut with `journal.complete`. */
|
|
73
|
+
export type RecoveryEffectParams = Parameters<NonNullable<WorkflowDeps["runEffect"]>>[0] & {
|
|
74
|
+
call?: (record: unknown) => void;
|
|
75
|
+
effect?: {
|
|
76
|
+
id: string;
|
|
77
|
+
argsHash: string;
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
/** Opens the durable state of one run of `workflow` in `store` and takes ownership of it. Execution remains in the
|
|
81
|
+
* interpreter: the workflow runs with the returned driver's hooks, and `close` lets go of the run. */
|
|
82
|
+
export declare function openRecovery(store: RecoveryStore, workflow: Workflow, options: RecoveryOptions): Promise<{
|
|
83
|
+
recovery: {
|
|
84
|
+
supportsExecutionPaths?: boolean;
|
|
85
|
+
resume: (node: WorkflowNode, state: Record<string, unknown>, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<Record<string, unknown> | undefined>;
|
|
86
|
+
commit: (node: WorkflowNode, state: Record<string, unknown>, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<void>;
|
|
87
|
+
pollStartedAt: (node: import("../workflow.js").CallNode, item?: import("../workflow.js").MapItem, executionPath?: string) => number;
|
|
88
|
+
wait: (node: import("../workflow.js").CallNode, ms: number, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<void>;
|
|
89
|
+
fail?: (node: WorkflowNode, results: unknown[], error: unknown, executionPath?: string) => Promise<void>;
|
|
90
|
+
decision?: (id: string) => Promise<import("../decision-receipts.js").DecisionReceipt | undefined>;
|
|
91
|
+
};
|
|
92
|
+
signal: AbortSignal;
|
|
93
|
+
resumed: boolean;
|
|
94
|
+
/** This process's generation of the run: a request this process makes is named with it, so a
|
|
95
|
+
* process that asks again never reuses an earlier process's invocation. */
|
|
96
|
+
readonly generation: number;
|
|
97
|
+
/** A refusal found before any step, or null: the host escalates it before any step runs. */
|
|
98
|
+
preStepRefusal: {
|
|
99
|
+
code: string;
|
|
100
|
+
kind: string;
|
|
101
|
+
message: string;
|
|
102
|
+
label: string;
|
|
103
|
+
} | null;
|
|
104
|
+
binding: string;
|
|
105
|
+
/** The run's key: what its step sessions and effects are named under. */
|
|
106
|
+
driverId: string;
|
|
107
|
+
/** The host hands the driver its stop here. A cancel stops the driver at once, and its steps and effects through
|
|
108
|
+
* its signal. A pause refuses new work at once and is taken when no effect is in flight: an effect already
|
|
109
|
+
* dispatched completes and commits its receipt first, so a paused run resumes without a reconciliation. */
|
|
110
|
+
stop: (stop: RecoveryStop) => void;
|
|
111
|
+
/** The driver's stop check, for a branch that hands off without entering the interpreter: a pause or cancel the
|
|
112
|
+
* driver took stops the run here, before anything resumes. */
|
|
113
|
+
checkStop(): void;
|
|
114
|
+
/** A seam for new work: it waits while a pause waits for an effect in flight, then applies any stop taken. */
|
|
115
|
+
seam: () => Promise<void>;
|
|
116
|
+
/** An LLM step's execution record, admitted before it dispatches. The first call fixes the label
|
|
117
|
+
* the interpreter names it by (a child's step under its invocation) and the retry limit; a resume
|
|
118
|
+
* at this path gets the same record, so its session is found again. A closed attempt advances to a new
|
|
119
|
+
* session identity here, and only here; a failed step never gets another. */
|
|
120
|
+
stepSession(executionPath: unknown, label: string, admission?: {
|
|
121
|
+
attemptsAllowed: number;
|
|
122
|
+
}): StepRecord & {
|
|
123
|
+
stepId: string;
|
|
124
|
+
sessionId: string;
|
|
125
|
+
earlierSessionIds: string[];
|
|
126
|
+
};
|
|
127
|
+
/** Whether the step already has an execution record: a resumed step was admitted in an earlier
|
|
128
|
+
* process and is continued, never refused again. */
|
|
129
|
+
stepAdmitted(executionPath: unknown): boolean;
|
|
130
|
+
/** The current attempt did not submit: its session closes with its spend kept.
|
|
131
|
+
* The step is `closed` until a retry is admitted, or `failed` when no attempt remains. */
|
|
132
|
+
stepAttemptFailed(executionPath: unknown, final?: boolean): void;
|
|
133
|
+
/** The step delivered its record; the row and the step record agree before the step commit. */
|
|
134
|
+
stepSubmitted(executionPath: unknown): void;
|
|
135
|
+
/** The short identity of an admitted LLM step (a digest of its frame and path), for the escalation
|
|
136
|
+
* row when it fails; null for a path that ran no LLM step. */
|
|
137
|
+
stepId(executionPath: unknown): string | null;
|
|
138
|
+
/** Spend outside any question or session, committed with the driver's state the moment it is priced, so the run's
|
|
139
|
+
* recorded spend holds it. It may be called inside a tool, so it never applies a stop; a failed commit is the run's
|
|
140
|
+
* persistence failure. */
|
|
141
|
+
charge(usd: number): Promise<void>;
|
|
142
|
+
/** A question's metered spend, committed with the driver's state so a resume that skips the
|
|
143
|
+
* finished question still reports it; an unpriced answer (`null`) adds nothing. A route's answer is its decision: it commits in the same save, once per route path, and a resume
|
|
144
|
+
* inside the branch follows it instead of asking again. */
|
|
145
|
+
recordQuestionSpend(usd: number | null, route?: {
|
|
146
|
+
executionPath: unknown;
|
|
147
|
+
label: string;
|
|
148
|
+
result: Record<string, unknown>;
|
|
149
|
+
receipts: QuestionReceipts | null;
|
|
150
|
+
}): void;
|
|
151
|
+
/** The host has written what it keeps of the route at `executionPath`: its decision no longer carries the
|
|
152
|
+
* receipts a resume would write. */
|
|
153
|
+
routeReceipted(executionPath: unknown): void;
|
|
154
|
+
/** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
|
|
155
|
+
routeDecision(executionPath: unknown): RouteDecision | undefined;
|
|
156
|
+
/** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
|
|
157
|
+
* as an escalation commit before anything acts on it. A later open gets the same row and the same
|
|
158
|
+
* continuation identity, whatever fires again. */
|
|
159
|
+
escalate(row: Omit<EscalationRow, "tail" | "revision">): Promise<EscalationRow>;
|
|
160
|
+
escalation(): EscalationRow | undefined;
|
|
161
|
+
/** How many effects the driver admitted. */
|
|
162
|
+
effectCalls(): number;
|
|
163
|
+
/** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
|
|
164
|
+
* read and its identity. */
|
|
165
|
+
annotateHandoff(detail: {
|
|
166
|
+
escalation_revision: number;
|
|
167
|
+
tail: string;
|
|
168
|
+
inherit: string;
|
|
169
|
+
block_chars: number;
|
|
170
|
+
digest_chars: number;
|
|
171
|
+
}): Promise<void>;
|
|
172
|
+
/** The run's spend at the moment its continuation is admitted. Spend may land under this run after
|
|
173
|
+
* the escalation commit, so the row the continuation reads the spend from is brought current here,
|
|
174
|
+
* by one `handoff` commit that names the escalation. The escalation's revision, what the
|
|
175
|
+
* continuation binds on, does not change. */
|
|
176
|
+
handoff(spend: Pick<EscalationRow, "cost_usd" | "turns" | "effect_calls">): Promise<EscalationRow>;
|
|
177
|
+
/** The state the document's committed top-level prefix left behind, plus what a failed map's finished
|
|
178
|
+
* items produced under the map's key: what an escalation on a failure carries. */
|
|
179
|
+
lastState(): Record<string, unknown>;
|
|
180
|
+
readonly started: boolean;
|
|
181
|
+
wrapEffect(run: (params: RecoveryEffectParams) => Promise<unknown>): NonNullable<WorkflowDeps["runEffect"]>;
|
|
182
|
+
/** Every commit the driver started has landed; a failed one is thrown. */
|
|
183
|
+
flush: () => Promise<void>;
|
|
184
|
+
/** Let go of the run once every commit the driver started has landed. */
|
|
185
|
+
close(): Promise<void>;
|
|
186
|
+
}>;
|