@parcha/agentrun-dsl 0.1.0-beta.23 → 0.1.0-beta.231

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +22 -17
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +0 -2
  6. package/dist/author.js +15 -8
  7. package/dist/authoring.js +4 -3
  8. package/dist/cli.js +13 -12
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +64 -3
  14. package/dist/decision-receipts.js +50 -8
  15. package/dist/dry-run.d.ts +31 -1
  16. package/dist/dry-run.js +122 -16
  17. package/dist/edit.d.ts +149 -0
  18. package/dist/edit.js +1422 -0
  19. package/dist/evidence.d.ts +19 -0
  20. package/dist/evidence.js +63 -0
  21. package/dist/graph.d.ts +17 -0
  22. package/dist/graph.js +71 -6
  23. package/dist/index.d.ts +18 -12
  24. package/dist/index.js +17 -10
  25. package/dist/inspection.d.ts +5 -0
  26. package/dist/inspection.js +14 -1
  27. package/dist/pattern-screen.d.ts +14 -0
  28. package/dist/pattern-screen.js +451 -0
  29. package/dist/pointer-warning.d.ts +14 -0
  30. package/dist/pointer-warning.js +22 -0
  31. package/dist/predicates.d.ts +32 -2
  32. package/dist/predicates.js +66 -6
  33. package/dist/record.d.ts +4 -0
  34. package/dist/record.js +6 -0
  35. package/dist/recovery/binding.js +2 -1
  36. package/dist/recovery/call-key.d.ts +0 -4
  37. package/dist/recovery/call-key.js +0 -7
  38. package/dist/recovery/driver.d.ts +43 -20
  39. package/dist/recovery/driver.js +144 -48
  40. package/dist/recovery/frozen-snapshot.d.ts +33 -3
  41. package/dist/recovery/frozen-snapshot.js +28 -12
  42. package/dist/recovery/handoff-receipts.d.ts +0 -35
  43. package/dist/recovery/handoff-receipts.js +2 -44
  44. package/dist/recovery/index.d.ts +4 -8
  45. package/dist/recovery/index.js +4 -7
  46. package/dist/recovery/item-state.d.ts +2 -1
  47. package/dist/recovery/item-state.js +7 -13
  48. package/dist/recovery/with-recovery.d.ts +9 -3
  49. package/dist/recovery/with-recovery.js +72 -15
  50. package/dist/submit-envelope.d.ts +9 -0
  51. package/dist/submit-envelope.js +44 -0
  52. package/dist/system-one.d.ts +21 -2
  53. package/dist/system-one.js +96 -18
  54. package/dist/testing/decision-provider.d.ts +32 -0
  55. package/dist/testing/decision-provider.js +183 -0
  56. package/dist/testing/index.d.ts +1 -0
  57. package/dist/testing/index.js +2 -0
  58. package/dist/vocabulary.d.ts +16 -3
  59. package/dist/vocabulary.js +23 -8
  60. package/dist/workflow-shape.js +4 -2
  61. package/dist/workflow.d.ts +145 -19
  62. package/dist/workflow.js +795 -236
  63. package/dist/zod-json-contract.js +6 -8
  64. package/package.json +16 -4
  65. package/schema/workflow.schema.json +352 -1
  66. package/skills/author/SKILL.md +4 -1
  67. package/skills/author/references/jev-decisions.md +50 -5
  68. package/skills/author/references/language.md +16 -11
  69. package/dist/recovery/effect-failure.d.ts +0 -34
  70. package/dist/recovery/effect-failure.js +0 -62
  71. package/dist/recovery/handoff-block.d.ts +0 -36
  72. package/dist/recovery/handoff-block.js +0 -148
  73. package/dist/recovery/handoff-digest.d.ts +0 -58
  74. package/dist/recovery/handoff-digest.js +0 -195
  75. package/dist/recovery/handoff-files.d.ts +0 -54
  76. package/dist/recovery/handoff-files.js +0 -162
  77. package/dist/recovery/handoff-redact.d.ts +0 -12
  78. package/dist/recovery/handoff-redact.js +0 -44
  79. package/dist/recovery/handoff.d.ts +0 -44
  80. package/dist/recovery/handoff.js +0 -46
@@ -1,5 +1,38 @@
1
- import { type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
1
+ import type { CostBasis, DecisionEvidence } from "./decision-provider.js";
2
+ import { type ConfidenceSource, type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
2
3
  export declare const DECISION_RECEIPT_VERSION = 1;
4
+ /** The escalation kind of a decision its provider refused: the run ends `escalated` at stage "decision", for a person. */
5
+ export declare const DECISION_REFUSED = "decision_refused";
6
+ /** The escalation kind of a run whose decision was asked by an earlier process and never answered there: it is routed to
7
+ * review instead of being asked, and paid for, again. Its stage is `decision`. */
8
+ export declare const DECISION_INTERRUPTED = "decision_interrupted";
9
+ /** The most of the state a receipt keeps, as UTF-8 JSON bytes: a larger state is kept as the first this many bytes of its
10
+ * JSON text, with `state_truncated: true`. */
11
+ export declare const DECISION_STATE_MAX_BYTES: number;
12
+ /** The most of a request's error a receipt keeps, in characters; a longer one is kept to it with `error_truncated`. */
13
+ export declare const DECISION_ERROR_MAX: number;
14
+ /** An image a request carried, as its receipt names it: the token the request used, the reference the host loaded, and
15
+ * the image's SHA-256, type and size (never the bytes). The digest fields are null when the image was never loaded (a
16
+ * request that failed before its images were read). */
17
+ export type DecisionImageDigest = {
18
+ token: string;
19
+ ref: string;
20
+ sha256: string | null;
21
+ mime: string | null;
22
+ bytes: number | null;
23
+ };
24
+ /** A state value a provider cut to fit its model's context before it sent the request: where it sits in the state (a JSON
25
+ * Pointer, RFC 6901), and its UTF-8 bytes as asked and as sent (its start and the provider's cut mark). */
26
+ export type DecisionStateCut = {
27
+ path: string;
28
+ bytes: number;
29
+ sent_bytes: number;
30
+ };
31
+ /** The state a provider sent when it sent other than it was asked (values cut to fit its context), and the values it cut. */
32
+ export type DecisionStateSent = {
33
+ state: unknown;
34
+ cut: DecisionStateCut[];
35
+ };
3
36
  /** The typed questions the interpreter asks: the five question nodes and predicates, and a generative
4
37
  * node's `verify` clause. */
5
38
  export type DecisionKind = "judge" | "pick" | "sift" | "route" | "ask" | "verify";
@@ -15,9 +48,12 @@ export type DecisionRule =
15
48
  options: string[];
16
49
  none: string | null;
17
50
  }
18
- /** route: the chosen branch, or the unsure branch when the choice's confidence is below `gte`. */
51
+ /** route: the chosen branch, or the unsure branch when the choice's confidence is below `gte`. The chosen
52
+ * branch names one of `branches`; `unsure`, when set, judges its confidence against `gte`. `branches` is
53
+ * absent on a rule recorded before it was added, and such a rule skips the branch-membership check. */
19
54
  | {
20
55
  kind: "route";
56
+ branches?: string[];
21
57
  unsure: {
22
58
  gte: number;
23
59
  branch: string;
@@ -73,7 +109,8 @@ export type DecisionReceipt = {
73
109
  * were refused. `cancelled`: the request's signal was aborted before it settled, so whether it was
74
110
  * served is not known. */
75
111
  status: "answered" | "failed" | "cancelled";
76
- /** SHA-256 of the canonical JSON of the state the judge was given. */
112
+ /** SHA-256 of the canonical JSON of the state the judge was asked with: part of the request's identity (`id`). What
113
+ * the provider sent is `state` and `request_sha256`, which differ when it cut values to fit (`state_cut`). */
77
114
  state_sha256: string;
78
115
  questions: Record<string, SystemOneQuestion>;
79
116
  /** What came back, as it came back; empty when nothing did. */
@@ -91,7 +128,31 @@ export type DecisionReceipt = {
91
128
  request_sha256: string | null;
92
129
  /** Wall time of the judge call, in milliseconds. */
93
130
  latency_ms: number;
131
+ /** The questions whose answer came back as a refusal, when any did. A refusal decodes to no value: the request is
132
+ * `failed` and the run escalates (DECISION_REFUSED), except a route with an `unsure` branch, which takes that branch. */
133
+ refused?: string[];
134
+ /** For each choice and score answer, whether its confidence is the provider's own or was derived from its
135
+ * probabilities; present when the judge said. */
136
+ confidence_source?: Record<string, ConfidenceSource>;
137
+ /** The provider that answered, when the host's judge names it or the node pins it. */
138
+ provider?: string;
139
+ /** The sources the provider grounded its answers in, unless the node said `evidence: "off"`; absent when it gave none. */
140
+ evidence?: DecisionEvidence[];
141
+ /** How `cost_usd` was reached (reported by the provider, estimated by the host, unknown), when the judge said. */
142
+ cost_basis?: CostBasis;
143
+ /** The images the request carried, by digest; absent when it carried none. */
144
+ images?: DecisionImageDigest[];
145
+ /** The state the judge saw, as its provider sent it (with any value it cut, cut): the value itself, or, past
146
+ * `DECISION_STATE_MAX_BYTES` of JSON, the first that many bytes of its JSON text (a string) with `state_truncated: true`.
147
+ * Absent on a receipt recorded before it was kept. */
148
+ state?: unknown;
149
+ state_truncated?: boolean;
150
+ /** The state values the provider cut to fit its model's context before sending; absent when it sent the state as asked. */
151
+ state_cut?: DecisionStateCut[];
152
+ /** The request's error, whole up to `DECISION_ERROR_MAX` characters: a host redacts it before it cuts it for a person.
153
+ * A longer one is kept to that many with `error_truncated: true`; one recorded before was cut at 2000. */
94
154
  error?: string;
155
+ error_truncated?: boolean;
95
156
  };
96
157
  /** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
97
158
  * receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
@@ -1,8 +1,15 @@
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
1
  import { answerConfidence, answersToValue } from "./system-one.js";
5
2
  export const DECISION_RECEIPT_VERSION = 1;
3
+ /** The escalation kind of a decision its provider refused: the run ends `escalated` at stage "decision", for a person. */
4
+ export const DECISION_REFUSED = "decision_refused";
5
+ /** The escalation kind of a run whose decision was asked by an earlier process and never answered there: it is routed to
6
+ * review instead of being asked, and paid for, again. Its stage is `decision`. */
7
+ export const DECISION_INTERRUPTED = "decision_interrupted";
8
+ /** The most of the state a receipt keeps, as UTF-8 JSON bytes: a larger state is kept as the first this many bytes of its
9
+ * JSON text, with `state_truncated: true`. */
10
+ export const DECISION_STATE_MAX_BYTES = 64 * 1024;
11
+ /** The most of a request's error a receipt keeps, in characters; a longer one is kept to it with `error_truncated`. */
12
+ export const DECISION_ERROR_MAX = 64 * 1024;
6
13
  /** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
7
14
  * receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
8
15
  export function rederiveDecision(receipt) {
@@ -13,13 +20,39 @@ export function rederiveDecision(receipt) {
13
20
  switch (rule.kind) {
14
21
  case "judge": return answersToValue(receipt.answers, receipt.questions);
15
22
  case "pick": {
16
- const choice = answers.pick?.choice;
23
+ // An answered pick carries its pick answer; a receipt without one decided nothing.
24
+ const answer = answers.pick;
25
+ if (!answer || typeof answer !== "object")
26
+ return null;
27
+ const choice = answer.choice;
28
+ // The choice must be a string that names an option, or the none option. Anything else (no string
29
+ // choice, or a choice in neither set) is a malformed answer, never a fail-open {index: -1}.
30
+ if (typeof choice !== "string")
31
+ return null;
17
32
  const none = rule.none !== null && choice === rule.none;
33
+ if (!none && !rule.options.includes(choice))
34
+ return null;
18
35
  return { index: none ? null : rule.options.indexOf(choice), none };
19
36
  }
20
37
  case "route": {
21
- const branch = answers.branch?.choice;
22
- const unsure = Boolean(rule.unsure && answers.branch.confidence < rule.unsure.gte);
38
+ // An answered route carries its branch answer; a receipt without one decided nothing.
39
+ const answer = answers.branch;
40
+ if (!answer || typeof answer !== "object")
41
+ return null;
42
+ // A refused route has no branch of its own: it took the unsure branch, and without one it decided nothing.
43
+ if (answer.type === "refusal")
44
+ return rule.unsure ? { branch: null, taken: rule.unsure.branch, unsure: true, refused: true } : null;
45
+ const branch = answer.choice;
46
+ // The chosen branch must be a string; when the rule carries `branches` (recorded since this check was
47
+ // added) it must name one of them. A rule recorded before `branches` skips the membership check, so an
48
+ // older route receipt re-derives as it did before, never throwing on a missing field.
49
+ if (typeof branch !== "string" || (rule.branches && !rule.branches.includes(branch)))
50
+ return null;
51
+ // When unsure is set, judging SURE/UNSURE needs a finite numeric confidence. A missing or non-numeric
52
+ // confidence must not compare false and re-derive as SURE (a fail-open onto the chosen branch).
53
+ if (rule.unsure && !(typeof answer.confidence === "number" && Number.isFinite(answer.confidence)))
54
+ return null;
55
+ const unsure = Boolean(rule.unsure && answer.confidence < rule.unsure.gte);
23
56
  return { branch, taken: unsure ? rule.unsure.branch : branch, unsure };
24
57
  }
25
58
  case "sift": {
@@ -41,9 +74,18 @@ export function rederiveDecision(receipt) {
41
74
  const doubted = [];
42
75
  const unmet = [];
43
76
  for (const [id, threshold] of Object.entries(rule.thresholds)) {
44
- if (threshold === null || !(Number(answers[id]?.noul) < threshold))
77
+ if (threshold === null)
45
78
  continue;
46
- (rule.present.includes(id) ? doubted : unmet).push(id);
79
+ // A field with a threshold needs its yes/no answer; a receipt missing one, or holding another shape, decided
80
+ // nothing (null), never a fail-open "accepted".
81
+ const answer = answers[id];
82
+ // The answer must be a noul with a finite numeric probability. A noul-typed answer whose noul is
83
+ // absent or not a finite number would compare NaN < threshold (false), reading as supported: a
84
+ // fail-open one level down. It decided nothing.
85
+ if (answer?.type !== "noul" || typeof answer.noul !== "number" || !Number.isFinite(answer.noul))
86
+ return null;
87
+ if (answer.noul < threshold)
88
+ (rule.present.includes(id) ? doubted : unmet).push(id);
47
89
  }
48
90
  return { accepted: doubted.length === 0 && unmet.length === 0, doubted, unmet };
49
91
  }
package/dist/dry-run.d.ts CHANGED
@@ -11,7 +11,24 @@ export type DryRunResult = {
11
11
  problems: string[];
12
12
  stage?: string;
13
13
  };
14
- export declare function synthesizeInstance(schema: unknown, definitions?: Record<string, unknown>, depth?: number): unknown;
14
+ /** What one dry run may synthesize in all, across its input and every step's answer (DryRunOptions.budget), and what one
15
+ * synthesizeInstance call may when none is given: values (each array item, object, string, number...) and string
16
+ * characters. Synthesis counts each before it makes it and throws SynthesisTooLarge past either, so a schema that asks
17
+ * for a huge value (nested arrays of a large minItems, a long minLength) never allocates past the budget. */
18
+ export type SynthesisBudget = {
19
+ values: number;
20
+ chars: number;
21
+ };
22
+ /** The default: a million values and 16 million characters, far past what a real workflow's dry run builds (a few
23
+ * thousand values at most), and well within a host's memory (a few hundred MB at worst). */
24
+ export declare const SYNTHESIS_BUDGET: Readonly<SynthesisBudget>;
25
+ /** The schema asked synthesis for more than its budget: the dry run ends not run, saying so. */
26
+ export declare class SynthesisTooLarge extends Error {
27
+ name: string;
28
+ }
29
+ /** A value of `schema` (its `$ref`s read from `definitions`), synthesized within `budget` (SYNTHESIS_BUDGET when none):
30
+ * past it, SynthesisTooLarge. */
31
+ export declare function synthesizeInstance(schema: unknown, definitions?: Record<string, unknown>, depth?: number, budget?: Partial<SynthesisBudget>): unknown;
15
32
  export type DryRunOptions = {
16
33
  sop?: string;
17
34
  probeContext?: {
@@ -28,5 +45,18 @@ export type DryRunOptions = {
28
45
  * stops, as not run: synthetic answers can keep a loop going to its bound, and a map over a long list. 10,000 by
29
46
  * default. */
30
47
  maxSteps?: number;
48
+ /** What the whole dry run may synthesize (SynthesisBudget): its input and every step's answer together. Past it the dry
49
+ * run stops, as not run ("the schema is too large to synthesize"). SYNTHESIS_BUDGET by default. */
50
+ budget?: Partial<SynthesisBudget>;
51
+ /** The longest the dry run may take by the clock (ms): past it, it stops at its next node or step, as not run. Read
52
+ * from the clock at each, never from a timer, so a dry run that never yields still stops. 60,000 by default. */
53
+ deadlineMs?: number;
54
+ /** The most node visits (a loop's body each iteration, a map's body for each item, any node run), whether or not they
55
+ * ask anything, before the dry run stops, as not run: a loop whose body asks nothing is no step, so maxSteps alone
56
+ * never ends it. Ten times maxSteps by default. */
57
+ maxVisits?: number;
58
+ /** Handed the workflow's output when the dry run passed (on synthetic values): what a host holds to a shape of its own
59
+ * (the answer it serves) before it calls the draft good. The result keeps its shape either way. */
60
+ onOutput?: (output: unknown) => void;
31
61
  };
32
62
  export declare function dryRunWorkflow(workflow: Workflow, opts?: DryRunOptions): Promise<DryRunResult>;
package/dist/dry-run.js CHANGED
@@ -2,29 +2,75 @@ import { Compile } from "typebox/compile";
2
2
  import { runWorkflow, validateWorkflow, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError } from "./workflow.js";
3
3
  import { resolveSchemaForWorkflow } from "./schema-references.js";
4
4
  import { synthesizeAnswers } from "./system-one.js";
5
- export function synthesizeInstance(schema, definitions = {}, depth = 0) {
5
+ import { isRecord } from "./record.js";
6
+ /** A provider for every id the workflow names, and a default: the dry run answers each decision itself, so a node's
7
+ * provider and timeoutMs hold it to no host's providers. */
8
+ function syntheticProviders(workflow) {
9
+ const ids = new Set(["dry-run"]);
10
+ JSON.stringify(workflow, (key, value) => { if (key === "provider" && typeof value === "string")
11
+ ids.add(value); return value; });
12
+ const capabilities = { types: ["noul", "choice", "score", "box"], inputs: ["text", "json", "image", "pdf", "url"], evidence: "citations",
13
+ probability: "none", grounding: false, replay: "deduped", maxQuestions: null, maxStateBytes: null };
14
+ const provider = (id) => ({ id, needs: [], capabilities, decide: async () => { throw new Error("A dry run answers its decisions itself."); } });
15
+ return { providers: Object.fromEntries([...ids].map((id) => [id, provider(id)])), default: "dry-run" };
16
+ }
17
+ /** The default: a million values and 16 million characters, far past what a real workflow's dry run builds (a few
18
+ * thousand values at most), and well within a host's memory (a few hundred MB at worst). */
19
+ export const SYNTHESIS_BUDGET = { values: 1_000_000, chars: 16_000_000 };
20
+ /** The schema asked synthesis for more than its budget: the dry run ends not run, saying so. */
21
+ export class SynthesisTooLarge extends Error {
22
+ name = "SynthesisTooLarge";
23
+ }
24
+ /** A budget's limits, each field the default unless given as a number (a field given as undefined keeps the default). */
25
+ const spendOf = (limit = {}) => ({
26
+ values: 0,
27
+ chars: 0,
28
+ limit: { values: typeof limit.values === "number" ? limit.values : SYNTHESIS_BUDGET.values, chars: typeof limit.chars === "number" ? limit.chars : SYNTHESIS_BUDGET.chars },
29
+ });
30
+ /** A literal's characters as the value it is (a const, an enum's first): its serialized size. */
31
+ const literalChars = (value) => JSON.stringify(value)?.length ?? 0;
32
+ function charge(spend, values, chars) {
33
+ spend.values += values;
34
+ spend.chars += chars;
35
+ if (spend.values > spend.limit.values || spend.chars > spend.limit.chars) {
36
+ throw new SynthesisTooLarge(`the schema is too large to synthesize: past ${spend.limit.values} values or ${spend.limit.chars} characters`);
37
+ }
38
+ }
39
+ /** A value of `schema` (its `$ref`s read from `definitions`), synthesized within `budget` (SYNTHESIS_BUDGET when none):
40
+ * past it, SynthesisTooLarge. */
41
+ export function synthesizeInstance(schema, definitions = {}, depth = 0, budget = SYNTHESIS_BUDGET) {
42
+ return synthesize(schema, definitions, depth, spendOf(budget));
43
+ }
44
+ function synthesize(schema, definitions, depth, spend) {
45
+ // Every value it makes is counted before it is made, once (a $ref, an anyOf or a oneOf is the value it leads to, not one
46
+ // of its own): past the budget it throws, having built no more than the budget.
6
47
  if (depth > 12 || !schema || typeof schema !== "object")
7
- return null;
48
+ return (charge(spend, 1, 0), null);
8
49
  const spec = schema;
9
50
  if (typeof spec.$ref === "string") {
10
51
  const match = /^#\/definitions\/(.+)$/.exec(spec.$ref);
11
- return match && definitions[match[1]] ? synthesizeInstance(definitions[match[1]], definitions, depth + 1) : null;
52
+ return match && definitions[match[1]] ? synthesize(definitions[match[1]], definitions, depth + 1, spend) : (charge(spend, 1, 0), null);
12
53
  }
54
+ // A literal is charged its serialized size: one written long in the schema does not escape the character budget.
13
55
  if (spec.const !== undefined)
14
- return spec.const;
56
+ return (charge(spend, 1, literalChars(spec.const)), spec.const);
15
57
  if (Array.isArray(spec.enum) && spec.enum.length)
16
- return spec.enum[0];
58
+ return (charge(spend, 1, literalChars(spec.enum[0])), spec.enum[0]);
17
59
  if (Array.isArray(spec.anyOf) && spec.anyOf.length) {
18
60
  const branch = spec.anyOf.find((candidate) => candidate?.type !== "null") ?? spec.anyOf[0];
19
- return synthesizeInstance(branch, definitions, depth + 1);
61
+ return synthesize(branch, definitions, depth + 1, spend);
20
62
  }
21
63
  if (Array.isArray(spec.oneOf) && spec.oneOf.length)
22
- return synthesizeInstance(spec.oneOf[0], definitions, depth + 1);
64
+ return synthesize(spec.oneOf[0], definitions, depth + 1, spend);
65
+ // The one value made below.
66
+ charge(spend, 1, 0);
23
67
  const type = Array.isArray(spec.type) ? spec.type[0] : spec.type;
24
68
  if (type === "object" || (!type && spec.properties)) {
25
69
  const out = Object.create(null);
26
70
  for (const [key, property] of Object.entries(spec.properties || {})) {
27
- out[key] = synthesizeInstance(property, definitions, depth + 1);
71
+ // Its name is built into every value made under it, and serialized with it: charged before it is added.
72
+ charge(spend, 0, key.length);
73
+ out[key] = synthesize(property, definitions, depth + 1, spend);
28
74
  }
29
75
  return { ...out };
30
76
  }
@@ -34,12 +80,17 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
34
80
  const min = Number.isInteger(spec.minItems) ? spec.minItems : 1;
35
81
  if (!spec.items)
36
82
  return [];
37
- return Array.from({ length: Math.max(1, min) }, () => synthesizeInstance(spec.items, definitions, depth + 1));
83
+ // Each item is at least one value: a length past what the budget has left is refused before the array is made.
84
+ const length = Math.max(1, min);
85
+ if (length > spend.limit.values - spend.values)
86
+ charge(spend, length, 0);
87
+ return Array.from({ length }, () => synthesize(spec.items, definitions, depth + 1, spend));
38
88
  }
39
89
  if (type === "string") {
40
90
  if (spec.maxLength === 0)
41
91
  return "";
42
92
  const min = Number.isInteger(spec.minLength) ? spec.minLength : 1;
93
+ charge(spend, 0, Math.max(1, min));
43
94
  return "x".repeat(Math.max(1, min));
44
95
  }
45
96
  if (type === "integer") {
@@ -79,6 +130,8 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
79
130
  return false;
80
131
  if (type === "null")
81
132
  return null;
133
+ // A schema synthesis cannot read: one character.
134
+ charge(spend, 0, 1);
82
135
  return "x";
83
136
  }
84
137
  function unsupportedConstructs(schema, path, found, depth = 0) {
@@ -140,19 +193,29 @@ export async function dryRunWorkflow(workflow, opts = {}) {
140
193
  scanSchemas(workflow);
141
194
  if (skipped.length)
142
195
  return { ok: true, status: "not_run", skipped };
196
+ // One budget for everything this dry run synthesizes.
197
+ const spend = spendOf(opts.budget);
143
198
  let input = opts.input ?? {};
144
199
  if (opts.input === undefined && workflow.input) {
145
200
  const schema = resolveSchemaForWorkflow(workflow, workflow.schemas[workflow.input.schemaId]);
146
- const generated = synthesizeInstance(schema, schema.definitions ?? workflow.schemas);
147
- if (!generated || typeof generated !== "object" || Array.isArray(generated) || !Compile(schema).Check(generated)) {
201
+ let generated;
202
+ try {
203
+ generated = synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend);
204
+ }
205
+ catch (error) {
206
+ if (error instanceof SynthesisTooLarge)
207
+ return { ok: true, status: "not_run", skipped: [error.message] };
208
+ throw error;
209
+ }
210
+ if (!isRecord(generated) || !Compile(schema).Check(generated)) {
148
211
  return { ok: true, status: "not_run", skipped: ["Could not synthesize a valid input object. Supply input explicitly to dryRunWorkflow or the dry-run CLI."] };
149
212
  }
150
213
  input = generated;
151
214
  }
152
215
  if (opts.probeContext && !Object.prototype.hasOwnProperty.call(input, "context")) {
153
216
  input = { ...input, context: {
154
- references: opts.probeContext?.references ?? {},
155
- references_parsed: opts.probeContext?.references_parsed ?? {},
217
+ references: opts.probeContext.references ?? {},
218
+ references_parsed: opts.probeContext.references_parsed ?? {},
156
219
  } };
157
220
  }
158
221
  let currentLabel = "";
@@ -162,12 +225,43 @@ export async function dryRunWorkflow(workflow, opts = {}) {
162
225
  // Why the dry run stopped early, kept here: the interpreter may wrap what an adapter throws.
163
226
  let stopped;
164
227
  const stop = (reason) => { stopped ??= reason; throw new Error(stopped); };
228
+ /** A step's synthetic answer within the run's budget: past it, the dry run stops (the interpreter may wrap the throw). */
229
+ const synthesized = (make) => {
230
+ try {
231
+ return make();
232
+ }
233
+ catch (error) {
234
+ if (error instanceof SynthesisTooLarge)
235
+ stop(error.message);
236
+ throw error;
237
+ }
238
+ };
239
+ const deadlineMs = opts.deadlineMs ?? 60_000;
240
+ const deadline = Date.now() + deadlineMs;
241
+ const maxVisits = opts.maxVisits ?? maxSteps * 10;
242
+ let visits = 0;
243
+ const pastDeadline = () => {
244
+ if (Date.now() > deadline)
245
+ stop(`The dry run stopped past its ${deadlineMs} ms deadline.`);
246
+ };
247
+ /** A node's visit (a loop's body each iteration, a map's body for each item), counted against maxVisits and the
248
+ * deadline, so a loop whose body asks nothing (no step) still ends. Synchronous: it reads the clock, never a timer, so
249
+ * a run that never yields still stops. */
250
+ const visit = () => {
251
+ if (opts.signal?.aborted)
252
+ stop("The dry run was stopped before it finished.");
253
+ visits += 1;
254
+ if (visits > maxVisits)
255
+ stop(`The dry run stopped after ${maxVisits} node visits: on synthetic values the workflow's loops or maps go on further, asking nothing. Supply input, or lower a loop's maxIters.`);
256
+ pastDeadline();
257
+ };
165
258
  const step = async () => {
166
259
  if (opts.signal?.aborted)
167
260
  stop("The dry run was stopped before it finished.");
168
261
  steps += 1;
169
262
  if (steps > maxSteps)
170
263
  stop(`The dry run stopped after ${maxSteps} synthetic steps: on synthetic values the workflow's loops or maps go on further. Supply input, or lower a loop's maxIters.`);
264
+ pastDeadline();
171
265
  if (steps % 64 === 0) {
172
266
  await new Promise((resolve) => setTimeout(resolve, 0));
173
267
  if (opts.signal?.aborted)
@@ -177,30 +271,42 @@ export async function dryRunWorkflow(workflow, opts = {}) {
177
271
  const runCode = opts.runCode;
178
272
  try {
179
273
  const result = await runWorkflow(workflow, input, {
274
+ onVisit: () => visit(),
180
275
  sop: opts.sop,
181
276
  ...(runCode ? { runCode: async (...args) => { await step(); return runCode(...args); } } : {}),
182
277
  onEvent: (event) => { if (typeof event.label === "string")
183
278
  currentLabel = event.label; },
184
279
  runNode: async ({ schema, review }) => {
185
280
  await step();
186
- const candidate = synthesizeInstance(schema, schema.definitions ?? workflow.schemas);
281
+ const candidate = synthesized(() => synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend));
187
282
  if (review)
188
283
  await review(candidate);
189
284
  return candidate;
190
285
  },
191
- runJudge: async ({ questions }) => { await step(); return { answers: synthesizeAnswers(questions), model: "synthetic", usage: null, cost_usd: null, request_sha256: "" }; },
286
+ // A node that requires evidence gets a placeholder, as a provider that gives evidence would answer it.
287
+ runJudge: async ({ questions, evidence }) => {
288
+ await step();
289
+ // Its answers are synthetic values like any step's: each charged its serialized size against the run's budget (a
290
+ // choice's first option may be a long string, and a map collects one per item).
291
+ const answers = synthesizeAnswers(questions);
292
+ synthesized(() => charge(spend, Object.keys(answers).length, literalChars(answers)));
293
+ return { answers, model: "synthetic", usage: null, cost_usd: null, request_sha256: "",
294
+ ...(evidence === "required" ? { evidence: [{ url: "https://example.invalid/dry-run", title: null, excerpts: [], scope: "dry_run" }] } : {}) };
295
+ },
192
296
  syntheticEffects: true,
297
+ decisionProviders: syntheticProviders(workflow),
193
298
  runEffect: async ({ node, schema }) => {
194
299
  await step();
195
300
  return node.via === "shell"
196
301
  ? { code: 0, stdout: "{}", stderr: "", truncated: false }
197
- : synthesizeInstance(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {});
302
+ : synthesized(() => synthesize(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {}, 0, spend));
198
303
  },
199
304
  });
200
305
  if (result.status === "escalated") {
201
306
  // Synthetic values tripping an escalate predicate proves nothing about real cases.
202
307
  return { ok: true, status: "not_run", skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
203
308
  }
309
+ opts.onOutput?.(result.output);
204
310
  return { ok: true, status: "passed" };
205
311
  }
206
312
  catch (error) {
package/dist/edit.d.ts ADDED
@@ -0,0 +1,149 @@
1
+ /** A workflow document as JSON: an object whose `root` is a node. */
2
+ export type WorkflowDocument = Record<string, unknown>;
3
+ /** A node as JSON: an object whose `node` is its kind. */
4
+ export type WorkflowNodeJson = Record<string, unknown>;
5
+ /** Where a child sits under its parent node: the pointer segments from the parent to it. A chain's `steps` and a
6
+ * parallel's `branches` hold many, by index; a map's or a loop's `body`, a route branch's `branches/<name>/body` (the
7
+ * name pointer-escaped, as in a graph path) and a child workflow's `workflow/root` hold one. The document holds its
8
+ * root at `root`, under the parent path `""`. */
9
+ export type Slot = "root" | "steps" | "branches" | "body" | "workflow/root" | `branches/${string}/body`;
10
+ /** What an operation returns: the next document and what happened to the nodes of the one it was given. */
11
+ export type EditResult = {
12
+ doc: WorkflowDocument;
13
+ /** Each node whose path changed, from its path before to its path after, in the input's document order. */
14
+ moved: Map<string, string>;
15
+ /** The paths, in the result, of the nodes the input did not have. */
16
+ added: string[];
17
+ /** The paths, in the input, of the nodes the result does not have. */
18
+ removed: string[];
19
+ /** The paths, in the result, of the nodes that were kept with their own fields changed. */
20
+ changed: string[];
21
+ };
22
+ /** What rename returns: an EditResult, and the code and shell sources in scope that mention the old key. */
23
+ export type RenameResult = EditResult & {
24
+ mentions: string[];
25
+ };
26
+ /** What duplicate returns: an EditResult, and the paths, in the result, of the copy's code and shell sources that
27
+ * mention a key the copy writes under a fresh name, by its old name. */
28
+ export type DuplicateResult = EditResult & {
29
+ mentions: string[];
30
+ };
31
+ /** Every code an EditError carries. */
32
+ export declare const EDIT_ERROR_CODES: readonly ["DOCUMENT_INVALID", "PATH_NOT_FOUND", "SLOT_INVALID", "INDEX_OUT_OF_RANGE", "NODE_INVALID", "FIELD_INVALID", "NAME_INVALID", "NAME_TAKEN", "NAME_SHARED", "BRANCH_NOT_FOUND", "BRANCH_TAKEN", "BRANCH_IN_USE", "MOVE_INTO_SELF", "WRAP_INVALID", "UNWRAP_INVALID", "STRUCTURE_INVALID", "SCHEMA_NOT_FOUND", "SCHEMA_IN_USE", "SCHEMA_INVALID"];
33
+ export type EditErrorCode = typeof EDIT_ERROR_CODES[number];
34
+ /** The one error the operations throw. `path` is the node it is about, in the input document where that node existed
35
+ * there; `related` names other nodes the error is about: the one holding a taken name, the other writers of a key. */
36
+ export declare class EditError extends Error {
37
+ readonly code: EditErrorCode;
38
+ readonly path: string;
39
+ readonly related: readonly string[];
40
+ constructor(code: EditErrorCode, path: string, message: string, related?: readonly string[]);
41
+ }
42
+ /** The placeholder a required field takes in a new node: a value insert accepts and the validator flags until someone
43
+ * fills it in (an empty text, an empty state map, a predicate with no name, a deadline of 0 seconds), or, for a loop's
44
+ * `maxIters`, the smallest bound. placeholderNode and wrap fill fields from it. */
45
+ export declare const FIELD_PLACEHOLDERS: Readonly<Record<string, unknown>>;
46
+ /** The fields setField writes on this node: its kind's (and its route form's) own fields, without `node` and the child
47
+ * slots. A property panel lists these. */
48
+ export declare function editableFields(node: WorkflowNodeJson): string[];
49
+ /** The fields the schema requires of this node's kind (and its route form), `node` included. */
50
+ export declare function requiredFields(node: WorkflowNodeJson): string[];
51
+ /** Where the node at `path` sits: its parent's path, the slot it is in, and its index there (0 in a slot that holds one
52
+ * node). Undefined when no node sits there. */
53
+ export declare function locate(doc: WorkflowDocument, path: string): {
54
+ parentPath: string;
55
+ slot: Slot;
56
+ index: number;
57
+ } | undefined;
58
+ /** Put `node` (copied) into `slot` of the node at `parentPath`, at `index`. In a chain's steps or a parallel's branches
59
+ * the index is a position, 0 to the count. A slot that holds one node takes index 0 when empty; when it holds a node,
60
+ * 0 puts the new one first and 1 puts it last, in a new chain of the two. */
61
+ export declare function insert(doc: WorkflowDocument, parentPath: string, slot: Slot, index: number, node: WorkflowNodeJson): EditResult;
62
+ /** Take out the node at `path`, and everything inside it. */
63
+ export declare function remove(doc: WorkflowDocument, path: string): EditResult;
64
+ /** Move the node at `fromPath` into `slot` of the node at `toParentPath`, at `index`, counted in the document as given:
65
+ * the drop point a canvas shows. A node never moves inside itself. */
66
+ export declare function move(doc: WorkflowDocument, fromPath: string, toParentPath: string, slot: Slot, index: number): EditResult;
67
+ /** Put a copy of the node at `path` right after it: the next step or branch, or, in a slot that holds one node, the
68
+ * second step of a new chain. Every node of the copy gets a fresh label, every key it writes a fresh name, and its own
69
+ * references follow its keys; the copy's code and shell sources that mention an old key are listed in `mentions`. */
70
+ export declare function duplicate(doc: WorkflowDocument, path: string): DuplicateResult;
71
+ /** The containers wrap makes. */
72
+ export type WrapKind = "map" | "loop" | "route" | "parallel" | "chain";
73
+ /** Put the nodes at `paths` (one node, or consecutive steps or branches of one container, in any order) into a new
74
+ * container of `kind`, where the first of them was. A map's, loop's or route's body is the one node or a chain of
75
+ * them; a parallel takes each as a branch. The new container's fields are placeholders the validator flags. */
76
+ export declare function wrap(doc: WorkflowDocument, paths: readonly string[], kind: WrapKind): EditResult;
77
+ /** Put the children of the container at `path` where it was: a chain's steps or a parallel's branches, the body of a
78
+ * map or a loop, or the body of the route branch `branch` names. Into a chain they are spliced; a parallel's branches
79
+ * join an enclosing parallel; a slot that holds one node takes one child, or a chain of a parallel's branches. */
80
+ export declare function unwrap(doc: WorkflowDocument, path: string, branch?: string): EditResult;
81
+ /** Add a branch to the parallel or route at `path`: `node` (copied) last among a parallel's branches, or as the body of
82
+ * a new route branch `name`, after the others. */
83
+ export declare function addBranch(doc: WorkflowDocument, path: string, node: WorkflowNodeJson, name?: string): EditResult;
84
+ /** Take out a branch of the parallel or route at `path`: a parallel's by its index, a route's by its name. */
85
+ export declare function removeBranch(doc: WorkflowDocument, path: string, branch: string | number): EditResult;
86
+ /** Rename branch `from` of the route at `path` to `to`, in its place among the others; `otherwise` and `unsure` follow. */
87
+ export declare function renameBranch(doc: WorkflowDocument, path: string, from: string, to: string): EditResult;
88
+ /** Write `value` (copied) at the field of the node at `path`, in its place; `undefined` removes an optional field. */
89
+ export declare function setField(doc: WorkflowDocument, path: string, field: string, value: unknown): EditResult;
90
+ /** Rename the label of the node at `path`. When the label is the key the node writes (an agent, decide, extract or code
91
+ * node with no `as`), every reference in scope follows it, and the code and shell sources in scope that mention the old
92
+ * key are listed in `mentions`, unchanged: a code node's own code included, when it names the key. */
93
+ export declare function rename(doc: WorkflowDocument, path: string, name: string): RenameResult;
94
+ /** Which key renameKey renames: the node's `as` (the default), or a map's `failedAs`. */
95
+ export type RenameKeyOptions = {
96
+ field?: "as" | "failedAs";
97
+ };
98
+ /** Rename the state key the node at `path` writes: its `as` when it has one, else its label when the label is the key
99
+ * (an agent, decide, extract or code node with no `as`, where this is `rename`); or, with `field: "failedAs"`, the key a
100
+ * map writes its failed items under. Every reference in scope follows it, `<key>$answers` and `<key>$verify` included,
101
+ * and the code and shell sources in scope that mention the old key are listed in `mentions`, unchanged. */
102
+ export declare function renameKey(doc: WorkflowDocument, path: string, name: string, options?: RenameKeyOptions): RenameResult;
103
+ /** Write `criteria`, the text Jev reads to choose it, on branch `branch` of the judged route at `path`, in its place;
104
+ * `undefined` removes it. A route by value matches its branches by name and takes no criteria. */
105
+ export declare function setBranchCriteria(doc: WorkflowDocument, path: string, branch: string, criteria: string | undefined): EditResult;
106
+ /** The JSON Pointers of the values that name schema `id` of a scope ("" for the document, or a workflow node's path
107
+ * for its child's schemas): the workflow's `input.schemaId` and `output.schemaId`, a `$ref` from another of its
108
+ * schemas, and the `out` and `verify.out` of its nodes (a workflow node's `out` names its parent's schema). */
109
+ export declare function schemaUsers(doc: WorkflowDocument, id: string, scope?: string): string[];
110
+ /** Write `schema` (copied) as schema `id` of a scope ("" for the document, or a workflow node's path for its child), in
111
+ * its place when it exists; `undefined` removes it, unless something still names it (`schemaUsers`). */
112
+ export declare function setSchema(doc: WorkflowDocument, id: string, schema: Record<string, unknown> | undefined, scope?: string): EditResult;
113
+ /** A name a node may read, and what gives it: the path of the node that writes it, "input" (the workflow's input, or a
114
+ * child's), or "engine" (a map body's `item` and `item_index`). */
115
+ export type NameInScope = {
116
+ name: string;
117
+ from: string;
118
+ };
119
+ /** The names the node at `path` may read, each with what gives it, by the scope rules rename carries a key along: its
120
+ * workflow's input keys, a map body's `item` and `item_index`, and the keys (with their `<key>$answers` and
121
+ * `<key>$verify`) of each node whose write it runs after and sees. With `field`, the names that one field of the node
122
+ * reads, where it sees more than the rest: a map's `resultPath` its body's keys and item, a loop's `until` its body's
123
+ * keys, `verify` the node's own `as` and `submission`, a pick's or sift's `describe` its own `item` and `item_index`,
124
+ * and a workflow node's `workflow` (its child's `output.path`) the child's state. */
125
+ export declare function namesInScope(doc: WorkflowDocument, path: string, field?: string): NameInScope[];
126
+ /** A reference a node makes: the JSON Pointer of the value it sits in, the name it reads (the head of its path), and
127
+ * `optional` for a whole-string placeholder marked `?` (`"{plan?}"`), which the engine fills with null while unset. */
128
+ export type NodeRead = {
129
+ pointer: string;
130
+ name: string;
131
+ optional?: true;
132
+ };
133
+ /** Each `{placeholder}` and state path the node at `path` reads, in its fields' order: the references rename carries,
134
+ * found by the same walk. A workflow node's include its child's `output.path`, which reads the child's state. */
135
+ export declare function readsOf(doc: WorkflowDocument, path: string): NodeRead[];
136
+ /** The `{placeholder` open at `offset` in `text`: the index of its `{` and the name typed after it up to the cursor, by
137
+ * the placeholder grammar (letters, digits, "_", "." and "$"; a reference may start with `state.`). Undefined when no
138
+ * placeholder's name holds the cursor. The placeholder may already be closed after it. */
139
+ export declare function openPlaceholderAt(text: string, offset: number): {
140
+ start: number;
141
+ prefix: string;
142
+ } | undefined;
143
+ /** `base`, or its stem (`base` without a `_<n>` ending) with the smallest `_<n>` from 2, so that no label, key,
144
+ * reference, input key or word of code of any scope of the document holds it (a child workflow's that holds no node
145
+ * yet among them), nor an engine key or a name `Object.prototype` has. `base` is a state key name. */
146
+ export declare function freshName(doc: WorkflowDocument, base: string): string;
147
+ /** The smallest node of `kind` for `doc`: its required fields in the schema's order, a fresh name as its label (and its
148
+ * `as`, where it needs one), and each other field's placeholder. A container is made by wrapping nodes that exist. */
149
+ export declare function placeholderNode(doc: WorkflowDocument, kind: string): WorkflowNodeJson;