@parcha/agentrun-dsl 0.1.0-beta.41 → 0.1.0-beta.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/workflow.js CHANGED
@@ -2,7 +2,7 @@ import { observerSnapshot } from "./observer-snapshot.js";
2
2
  import { createHash } from "node:crypto";
3
3
  import { isDeepStrictEqual, types as utilTypes } from "node:util";
4
4
  import { predicateMatches, getPath, MECHANICAL_PREDICATE_NAMES, quoteCheck } from "./predicates.js";
5
- import { DECISION_NODE_FIELDS, DECISION_TIMEOUT_MAX_MS, GUARD_FIELDS, GUARD_SIGNALS, GUARDED_NODE_KINDS, SELF_CONFIDENCE_KINDS, WORKFLOW_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, WORKFLOW_PREDICATES, FIELD_TYPES, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES } from "./vocabulary.js";
5
+ import { DECISION_NODE_FIELDS, DECISION_TIMEOUT_MAX_MS, WORKFLOW_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, WORKFLOW_PREDICATES, FIELD_TYPES, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES } from "./vocabulary.js";
6
6
  import { validateAnswers, answerConfidence, answersSidecar, answersToValue, compileQuestions, refusedQuestions, SYSTEM_ONE_LIMITS } from "./system-one.js";
7
7
  import { chargedCost, DecisionProviderError } from "./decision-provider.js";
8
8
  import { DECISION_ERROR_MAX, DECISION_RECEIPT_VERSION, DECISION_INTERRUPTED, DECISION_REFUSED, DECISION_STATE_MAX_BYTES } from "./decision-receipts.js";
@@ -16,8 +16,6 @@ import { isRecoveryError } from "./recovery/errors.js";
16
16
  /** A request's error as its receipt keeps it: whole up to DECISION_ERROR_MAX characters, a longer one cut there and
17
17
  * marked, so a host redacts it before it cuts it and holds a cut one's tail back (decision-receipts.ts). */
18
18
  const errorOfReceipt = (text) => text.length > DECISION_ERROR_MAX ? { error: text.slice(0, DECISION_ERROR_MAX), error_truncated: true } : { error: text };
19
- /** The longest question a guard asks Jev, in characters. */
20
- export const GUARD_QUESTION_MAX = 2_000;
21
19
  export const routesByValue = (node) => typeof node.valuePath === "string";
22
20
  export function artifactNodeIsProse(node) {
23
21
  return PROSE_ARTIFACT_TYPES.includes(node.type);
@@ -872,58 +870,6 @@ export function validateWorkflow(workflow, opts) {
872
870
  return checkPredicate(pred.of, label, path, `${field}.of`, "not");
873
871
  return true;
874
872
  };
875
- /** A node's step guard (StepGuard), field by field, in words an author can act on: where it may sit, its signal (and
876
- * whether the node reports the confidence `self` reads), its threshold, its question and its fit. */
877
- const checkGuard = (node, path) => {
878
- if (node.guard === undefined)
879
- return;
880
- const at = `${path} (${node.label || node.node}): guard`;
881
- const bad = (message) => fail("NODE_FIELD_INVALID", ptrOf(path), `${at}${message}`);
882
- if (!GUARDED_NODE_KINDS.includes(node.node)) {
883
- fail("NODE_KEY_UNKNOWN", ptrOf(path), `${at}: a guard sits on a step that writes a value (${GUARDED_NODE_KINDS.join(", ")}); a ${node.node} node takes none`);
884
- return;
885
- }
886
- const guard = node.guard;
887
- if (!guard || typeof guard !== "object" || Array.isArray(guard)) {
888
- bad(` must be an object: {"signal": "self" | "jev" | "both", "threshold": a number between 0 and 1, "question"?: text, "fit"?: {...}}`);
889
- return;
890
- }
891
- const extra = Object.keys(guard).filter((key) => !GUARD_FIELDS.includes(key));
892
- if (extra.length)
893
- bad(`: unknown key(s) ${extra.join(", ")}; a guard takes ${GUARD_FIELDS.join(", ")}`);
894
- const signal = guard.signal;
895
- const known = GUARD_SIGNALS.includes(signal);
896
- if (!known)
897
- bad(`.signal must be "self", "jev" or "both" (got ${JSON.stringify(signal) ?? "none"})`);
898
- else if (signal !== "jev" && !SELF_CONFIDENCE_KINDS.includes(node.node))
899
- bad(`.signal "${signal}" reads the step's own confidence, which a ${node.node} node does not report (only ${SELF_CONFIDENCE_KINDS.join(", ")} nodes do); use "jev"`);
900
- else if (signal !== "jev" && (node.node === "agent" || node.node === "decide") && typeof node.out === "string" && Object.hasOwn(workflow.schemas ?? {}, node.out)) {
901
- const out = resolveSchemaForWorkflow(workflow, workflow.schemas[node.out]);
902
- if (!confidenceChannelOf(out))
903
- bad(`.signal "${signal}" has the node submit its confidence beside its record, so its out schema "${node.out}" must be an object schema`);
904
- }
905
- const threshold = guard.threshold;
906
- if (!(typeof threshold === "number" && Number.isFinite(threshold) && threshold > 0 && threshold < 1))
907
- bad(`.threshold must be a number between 0 and 1, exclusive: the chance the step is right below which the run hands the job back (got ${JSON.stringify(threshold) ?? "none"})`);
908
- if (guard.question !== undefined) {
909
- if (typeof guard.question !== "string" || !guard.question.trim())
910
- bad(`.question must be non-empty text: the yes/no question Jev is asked about the step's input and output`);
911
- else if (signal === "self")
912
- bad(`.question is Jev's; a "self" guard asks Jev nothing. Use "jev" or "both", or leave question out`);
913
- else if (guard.question.length > GUARD_QUESTION_MAX)
914
- bad(`.question is ${guard.question.length} characters; at most ${GUARD_QUESTION_MAX}`);
915
- }
916
- if (guard.fit !== undefined) {
917
- const fit = guard.fit;
918
- const width = signal === "both" ? 2 : 1;
919
- const finite = (n) => typeof n === "number" && Number.isFinite(n);
920
- const ok = fit && typeof fit === "object" && !Array.isArray(fit) && Array.isArray(fit.w) && fit.w.length === width && fit.w.every(finite) && finite(fit.b)
921
- && Number.isSafeInteger(fit.n) && fit.n >= 1 && typeof fit.fitted_at === "string" && !Number.isNaN(Date.parse(fit.fitted_at))
922
- && Object.keys(fit).every((key) => ["w", "b", "n", "fitted_at"].includes(key));
923
- if (!ok)
924
- bad(`.fit must be {"w": [${known ? (width === 2 ? "w_self, w_jev" : `w_${signal}`) : "one weight per signal"}], "b": a number, "n": the graded runs it was fitted on (an integer of at least 1), "fitted_at": an ISO 8601 time}`);
925
- }
926
- };
927
873
  const walk = (node, path, ptr) => {
928
874
  // A node that is missing (a map or loop without a body) is reported on the node that should hold it.
929
875
  pointers.set(path, node === undefined ? ptr.slice(0, ptr.lastIndexOf("/")) : ptr);
@@ -933,11 +879,9 @@ export function validateWorkflow(workflow, opts) {
933
879
  }
934
880
  {
935
881
  const allowed = KIND_KEYS[node.node];
936
- // A guard is checked on its own (checkGuard), with its own words where it may not sit.
937
- const extraneous = Object.keys(node).filter((key) => !allowed.has(key) && key !== "guard");
882
+ const extraneous = Object.keys(node).filter((key) => !allowed.has(key));
938
883
  if (extraneous.length)
939
884
  fail("NODE_KEY_UNKNOWN", ptrOf(path), `${path} (${node.label || node.node}): unknown key(s) for a ${node.node} node: ${extraneous.join(", ")}`);
940
- checkGuard(node, path);
941
885
  // State keys that hold a `$` are engine-owned (`$host`, and a typed question's `<as>$answers` and `<as>$verify`): no node
942
886
  // may write one, wherever the `$` is. A label is the state key whenever `as` is omitted, so labels are held to the same rule.
943
887
  if (typeof node.as === "string" && holdsDollar(node.as))
@@ -1592,11 +1536,28 @@ export function validateWorkflow(workflow, opts) {
1592
1536
  const warnings = workflowWarnings(workflow);
1593
1537
  return errors.length ? { ok: false, errors, issues, ...(warnings.length ? { warnings } : {}) } : { ok: true, ...(warnings.length ? { warnings } : {}) };
1594
1538
  }
1539
+ /** The value a `{path}` placeholder reads from state, in interpolation's lookup order: the path as written, else, for a
1540
+ * `state.` path, the path after `state.` (so `{state.x}` reads a real `state` key first). undefined when neither
1541
+ * resolves. Every placeholder the engine fills reads through it; a static check of what a step reads can too. */
1542
+ export function placeholderValue(state, path) {
1543
+ const v = getPath(state, path);
1544
+ return v === undefined && path.startsWith("state.") ? getPath(state, path.slice(6)) : v;
1545
+ }
1546
+ /** A whole-string placeholder, marked optional or not (interpolateValue keeps its value's type). */
1547
+ const WHOLE_PLACEHOLDER = /^\{([a-zA-Z0-9_.$]+)(\?)?\}$/;
1548
+ /** A placeholder inside a longer string: never marked (`{x?}` there is literal text). */
1549
+ const INNER_PLACEHOLDER = /\{([a-zA-Z0-9_.$]+)\}/g;
1550
+ /** The placeholders a state value's string holds, as interpolateValue fills them: a whole string is one, marked optional
1551
+ * (`"{draft?}"`) or not; inside a longer string only unmarked ones are. For a host check of what a step reads. */
1552
+ export function placeholdersOf(text) {
1553
+ const whole = WHOLE_PLACEHOLDER.exec(text);
1554
+ if (whole)
1555
+ return [{ path: whole[1], optional: !!whole[2] }];
1556
+ return [...text.matchAll(INNER_PLACEHOLDER)].map((match) => ({ path: match[1], optional: false }));
1557
+ }
1595
1558
  function interpolate(template, state) {
1596
- return template.replace(/\{([a-zA-Z0-9_.$]+)\}/g, (_, p) => {
1597
- let v = getPath(state, p);
1598
- if (v === undefined && p.startsWith("state."))
1599
- v = getPath(state, p.slice(6));
1559
+ return template.replace(INNER_PLACEHOLDER, (_, p) => {
1560
+ const v = placeholderValue(state, p);
1600
1561
  return v === undefined || v === null ? `(${p} unset)` : typeof v === "string" ? v : JSON.stringify(v);
1601
1562
  });
1602
1563
  }
@@ -1902,22 +1863,23 @@ function shapeFromSchema(schema) {
1902
1863
  return "";
1903
1864
  return Object.fromEntries(Object.entries(properties).map(([key, sub]) => [key, shapeFromSchema(sub)]));
1904
1865
  }
1866
+ /** `interpolateValue`: a whole-string placeholder keeps its value's type; one marked optional (`"{draft?}"`) is null while
1867
+ * its path is absent (a loop's first pass, before the step that writes it ran) instead of failing. Only a whole string
1868
+ * may be marked: inside a longer string `{draft?}` is literal text. */
1905
1869
  function interpolateValue(value, state, stage = "interpolation") {
1906
1870
  if (typeof value === "string") {
1907
- const whole = value.match(/^\{([a-zA-Z0-9_.$]+)\}$/);
1871
+ const whole = WHOLE_PLACEHOLDER.exec(value);
1908
1872
  if (whole) {
1909
1873
  const p = whole[1];
1910
- let v = getPath(state, p);
1911
- if (v === undefined && p.startsWith("state."))
1912
- v = getPath(state, p.slice(6));
1874
+ const v = placeholderValue(state, p);
1875
+ if (v === undefined && whole[2])
1876
+ return null;
1913
1877
  if (v === undefined)
1914
1878
  throw new WorkflowStateError(`interpolation path "${p}" is not present in the state`, stage, p, "missing_interpolation");
1915
1879
  return v;
1916
1880
  }
1917
- return value.replace(/\{([a-zA-Z0-9_.$]+)\}/g, (_, p) => {
1918
- let v = getPath(state, p);
1919
- if (v === undefined && p.startsWith("state."))
1920
- v = getPath(state, p.slice(6));
1881
+ return value.replace(INNER_PLACEHOLDER, (_, p) => {
1882
+ const v = placeholderValue(state, p);
1921
1883
  if (v === undefined)
1922
1884
  throw new WorkflowStateError(`interpolation path "${p}" is not present in the state`, stage, p, "missing_interpolation");
1923
1885
  return typeof v === "string" ? v : JSON.stringify(v);
@@ -2507,7 +2469,7 @@ async function runJudgeNode(node, state, workflow, deps) {
2507
2469
  return { ...state, [node.as]: value, [`${node.as}$answers`]: sidecar };
2508
2470
  }
2509
2471
  /** What a pick's judge is asked about `items`: each candidate described (`item_<i>`), beside its interpolated `state` (else
2510
- * the workflow's state as context). Its guard is asked about the same (guardInputOf). */
2472
+ * the workflow's state as context). */
2511
2473
  function pickAskOf(node, state, items, workflow) {
2512
2474
  const options = Object.fromEntries(items.map((item, i) => [`item_${i}`, describeItem(node.describe, state, item, i) || `item ${i}`]));
2513
2475
  return { options, asked: { ...(node.state ? interpolateValue(node.state, state, node.label) : { context: promptStateOf(state, workflow) }), candidates: options } };
@@ -2787,8 +2749,6 @@ function scopeDepsToChild(deps, invocation) {
2787
2749
  ...(deps.runNode ? { runNode: params => deps.runNode({ ...params, label: `${prefix}/${params.label}` }) } : {}),
2788
2750
  ...(deps.runEffect ? { runEffect: params => deps.runEffect({ ...params, node: relabel(params.node) }) } : {}),
2789
2751
  ...(deps.runJudge ? { runJudge: params => deps.runJudge({ ...params, label: `${prefix}/${params.label}` }) } : {}),
2790
- ...(deps.guardStep ? { guardStep: params => deps.guardStep({ ...params, label: `${prefix}/${params.label}` }) } : {}),
2791
- ...(deps.softEscalate ? { softEscalate: label => deps.softEscalate(`${prefix}/${label}`) } : {}),
2792
2752
  ...(deps.recordDecision ? { recordDecision: (receipt, exchange) => deps.recordDecision({ ...receipt, node: `${prefix}/${receipt.node}` }, { ...exchange, request: { ...exchange.request, label: `${prefix}/${exchange.request.label}` } }) } : {}),
2793
2753
  ...(deps.runCode ? { runCode: (node, state, ctx) => deps.runCode(relabel(node), state, { ...ctx, label: `${prefix}/${ctx.label}` }) } : {}),
2794
2754
  ...(recovery ? { recovery: {
@@ -2806,197 +2766,6 @@ function scopeDepsToChild(deps, invocation) {
2806
2766
  };
2807
2767
  }
2808
2768
  const STEP_KINDS = new Set(["agent", "decide", "extract", "report", "code", "call", "artifact", "workflow", "judge", "pick", "sift"]);
2809
- /** A node's step guard, as the document holds it (validateWorkflow refused any other shape). */
2810
- export function stepGuardOf(node) {
2811
- const guard = node.guard;
2812
- return guard && typeof guard === "object" && !Array.isArray(guard) ? guard : undefined;
2813
- }
2814
- /** Whether a guard reads the step's own confidence. */
2815
- const readsSelf = (guard) => guard.signal === "self" || guard.signal === "both";
2816
- /** The field an agent or decide node whose guard reads `self` submits its confidence in, beside its record. */
2817
- export const SELF_CONFIDENCE_FIELD = "confidence";
2818
- /** What the model is told the field holds. */
2819
- const SELF_CONFIDENCE_WORDS = "How sure you are that this submission is right for this input, from 0 (a guess) to 1 (certain): the probability it is correct.";
2820
- /** The engine-owned state key an agent or decide node's own confidence lands under, beside its value: `<key>$confidence`. */
2821
- export const confidenceKey = (key) => `${key}$confidence`;
2822
- /** The state key a step writes its value under: its `as`, or an unaliased agent, decide, extract or code node's label. */
2823
- const writeKeyOf = (node) => {
2824
- const { as, label } = node;
2825
- if (typeof as === "string" && as)
2826
- return as;
2827
- return ["agent", "decide", "extract", "code"].includes(node.node) && typeof label === "string" ? label : undefined;
2828
- };
2829
- /** An object out schema the confidence field can sit beside, widened with it (required), or as it is when it declares the
2830
- * field itself (then the node's own field is its confidence, kept in its value); undefined for a schema that is no object. */
2831
- function confidenceChannelOf(schema) {
2832
- const properties = schema.properties;
2833
- if (schema.type !== "object" && (!properties || typeof properties !== "object"))
2834
- return undefined;
2835
- if (declaresConfidence(schema))
2836
- return { schema, declared: true };
2837
- const field = { type: "number", minimum: 0, maximum: 1, description: SELF_CONFIDENCE_WORDS };
2838
- const required = Array.isArray(schema.required) ? schema.required : [];
2839
- const widened = withConfidenceInMembers(schema, field);
2840
- return {
2841
- schema: { ...widened, properties: { ...(properties ?? {}), [SELF_CONFIDENCE_FIELD]: field }, required: [...required, SELF_CONFIDENCE_FIELD] },
2842
- declared: false,
2843
- };
2844
- }
2845
- const COMPOSED = ["allOf", "anyOf", "oneOf"];
2846
- const membersOf = (schema) => COMPOSED.flatMap((key) => (Array.isArray(schema[key]) ? schema[key] : [])).filter((m) => Boolean(m) && typeof m === "object" && !Array.isArray(m));
2847
- /** Whether the schema, or a member of its allOf / anyOf / oneOf (at any depth), declares the confidence field itself. */
2848
- function declaresConfidence(schema) {
2849
- const properties = schema.properties;
2850
- if (properties && typeof properties === "object" && Object.hasOwn(properties, SELF_CONFIDENCE_FIELD))
2851
- return true;
2852
- return membersOf(schema).some(declaresConfidence);
2853
- }
2854
- /** The schema with the confidence field allowed in every allOf / anyOf / oneOf member (at any depth): a member that is
2855
- * closed (`additionalProperties` or `unevaluatedProperties` other than true) would otherwise refuse the field the root
2856
- * requires, and every submission with it. The field is never required in a member; the root requires it. */
2857
- function withConfidenceInMembers(schema, field) {
2858
- let out = schema;
2859
- for (const key of COMPOSED) {
2860
- const members = schema[key];
2861
- if (!Array.isArray(members))
2862
- continue;
2863
- out = { ...out, [key]: members.map((member) => {
2864
- if (!member || typeof member !== "object" || Array.isArray(member))
2865
- return member;
2866
- const inner = withConfidenceInMembers(member, field);
2867
- const own = inner.properties && typeof inner.properties === "object" ? inner.properties : {};
2868
- return { ...inner, properties: { ...own, [SELF_CONFIDENCE_FIELD]: field } };
2869
- }) };
2870
- }
2871
- return out;
2872
- }
2873
- /** A confidence as a guard reads it: a number in [0, 1], else none. */
2874
- const confidenceOf = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1 ? value : null);
2875
- /** The step's own confidence from its state once it ran: an agent or decide node's `<key>$confidence`, a judge or pick
2876
- * node's weakest answer's (`<as>$answers.min_confidence`), a sift's weakest over every item's answers (`<as>.answers[i]`,
2877
- * none when it was asked about no item, or one item's is missing). */
2878
- function selfConfidenceOf(node, out) {
2879
- const key = writeKeyOf(node);
2880
- if (!key)
2881
- return null;
2882
- if (node.node === "agent" || node.node === "decide")
2883
- return confidenceOf(out[confidenceKey(key)]);
2884
- if (node.node === "sift") {
2885
- const answers = out[key]?.answers;
2886
- if (!Array.isArray(answers) || !answers.length)
2887
- return null;
2888
- // A loop, not Math.min(...each): a sift may hold more items than a call takes arguments.
2889
- let weakest = 1;
2890
- for (const sidecar of answers) {
2891
- const confidence = confidenceOf(sidecar?.min_confidence);
2892
- if (confidence === null)
2893
- return null;
2894
- if (confidence < weakest)
2895
- weakest = confidence;
2896
- }
2897
- return weakest;
2898
- }
2899
- return confidenceOf(out[`${key}$answers`]?.min_confidence);
2900
- }
2901
- /** What a guarded step is asked about, for every node kind in one place: what it was asked to do (guardTaskOf), what it
2902
- * saw (guardInputOf) and what it wrote (guardOutputOf). */
2903
- function guardAskOf(node, before, after, workflow) {
2904
- return { task: guardTaskOf(node, workflow), input: guardInputOf(node, before, workflow), output: guardOutputOf(node, before, after) };
2905
- }
2906
- /** What a step was asked to do (GuardTask). The step ran, so its schemas resolve and its questions compile; should one
2907
- * not, the schema as the document holds it stands in. */
2908
- function guardTaskOf(node, workflow) {
2909
- const schemaOf = (id) => {
2910
- if (typeof id !== "string" || !Object.hasOwn(workflow.schemas, id))
2911
- return {};
2912
- try {
2913
- return { schema: resolveSchemaForWorkflow(workflow, workflow.schemas[id]) };
2914
- }
2915
- catch {
2916
- return { schema: workflow.schemas[id] };
2917
- }
2918
- };
2919
- switch (node.node) {
2920
- case "agent":
2921
- case "decide":
2922
- case "extract": return { instructions: node.instructions, ...schemaOf(node.out) };
2923
- case "pick": return { instructions: node.instructions, allow_none: node.allowNone === true };
2924
- case "judge":
2925
- case "sift":
2926
- try {
2927
- return { questions: questionSetOf(workflow, node).questions };
2928
- }
2929
- catch {
2930
- return schemaOf(node.out);
2931
- }
2932
- case "code": return { code: node.code };
2933
- case "call": {
2934
- const what = node.via === "tool" ? { tool: node.tool } : node.via === "executor" ? { code: node.code } : { command: node.command };
2935
- return { ...what, ...(node.via === "shell" ? {} : schemaOf(node.out)) };
2936
- }
2937
- case "workflow": return { workflow: node.workflow?.name, ...schemaOf(node.out) };
2938
- default: return {};
2939
- }
2940
- }
2941
- /** What a step saw, as its guard is asked about it: its interpolated `state`, a call's `args` (or an executor's `input`, a
2942
- * shell's `env`), a child's `input`; a pick's, what its judge chose among (its state, the candidates); a sift's, its
2943
- * state and the items its judge was asked about; else the workflow's state before it, as a generative node with no
2944
- * `state` sees it. */
2945
- function guardInputOf(node, state, workflow) {
2946
- try {
2947
- if (node.node === "call")
2948
- return interpolateValue(node.via === "tool" ? node.args ?? {} : node.via === "executor" ? node.input ?? {} : node.env ?? {}, state, node.label);
2949
- if (node.node === "workflow")
2950
- return interpolateValue(node.input, state, node.label);
2951
- if (node.node === "pick" || node.node === "sift") {
2952
- const items = getPath(state, node.itemsPath);
2953
- const list = Array.isArray(items) ? items : [];
2954
- if (node.node === "pick")
2955
- return pickAskOf(node, state, list, workflow).asked;
2956
- return { ...(node.state ? interpolateValue(node.state, state, node.label) : {}), items: siftItemsOf(node, state, list) };
2957
- }
2958
- const own = node.state;
2959
- if (own && typeof own === "object")
2960
- return interpolateValue(own, state, node.label);
2961
- }
2962
- catch { /* The step ran on it, so it resolves; should it not, the state it ran on stands in. */ }
2963
- return promptStateOf(state, workflow);
2964
- }
2965
- /** What a code node returned, by the state it produced: a code node with no `as` merges an object it returns, so its
2966
- * write key alone cannot say what it wrote. */
2967
- const codeWrote = new WeakMap();
2968
- /** What a step wrote, even when it equals what was there before: what a code node returned, else the value under its
2969
- * write key, else the keys it changed (none engine-owned). */
2970
- function guardOutputOf(node, before, after) {
2971
- const returned = node.node === "code" ? codeWrote.get(after) : undefined;
2972
- if (returned)
2973
- return returned.value;
2974
- const key = writeKeyOf(node);
2975
- if (key && Object.hasOwn(after, key))
2976
- return after[key];
2977
- return Object.fromEntries(Object.entries(after).filter(([name, value]) => !holdsDollar(name) && before[name] !== value));
2978
- }
2979
- /** A guarded step's check, once it ran: the host's guardStep gives p, and p below the guard's threshold (or no p at all)
2980
- * hands the job back, an escalation of kind `guard` at the step, with the state it reached. Every check is an event
2981
- * (`guard.evaluated`: signal, threshold, p, self, jev, escalated). */
2982
- async function checkStepGuard(node, guard, before, after, workflow, deps) {
2983
- const label = node.label;
2984
- if (!deps.guardStep)
2985
- throw new Error(`${node.node} node "${label}" requires guardStep`);
2986
- const self = readsSelf(guard) ? selfConfidenceOf(node, after) : null;
2987
- const item = deps[MAP_ITEM];
2988
- const verdict = await deps.guardStep({ label, kind: node.node, guard, ...guardAskOf(node, before, after, workflow), self, executionPath: executionPath(deps), ...(item ? { item } : {}), ...(deps.signal ? { signal: deps.signal } : {}) });
2989
- const p = typeof verdict?.p === "number" && Number.isFinite(verdict.p) ? Math.min(1, Math.max(0, verdict.p)) : null;
2990
- const jev = typeof verdict?.jev === "number" && Number.isFinite(verdict.jev) ? verdict.jev : null;
2991
- // No p is no evidence the step is right: it hands back, never passes.
2992
- const escalated = p === null || p < guard.threshold;
2993
- deps.onEvent?.({ type: "guard.evaluated", label, detail: { kind: node.node, signal: guard.signal, threshold: guard.threshold, p, self, jev, escalated } });
2994
- if (!escalated)
2995
- return;
2996
- const said = (n) => (n === null ? "none" : n.toFixed(2));
2997
- const why = guard.signal === "self" ? `its own confidence ${said(self)}` : guard.signal === "jev" ? `Jev's ${said(jev)}` : `its own confidence ${said(self)} and Jev's ${said(jev)}`;
2998
- throw new EscalationSignal({ kind: "guard", stage: label, summary: `its guard put the chance this step is right at ${said(p)} (${why}), under its threshold ${guard.threshold}`, state: after, label, executionPath: executionPath(deps) });
2999
- }
3000
2769
  const CHECKPOINTED_STRUCTURE_KINDS = new Set(["map", "parallel", "loop", "route"]);
3001
2770
  const guardedObservers = new WeakSet();
3002
2771
  function forwardObserver(observer, transform) {
@@ -3054,10 +2823,6 @@ async function runNodeOnState(node, state, workflow, deps) {
3054
2823
  let out = await runNodeBody(node, state, workflow, deps);
3055
2824
  if (deps.signal?.aborted)
3056
2825
  throw deps.signal.reason ?? new Error("workflow aborted");
3057
- // A guarded step's check, before anything of it is committed: one that hands back is never resumed as done.
3058
- const guard = isStep ? stepGuardOf(node) : undefined;
3059
- if (guard)
3060
- await checkStepGuard(node, guard, state, out, workflow, deps);
3061
2826
  // Host policy enrichment lands before commit and checkpoint: a resumed run sees exactly what ran.
3062
2827
  if (isStep && deps.hostPolicy?.afterNode) {
3063
2828
  const patch = deps.hostPolicy.afterNode({ ...hostContext(workflow, node, deps), state: out });
@@ -3121,152 +2886,6 @@ function withSiblingUncertainty(primary, uncertainties) {
3121
2886
  ? new AggregateError([primary, ...additional], "Workflow branches failed with uncertain effects; reconcile each effect before retrying", { cause: primary })
3122
2887
  : primary;
3123
2888
  }
3124
- const JUDGE_WROTE = new Set(["judge"]);
3125
- const OTHER_WROTE = new Set(["other"]);
3126
- const writersOf = (state, key) => state.get(key) ?? OTHER_WROTE;
3127
- /** The writers after any one of `states`: each key's writers on every one of them. */
3128
- function joinWriters(states) {
3129
- const out = new Map();
3130
- for (const key of new Set(states.flatMap((state) => [...state.keys()]))) {
3131
- const each = states.map((state) => writersOf(state, key));
3132
- out.set(key, each.every((writers) => writers === each[0]) ? each[0] : new Set(each.flatMap((writers) => [...writers])));
3133
- }
3134
- return out;
3135
- }
3136
- const sameWriters = (a, b) => a.size === b.size && [...a].every(([key, writers]) => { const other = b.get(key); return other !== undefined && other.size === writers.size && [...writers].every((w) => other.has(w)); });
3137
- /** Past this nesting, or this many passes over a loop's body, softEscalates reads every escalate as hard. */
3138
- const SOFT_WALK_DEPTH = 256;
3139
- const SOFT_WALK_PASSES = 16;
3140
- class SoftWalkTooDeep extends Error {
3141
- }
3142
- const docOf = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : undefined);
3143
- /** A node that writes its value under its `as`, else its label (mergeStageDelta, runCallNode, runPickNode, runSiftNode). */
3144
- const writesItsKey = (node, at) => at.wrote(typeof node.as === "string" && node.as !== "" ? node.as : node.label, OTHER_WROTE);
3145
- /** The state keys an `ask` predicate reads (evaluatePredicate): the head of each `{path}` its `state` and its `images`
3146
- * interpolate, both `state` and the key after it for a `{state.…}` reference (interpolateValue tries either). With no
3147
- * `state` it reads the whole state, the input with it: no key list, so none. */
3148
- function askHeads(ask) {
3149
- if (ask.state === undefined)
3150
- return [];
3151
- const heads = [];
3152
- // String values only, at any depth: interpolateValue replaces values, so an object key that looks like a reference is a literal.
3153
- const read = (value) => {
3154
- if (typeof value === "string") {
3155
- for (const m of value.matchAll(/\{([a-zA-Z0-9_.$]+)\}/g)) {
3156
- const [head, next] = m[1].split(".");
3157
- heads.push(head);
3158
- if (head === "state" && next)
3159
- heads.push(next);
3160
- }
3161
- }
3162
- else if (Array.isArray(value))
3163
- value.forEach(read);
3164
- else if (value && typeof value === "object")
3165
- Object.values(value).forEach(read);
3166
- };
3167
- read(ask.state);
3168
- read(ask.images);
3169
- return heads;
3170
- }
3171
- /** What each node kind writes to the state when runNodeBody (below) runs it: the writers of every key after the node runs
3172
- * from `at.state`. One entry per kind, so a new kind says here what it writes. A chain runs its steps in order; a route
3173
- * one branch, any of them, after its `as` (its choice); a parallel its branches each from the same state, a key one wrote
3174
- * taking that branch's writer; a loop its body once or more, each pass from the last's; a map its body per item on its
3175
- * own copy (with `item`, `item_index`), only its `as` (and `failedAs`) left after; a child workflow on its own state, only
3176
- * its `as` left after. A judge writes its `as` and `<as>$answers`; a code node with no `as` may write any key. */
3177
- const NODE_WRITES = {
3178
- chain: (node, at) => (Array.isArray(node.steps) ? node.steps : []).reduce((state, step) => at.walk(step, state), at.state),
3179
- route: (node, at) => {
3180
- const routed = at.wrote(node.as, OTHER_WROTE);
3181
- const bodies = docOf(node.branches) ? Object.values(node.branches).map((branch) => docOf(branch)?.body) : [];
3182
- return bodies.length ? joinWriters(bodies.map((body) => at.walk(body, routed))) : routed;
3183
- },
3184
- parallel: (node, at) => {
3185
- const outs = (Array.isArray(node.branches) ? node.branches : []).map((branch) => at.walk(branch, at.state));
3186
- const merged = new Map(at.state);
3187
- for (const key of new Set(outs.flatMap((out) => [...out.keys()]))) {
3188
- const writers = outs.filter((out) => out.get(key) !== at.state.get(key));
3189
- if (writers.length)
3190
- merged.set(key, joinWriters(writers).get(key));
3191
- }
3192
- return merged;
3193
- },
3194
- loop: (node, at) => {
3195
- let entry = at.state;
3196
- for (let pass = 0; pass < SOFT_WALK_PASSES; pass++) {
3197
- const out = at.walk(node.body, entry);
3198
- const next = joinWriters([at.state, out]);
3199
- if (sameWriters(next, entry))
3200
- return out;
3201
- entry = next;
3202
- }
3203
- throw new SoftWalkTooDeep();
3204
- },
3205
- map: (node, at) => {
3206
- at.walk(node.body, at.wrote("item_index", OTHER_WROTE, at.wrote("item", OTHER_WROTE)));
3207
- return at.wrote(node.failedAs, OTHER_WROTE, at.wrote(node.as, OTHER_WROTE));
3208
- },
3209
- workflow: (node, at) => {
3210
- at.walk(docOf(node.workflow)?.root, new Map(), typeof node.label === "string" ? `${at.prefix}${node.label}/` : at.prefix);
3211
- return at.wrote(node.as, OTHER_WROTE);
3212
- },
3213
- // A judge writes its `as` and the question's answers at `<as>$answers` (runJudgeNode): both are the judge's.
3214
- judge: (node, at) => at.wrote(node.as, JUDGE_WROTE, typeof node.as === "string" ? at.wrote(`${node.as}$answers`, JUDGE_WROTE) : at.state),
3215
- escalate: (node, at) => {
3216
- if (typeof node.label !== "string")
3217
- return at.state;
3218
- let when = docOf(node.when);
3219
- while (when?.predicate === "not")
3220
- when = docOf(when.of);
3221
- const heads = when?.predicate === "ask" ? askHeads(when) : typeof when?.path === "string" ? [when.path.split(".")[0]] : [];
3222
- at.escalate(node.label, heads.length > 0 && heads.every((head) => { const writers = writersOf(at.state, head); return writers.size === 1 && writers.has("judge"); }));
3223
- return at.state;
3224
- },
3225
- code: (node, at) => {
3226
- if (typeof node.as === "string" && node.as !== "")
3227
- return at.wrote(node.as, OTHER_WROTE);
3228
- return new Map([...at.state].map(([key, writers]) => [key, writers.has("other") ? writers : new Set([...writers, "other"])]));
3229
- },
3230
- report: (_node, at) => at.wrote("report_markdown", OTHER_WROTE),
3231
- artifact: (_node, at) => at.wrote("artifact", OTHER_WROTE),
3232
- agent: writesItsKey, decide: writesItsKey, extract: writesItsKey, pick: writesItsKey, sift: writesItsKey, call: writesItsKey,
3233
- };
3234
- /** The writers after `value` (a node of a workflow document) runs from `state` (NODE_WRITES). Each escalate's verdict
3235
- * lands in `verdicts`, false on any pass where it is not soft. */
3236
- function walkWriters(value, state, prefix, verdicts, depth) {
3237
- const node = docOf(value);
3238
- if (!node)
3239
- return state;
3240
- if (depth > SOFT_WALK_DEPTH)
3241
- throw new SoftWalkTooDeep();
3242
- const writes = Object.hasOwn(NODE_WRITES, node.node) ? NODE_WRITES[node.node] : writesItsKey;
3243
- return writes(node, {
3244
- state, prefix,
3245
- walk: (inner, from, at = prefix) => walkWriters(inner, from, at, verdicts, depth + 1),
3246
- wrote: (key, writers, from = state) => (typeof key === "string" && key !== "" ? new Map(from).set(key, writers) : from),
3247
- escalate: (label, soft) => { const name = `${prefix}${label}`; verdicts.set(name, (verdicts.get(name) ?? true) && soft); },
3248
- });
3249
- }
3250
- /** The escalate nodes of a workflow document that read a judge's output, by label as a run names its step (a child's
3251
- * `parent/child`, as WorkflowDeps.softEscalate is asked): each whose `when` (under any number of `not`s) reads a field a
3252
- * judge node wrote (an `ask` predicate: every key its `state` reads, and it reads at least one), the judge being the step that last wrote that path's head on every path a run can take to the
3253
- * escalate (a judge an extract overwrites, one in only some of a route's branches, one a code node with no `as` may have
3254
- * overwritten, are not). A judge's field is one model's opinion of a draft the workflow already wrote, so a host that
3255
- * measures the check may record it instead of obeying it (WorkflowDeps.softEscalate) and read the draft past it. A
3256
- * document too deep to walk, or whose loop's writes do not settle, has none. The document is read as it is: no
3257
- * validation, and a malformed node writes nothing it cannot name. */
3258
- export function softEscalates(doc) {
3259
- const verdicts = new Map();
3260
- try {
3261
- walkWriters(docOf(doc)?.root, new Map(), "", verdicts, 0);
3262
- }
3263
- catch (error) {
3264
- if (error instanceof SoftWalkTooDeep)
3265
- return new Set();
3266
- throw error;
3267
- }
3268
- return new Set([...verdicts].flatMap(([name, soft]) => (soft ? [name] : [])));
3269
- }
3270
2889
  async function runNodeBody(node, state, workflow, deps) {
3271
2890
  switch (node.node) {
3272
2891
  case "chain": {
@@ -3295,7 +2914,6 @@ async function runNodeBody(node, state, workflow, deps) {
3295
2914
  throw new WorkflowStateError(`code node "${node.label}" wrote the reserved "${HOST_STATE_KEY}" state key`, node.label, HOST_STATE_KEY, "reserved_state_key");
3296
2915
  deps.onEvent?.({ type: "code.patch", label: node.label, detail: patch });
3297
2916
  const next = { ...state, ...patch };
3298
- codeWrote.set(next, { value: out });
3299
2917
  return next;
3300
2918
  }
3301
2919
  case "agent":
@@ -3316,27 +2934,14 @@ async function runNodeBody(node, state, workflow, deps) {
3316
2934
  const policy = deps.hostPolicy;
3317
2935
  const context = policy ? hostContext(workflow, node, deps) : null;
3318
2936
  const hostSchema = policy?.submissionSchema && context ? policy.submissionSchema(schema, context) : schema;
3319
- // A guard that reads the node's own confidence (agent, decide): the node submits it beside its record, in the field
3320
- // SELF_CONFIDENCE_FIELD, split off before the stage schema sees the value (unless the stage schema declares it), and
3321
- // kept at `<key>$confidence`.
3322
- const guard = node.node === "agent" || node.node === "decide" ? stepGuardOf(node) : undefined;
3323
- const channel = guard && readsSelf(guard) ? confidenceChannelOf(hostSchema) : undefined;
3324
- const transportSchema = channel ? channel.schema : hostSchema;
2937
+ const transportSchema = hostSchema;
3325
2938
  const transportValidator = transportSchema === schema ? validator : Compile(transportSchema);
3326
2939
  const stageName = node.node === "report" ? "report" : node.out;
3327
- let confidence = null;
3328
2940
  const decode = (raw) => {
3329
2941
  normalizeStringNullsForSchema(raw, transportSchema);
3330
2942
  if (!transportValidator.Check(raw)) {
3331
2943
  throw new WorkflowOutputInvalidError(`${node.node} node "${node.label}" submission does not satisfy schema "${stageName}"`, schemaProblems(transportValidator, raw), node.label);
3332
2944
  }
3333
- if (channel && raw && typeof raw === "object" && !Array.isArray(raw)) {
3334
- confidence = confidenceOf(raw[SELF_CONFIDENCE_FIELD]);
3335
- if (!channel.declared) {
3336
- const { [SELF_CONFIDENCE_FIELD]: _confidence, ...rest } = raw;
3337
- raw = rest;
3338
- }
3339
- }
3340
2945
  const decoded = policy?.decodeSubmission && context ? policy.decodeSubmission(raw, { ...context, host: hostStateOf(state) }) : { value: raw };
3341
2946
  if (decoded !== null && typeof decoded === "object" && decoded.value !== raw)
3342
2947
  normalizeStringNullsForSchema(decoded.value, schema);
@@ -3384,8 +2989,6 @@ async function runNodeBody(node, state, workflow, deps) {
3384
2989
  let merged = mergeStageDelta(state, node, verified ? verified.submission : result, stageSchema);
3385
2990
  if (verified)
3386
2991
  merged = { ...merged, [`${("as" in node && node.as) || node.label}$verify`]: verified.record };
3387
- if (channel)
3388
- merged = { ...merged, [confidenceKey(writeKeyOf(node))]: confidence };
3389
2992
  const hostState = decoded.host && typeof decoded.host === "object" && !Array.isArray(decoded.host) ? decoded.host : null;
3390
2993
  if (hostState && Object.keys(hostState).length) {
3391
2994
  deps.onEvent?.({ type: "host.decoded", label: node.label, detail: { keys: Object.keys(hostState) } });
@@ -3635,9 +3238,8 @@ async function runNodeBody(node, state, workflow, deps) {
3635
3238
  const pathValue = node.when?.path
3636
3239
  ? String(node.when.path).split(".").reduce((acc, key) => (acc == null ? acc : acc[key]), state)
3637
3240
  : undefined;
3638
- const soft = deps.softEscalate?.(node.label) === true;
3639
- deps.onEvent?.({ type: "escalate.evaluated", label: node.label, detail: { fired, path: node.when?.path ?? null, path_resolved: pathValue !== undefined, ...(evaluated.detail ?? {}), ...(soft ? { soft: true } : {}) } });
3640
- if (fired && !soft) {
3241
+ deps.onEvent?.({ type: "escalate.evaluated", label: node.label, detail: { fired, path: node.when?.path ?? null, path_resolved: pathValue !== undefined, ...(evaluated.detail ?? {}) } });
3242
+ if (fired) {
3641
3243
  throw new EscalationSignal({ kind: node.kind, stage: node.stage, summary: interpolate(node.summary, state), state, label: node.label, executionPath: executionPath(deps) });
3642
3244
  }
3643
3245
  return state;
@@ -3832,8 +3434,6 @@ export function assertWorkflowCapabilities(node, deps, workflow) {
3832
3434
  node.node === "loop" && node.until?.predicate === "ask" ||
3833
3435
  node.node === "escalate" && node.when?.predicate === "ask") && !deps.runJudge)
3834
3436
  missing("runJudge");
3835
- if (stepGuardOf(node) && !deps.guardStep)
3836
- missing("guardStep");
3837
3437
  checkDecisionProviders(node, deps, workflow);
3838
3438
  // A store that cannot commit an item's failure would run the item again in the next process.
3839
3439
  if (node.node === "map" && node.onItemFailure === "collect" && deps.recovery && !(deps.recovery.failItem && deps.recovery.itemFailure))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-dsl",
3
- "version": "0.1.0-beta.41",
3
+ "version": "0.1.0-beta.43",
4
4
  "description": "Composable, typed workflows for agents",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",