@parcha/agentrun-dsl 0.1.0-beta.42 → 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))
@@ -2525,7 +2469,7 @@ async function runJudgeNode(node, state, workflow, deps) {
2525
2469
  return { ...state, [node.as]: value, [`${node.as}$answers`]: sidecar };
2526
2470
  }
2527
2471
  /** What a pick's judge is asked about `items`: each candidate described (`item_<i>`), beside its interpolated `state` (else
2528
- * the workflow's state as context). Its guard is asked about the same (guardInputOf). */
2472
+ * the workflow's state as context). */
2529
2473
  function pickAskOf(node, state, items, workflow) {
2530
2474
  const options = Object.fromEntries(items.map((item, i) => [`item_${i}`, describeItem(node.describe, state, item, i) || `item ${i}`]));
2531
2475
  return { options, asked: { ...(node.state ? interpolateValue(node.state, state, node.label) : { context: promptStateOf(state, workflow) }), candidates: options } };
@@ -2805,8 +2749,6 @@ function scopeDepsToChild(deps, invocation) {
2805
2749
  ...(deps.runNode ? { runNode: params => deps.runNode({ ...params, label: `${prefix}/${params.label}` }) } : {}),
2806
2750
  ...(deps.runEffect ? { runEffect: params => deps.runEffect({ ...params, node: relabel(params.node) }) } : {}),
2807
2751
  ...(deps.runJudge ? { runJudge: params => deps.runJudge({ ...params, label: `${prefix}/${params.label}` }) } : {}),
2808
- ...(deps.guardStep ? { guardStep: params => deps.guardStep({ ...params, label: `${prefix}/${params.label}` }) } : {}),
2809
- ...(deps.softEscalate ? { softEscalate: label => deps.softEscalate(`${prefix}/${label}`) } : {}),
2810
2752
  ...(deps.recordDecision ? { recordDecision: (receipt, exchange) => deps.recordDecision({ ...receipt, node: `${prefix}/${receipt.node}` }, { ...exchange, request: { ...exchange.request, label: `${prefix}/${exchange.request.label}` } }) } : {}),
2811
2753
  ...(deps.runCode ? { runCode: (node, state, ctx) => deps.runCode(relabel(node), state, { ...ctx, label: `${prefix}/${ctx.label}` }) } : {}),
2812
2754
  ...(recovery ? { recovery: {
@@ -2824,197 +2766,6 @@ function scopeDepsToChild(deps, invocation) {
2824
2766
  };
2825
2767
  }
2826
2768
  const STEP_KINDS = new Set(["agent", "decide", "extract", "report", "code", "call", "artifact", "workflow", "judge", "pick", "sift"]);
2827
- /** A node's step guard, as the document holds it (validateWorkflow refused any other shape). */
2828
- export function stepGuardOf(node) {
2829
- const guard = node.guard;
2830
- return guard && typeof guard === "object" && !Array.isArray(guard) ? guard : undefined;
2831
- }
2832
- /** Whether a guard reads the step's own confidence. */
2833
- const readsSelf = (guard) => guard.signal === "self" || guard.signal === "both";
2834
- /** The field an agent or decide node whose guard reads `self` submits its confidence in, beside its record. */
2835
- export const SELF_CONFIDENCE_FIELD = "confidence";
2836
- /** What the model is told the field holds. */
2837
- 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.";
2838
- /** The engine-owned state key an agent or decide node's own confidence lands under, beside its value: `<key>$confidence`. */
2839
- export const confidenceKey = (key) => `${key}$confidence`;
2840
- /** The state key a step writes its value under: its `as`, or an unaliased agent, decide, extract or code node's label. */
2841
- const writeKeyOf = (node) => {
2842
- const { as, label } = node;
2843
- if (typeof as === "string" && as)
2844
- return as;
2845
- return ["agent", "decide", "extract", "code"].includes(node.node) && typeof label === "string" ? label : undefined;
2846
- };
2847
- /** An object out schema the confidence field can sit beside, widened with it (required), or as it is when it declares the
2848
- * field itself (then the node's own field is its confidence, kept in its value); undefined for a schema that is no object. */
2849
- function confidenceChannelOf(schema) {
2850
- const properties = schema.properties;
2851
- if (schema.type !== "object" && (!properties || typeof properties !== "object"))
2852
- return undefined;
2853
- if (declaresConfidence(schema))
2854
- return { schema, declared: true };
2855
- const field = { type: "number", minimum: 0, maximum: 1, description: SELF_CONFIDENCE_WORDS };
2856
- const required = Array.isArray(schema.required) ? schema.required : [];
2857
- const widened = withConfidenceInMembers(schema, field);
2858
- return {
2859
- schema: { ...widened, properties: { ...(properties ?? {}), [SELF_CONFIDENCE_FIELD]: field }, required: [...required, SELF_CONFIDENCE_FIELD] },
2860
- declared: false,
2861
- };
2862
- }
2863
- const COMPOSED = ["allOf", "anyOf", "oneOf"];
2864
- const membersOf = (schema) => COMPOSED.flatMap((key) => (Array.isArray(schema[key]) ? schema[key] : [])).filter((m) => Boolean(m) && typeof m === "object" && !Array.isArray(m));
2865
- /** Whether the schema, or a member of its allOf / anyOf / oneOf (at any depth), declares the confidence field itself. */
2866
- function declaresConfidence(schema) {
2867
- const properties = schema.properties;
2868
- if (properties && typeof properties === "object" && Object.hasOwn(properties, SELF_CONFIDENCE_FIELD))
2869
- return true;
2870
- return membersOf(schema).some(declaresConfidence);
2871
- }
2872
- /** The schema with the confidence field allowed in every allOf / anyOf / oneOf member (at any depth): a member that is
2873
- * closed (`additionalProperties` or `unevaluatedProperties` other than true) would otherwise refuse the field the root
2874
- * requires, and every submission with it. The field is never required in a member; the root requires it. */
2875
- function withConfidenceInMembers(schema, field) {
2876
- let out = schema;
2877
- for (const key of COMPOSED) {
2878
- const members = schema[key];
2879
- if (!Array.isArray(members))
2880
- continue;
2881
- out = { ...out, [key]: members.map((member) => {
2882
- if (!member || typeof member !== "object" || Array.isArray(member))
2883
- return member;
2884
- const inner = withConfidenceInMembers(member, field);
2885
- const own = inner.properties && typeof inner.properties === "object" ? inner.properties : {};
2886
- return { ...inner, properties: { ...own, [SELF_CONFIDENCE_FIELD]: field } };
2887
- }) };
2888
- }
2889
- return out;
2890
- }
2891
- /** A confidence as a guard reads it: a number in [0, 1], else none. */
2892
- const confidenceOf = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1 ? value : null);
2893
- /** The step's own confidence from its state once it ran: an agent or decide node's `<key>$confidence`, a judge or pick
2894
- * node's weakest answer's (`<as>$answers.min_confidence`), a sift's weakest over every item's answers (`<as>.answers[i]`,
2895
- * none when it was asked about no item, or one item's is missing). */
2896
- function selfConfidenceOf(node, out) {
2897
- const key = writeKeyOf(node);
2898
- if (!key)
2899
- return null;
2900
- if (node.node === "agent" || node.node === "decide")
2901
- return confidenceOf(out[confidenceKey(key)]);
2902
- if (node.node === "sift") {
2903
- const answers = out[key]?.answers;
2904
- if (!Array.isArray(answers) || !answers.length)
2905
- return null;
2906
- // A loop, not Math.min(...each): a sift may hold more items than a call takes arguments.
2907
- let weakest = 1;
2908
- for (const sidecar of answers) {
2909
- const confidence = confidenceOf(sidecar?.min_confidence);
2910
- if (confidence === null)
2911
- return null;
2912
- if (confidence < weakest)
2913
- weakest = confidence;
2914
- }
2915
- return weakest;
2916
- }
2917
- return confidenceOf(out[`${key}$answers`]?.min_confidence);
2918
- }
2919
- /** What a guarded step is asked about, for every node kind in one place: what it was asked to do (guardTaskOf), what it
2920
- * saw (guardInputOf) and what it wrote (guardOutputOf). */
2921
- function guardAskOf(node, before, after, workflow) {
2922
- return { task: guardTaskOf(node, workflow), input: guardInputOf(node, before, workflow), output: guardOutputOf(node, before, after) };
2923
- }
2924
- /** What a step was asked to do (GuardTask). The step ran, so its schemas resolve and its questions compile; should one
2925
- * not, the schema as the document holds it stands in. */
2926
- function guardTaskOf(node, workflow) {
2927
- const schemaOf = (id) => {
2928
- if (typeof id !== "string" || !Object.hasOwn(workflow.schemas, id))
2929
- return {};
2930
- try {
2931
- return { schema: resolveSchemaForWorkflow(workflow, workflow.schemas[id]) };
2932
- }
2933
- catch {
2934
- return { schema: workflow.schemas[id] };
2935
- }
2936
- };
2937
- switch (node.node) {
2938
- case "agent":
2939
- case "decide":
2940
- case "extract": return { instructions: node.instructions, ...schemaOf(node.out) };
2941
- case "pick": return { instructions: node.instructions, allow_none: node.allowNone === true };
2942
- case "judge":
2943
- case "sift":
2944
- try {
2945
- return { questions: questionSetOf(workflow, node).questions };
2946
- }
2947
- catch {
2948
- return schemaOf(node.out);
2949
- }
2950
- case "code": return { code: node.code };
2951
- case "call": {
2952
- const what = node.via === "tool" ? { tool: node.tool } : node.via === "executor" ? { code: node.code } : { command: node.command };
2953
- return { ...what, ...(node.via === "shell" ? {} : schemaOf(node.out)) };
2954
- }
2955
- case "workflow": return { workflow: node.workflow?.name, ...schemaOf(node.out) };
2956
- default: return {};
2957
- }
2958
- }
2959
- /** What a step saw, as its guard is asked about it: its interpolated `state`, a call's `args` (or an executor's `input`, a
2960
- * shell's `env`), a child's `input`; a pick's, what its judge chose among (its state, the candidates); a sift's, its
2961
- * state and the items its judge was asked about; else the workflow's state before it, as a generative node with no
2962
- * `state` sees it. */
2963
- function guardInputOf(node, state, workflow) {
2964
- try {
2965
- if (node.node === "call")
2966
- return interpolateValue(node.via === "tool" ? node.args ?? {} : node.via === "executor" ? node.input ?? {} : node.env ?? {}, state, node.label);
2967
- if (node.node === "workflow")
2968
- return interpolateValue(node.input, state, node.label);
2969
- if (node.node === "pick" || node.node === "sift") {
2970
- const items = getPath(state, node.itemsPath);
2971
- const list = Array.isArray(items) ? items : [];
2972
- if (node.node === "pick")
2973
- return pickAskOf(node, state, list, workflow).asked;
2974
- return { ...(node.state ? interpolateValue(node.state, state, node.label) : {}), items: siftItemsOf(node, state, list) };
2975
- }
2976
- const own = node.state;
2977
- if (own && typeof own === "object")
2978
- return interpolateValue(own, state, node.label);
2979
- }
2980
- catch { /* The step ran on it, so it resolves; should it not, the state it ran on stands in. */ }
2981
- return promptStateOf(state, workflow);
2982
- }
2983
- /** What a code node returned, by the state it produced: a code node with no `as` merges an object it returns, so its
2984
- * write key alone cannot say what it wrote. */
2985
- const codeWrote = new WeakMap();
2986
- /** What a step wrote, even when it equals what was there before: what a code node returned, else the value under its
2987
- * write key, else the keys it changed (none engine-owned). */
2988
- function guardOutputOf(node, before, after) {
2989
- const returned = node.node === "code" ? codeWrote.get(after) : undefined;
2990
- if (returned)
2991
- return returned.value;
2992
- const key = writeKeyOf(node);
2993
- if (key && Object.hasOwn(after, key))
2994
- return after[key];
2995
- return Object.fromEntries(Object.entries(after).filter(([name, value]) => !holdsDollar(name) && before[name] !== value));
2996
- }
2997
- /** 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)
2998
- * hands the job back, an escalation of kind `guard` at the step, with the state it reached. Every check is an event
2999
- * (`guard.evaluated`: signal, threshold, p, self, jev, escalated). */
3000
- async function checkStepGuard(node, guard, before, after, workflow, deps) {
3001
- const label = node.label;
3002
- if (!deps.guardStep)
3003
- throw new Error(`${node.node} node "${label}" requires guardStep`);
3004
- const self = readsSelf(guard) ? selfConfidenceOf(node, after) : null;
3005
- const item = deps[MAP_ITEM];
3006
- 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 } : {}) });
3007
- const p = typeof verdict?.p === "number" && Number.isFinite(verdict.p) ? Math.min(1, Math.max(0, verdict.p)) : null;
3008
- const jev = typeof verdict?.jev === "number" && Number.isFinite(verdict.jev) ? verdict.jev : null;
3009
- // No p is no evidence the step is right: it hands back, never passes.
3010
- const escalated = p === null || p < guard.threshold;
3011
- deps.onEvent?.({ type: "guard.evaluated", label, detail: { kind: node.node, signal: guard.signal, threshold: guard.threshold, p, self, jev, escalated } });
3012
- if (!escalated)
3013
- return;
3014
- const said = (n) => (n === null ? "none" : n.toFixed(2));
3015
- 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)}`;
3016
- 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) });
3017
- }
3018
2769
  const CHECKPOINTED_STRUCTURE_KINDS = new Set(["map", "parallel", "loop", "route"]);
3019
2770
  const guardedObservers = new WeakSet();
3020
2771
  function forwardObserver(observer, transform) {
@@ -3072,10 +2823,6 @@ async function runNodeOnState(node, state, workflow, deps) {
3072
2823
  let out = await runNodeBody(node, state, workflow, deps);
3073
2824
  if (deps.signal?.aborted)
3074
2825
  throw deps.signal.reason ?? new Error("workflow aborted");
3075
- // A guarded step's check, before anything of it is committed: one that hands back is never resumed as done.
3076
- const guard = isStep ? stepGuardOf(node) : undefined;
3077
- if (guard)
3078
- await checkStepGuard(node, guard, state, out, workflow, deps);
3079
2826
  // Host policy enrichment lands before commit and checkpoint: a resumed run sees exactly what ran.
3080
2827
  if (isStep && deps.hostPolicy?.afterNode) {
3081
2828
  const patch = deps.hostPolicy.afterNode({ ...hostContext(workflow, node, deps), state: out });
@@ -3139,152 +2886,6 @@ function withSiblingUncertainty(primary, uncertainties) {
3139
2886
  ? new AggregateError([primary, ...additional], "Workflow branches failed with uncertain effects; reconcile each effect before retrying", { cause: primary })
3140
2887
  : primary;
3141
2888
  }
3142
- const JUDGE_WROTE = new Set(["judge"]);
3143
- const OTHER_WROTE = new Set(["other"]);
3144
- const writersOf = (state, key) => state.get(key) ?? OTHER_WROTE;
3145
- /** The writers after any one of `states`: each key's writers on every one of them. */
3146
- function joinWriters(states) {
3147
- const out = new Map();
3148
- for (const key of new Set(states.flatMap((state) => [...state.keys()]))) {
3149
- const each = states.map((state) => writersOf(state, key));
3150
- out.set(key, each.every((writers) => writers === each[0]) ? each[0] : new Set(each.flatMap((writers) => [...writers])));
3151
- }
3152
- return out;
3153
- }
3154
- 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)); });
3155
- /** Past this nesting, or this many passes over a loop's body, softEscalates reads every escalate as hard. */
3156
- const SOFT_WALK_DEPTH = 256;
3157
- const SOFT_WALK_PASSES = 16;
3158
- class SoftWalkTooDeep extends Error {
3159
- }
3160
- const docOf = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : undefined);
3161
- /** A node that writes its value under its `as`, else its label (mergeStageDelta, runCallNode, runPickNode, runSiftNode). */
3162
- const writesItsKey = (node, at) => at.wrote(typeof node.as === "string" && node.as !== "" ? node.as : node.label, OTHER_WROTE);
3163
- /** The state keys an `ask` predicate reads (evaluatePredicate): the head of each `{path}` its `state` and its `images`
3164
- * interpolate, both `state` and the key after it for a `{state.…}` reference (interpolateValue tries either). With no
3165
- * `state` it reads the whole state, the input with it: no key list, so none. */
3166
- function askHeads(ask) {
3167
- if (ask.state === undefined)
3168
- return [];
3169
- const heads = [];
3170
- // String values only, at any depth: interpolateValue replaces values, so an object key that looks like a reference is a literal.
3171
- const read = (value) => {
3172
- if (typeof value === "string") {
3173
- for (const m of value.matchAll(/\{([a-zA-Z0-9_.$]+)\}/g)) {
3174
- const [head, next] = m[1].split(".");
3175
- heads.push(head);
3176
- if (head === "state" && next)
3177
- heads.push(next);
3178
- }
3179
- }
3180
- else if (Array.isArray(value))
3181
- value.forEach(read);
3182
- else if (value && typeof value === "object")
3183
- Object.values(value).forEach(read);
3184
- };
3185
- read(ask.state);
3186
- read(ask.images);
3187
- return heads;
3188
- }
3189
- /** What each node kind writes to the state when runNodeBody (below) runs it: the writers of every key after the node runs
3190
- * 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
3191
- * one branch, any of them, after its `as` (its choice); a parallel its branches each from the same state, a key one wrote
3192
- * 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
3193
- * own copy (with `item`, `item_index`), only its `as` (and `failedAs`) left after; a child workflow on its own state, only
3194
- * its `as` left after. A judge writes its `as` and `<as>$answers`; a code node with no `as` may write any key. */
3195
- const NODE_WRITES = {
3196
- chain: (node, at) => (Array.isArray(node.steps) ? node.steps : []).reduce((state, step) => at.walk(step, state), at.state),
3197
- route: (node, at) => {
3198
- const routed = at.wrote(node.as, OTHER_WROTE);
3199
- const bodies = docOf(node.branches) ? Object.values(node.branches).map((branch) => docOf(branch)?.body) : [];
3200
- return bodies.length ? joinWriters(bodies.map((body) => at.walk(body, routed))) : routed;
3201
- },
3202
- parallel: (node, at) => {
3203
- const outs = (Array.isArray(node.branches) ? node.branches : []).map((branch) => at.walk(branch, at.state));
3204
- const merged = new Map(at.state);
3205
- for (const key of new Set(outs.flatMap((out) => [...out.keys()]))) {
3206
- const writers = outs.filter((out) => out.get(key) !== at.state.get(key));
3207
- if (writers.length)
3208
- merged.set(key, joinWriters(writers).get(key));
3209
- }
3210
- return merged;
3211
- },
3212
- loop: (node, at) => {
3213
- let entry = at.state;
3214
- for (let pass = 0; pass < SOFT_WALK_PASSES; pass++) {
3215
- const out = at.walk(node.body, entry);
3216
- const next = joinWriters([at.state, out]);
3217
- if (sameWriters(next, entry))
3218
- return out;
3219
- entry = next;
3220
- }
3221
- throw new SoftWalkTooDeep();
3222
- },
3223
- map: (node, at) => {
3224
- at.walk(node.body, at.wrote("item_index", OTHER_WROTE, at.wrote("item", OTHER_WROTE)));
3225
- return at.wrote(node.failedAs, OTHER_WROTE, at.wrote(node.as, OTHER_WROTE));
3226
- },
3227
- workflow: (node, at) => {
3228
- at.walk(docOf(node.workflow)?.root, new Map(), typeof node.label === "string" ? `${at.prefix}${node.label}/` : at.prefix);
3229
- return at.wrote(node.as, OTHER_WROTE);
3230
- },
3231
- // A judge writes its `as` and the question's answers at `<as>$answers` (runJudgeNode): both are the judge's.
3232
- judge: (node, at) => at.wrote(node.as, JUDGE_WROTE, typeof node.as === "string" ? at.wrote(`${node.as}$answers`, JUDGE_WROTE) : at.state),
3233
- escalate: (node, at) => {
3234
- if (typeof node.label !== "string")
3235
- return at.state;
3236
- let when = docOf(node.when);
3237
- while (when?.predicate === "not")
3238
- when = docOf(when.of);
3239
- const heads = when?.predicate === "ask" ? askHeads(when) : typeof when?.path === "string" ? [when.path.split(".")[0]] : [];
3240
- at.escalate(node.label, heads.length > 0 && heads.every((head) => { const writers = writersOf(at.state, head); return writers.size === 1 && writers.has("judge"); }));
3241
- return at.state;
3242
- },
3243
- code: (node, at) => {
3244
- if (typeof node.as === "string" && node.as !== "")
3245
- return at.wrote(node.as, OTHER_WROTE);
3246
- return new Map([...at.state].map(([key, writers]) => [key, writers.has("other") ? writers : new Set([...writers, "other"])]));
3247
- },
3248
- report: (_node, at) => at.wrote("report_markdown", OTHER_WROTE),
3249
- artifact: (_node, at) => at.wrote("artifact", OTHER_WROTE),
3250
- agent: writesItsKey, decide: writesItsKey, extract: writesItsKey, pick: writesItsKey, sift: writesItsKey, call: writesItsKey,
3251
- };
3252
- /** The writers after `value` (a node of a workflow document) runs from `state` (NODE_WRITES). Each escalate's verdict
3253
- * lands in `verdicts`, false on any pass where it is not soft. */
3254
- function walkWriters(value, state, prefix, verdicts, depth) {
3255
- const node = docOf(value);
3256
- if (!node)
3257
- return state;
3258
- if (depth > SOFT_WALK_DEPTH)
3259
- throw new SoftWalkTooDeep();
3260
- const writes = Object.hasOwn(NODE_WRITES, node.node) ? NODE_WRITES[node.node] : writesItsKey;
3261
- return writes(node, {
3262
- state, prefix,
3263
- walk: (inner, from, at = prefix) => walkWriters(inner, from, at, verdicts, depth + 1),
3264
- wrote: (key, writers, from = state) => (typeof key === "string" && key !== "" ? new Map(from).set(key, writers) : from),
3265
- escalate: (label, soft) => { const name = `${prefix}${label}`; verdicts.set(name, (verdicts.get(name) ?? true) && soft); },
3266
- });
3267
- }
3268
- /** The escalate nodes of a workflow document that read a judge's output, by label as a run names its step (a child's
3269
- * `parent/child`, as WorkflowDeps.softEscalate is asked): each whose `when` (under any number of `not`s) reads a field a
3270
- * 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
3271
- * escalate (a judge an extract overwrites, one in only some of a route's branches, one a code node with no `as` may have
3272
- * overwritten, are not). A judge's field is one model's opinion of a draft the workflow already wrote, so a host that
3273
- * measures the check may record it instead of obeying it (WorkflowDeps.softEscalate) and read the draft past it. A
3274
- * document too deep to walk, or whose loop's writes do not settle, has none. The document is read as it is: no
3275
- * validation, and a malformed node writes nothing it cannot name. */
3276
- export function softEscalates(doc) {
3277
- const verdicts = new Map();
3278
- try {
3279
- walkWriters(docOf(doc)?.root, new Map(), "", verdicts, 0);
3280
- }
3281
- catch (error) {
3282
- if (error instanceof SoftWalkTooDeep)
3283
- return new Set();
3284
- throw error;
3285
- }
3286
- return new Set([...verdicts].flatMap(([name, soft]) => (soft ? [name] : [])));
3287
- }
3288
2889
  async function runNodeBody(node, state, workflow, deps) {
3289
2890
  switch (node.node) {
3290
2891
  case "chain": {
@@ -3313,7 +2914,6 @@ async function runNodeBody(node, state, workflow, deps) {
3313
2914
  throw new WorkflowStateError(`code node "${node.label}" wrote the reserved "${HOST_STATE_KEY}" state key`, node.label, HOST_STATE_KEY, "reserved_state_key");
3314
2915
  deps.onEvent?.({ type: "code.patch", label: node.label, detail: patch });
3315
2916
  const next = { ...state, ...patch };
3316
- codeWrote.set(next, { value: out });
3317
2917
  return next;
3318
2918
  }
3319
2919
  case "agent":
@@ -3334,27 +2934,14 @@ async function runNodeBody(node, state, workflow, deps) {
3334
2934
  const policy = deps.hostPolicy;
3335
2935
  const context = policy ? hostContext(workflow, node, deps) : null;
3336
2936
  const hostSchema = policy?.submissionSchema && context ? policy.submissionSchema(schema, context) : schema;
3337
- // A guard that reads the node's own confidence (agent, decide): the node submits it beside its record, in the field
3338
- // SELF_CONFIDENCE_FIELD, split off before the stage schema sees the value (unless the stage schema declares it), and
3339
- // kept at `<key>$confidence`.
3340
- const guard = node.node === "agent" || node.node === "decide" ? stepGuardOf(node) : undefined;
3341
- const channel = guard && readsSelf(guard) ? confidenceChannelOf(hostSchema) : undefined;
3342
- const transportSchema = channel ? channel.schema : hostSchema;
2937
+ const transportSchema = hostSchema;
3343
2938
  const transportValidator = transportSchema === schema ? validator : Compile(transportSchema);
3344
2939
  const stageName = node.node === "report" ? "report" : node.out;
3345
- let confidence = null;
3346
2940
  const decode = (raw) => {
3347
2941
  normalizeStringNullsForSchema(raw, transportSchema);
3348
2942
  if (!transportValidator.Check(raw)) {
3349
2943
  throw new WorkflowOutputInvalidError(`${node.node} node "${node.label}" submission does not satisfy schema "${stageName}"`, schemaProblems(transportValidator, raw), node.label);
3350
2944
  }
3351
- if (channel && raw && typeof raw === "object" && !Array.isArray(raw)) {
3352
- confidence = confidenceOf(raw[SELF_CONFIDENCE_FIELD]);
3353
- if (!channel.declared) {
3354
- const { [SELF_CONFIDENCE_FIELD]: _confidence, ...rest } = raw;
3355
- raw = rest;
3356
- }
3357
- }
3358
2945
  const decoded = policy?.decodeSubmission && context ? policy.decodeSubmission(raw, { ...context, host: hostStateOf(state) }) : { value: raw };
3359
2946
  if (decoded !== null && typeof decoded === "object" && decoded.value !== raw)
3360
2947
  normalizeStringNullsForSchema(decoded.value, schema);
@@ -3402,8 +2989,6 @@ async function runNodeBody(node, state, workflow, deps) {
3402
2989
  let merged = mergeStageDelta(state, node, verified ? verified.submission : result, stageSchema);
3403
2990
  if (verified)
3404
2991
  merged = { ...merged, [`${("as" in node && node.as) || node.label}$verify`]: verified.record };
3405
- if (channel)
3406
- merged = { ...merged, [confidenceKey(writeKeyOf(node))]: confidence };
3407
2992
  const hostState = decoded.host && typeof decoded.host === "object" && !Array.isArray(decoded.host) ? decoded.host : null;
3408
2993
  if (hostState && Object.keys(hostState).length) {
3409
2994
  deps.onEvent?.({ type: "host.decoded", label: node.label, detail: { keys: Object.keys(hostState) } });
@@ -3653,9 +3238,8 @@ async function runNodeBody(node, state, workflow, deps) {
3653
3238
  const pathValue = node.when?.path
3654
3239
  ? String(node.when.path).split(".").reduce((acc, key) => (acc == null ? acc : acc[key]), state)
3655
3240
  : undefined;
3656
- const soft = deps.softEscalate?.(node.label) === true;
3657
- deps.onEvent?.({ type: "escalate.evaluated", label: node.label, detail: { fired, path: node.when?.path ?? null, path_resolved: pathValue !== undefined, ...(evaluated.detail ?? {}), ...(soft ? { soft: true } : {}) } });
3658
- 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) {
3659
3243
  throw new EscalationSignal({ kind: node.kind, stage: node.stage, summary: interpolate(node.summary, state), state, label: node.label, executionPath: executionPath(deps) });
3660
3244
  }
3661
3245
  return state;
@@ -3850,8 +3434,6 @@ export function assertWorkflowCapabilities(node, deps, workflow) {
3850
3434
  node.node === "loop" && node.until?.predicate === "ask" ||
3851
3435
  node.node === "escalate" && node.when?.predicate === "ask") && !deps.runJudge)
3852
3436
  missing("runJudge");
3853
- if (stepGuardOf(node) && !deps.guardStep)
3854
- missing("guardStep");
3855
3437
  checkDecisionProviders(node, deps, workflow);
3856
3438
  // A store that cannot commit an item's failure would run the item again in the next process.
3857
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.42",
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",