@parcha/agentrun-dsl 0.1.0-beta.1 → 0.1.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +25 -11
  2. package/dist/author.d.ts +89 -0
  3. package/dist/author.js +317 -0
  4. package/dist/code-exec.d.ts +6 -0
  5. package/dist/code-exec.js +126 -0
  6. package/dist/dry-run.d.ts +4 -1
  7. package/dist/dry-run.js +2 -1
  8. package/dist/index.d.ts +8 -3
  9. package/dist/index.js +9 -2
  10. package/dist/inspection.js +2 -2
  11. package/dist/long-timer.d.ts +7 -0
  12. package/dist/long-timer.js +22 -0
  13. package/dist/observer-snapshot.d.ts +3 -0
  14. package/dist/observer-snapshot.js +46 -0
  15. package/dist/predicates.d.ts +4 -0
  16. package/dist/predicates.js +19 -2
  17. package/dist/system-one.js +45 -4
  18. package/dist/vocabulary.d.ts +42 -0
  19. package/dist/vocabulary.js +74 -0
  20. package/dist/workflow-shape.js +6 -2
  21. package/dist/workflow.d.ts +164 -15
  22. package/dist/workflow.js +551 -118
  23. package/package.json +3 -2
  24. package/schema/workflow.schema.json +237 -15
  25. package/skills/author/SKILL.md +120 -0
  26. package/skills/author/examples/evidence-gate.input.json +6 -0
  27. package/skills/author/examples/evidence-gate.json +125 -0
  28. package/skills/author/examples/read-file.input.json +1 -0
  29. package/skills/author/examples/read-file.json +44 -0
  30. package/skills/author/examples/read-source-decision.input.json +4 -0
  31. package/skills/author/examples/read-source-decision.json +37 -0
  32. package/skills/author/examples/release-note.txt +10 -0
  33. package/skills/author/examples/review-release-notes.input.json +6 -0
  34. package/skills/author/examples/review-release-notes.json +123 -0
  35. package/skills/author/references/jev-decisions.md +125 -0
  36. package/skills/author/references/language.md +118 -0
  37. package/skills/author/references/sdk-authoring.md +9 -0
  38. package/skills/author/references/workflow-format.md +137 -0
package/dist/code-exec.js CHANGED
@@ -10,6 +10,132 @@ const DENIED_GLOBALS = [
10
10
  "fetch", "XMLHttpRequest", "Function", "Buffer",
11
11
  "setTimeout", "setInterval", "setImmediate", "queueMicrotask", "Promise", "Date",
12
12
  ];
13
+ /** Words after which a `/` starts a regular expression rather than a division. */
14
+ const REGEX_AFTER_WORDS = new Set(["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]);
15
+ const IDENTIFIER_START = /[A-Za-z_$\u0080-\uffff]/;
16
+ const IDENTIFIER_PART = /[A-Za-z0-9_$\u0080-\uffff]/;
17
+ /** The denied globals a transform's source names, in DENIED_GLOBALS order: a lexical scan of the source
18
+ * that skips comments, string and template text and regular-expression literals, and ignores a name
19
+ * read as a property (after `.` or `?.`). A name used as an object key or a local binding is still
20
+ * named: the lint refuses rather than guesses. It is a lint for untrusted authors, never a boundary:
21
+ * a host that runs such code isolates it (deps.runCode). */
22
+ export function deniedGlobalReferences(src) {
23
+ const denied = new Set(DENIED_GLOBALS);
24
+ const found = new Set();
25
+ const braces = [];
26
+ const n = typeof src === "string" ? src.length : 0;
27
+ let i = 0;
28
+ // The previous significant token: a word, a value (literal, closing bracket), or punctuation.
29
+ let prev = null;
30
+ /** Template text from i: true when it stopped at `${` (code follows), false at its closing backtick. */
31
+ const templateText = () => {
32
+ while (i < n) {
33
+ if (src[i] === "\\") {
34
+ i += 2;
35
+ continue;
36
+ }
37
+ if (src[i] === "`") {
38
+ i += 1;
39
+ return false;
40
+ }
41
+ if (src[i] === "$" && src[i + 1] === "{") {
42
+ i += 2;
43
+ braces.push("template");
44
+ return true;
45
+ }
46
+ i += 1;
47
+ }
48
+ return false;
49
+ };
50
+ while (i < n) {
51
+ const c = src[i];
52
+ if (/\s/.test(c)) {
53
+ i += 1;
54
+ continue;
55
+ }
56
+ if (c === "/" && src[i + 1] === "/") {
57
+ const end = src.indexOf("\n", i);
58
+ i = end < 0 ? n : end;
59
+ continue;
60
+ }
61
+ if (c === "/" && src[i + 1] === "*") {
62
+ const end = src.indexOf("*/", i + 2);
63
+ i = end < 0 ? n : end + 2;
64
+ continue;
65
+ }
66
+ if (c === "'" || c === '"') {
67
+ i += 1;
68
+ while (i < n && src[i] !== c)
69
+ i += src[i] === "\\" ? 2 : 1;
70
+ i += 1;
71
+ prev = { kind: "value", text: c };
72
+ continue;
73
+ }
74
+ if (c === "`" || (c === "}" && braces[braces.length - 1] === "template")) {
75
+ if (c === "}")
76
+ braces.pop();
77
+ i += 1;
78
+ prev = templateText() ? null : { kind: "value", text: "`" };
79
+ continue;
80
+ }
81
+ if (c === "/") {
82
+ const regex = prev === null || (prev.kind === "punct" && !")]}".includes(prev.text)) || (prev.kind === "word" && REGEX_AFTER_WORDS.has(prev.text));
83
+ if (regex) {
84
+ i += 1;
85
+ let inClass = false;
86
+ while (i < n && (inClass || src[i] !== "/")) {
87
+ if (src[i] === "\\") {
88
+ i += 2;
89
+ continue;
90
+ }
91
+ if (src[i] === "[")
92
+ inClass = true;
93
+ else if (src[i] === "]")
94
+ inClass = false;
95
+ i += 1;
96
+ }
97
+ i += 1;
98
+ while (i < n && IDENTIFIER_PART.test(src[i]))
99
+ i += 1;
100
+ prev = { kind: "value", text: "/" };
101
+ continue;
102
+ }
103
+ }
104
+ if (IDENTIFIER_START.test(c)) {
105
+ const start = i;
106
+ while (i < n && IDENTIFIER_PART.test(src[i]))
107
+ i += 1;
108
+ const word = src.slice(start, i);
109
+ if (denied.has(word) && !(prev?.kind === "punct" && prev.text === "."))
110
+ found.add(word);
111
+ prev = { kind: "word", text: word };
112
+ continue;
113
+ }
114
+ if (/[0-9]/.test(c)) {
115
+ while (i < n && IDENTIFIER_PART.test(src[i]))
116
+ i += 1;
117
+ prev = { kind: "value", text: "0" };
118
+ continue;
119
+ }
120
+ if (c === "." && src.startsWith("...", i)) {
121
+ i += 3;
122
+ prev = { kind: "punct", text: "..." };
123
+ continue;
124
+ }
125
+ if (c === "?" && src[i + 1] === "." && !/[0-9]/.test(src[i + 2] ?? "")) {
126
+ i += 2;
127
+ prev = { kind: "punct", text: "." };
128
+ continue;
129
+ }
130
+ if (c === "{")
131
+ braces.push("brace");
132
+ if (c === "}")
133
+ braces.pop();
134
+ i += 1;
135
+ prev = c === ")" || c === "]" || c === "}" ? { kind: "value", text: c } : { kind: "punct", text: c };
136
+ }
137
+ return DENIED_GLOBALS.filter((name) => found.has(name));
138
+ }
13
139
  function createTransformFactory(src) {
14
140
  if (typeof src !== "string" || !src.trim())
15
141
  throw new Error("code transform source must be a non-empty string");
package/dist/dry-run.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Workflow } from "./workflow.js";
1
+ import { type Workflow, type WorkflowDeps } from "./workflow.js";
2
2
  export type DryRunResult = {
3
3
  ok: true;
4
4
  skipped?: string[];
@@ -15,5 +15,8 @@ export type DryRunOptions = {
15
15
  references_parsed?: Record<string, unknown>;
16
16
  };
17
17
  input?: Record<string, unknown>;
18
+ /** The host's executor for `code` nodes (WorkflowDeps.runCode). Present, the dry run validates
19
+ * with executeCode:false and hands every code node to it, so no code body runs in this process. */
20
+ runCode?: WorkflowDeps["runCode"];
18
21
  };
19
22
  export declare function dryRunWorkflow(workflow: Workflow, opts?: DryRunOptions): Promise<DryRunResult>;
package/dist/dry-run.js CHANGED
@@ -116,7 +116,7 @@ function unsupportedConstructs(schema, path, found, depth = 0) {
116
116
  return found;
117
117
  }
118
118
  export async function dryRunWorkflow(workflow, opts = {}) {
119
- const valid = validateWorkflow(workflow, opts.input === undefined ? undefined : { input: opts.input });
119
+ const valid = validateWorkflow(workflow, { ...(opts.input === undefined ? {} : { input: opts.input }), ...(opts.runCode ? { executeCode: false } : {}) });
120
120
  if (!valid.ok)
121
121
  return { ok: false, problems: [new WorkflowInvalidError(String(workflow?.name), valid.errors).message] };
122
122
  const skipped = [];
@@ -159,6 +159,7 @@ export async function dryRunWorkflow(workflow, opts = {}) {
159
159
  try {
160
160
  const result = await runWorkflow(workflow, input, {
161
161
  sop: opts.sop,
162
+ ...(opts.runCode ? { runCode: opts.runCode } : {}),
162
163
  onEvent: (event) => { if (typeof event.label === "string")
163
164
  currentLabel = event.label; },
164
165
  runNode: async ({ schema, review }) => {
package/dist/index.d.ts CHANGED
@@ -1,14 +1,19 @@
1
1
  export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
2
2
  export type { StandardJSONSchema, AuthoringSchema, TypedWorkflow, TypedWorkflowRunResult, WorkflowInput, WorkflowOutput, } from "./authoring.js";
3
- export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, } 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";
3
+ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, } from "./workflow.js";
4
+ export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, MechanicalPredicate, Predicate, } from "./workflow.js";
5
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, deniedGlobalReferences } 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";
16
+ export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
17
+ export type { AuthorHostAddendum, CandidatePolicyOptions, AuthorWorkflowOptions, AuthoredWorkflow } from "./author.js";
18
+ export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
19
+ export type { WorkflowNodeKind, WorkflowPredicateName } from "./vocabulary.js";
package/dist/index.js CHANGED
@@ -1,8 +1,15 @@
1
1
  export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
2
- export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, } from "./workflow.js";
2
+ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, } from "./workflow.js";
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, } from "./workflow.js";
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, deniedGlobalReferences } from "./code-exec.js";
7
12
  export { resolveSchemaForWorkflow } from "./schema-references.js";
8
13
  export { getPath, predicateMatches } from "./predicates.js";
14
+ export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
15
+ export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
@@ -1,4 +1,4 @@
1
- import { workflowDocumentError, workflowSha256 } from "./workflow.js";
1
+ import { routesByValue, workflowDocumentError, workflowSha256 } from "./workflow.js";
2
2
  import { workflowShapeErrors } from "./workflow-shape.js";
3
3
  const pointer = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
4
4
  /** Inspect a workflow's structure without running authored code, adapters, or schema probes.
@@ -30,7 +30,7 @@ export function inspectWorkflow(value) {
30
30
  if (["agent", "decide", "extract", "report"].includes(node.node) ||
31
31
  node.node === "artifact" && ["markdown", "report"].includes(node.type))
32
32
  adapters.add("runNode");
33
- if (["judge", "pick", "sift", "route"].includes(node.node) ||
33
+ if (["judge", "pick", "sift"].includes(node.node) || node.node === "route" && !routesByValue(node) ||
34
34
  "verify" in node && node.verify || node.node === "loop" && node.until.predicate === "ask" ||
35
35
  node.node === "escalate" && node.when.predicate === "ask")
36
36
  adapters.add("runJudge");
@@ -0,0 +1,7 @@
1
+ export declare const MAX_TIMER_DELAY_MS: number;
2
+ export type LongTimer = {
3
+ clear(): void;
4
+ };
5
+ /** Schedule `fn` after `ms`, re-arming in <= MAX_TIMER_DELAY_MS chunks so a delay past Node's timer
6
+ * limit still fires on time instead of overflowing. `clear()` cancels the pending chunk. */
7
+ export declare function setLongTimeout(fn: () => void, ms: number): LongTimer;
@@ -0,0 +1,22 @@
1
+ // Node's timers accept a delay of at most 2^31-1 ms (~24.8 days); a larger delay silently overflows
2
+ // to a near-immediate fire with a TimeoutOverflowWarning. A workflow's deadline_s, poll.deadline_s,
3
+ // poll.interval_s and retry.backoff_s carry no upper ceiling, so a delay derived from them can exceed
4
+ // that. `setLongTimeout` re-arms in <= MAX_TIMER_DELAY_MS chunks, so the callback fires at the
5
+ // intended time however far out it is, and returns a handle that clears whichever chunk is pending.
6
+ export const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
7
+ /** Schedule `fn` after `ms`, re-arming in <= MAX_TIMER_DELAY_MS chunks so a delay past Node's timer
8
+ * limit still fires on time instead of overflowing. `clear()` cancels the pending chunk. */
9
+ export function setLongTimeout(fn, ms) {
10
+ let remaining = Number.isFinite(ms) ? Math.max(0, ms) : MAX_TIMER_DELAY_MS;
11
+ let handle;
12
+ const tick = () => {
13
+ if (remaining <= MAX_TIMER_DELAY_MS) {
14
+ handle = setTimeout(fn, remaining);
15
+ return;
16
+ }
17
+ remaining -= MAX_TIMER_DELAY_MS;
18
+ handle = setTimeout(tick, MAX_TIMER_DELAY_MS);
19
+ };
20
+ tick();
21
+ return { clear() { clearTimeout(handle); } };
22
+ }
@@ -0,0 +1,3 @@
1
+ /** Copy observation data without reading accessors or sharing mutable data objects.
2
+ * Keep invalid JSON shapes visible so required host trace validation can reject them. */
3
+ export declare function observerSnapshot<T>(value: T): T;
@@ -0,0 +1,46 @@
1
+ import { isProxy } from "node:util/types";
2
+ /** Copy observation data without reading accessors or sharing mutable data objects.
3
+ * Keep invalid JSON shapes visible so required host trace validation can reject them. */
4
+ export function observerSnapshot(value) {
5
+ const seen = new Map();
6
+ const pending = [];
7
+ const copy = (item) => {
8
+ // A proxy can execute code even when its property descriptors are inspected.
9
+ if (isProxy(item))
10
+ return function unavailable() { };
11
+ if (item === null || typeof item !== "object") {
12
+ // Functions are invalid observation data; an inert function preserves that
13
+ // fact without giving an observer the original callable or its properties.
14
+ return typeof item === "function" ? function unavailable() { } : item;
15
+ }
16
+ const known = seen.get(item);
17
+ if (known)
18
+ return known;
19
+ const prototype = Object.getPrototypeOf(item);
20
+ if (prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null)
21
+ return function unavailable() { };
22
+ const target = Array.isArray(item) ? [] : Object.create(prototype);
23
+ seen.set(item, target);
24
+ pending.push([item, target]);
25
+ return target;
26
+ };
27
+ const result = copy(value);
28
+ while (pending.length) {
29
+ const [source, target] = pending.pop();
30
+ for (const key of Reflect.ownKeys(source)) {
31
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
32
+ if ("value" in descriptor)
33
+ descriptor.value = copy(descriptor.value);
34
+ else {
35
+ // Never invoke authored getters, including during cloning. Their shape
36
+ // remains an accessor so a JSON-validating host still fails closed.
37
+ if (descriptor.get)
38
+ descriptor.get = () => undefined;
39
+ if (descriptor.set)
40
+ descriptor.set = () => { };
41
+ }
42
+ Object.defineProperty(target, key, descriptor);
43
+ }
44
+ }
45
+ return result;
46
+ }
@@ -30,5 +30,9 @@ export type AcceptPredicate = StopPredicate | {
30
30
  values: Array<string | number | boolean>;
31
31
  };
32
32
  export declare const MECHANICAL_PREDICATE_NAMES: ReadonlySet<string>;
33
+ /** Resolve a dotted state path the one way every reader does: a record by key, an array by a
34
+ * non-negative integer index, anything else (a string, a number, a missing value) to undefined.
35
+ * `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
36
+ * path that names a value for one names it for all. */
33
37
  export declare function getPath(value: unknown, key: string): unknown;
34
38
  export declare function predicateMatches(predicate: StopPredicate | AcceptPredicate, value: unknown): boolean;
@@ -1,11 +1,28 @@
1
- export const MECHANICAL_PREDICATE_NAMES = new Set(["no_new_items", "field_true", "count_gte", "empty", "field_equals", "in", "gte", "lt"]);
1
+ import { MECHANICAL_PREDICATES } from "./vocabulary.js";
2
+ export const MECHANICAL_PREDICATE_NAMES = new Set(MECHANICAL_PREDICATES);
2
3
  function isRecord(value) {
3
4
  return typeof value === "object" && value !== null && !Array.isArray(value);
4
5
  }
6
+ /** Resolve a dotted state path the one way every reader does: a record by key, an array by a
7
+ * non-negative integer index, anything else (a string, a number, a missing value) to undefined.
8
+ * `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
9
+ * path that names a value for one names it for all. */
5
10
  export function getPath(value, key) {
6
11
  if (!key)
7
12
  return value;
8
- return key.split(".").reduce((current, part) => (isRecord(current) ? current[part] : undefined), value);
13
+ return key.split(".").reduce((current, part) => {
14
+ if (isRecord(current))
15
+ return current[part];
16
+ if (Array.isArray(current)) {
17
+ // Only a position inside the array resolves: a canonical integer below its length. Anything
18
+ // else (a property name, an out-of-range or non-canonical number) is not an element.
19
+ if (!/^(0|[1-9][0-9]*)$/.test(part))
20
+ return undefined;
21
+ const index = Number(part);
22
+ return Number.isSafeInteger(index) && index < current.length ? current[index] : undefined;
23
+ }
24
+ return undefined;
25
+ }, value);
9
26
  }
10
27
  export function predicateMatches(predicate, value) {
11
28
  switch (predicate.predicate) {
@@ -150,6 +150,49 @@ export class SystemOneError extends Error {
150
150
  }
151
151
  }
152
152
  const unit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
153
+ // System One reports probabilities rounded to two places, so the reported sum drifts from 1 by up to
154
+ // half a step per option (3 × 0.33 = 0.99; 8 × 0.13 = 1.04). A distribution is accepted when it could
155
+ // be that rounding of one summing to 1: a value on the two-place grid may be off by ±0.005 (within
156
+ // [0, 1]); any other value is taken as exact. With no grid values this is |sum − 1| ≤ 1e-5, the
157
+ // check for full-precision distributions. Answers are accepted as reported, never rescaled.
158
+ const ROUNDING_HALF_STEP = 0.005;
159
+ const onTwoPlaceGrid = (p) => Math.abs(p * 100 - Math.round(p * 100)) < 1e-9;
160
+ function roundedFromUnitMass(probabilities) {
161
+ let low = 0, high = 0;
162
+ for (const p of probabilities) {
163
+ const step = onTwoPlaceGrid(p) ? ROUNDING_HALF_STEP : 0;
164
+ low += Math.max(0, p - step);
165
+ high += Math.min(1, p + step);
166
+ }
167
+ return low <= 1 + 1e-5 && high >= 1 - 1e-5;
168
+ }
169
+ // A Score's weighted level drifts the same way. The unrounded probabilities lie within their rounding
170
+ // intervals and sum to 1, so Σ level·p lies between two bounds: start every level at its interval's
171
+ // low end, then give the rest of the unit mass to the lowest levels (the minimum) or the highest (the
172
+ // maximum), each up to its interval's high end. A score on the grid is itself off by up to 0.005. The
173
+ // score is accepted when its interval meets [min, max]; with no grid values this is
174
+ // |score − Σ level·p| ≤ 1e-5. A score that is not a number contradicts nothing here and is left to
175
+ // the range check, as before.
176
+ function scoreContradictsDistribution(score, probabilities) {
177
+ const levels = Object.entries(probabilities).map(([level, p]) => {
178
+ const step = onTwoPlaceGrid(p) ? ROUNDING_HALF_STEP : 0;
179
+ return { level: Number(level), low: Math.max(0, p - step), high: Math.min(1, p + step) };
180
+ }).sort((a, b) => a.level - b.level);
181
+ const floor = levels.reduce((sum, l) => sum + l.level * l.low, 0);
182
+ const spare = Math.max(0, 1 - levels.reduce((sum, l) => sum + l.low, 0));
183
+ const fill = (order) => {
184
+ let rest = spare, weighted = floor;
185
+ for (const l of order) {
186
+ const add = Math.min(rest, l.high - l.low);
187
+ weighted += l.level * add;
188
+ rest -= add;
189
+ }
190
+ return weighted;
191
+ };
192
+ const min = fill(levels), max = fill([...levels].reverse());
193
+ const step = onTwoPlaceGrid(score) ? ROUNDING_HALF_STEP : 0;
194
+ return score - step > max + 1e-5 || score + step < min - 1e-5;
195
+ }
153
196
  export function validateAnswers(questions, answers) {
154
197
  if (!answers || typeof answers !== "object" || Array.isArray(answers))
155
198
  throw new SystemOneError("System One response carries no answers", null, undefined, "answers_shape");
@@ -175,14 +218,12 @@ export function validateAnswers(questions, answers) {
175
218
  const probabilityKeys = Object.keys(a.probabilities);
176
219
  if (Array.isArray(a.probabilities) || probabilityKeys.length !== expectedKeys.length || expectedKeys.some(key => !Object.hasOwn(a.probabilities, key)))
177
220
  throw new SystemOneError("System One answer: probabilities must contain exactly the declared options", null, undefined, "probability_keys");
178
- const mass = Object.values(a.probabilities).reduce((sum, p) => sum + p, 0);
179
- if (Math.abs(mass - 1) > 1e-5)
221
+ if (!roundedFromUnitMass(Object.values(a.probabilities)))
180
222
  throw new SystemOneError("System One answer: probabilities must sum to 1", null, undefined, "probability_mass");
181
223
  if (q.type === "score") {
182
224
  if (!a.legend || typeof a.legend !== "object" || Array.isArray(a.legend) || Object.keys(a.legend).length !== expectedKeys.length || q.criteria.some((text, index) => a.legend[String(index)] !== text))
183
225
  throw new SystemOneError("System One answer: legend must match the score criteria", null, undefined, "score_legend");
184
- const weighted = expectedKeys.reduce((sum, key) => sum + Number(key) * a.probabilities[key], 0);
185
- if (Math.abs(weighted - a.score) > 1e-5)
226
+ if (scoreContradictsDistribution(a.score, a.probabilities))
186
227
  throw new SystemOneError("System One answer: score must match its weighted distribution", null, undefined, "score_consistency");
187
228
  }
188
229
  if (q.type === "choice" && !(typeof a.choice === "string" && Object.prototype.hasOwnProperty.call(q.criteria, a.choice)))
@@ -0,0 +1,42 @@
1
+ export declare const WORKFLOW_NODE_KINDS: readonly ["chain", "code", "agent", "decide", "extract", "report", "artifact", "map", "parallel", "loop", "escalate", "call", "workflow", "judge", "pick", "sift", "route"];
2
+ export type WorkflowNodeKind = typeof WORKFLOW_NODE_KINDS[number];
3
+ /** Generative kinds: one adapter session each, answering against a schema. */
4
+ export declare const GENERATIVE_NODE_KINDS: readonly ["agent", "decide", "extract", "report"];
5
+ /** Typed-question kinds: one judge request each, no tools and no session. */
6
+ export declare const JUDGMENT_NODE_KINDS: readonly ["judge", "pick", "sift", "route"];
7
+ /** The fields each node kind accepts. Any other key is an authoring error. */
8
+ export declare const NODE_FIELDS: {
9
+ readonly [Kind in WorkflowNodeKind]: readonly string[];
10
+ };
11
+ /** Fields every node kind accepts in addition to its own. `metadata` is the host's: an optional object of
12
+ * host markers the engine admits, carries and hashes with the document, and never reads. */
13
+ export declare const HOST_NODE_FIELDS: readonly ["metadata"];
14
+ /** Accepted and ignored for older v2 documents; never taught. The engine invokes the adapter once per node. */
15
+ export declare const IGNORED_NODE_FIELDS: {
16
+ readonly [Kind in WorkflowNodeKind]?: readonly string[];
17
+ };
18
+ /** Predicates that read a state value. `poll` accepts only these. */
19
+ export declare const MECHANICAL_PREDICATES: readonly ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items"];
20
+ /** Every predicate `loop.until` and `escalate.when` accept: the mechanical set plus `ask`, a yes/no judge question. */
21
+ export declare const WORKFLOW_PREDICATES: readonly ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items", "ask"];
22
+ export type WorkflowPredicateName = typeof WORKFLOW_PREDICATES[number];
23
+ /** The fields each predicate takes. */
24
+ export declare const PREDICATE_FIELDS: {
25
+ readonly [Name in WorkflowPredicateName]: readonly string[];
26
+ };
27
+ export declare const EFFORT_LEVELS: readonly ["minimal", "low", "medium", "high"];
28
+ /** There is no "off": every generative node thinks. */
29
+ export declare const THINKING_LEVELS: readonly ["low", "medium", "high"];
30
+ export declare const MODEL_TIERS: readonly ["fast", "default", "strong"];
31
+ /** An `agent` node's context: `fresh` sees its instructions and state only; `fork` asks the host to start
32
+ * the node from the caller's transcript, where the host can (a host refuses it where it cannot). */
33
+ export declare const AGENT_CONTEXTS: readonly ["fresh", "fork"];
34
+ export declare const CALL_TRANSPORTS: readonly ["tool", "executor", "shell"];
35
+ export declare const CALL_RETRY_CLASSES: readonly ["timeout", "http_5xx", "http_429", "connection", "exit"];
36
+ /** The closed codes a failed effect carries: a call's, or a code node's that a host runs out of process.
37
+ * `retry.on` names these or the retry classes above. A retry class implies its code (timeout is
38
+ * effect_timeout, exit is effect_exit, the transient transport classes are effect_transport); a host
39
+ * that types a failure itself names the code. */
40
+ export declare const EFFECT_FAILURE_CODES: readonly ["effect_timeout", "effect_exit", "effect_transport", "effect_not_granted", "effect_produces_missing", "effect_path_escape", "effect_code_unsafe", "output_invalid", "state_invalid", "effect_unknown_transport"];
41
+ /** Artifact types the engine itself treats as prose (the report writer). Every other type names a file. */
42
+ export declare const PROSE_ARTIFACT_TYPES: readonly ["markdown", "report"];
@@ -0,0 +1,74 @@
1
+ // The language's closed vocabulary. The validator admits exactly these kinds, fields and predicates,
2
+ // and the author contract names them from the same constants, so the two cannot drift.
3
+ export const WORKFLOW_NODE_KINDS = [
4
+ "chain", "code", "agent", "decide", "extract", "report", "artifact", "map", "parallel", "loop",
5
+ "escalate", "call", "workflow", "judge", "pick", "sift", "route",
6
+ ];
7
+ /** Generative kinds: one adapter session each, answering against a schema. */
8
+ export const GENERATIVE_NODE_KINDS = ["agent", "decide", "extract", "report"];
9
+ /** Typed-question kinds: one judge request each, no tools and no session. */
10
+ export const JUDGMENT_NODE_KINDS = ["judge", "pick", "sift", "route"];
11
+ const GENERATIVE_FIELDS = ["node", "label", "state", "instructions", "sopSection", "out", "as", "requires", "tools", "effort", "thinking", "verify", "tier"];
12
+ /** The fields each node kind accepts. Any other key is an authoring error. */
13
+ export const NODE_FIELDS = {
14
+ chain: ["node", "steps"],
15
+ code: ["node", "label", "code", "as"],
16
+ agent: [...GENERATIVE_FIELDS, "budget_usd", "context"],
17
+ decide: GENERATIVE_FIELDS,
18
+ extract: GENERATIVE_FIELDS,
19
+ report: ["node", "label", "state", "instructions", "sopSection", "requires", "tools", "effort", "thinking"],
20
+ artifact: ["node", "label", "state", "type", "path", "instructions", "sopSection", "requires", "tools", "effort", "thinking"],
21
+ map: ["node", "label", "itemsPath", "body", "as", "resultPath", "maxConcurrency"],
22
+ parallel: ["node", "label", "branches"],
23
+ loop: ["node", "label", "body", "until", "maxIters", "expect_iters"],
24
+ escalate: ["node", "label", "when", "kind", "stage", "summary"],
25
+ call: ["node", "label", "via", "tool", "args", "code", "input", "command", "env", "where", "out", "as", "produces", "deadline_s", "retry", "poll", "requires"],
26
+ workflow: ["node", "label", "workflow", "input", "out", "as"],
27
+ judge: ["node", "label", "state", "out", "as", "requires"],
28
+ pick: ["node", "label", "itemsPath", "describe", "instructions", "state", "allowNone", "as", "requires"],
29
+ sift: ["node", "label", "itemsPath", "describe", "state", "out", "as", "keep", "requires"],
30
+ route: ["node", "label", "state", "instructions", "branches", "unsure", "valuePath", "otherwise", "as", "requires"],
31
+ };
32
+ /** Fields every node kind accepts in addition to its own. `metadata` is the host's: an optional object of
33
+ * host markers the engine admits, carries and hashes with the document, and never reads. */
34
+ export const HOST_NODE_FIELDS = ["metadata"];
35
+ /** Accepted and ignored for older v2 documents; never taught. The engine invokes the adapter once per node. */
36
+ export const IGNORED_NODE_FIELDS = {
37
+ agent: ["budget"],
38
+ decide: ["samples", "voteField"],
39
+ };
40
+ /** Predicates that read a state value. `poll` accepts only these. */
41
+ export const MECHANICAL_PREDICATES = ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items"];
42
+ /** Every predicate `loop.until` and `escalate.when` accept: the mechanical set plus `ask`, a yes/no judge question. */
43
+ export const WORKFLOW_PREDICATES = [...MECHANICAL_PREDICATES, "ask"];
44
+ /** The fields each predicate takes. */
45
+ export const PREDICATE_FIELDS = {
46
+ field_equals: ["path", "value"],
47
+ field_true: ["path"],
48
+ in: ["path", "values"],
49
+ count_gte: ["path", "n"],
50
+ gte: ["path", "n"],
51
+ lt: ["path", "n"],
52
+ empty: ["path"],
53
+ no_new_items: ["key"],
54
+ ask: ["instructions", "state", "criteria", "gte"],
55
+ };
56
+ export const EFFORT_LEVELS = ["minimal", "low", "medium", "high"];
57
+ /** There is no "off": every generative node thinks. */
58
+ export const THINKING_LEVELS = ["low", "medium", "high"];
59
+ export const MODEL_TIERS = ["fast", "default", "strong"];
60
+ /** An `agent` node's context: `fresh` sees its instructions and state only; `fork` asks the host to start
61
+ * the node from the caller's transcript, where the host can (a host refuses it where it cannot). */
62
+ export const AGENT_CONTEXTS = ["fresh", "fork"];
63
+ export const CALL_TRANSPORTS = ["tool", "executor", "shell"];
64
+ export const CALL_RETRY_CLASSES = ["timeout", "http_5xx", "http_429", "connection", "exit"];
65
+ /** The closed codes a failed effect carries: a call's, or a code node's that a host runs out of process.
66
+ * `retry.on` names these or the retry classes above. A retry class implies its code (timeout is
67
+ * effect_timeout, exit is effect_exit, the transient transport classes are effect_transport); a host
68
+ * that types a failure itself names the code. */
69
+ export const EFFECT_FAILURE_CODES = [
70
+ "effect_timeout", "effect_exit", "effect_transport", "effect_not_granted", "effect_produces_missing",
71
+ "effect_path_escape", "effect_code_unsafe", "output_invalid", "state_invalid", "effect_unknown_transport",
72
+ ];
73
+ /** Artifact types the engine itself treats as prose (the report writer). Every other type names a file. */
74
+ export const PROSE_ARTIFACT_TYPES = ["markdown", "report"];
@@ -116,14 +116,18 @@ export function workflowShapeErrors(value, complete = false) {
116
116
  return; // missing bodies already receive semantic diagnostics
117
117
  if (!record(entry, path))
118
118
  return;
119
- strings(entry, path, ["node", "label", "code", "as", "out", "instructions", "itemsPath", "resultPath", "kind", "stage", "summary", "describe", "type", "path", "tool", "command", "via", "where", "effort", "thinking", "tier"]);
120
- numeric(entry, path, ["maxConcurrency", "maxIters", "deadline_s"]);
119
+ strings(entry, path, ["node", "label", "code", "as", "out", "instructions", "itemsPath", "resultPath", "kind", "stage", "summary", "describe", "type", "path", "tool", "command", "via", "where", "effort", "thinking", "tier", "valuePath", "otherwise"]);
120
+ numeric(entry, path, ["maxConcurrency", "maxIters", "expect_iters", "deadline_s"]);
121
121
  for (const key of ["requires", "tools", "produces"])
122
122
  stringList(entry[key], `${path}.${key}`);
123
123
  if (entry.sopSection !== undefined && typeof entry.sopSection !== "string")
124
124
  stringList(entry.sopSection, `${path}.sopSection`);
125
125
  for (const key of ["state", "args", "input", "env"])
126
126
  objectField(entry, path, key);
127
+ // Host-owned and opaque: only its container is checked, never its keys or values.
128
+ if (entry.metadata !== undefined && !isRecord(entry.metadata)) {
129
+ errors.push(`${path} (${typeof entry.label === "string" && entry.label ? entry.label : String(entry.node)}): metadata must be a plain object of host markers`);
130
+ }
127
131
  for (const key of ["until", "when"])
128
132
  objectField(entry, path, key, predicate);
129
133
  objectField(entry, path, "verify", (verify, at) => {