@parcha/agentrun-dsl 0.1.0-beta.1 → 0.1.0-beta.2
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/README.md +8 -1
- package/dist/cli.js +0 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +6 -1
- package/dist/workflow.d.ts +54 -2
- package/dist/workflow.js +134 -13
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,7 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
Composable, typed workflows for agents. The core provides the v2 workflow types, validator, interpreter, events, schema, and an offline CLI. Supply agent, judgment, and effect functions only when a workflow needs them.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Published beta: `0.1.0-beta.2`. Requires Node 22.19+; TypeScript consumers require TypeScript 5.4+.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @parcha/agentrun-dsl@beta
|
|
9
|
+
npx agentrun demo
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
For the JavaScript API, save this as `demo.mjs` and run `node demo.mjs`:
|
|
6
13
|
|
|
7
14
|
```js
|
|
8
15
|
import { runTriageDemo } from '@parcha/agentrun-dsl/demo';
|
package/dist/cli.js
CHANGED
|
File without changes
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
|
|
2
2
|
export type { StandardJSONSchema, AuthoringSchema, TypedWorkflow, TypedWorkflowRunResult, WorkflowInput, WorkflowOutput, } from "./authoring.js";
|
|
3
3
|
export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, } from "./workflow.js";
|
|
4
|
-
export type { Workflow, WorkflowNode, WorkflowDeps, WorkflowRunResult, Escalation, EffectSettlement, MapItem, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CallRetryClass, CallPredicate, PollClause, ModelTier, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, MechanicalPredicate, Predicate, } from "./workflow.js";
|
|
4
|
+
export type { Workflow, WorkflowNode, WorkflowDeps, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CallRetryClass, CallPredicate, PollClause, ModelTier, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, MechanicalPredicate, Predicate, } from "./workflow.js";
|
|
5
5
|
export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
|
|
6
6
|
export type { DryRunOptions, DryRunResult } from "./dry-run.js";
|
|
7
7
|
export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, } from "./system-one.js";
|
|
8
8
|
export type { SystemOneQuestion, SystemOneAnswer, SystemOneResult, SystemOneRetryClass, SystemOneResponseReason, CompiledQuestions, AnswersSidecar, } from "./system-one.js";
|
|
9
9
|
export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
|
|
10
10
|
export type { WorkflowInspection, WorkflowInspectionNode } from "./inspection.js";
|
|
11
|
-
export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA, } from "./workflow.js";
|
|
11
|
+
export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA, childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY, buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
|
|
12
|
+
export { compileTransform, compileTransformSyntax } from "./code-exec.js";
|
|
12
13
|
export { resolveSchemaForWorkflow } from "./schema-references.js";
|
|
13
14
|
export { getPath, predicateMatches } from "./predicates.js";
|
|
14
15
|
export type { StopPredicate, AcceptPredicate } from "./predicates.js";
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,11 @@ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, Wo
|
|
|
3
3
|
export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
|
|
4
4
|
export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, } from "./system-one.js";
|
|
5
5
|
export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
|
|
6
|
-
export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA,
|
|
6
|
+
export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA,
|
|
7
|
+
// Document helpers a host facade needs to speak about a workflow without re-implementing the walk.
|
|
8
|
+
childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
|
|
9
|
+
// Host-side data helpers the interpreter itself uses: the same normalization and reference shaping.
|
|
10
|
+
buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
|
|
11
|
+
export { compileTransform, compileTransformSyntax } from "./code-exec.js";
|
|
7
12
|
export { resolveSchemaForWorkflow } from "./schema-references.js";
|
|
8
13
|
export { getPath, predicateMatches } from "./predicates.js";
|
package/dist/workflow.d.ts
CHANGED
|
@@ -307,6 +307,8 @@ export type WorkflowRunResult = {
|
|
|
307
307
|
status: "complete";
|
|
308
308
|
state: Record<string, unknown>;
|
|
309
309
|
output: unknown;
|
|
310
|
+
/** What the host's policy wrote through `decodeSubmission`: the final `state.$host`, never part of `output`. */
|
|
311
|
+
host?: Record<string, unknown>;
|
|
310
312
|
} | {
|
|
311
313
|
status: "escalated";
|
|
312
314
|
state: Record<string, unknown>;
|
|
@@ -316,8 +318,56 @@ export type MapItem = {
|
|
|
316
318
|
label: string;
|
|
317
319
|
index: number;
|
|
318
320
|
};
|
|
321
|
+
/** Where a host policy hook is being applied. `terminal` is true for a generative node whose `out` is
|
|
322
|
+
* the workflow's output schema: the node that emits the terminal record. */
|
|
323
|
+
export type HostPolicyContext = {
|
|
324
|
+
workflow: {
|
|
325
|
+
name: string;
|
|
326
|
+
outputSchemaId: string;
|
|
327
|
+
};
|
|
328
|
+
node: {
|
|
329
|
+
kind: WorkflowNode["node"];
|
|
330
|
+
label: string;
|
|
331
|
+
out?: string;
|
|
332
|
+
as?: string;
|
|
333
|
+
};
|
|
334
|
+
terminal: boolean;
|
|
335
|
+
executionPath: string;
|
|
336
|
+
item?: MapItem;
|
|
337
|
+
};
|
|
338
|
+
/** Application policy around generative nodes and completed steps. This is host code handed in through
|
|
339
|
+
* deps: nothing in a workflow document can name or reach it, so a candidate workflow cannot change its
|
|
340
|
+
* host's channels. Each hook is a general capability rather than a product rule:
|
|
341
|
+
* - `systemBlocks` appends host text after the node's instructions.
|
|
342
|
+
* - `submissionSchema` widens the schema the adapter submits against with host-owned channels. The
|
|
343
|
+
* returned schema must accept every value the stage schema accepts; the engine validates the raw
|
|
344
|
+
* submission against it and the decoded domain value against the unchanged stage schema, so no host
|
|
345
|
+
* channel can bypass domain validation or verification.
|
|
346
|
+
* - `decodeSubmission` splits an accepted transport submission into the domain value and host state.
|
|
347
|
+
* Host state lives under the reserved `$host` state key (no workflow may write it), so it is
|
|
348
|
+
* checkpointed and resumed with the rest of the state, isolated per map item, branch and child
|
|
349
|
+
* exactly as the state is, excluded from a path-less output projection, and returned as `result.host`.
|
|
350
|
+
* Parallel branches merge their `$host` deltas key by key: arrays append, an unchanged value is kept,
|
|
351
|
+
* two branches changing one non-array key to different values is a write conflict.
|
|
352
|
+
* - `afterNode` enriches a completed step's state before commit and checkpoint. This is domain state:
|
|
353
|
+
* downstream nodes and output validation see it. */
|
|
354
|
+
export type HostPolicy = {
|
|
355
|
+
systemBlocks?: (context: HostPolicyContext) => string[];
|
|
356
|
+
submissionSchema?: (stageSchema: Record<string, unknown>, context: HostPolicyContext) => Record<string, unknown>;
|
|
357
|
+
decodeSubmission?: (submission: unknown, context: HostPolicyContext & {
|
|
358
|
+
host: Record<string, unknown>;
|
|
359
|
+
}) => {
|
|
360
|
+
value: unknown;
|
|
361
|
+
host?: Record<string, unknown>;
|
|
362
|
+
};
|
|
363
|
+
afterNode?: (context: HostPolicyContext & {
|
|
364
|
+
state: Record<string, unknown>;
|
|
365
|
+
}) => Record<string, unknown> | undefined;
|
|
366
|
+
};
|
|
319
367
|
export type WorkflowDeps = {
|
|
320
368
|
maxQuestionsPerRequest?: number;
|
|
369
|
+
/** Host application policy; see `HostPolicy`. Absent = the engine's own behavior, unchanged. */
|
|
370
|
+
hostPolicy?: HostPolicy;
|
|
321
371
|
runNode?: (params: {
|
|
322
372
|
kind: "agent" | "decide" | "extract" | "report";
|
|
323
373
|
label: string;
|
|
@@ -507,13 +557,15 @@ export declare class WorkflowCodeError extends Error {
|
|
|
507
557
|
export declare class WorkflowStateError extends Error {
|
|
508
558
|
readonly stage: string;
|
|
509
559
|
readonly path: string;
|
|
510
|
-
readonly reason: "required_nonempty" | "missing_interpolation" | "expected_list" | "empty_selection" | "missing_map_result" | "parallel_write_conflict";
|
|
560
|
+
readonly reason: "required_nonempty" | "missing_interpolation" | "expected_list" | "empty_selection" | "missing_map_result" | "parallel_write_conflict" | "reserved_state_key";
|
|
511
561
|
readonly code = "state_invalid";
|
|
512
|
-
constructor(summary: string, stage: string, path: string, reason: "required_nonempty" | "missing_interpolation" | "expected_list" | "empty_selection" | "missing_map_result" | "parallel_write_conflict");
|
|
562
|
+
constructor(summary: string, stage: string, path: string, reason: "required_nonempty" | "missing_interpolation" | "expected_list" | "empty_selection" | "missing_map_result" | "parallel_write_conflict" | "reserved_state_key");
|
|
513
563
|
}
|
|
514
564
|
export declare function stageSchemaForNode(workflow: Workflow, node: LlmNode): Record<string, unknown>;
|
|
515
565
|
export declare const submissionSchemaForNode: typeof stageSchemaForNode;
|
|
516
566
|
export declare function mergeStageDelta(state: Record<string, unknown>, node: LlmNode, result: Record<string, unknown>, schema: Record<string, unknown>): Record<string, unknown>;
|
|
567
|
+
/** The reserved state key host policy writes under. Engine-owned like every `$`-prefixed key: no node may name it. */
|
|
568
|
+
export declare const HOST_STATE_KEY = "$host";
|
|
517
569
|
export declare class WorkflowVerificationError extends Error {
|
|
518
570
|
readonly stage: string;
|
|
519
571
|
readonly candidate: unknown;
|
package/dist/workflow.js
CHANGED
|
@@ -633,6 +633,14 @@ export function validateWorkflow(workflow, opts) {
|
|
|
633
633
|
const extraneous = Object.keys(node).filter((key) => !allowed.has(key));
|
|
634
634
|
if (extraneous.length)
|
|
635
635
|
errors.push(`${path} (${node.label || node.node}): unknown key(s) for a ${node.node} node: ${extraneous.join(", ")}`);
|
|
636
|
+
// `$`-prefixed state keys are engine-owned (`$host`, `<as>$verify`): no node may write one. A label
|
|
637
|
+
// is the state key whenever `as` is omitted, so labels are held to the same rule.
|
|
638
|
+
if (typeof node.as === "string" && node.as.startsWith("$"))
|
|
639
|
+
errors.push(`${path} (${node.label || node.node}): "as" must not name an engine-owned "$" state key ("${node.as}")`);
|
|
640
|
+
// Only an unaliased generative or code node writes under its label; every other label is a name, not a key.
|
|
641
|
+
const labelIsKey = (node.node === "agent" || node.node === "decide" || node.node === "extract" || node.node === "code") && node.as === undefined;
|
|
642
|
+
if (labelIsKey && typeof node.label === "string" && node.label.startsWith("$"))
|
|
643
|
+
errors.push(`${path} (${node.label}): label must not begin with "$" — an unaliased ${node.node} node writes under its label, and "$" keys are engine-owned`);
|
|
636
644
|
}
|
|
637
645
|
switch (node.node) {
|
|
638
646
|
case "chain":
|
|
@@ -1705,6 +1713,25 @@ async function runRouteNode(node, state, workflow, deps) {
|
|
|
1705
1713
|
}
|
|
1706
1714
|
const EXECUTION_PATH = Symbol("workflow.executionPath");
|
|
1707
1715
|
const SCOPED_EFFECTS = Symbol("workflow.scopedEffects");
|
|
1716
|
+
/** The map item a scoped copy of deps runs for, so host policy context can name it. */
|
|
1717
|
+
const MAP_ITEM = Symbol("workflow.mapItem");
|
|
1718
|
+
/** The reserved state key host policy writes under. Engine-owned like every `$`-prefixed key: no node may name it. */
|
|
1719
|
+
export const HOST_STATE_KEY = "$host";
|
|
1720
|
+
const hostStateOf = (state) => {
|
|
1721
|
+
const host = state[HOST_STATE_KEY];
|
|
1722
|
+
return host && typeof host === "object" && !Array.isArray(host) ? host : {};
|
|
1723
|
+
};
|
|
1724
|
+
const hostContext = (workflow, node, deps) => {
|
|
1725
|
+
const item = deps[MAP_ITEM];
|
|
1726
|
+
const generative = node.node === "agent" || node.node === "decide" || node.node === "extract" || node.node === "report";
|
|
1727
|
+
return {
|
|
1728
|
+
workflow: { name: workflow.name, outputSchemaId: workflow.output.schemaId },
|
|
1729
|
+
node: { kind: node.node, label: String(node.label ?? node.node), ...("out" in node && typeof node.out === "string" ? { out: node.out } : {}), ...("as" in node && typeof node.as === "string" ? { as: node.as } : {}) },
|
|
1730
|
+
terminal: generative && node.node !== "report" && node.out === workflow.output.schemaId,
|
|
1731
|
+
executionPath: executionPath(deps),
|
|
1732
|
+
...(item ? { item } : {}),
|
|
1733
|
+
};
|
|
1734
|
+
};
|
|
1708
1735
|
const executionPath = (deps) => deps[EXECUTION_PATH] ?? "/root";
|
|
1709
1736
|
const scopeExecution = (deps, ...parts) => ({
|
|
1710
1737
|
...deps,
|
|
@@ -1741,6 +1768,7 @@ function scopeDepsToItem(deps, item, signal) {
|
|
|
1741
1768
|
const recovery = deps.recovery;
|
|
1742
1769
|
return {
|
|
1743
1770
|
...deps,
|
|
1771
|
+
...{ [MAP_ITEM]: item },
|
|
1744
1772
|
checkpoint: undefined,
|
|
1745
1773
|
...(signal ? { signal } : {}),
|
|
1746
1774
|
...(deps.runNode ? { runNode: params => deps.runNode({ ...params, item: params.item ?? item, ...(signal ? { signal: params.signal ?? signal } : {}) }) } : {}),
|
|
@@ -1816,9 +1844,20 @@ async function runNodeOnState(node, state, workflow, deps) {
|
|
|
1816
1844
|
try {
|
|
1817
1845
|
if (deps.signal?.aborted)
|
|
1818
1846
|
throw deps.signal.reason ?? new Error("workflow aborted");
|
|
1819
|
-
|
|
1847
|
+
let out = await runNodeBody(node, state, workflow, deps);
|
|
1820
1848
|
if (deps.signal?.aborted)
|
|
1821
1849
|
throw deps.signal.reason ?? new Error("workflow aborted");
|
|
1850
|
+
// Host policy enrichment lands before commit and checkpoint: a resumed run sees exactly what ran.
|
|
1851
|
+
if (isStep && deps.hostPolicy?.afterNode) {
|
|
1852
|
+
const patch = deps.hostPolicy.afterNode({ ...hostContext(workflow, node, deps), state: out });
|
|
1853
|
+
if (patch && typeof patch === "object" && !Array.isArray(patch) && Object.prototype.hasOwnProperty.call(patch, HOST_STATE_KEY)) {
|
|
1854
|
+
throw new WorkflowStateError(`host policy afterNode for "${label}" may not write the reserved "${HOST_STATE_KEY}" key; return host state from decodeSubmission`, label, HOST_STATE_KEY, "reserved_state_key");
|
|
1855
|
+
}
|
|
1856
|
+
if (patch && typeof patch === "object" && !Array.isArray(patch) && Object.keys(patch).length) {
|
|
1857
|
+
out = { ...out, ...patch };
|
|
1858
|
+
deps.onEvent?.({ type: "host.patched", label, detail: { keys: Object.keys(patch) } });
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1822
1861
|
if (deps.recovery && node.node !== "chain")
|
|
1823
1862
|
await deps.recovery.commit(node, out, undefined, executionPath(deps));
|
|
1824
1863
|
if (deps.signal?.aborted)
|
|
@@ -1881,6 +1920,8 @@ async function runNodeBody(node, state, workflow, deps) {
|
|
|
1881
1920
|
throw new WorkflowCodeError(node.label, cause);
|
|
1882
1921
|
}
|
|
1883
1922
|
const patch = node.as ? { [node.as]: out } : (out && typeof out === "object" && !Array.isArray(out) ? out : { [node.label]: out });
|
|
1923
|
+
if (Object.prototype.hasOwnProperty.call(patch, HOST_STATE_KEY))
|
|
1924
|
+
throw new WorkflowStateError(`code node "${node.label}" wrote the reserved "${HOST_STATE_KEY}" state key`, node.label, HOST_STATE_KEY, "reserved_state_key");
|
|
1884
1925
|
deps.onEvent?.({ type: "code.patch", label: node.label, detail: patch });
|
|
1885
1926
|
return { ...state, ...patch };
|
|
1886
1927
|
}
|
|
@@ -1897,27 +1938,68 @@ async function runNodeBody(node, state, workflow, deps) {
|
|
|
1897
1938
|
assertNodeInputs(node, state);
|
|
1898
1939
|
const promptState = node.state ? interpolateValue(node.state, state, node.label) : promptStateOf(state);
|
|
1899
1940
|
const verifier = node.node !== "report" && node.verify ? compileVerifier(workflow, node, state, deps) : null;
|
|
1941
|
+
// Host policy: the adapter submits against the transport schema (the stage schema plus the host's
|
|
1942
|
+
// channels); the decoded domain value is what the stage schema, the verifier and the state see.
|
|
1943
|
+
const policy = deps.hostPolicy;
|
|
1944
|
+
const context = policy ? hostContext(workflow, node, deps) : null;
|
|
1945
|
+
const transportSchema = policy?.submissionSchema && context ? policy.submissionSchema(schema, context) : schema;
|
|
1946
|
+
const transportValidator = transportSchema === schema ? validator : Compile(transportSchema);
|
|
1947
|
+
const stageName = node.node === "report" ? "report" : node.out;
|
|
1948
|
+
const decode = (raw) => {
|
|
1949
|
+
normalizeStringNullsForSchema(raw, transportSchema);
|
|
1950
|
+
if (!transportValidator.Check(raw)) {
|
|
1951
|
+
throw new WorkflowOutputInvalidError(`${node.node} node "${node.label}" submission does not satisfy schema "${stageName}"`, schemaProblems(transportValidator, raw), node.label);
|
|
1952
|
+
}
|
|
1953
|
+
const decoded = policy?.decodeSubmission && context ? policy.decodeSubmission(raw, { ...context, host: hostStateOf(state) }) : { value: raw };
|
|
1954
|
+
if (decoded !== null && typeof decoded === "object" && decoded.value !== raw)
|
|
1955
|
+
normalizeStringNullsForSchema(decoded.value, schema);
|
|
1956
|
+
if (!validator.Check(decoded.value)) {
|
|
1957
|
+
throw new WorkflowOutputInvalidError(`${node.node} node "${node.label}" decoded submission does not satisfy schema "${stageName}"`, schemaProblems(validator, decoded.value), node.label);
|
|
1958
|
+
}
|
|
1959
|
+
return decoded;
|
|
1960
|
+
};
|
|
1961
|
+
// A verify clause reviews the domain value: the host's channels are split off before the judge sees it.
|
|
1962
|
+
const review = verifier
|
|
1963
|
+
? (transportSchema === schema && !policy?.decodeSubmission
|
|
1964
|
+
? verifier.review
|
|
1965
|
+
: async (candidate) => {
|
|
1966
|
+
let decoded;
|
|
1967
|
+
try {
|
|
1968
|
+
decoded = decode(structuredClone(candidate));
|
|
1969
|
+
}
|
|
1970
|
+
catch (error) {
|
|
1971
|
+
if (error instanceof WorkflowOutputInvalidError)
|
|
1972
|
+
return { accepted: false, message: error.message };
|
|
1973
|
+
throw error;
|
|
1974
|
+
}
|
|
1975
|
+
return verifier.review(decoded.value);
|
|
1976
|
+
})
|
|
1977
|
+
: undefined;
|
|
1900
1978
|
let submission;
|
|
1901
1979
|
submission = await deps.runNode({
|
|
1902
1980
|
signal: deps.signal,
|
|
1903
1981
|
kind: node.node, label: node.label,
|
|
1904
|
-
...(
|
|
1982
|
+
...(review ? { review } : {}),
|
|
1905
1983
|
...(node.tier ? { tier: node.tier } : {}),
|
|
1906
|
-
system: [sopSlice, deps.skill, node.instructions].filter(Boolean),
|
|
1984
|
+
system: [sopSlice, deps.skill, node.instructions, ...(policy?.systemBlocks && context ? policy.systemBlocks(context) : [])].filter(Boolean),
|
|
1907
1985
|
user: JSON.stringify(promptState),
|
|
1908
|
-
schema,
|
|
1986
|
+
schema: transportSchema,
|
|
1909
1987
|
...(node.effort ? { effort: node.effort } : {}),
|
|
1910
1988
|
...(node.thinking ? { thinking: node.thinking } : {}),
|
|
1911
1989
|
...(Array.isArray(node.tools) ? { tools: node.tools } : {}),
|
|
1912
1990
|
});
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
throw new WorkflowOutputInvalidError(`${node.node} node "${node.label}" submission does not satisfy schema "${node.node === "report" ? "report" : node.out}"`, schemaProblems(validator, submission), node.label);
|
|
1916
|
-
}
|
|
1917
|
-
const result = submission;
|
|
1991
|
+
const decoded = decode(submission);
|
|
1992
|
+
const result = decoded.value;
|
|
1918
1993
|
const verified = verifier ? await verifier.finish(result) : null;
|
|
1919
|
-
|
|
1920
|
-
|
|
1994
|
+
let merged = mergeStageDelta(state, node, verified ? verified.submission : result, stageSchema);
|
|
1995
|
+
if (verified)
|
|
1996
|
+
merged = { ...merged, [`${("as" in node && node.as) || node.label}$verify`]: verified.record };
|
|
1997
|
+
const hostState = decoded.host && typeof decoded.host === "object" && !Array.isArray(decoded.host) ? decoded.host : null;
|
|
1998
|
+
if (hostState && Object.keys(hostState).length) {
|
|
1999
|
+
deps.onEvent?.({ type: "host.decoded", label: node.label, detail: { keys: Object.keys(hostState) } });
|
|
2000
|
+
merged = { ...merged, [HOST_STATE_KEY]: { ...hostStateOf(merged), ...hostState } };
|
|
2001
|
+
}
|
|
2002
|
+
return merged;
|
|
1921
2003
|
}
|
|
1922
2004
|
case "map": {
|
|
1923
2005
|
const items = getPath(state, node.itemsPath);
|
|
@@ -2009,8 +2091,42 @@ async function runNodeBody(node, state, workflow, deps) {
|
|
|
2009
2091
|
throw withSiblingUncertainty(failure, uncertainties);
|
|
2010
2092
|
const merged = { ...state };
|
|
2011
2093
|
const writer = new Map();
|
|
2094
|
+
// Host state is engine-owned and merges by delta: every branch started from the same `$host`, so an
|
|
2095
|
+
// array grows by what each branch appended, an unchanged value is kept, and two branches that set one
|
|
2096
|
+
// non-array key to different values are a write conflict like any other.
|
|
2097
|
+
const baseHost = hostStateOf(baseline);
|
|
2098
|
+
const mergedHost = { ...baseHost };
|
|
2099
|
+
const hostWriter = new Map();
|
|
2100
|
+
let hostChanged = false;
|
|
2101
|
+
outs.forEach((out, i) => {
|
|
2102
|
+
const branchHost = hostStateOf((out || {}));
|
|
2103
|
+
for (const [key, value] of Object.entries(branchHost)) {
|
|
2104
|
+
if (Object.hasOwn(baseHost, key) && isDeepStrictEqual(value, baseHost[key]))
|
|
2105
|
+
continue;
|
|
2106
|
+
hostChanged = true;
|
|
2107
|
+
// The same value from several branches is one write, whatever its shape.
|
|
2108
|
+
if (hostWriter.has(key) && isDeepStrictEqual(mergedHost[key], value))
|
|
2109
|
+
continue;
|
|
2110
|
+
const base = baseHost[key];
|
|
2111
|
+
if (Array.isArray(value) && (base === undefined || Array.isArray(base)) && (!Array.isArray(base) || (value.length >= base.length && base.every((entry, n) => isDeepStrictEqual(entry, value[n]))))) {
|
|
2112
|
+
const appended = value.slice(Array.isArray(base) ? base.length : 0);
|
|
2113
|
+
mergedHost[key] = [...(Array.isArray(mergedHost[key]) ? mergedHost[key] : []), ...appended];
|
|
2114
|
+
hostWriter.set(key, i);
|
|
2115
|
+
continue;
|
|
2116
|
+
}
|
|
2117
|
+
const prior = hostWriter.get(key);
|
|
2118
|
+
if (prior !== undefined && !isDeepStrictEqual(mergedHost[key], value))
|
|
2119
|
+
throw new WorkflowStateError(`parallel node "${node.label}": branches ${prior} and ${i} both wrote host state ${HOST_STATE_KEY}.${key} to different values`, node.label, `${HOST_STATE_KEY}.${key}`, "parallel_write_conflict");
|
|
2120
|
+
hostWriter.set(key, i);
|
|
2121
|
+
mergedHost[key] = value;
|
|
2122
|
+
}
|
|
2123
|
+
});
|
|
2124
|
+
if (hostChanged)
|
|
2125
|
+
merged[HOST_STATE_KEY] = mergedHost;
|
|
2012
2126
|
outs.forEach((out, i) => {
|
|
2013
2127
|
for (const [key, value] of Object.entries((out || {}))) {
|
|
2128
|
+
if (key === HOST_STATE_KEY)
|
|
2129
|
+
continue;
|
|
2014
2130
|
if (Object.hasOwn(baseline, key) && isDeepStrictEqual(value, baseline[key]))
|
|
2015
2131
|
continue;
|
|
2016
2132
|
const prior = writer.get(key);
|
|
@@ -2240,14 +2356,19 @@ export async function runWorkflow(workflow, input, deps) {
|
|
|
2240
2356
|
deps = { ...deps, [SCOPED_EFFECTS]: true };
|
|
2241
2357
|
if (deps.recovery && !deps.recovery.supportsExecutionPaths && needsComposedRecovery(workflow.root))
|
|
2242
2358
|
throw new Error("Composed child workflows require recovery.supportsExecutionPaths: true and stores keyed by executionPath");
|
|
2359
|
+
if (Object.prototype.hasOwnProperty.call(input, HOST_STATE_KEY))
|
|
2360
|
+
throw new WorkflowInputInvalidError(workflow.name, [`input must not contain the reserved "${HOST_STATE_KEY}" key`]);
|
|
2243
2361
|
try {
|
|
2244
2362
|
const state = await runNodeOnState(workflow.root, snapshotState(input), workflow, deps);
|
|
2245
|
-
const
|
|
2363
|
+
const host = hostStateOf(state);
|
|
2364
|
+
const output = workflow.output.path
|
|
2365
|
+
? getPath(state, workflow.output.path)
|
|
2366
|
+
: (Object.prototype.hasOwnProperty.call(state, HOST_STATE_KEY) ? Object.fromEntries(Object.entries(state).filter(([key]) => key !== HOST_STATE_KEY)) : state);
|
|
2246
2367
|
const validator = Compile(resolveSchemaForWorkflow(workflow, workflow.schemas[workflow.output.schemaId]));
|
|
2247
2368
|
if (!validator.Check(output)) {
|
|
2248
2369
|
throw new WorkflowOutputInvalidError(`workflow "${workflow.name}" output does not satisfy schema "${workflow.output.schemaId}"`, schemaProblems(validator, output));
|
|
2249
2370
|
}
|
|
2250
|
-
return { status: "complete", state, output };
|
|
2371
|
+
return { status: "complete", state, output, ...(Object.keys(host).length ? { host } : {}) };
|
|
2251
2372
|
}
|
|
2252
2373
|
catch (error) {
|
|
2253
2374
|
if (error instanceof EscalationSignal)
|