@parcha/agentrun-dsl 0.1.0-beta.30 → 0.1.0-beta.300

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 (68) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +11 -7
  3. package/dist/author-references.d.ts +2 -2
  4. package/dist/author-references.js +2 -2
  5. package/dist/author.d.ts +0 -2
  6. package/dist/author.js +7 -6
  7. package/dist/authoring.js +3 -2
  8. package/dist/cli.js +2 -1
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +11 -2
  12. package/dist/decision-provider.js +12 -4
  13. package/dist/decision-receipts.d.ts +19 -3
  14. package/dist/dry-run.d.ts +31 -1
  15. package/dist/dry-run.js +103 -14
  16. package/dist/edit.d.ts +158 -0
  17. package/dist/edit.js +1486 -0
  18. package/dist/evidence.d.ts +19 -0
  19. package/dist/evidence.js +63 -0
  20. package/dist/index.d.ts +12 -9
  21. package/dist/index.js +14 -9
  22. package/dist/pattern-screen.d.ts +14 -0
  23. package/dist/pattern-screen.js +451 -0
  24. package/dist/pointer-warning.d.ts +14 -0
  25. package/dist/pointer-warning.js +22 -0
  26. package/dist/predicates.d.ts +23 -3
  27. package/dist/predicates.js +48 -6
  28. package/dist/record.d.ts +4 -0
  29. package/dist/record.js +6 -0
  30. package/dist/recovery/binding.js +2 -1
  31. package/dist/recovery/call-key.d.ts +0 -4
  32. package/dist/recovery/call-key.js +0 -7
  33. package/dist/recovery/driver.d.ts +20 -14
  34. package/dist/recovery/driver.js +48 -26
  35. package/dist/recovery/frozen-snapshot.js +8 -8
  36. package/dist/recovery/handoff-receipts.d.ts +0 -35
  37. package/dist/recovery/handoff-receipts.js +2 -44
  38. package/dist/recovery/index.d.ts +2 -7
  39. package/dist/recovery/index.js +2 -6
  40. package/dist/recovery/item-state.d.ts +2 -1
  41. package/dist/recovery/item-state.js +7 -13
  42. package/dist/recovery/with-recovery.js +4 -2
  43. package/dist/submit-envelope.d.ts +1 -1
  44. package/dist/submit-envelope.js +11 -7
  45. package/dist/system-one.d.ts +0 -4
  46. package/dist/system-one.js +7 -8
  47. package/dist/vocabulary.d.ts +7 -2
  48. package/dist/vocabulary.js +7 -1
  49. package/dist/workflow-shape.js +4 -2
  50. package/dist/workflow.d.ts +64 -13
  51. package/dist/workflow.js +506 -202
  52. package/dist/zod-json-contract.js +6 -8
  53. package/package.json +7 -3
  54. package/schema/workflow.schema.json +93 -0
  55. package/skills/author/references/jev-decisions.md +10 -5
  56. package/skills/author/references/language.md +5 -4
  57. package/dist/recovery/effect-failure.d.ts +0 -34
  58. package/dist/recovery/effect-failure.js +0 -62
  59. package/dist/recovery/handoff-block.d.ts +0 -36
  60. package/dist/recovery/handoff-block.js +0 -148
  61. package/dist/recovery/handoff-digest.d.ts +0 -58
  62. package/dist/recovery/handoff-digest.js +0 -195
  63. package/dist/recovery/handoff-files.d.ts +0 -54
  64. package/dist/recovery/handoff-files.js +0 -162
  65. package/dist/recovery/handoff-redact.d.ts +0 -12
  66. package/dist/recovery/handoff-redact.js +0 -44
  67. package/dist/recovery/handoff.d.ts +0 -44
  68. package/dist/recovery/handoff.js +0 -46
@@ -0,0 +1,19 @@
1
+ import type { DecisionEvidence } from "./decision-provider.js";
2
+ /** The longest title an item keeps, in code points. */
3
+ export declare const EVIDENCE_TITLE_MAX = 300;
4
+ /** The longest passage an item keeps, in code points. */
5
+ export declare const EVIDENCE_EXCERPT_MAX = 4096;
6
+ /** The most passages one item keeps. */
7
+ export declare const EVIDENCE_EXCERPTS_PER_ITEM = 5;
8
+ /** The most items a decision's evidence keeps. */
9
+ export declare const EVIDENCE_ITEMS_MAX = 20;
10
+ /** The most code points of titles and passages a decision's evidence keeps, all items together. */
11
+ export declare const EVIDENCE_TEXT_MAX: number;
12
+ /** What a caller keeps of each citation: `excerpts: false` keeps none of its passages. */
13
+ export type EvidenceOptions = {
14
+ excerpts?: boolean;
15
+ };
16
+ /** Raw citations as a decision's evidence. Items in order, each kept or dropped by its URL, its text plain and cut, until
17
+ * the item count or the code-point budget is reached. With `excerpts: false` no item keeps a passage. Idempotent: clean
18
+ * evidence comes back as it went in. */
19
+ export declare function evidenceOf(raw: unknown, { excerpts: withExcerpts }?: EvidenceOptions): DecisionEvidence[];
@@ -0,0 +1,63 @@
1
+ import { isRecord } from "./record.js";
2
+ /** The longest title an item keeps, in code points. */
3
+ export const EVIDENCE_TITLE_MAX = 300;
4
+ /** The longest passage an item keeps, in code points. */
5
+ export const EVIDENCE_EXCERPT_MAX = 4096;
6
+ /** The most passages one item keeps. */
7
+ export const EVIDENCE_EXCERPTS_PER_ITEM = 5;
8
+ /** The most items a decision's evidence keeps. */
9
+ export const EVIDENCE_ITEMS_MAX = 20;
10
+ /** The most code points of titles and passages a decision's evidence keeps, all items together. */
11
+ export const EVIDENCE_TEXT_MAX = 32 * 1024;
12
+ /** The longest `scope` an item keeps, in code points. */
13
+ const SCOPE_MAX = 64;
14
+ // C0 controls but tab, newline and return; DEL and the C1 controls; the Unicode direction marks, overrides and isolates.
15
+ const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g;
16
+ const codePoints = (text) => Array.from(text).length;
17
+ /** `text` with its control characters gone, cut to `max` code points (an ellipsis marking a cut). */
18
+ function plain(text, max) {
19
+ const clean = text.replace(CONTROL, "");
20
+ const chars = Array.from(clean);
21
+ return chars.length <= max ? clean : `${chars.slice(0, Math.max(0, max - 1)).join("")}…`;
22
+ }
23
+ /** The URL as the parser normalizes it, if it is http(s) with no user or password; else undefined, and its item is dropped. */
24
+ function webUrl(url) {
25
+ if (typeof url !== "string")
26
+ return undefined;
27
+ const parsed = URL.parse(url);
28
+ if (!parsed || (parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password)
29
+ return undefined;
30
+ return parsed.href;
31
+ }
32
+ /** Raw citations as a decision's evidence. Items in order, each kept or dropped by its URL, its text plain and cut, until
33
+ * the item count or the code-point budget is reached. With `excerpts: false` no item keeps a passage. Idempotent: clean
34
+ * evidence comes back as it went in. */
35
+ export function evidenceOf(raw, { excerpts: withExcerpts = true } = {}) {
36
+ const kept = [];
37
+ let left = EVIDENCE_TEXT_MAX;
38
+ for (const item of Array.isArray(raw) ? raw : []) {
39
+ if (kept.length >= EVIDENCE_ITEMS_MAX || left <= 0)
40
+ break;
41
+ if (!isRecord(item))
42
+ continue;
43
+ const { url: rawUrl, title: rawTitle, excerpts: rawExcerpts, scope: rawScope } = item;
44
+ const url = webUrl(rawUrl);
45
+ if (!url)
46
+ continue;
47
+ const title = typeof rawTitle === "string" ? plain(rawTitle, Math.min(EVIDENCE_TITLE_MAX, left)) : null;
48
+ left -= title === null ? 0 : codePoints(title);
49
+ const excerpts = [];
50
+ for (const excerpt of withExcerpts && Array.isArray(rawExcerpts) ? rawExcerpts : []) {
51
+ if (excerpts.length >= EVIDENCE_EXCERPTS_PER_ITEM || left <= 0)
52
+ break;
53
+ if (typeof excerpt !== "string")
54
+ continue;
55
+ const text = plain(excerpt, Math.min(EVIDENCE_EXCERPT_MAX, left));
56
+ excerpts.push(text);
57
+ left -= codePoints(text);
58
+ }
59
+ const scope = typeof rawScope === "string" && rawScope ? plain(rawScope, SCOPE_MAX) : "call";
60
+ kept.push({ url, title, excerpts, scope });
61
+ }
62
+ return kept;
63
+ }
package/dist/index.d.ts CHANGED
@@ -1,26 +1,29 @@
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, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, } from "./workflow.js";
3
+ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, MAP_LIMITS, } from "./workflow.js";
4
4
  export { defineJob } from "./job.js";
5
5
  export type { Job } from "./job.js";
6
6
  export { DECISION_RECEIPT_VERSION, DECISION_INTERRUPTED, DECISION_REFUSED, DECISION_STATE_MAX_BYTES, rederiveDecision } from "./decision-receipts.js";
7
- export type { DecisionImageDigest, DecisionKind, DecisionReceipt, DecisionRule } from "./decision-receipts.js";
8
- export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, MapItemFailure, DecisionExchange, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, DecisionEvidenceMode, DecisionImages, MechanicalPredicate, Predicate, ValidationCode, ValidationIssue, ValidateWorkflowOptions, } from "./workflow.js";
9
- export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
7
+ export type { DecisionImageDigest, DecisionKind, DecisionReceipt, DecisionRule, DecisionStateCut, DecisionStateSent } from "./decision-receipts.js";
8
+ export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, MapLimits, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, MapItemFailure, DecisionExchange, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, DecisionEvidenceMode, DecisionImages, MechanicalPredicate, Predicate, ReservedName, ValidationCode, ValidationIssue, ValidateWorkflowOptions, } from "./workflow.js";
9
+ export { dryRunWorkflow, SYNTHESIS_BUDGET, SynthesisTooLarge, synthesizeInstance, type SynthesisBudget } from "./dry-run.js";
10
10
  export type { DryRunOptions, DryRunResult } from "./dry-run.js";
11
11
  export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, deriveConfidence, completeConfidence, refusedQuestions, } from "./system-one.js";
12
12
  export type { SystemOneQuestion, SystemOneAnswer, SystemOneBox, SystemOneResult, SystemOneRetryClass, SystemOneResponseReason, CompiledQuestions, AnswersSidecar, ConfidenceSource, } from "./system-one.js";
13
- export { judgeFromProvider, judgeFromProviders, checkCapabilities, DecisionProviderError, imageDimensions } from "./decision-provider.js";
13
+ export { judgeFromProvider, judgeFromProviders, checkCapabilities, chargedCost, DecisionProviderError, imageDimensions } from "./decision-provider.js";
14
+ export { evidenceOf, EVIDENCE_EXCERPT_MAX, EVIDENCE_EXCERPTS_PER_ITEM, EVIDENCE_ITEMS_MAX, EVIDENCE_TEXT_MAX, EVIDENCE_TITLE_MAX, type EvidenceOptions } from "./evidence.js";
14
15
  export type { DecisionProvider, DecisionCapabilities, DecisionInput, DecisionRequest, DecisionContext, DecisionEvidence, DecisionOutcome, ProviderAnswer, CostBasis, DecisionProviderErrorCode, DecisionImage, LoadImage, JudgeFromProviderOptions, } from "./decision-provider.js";
15
16
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
16
17
  export type { WorkflowInspection, WorkflowInspectionNode } from "./inspection.js";
17
- 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";
18
- export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
18
+ export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA, childSteps, declaredWrites, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY, normalizeStringNullsForSchema, placeholderValue, placeholdersOf, } from "./workflow.js";
19
+ export { compileTransform, compileTransformSyntax, deniedGlobalReferences, type TransformOutcome, transformScript } from "./code-exec.js";
19
20
  export { resolveSchemaForWorkflow } from "./schema-references.js";
21
+ export { formatPointerWarning, parsePointerWarning, type PointerWarning } from "./pointer-warning.js";
22
+ export { patternRisk, PATTERN_SCREEN_LIMITS } from "./pattern-screen.js";
20
23
  export { submitParameters } from "./submit-envelope.js";
21
24
  export { getPath, predicateMatches } from "./predicates.js";
22
25
  export type { StopPredicate, AcceptPredicate } from "./predicates.js";
23
- export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
26
+ export { authorContract, renderAuthorContract, renderAuthorHostAddendum, applyHostOutputTypes, authorWorkflow, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
24
27
  export type { AuthorHostAddendum, CandidatePolicyOptions, AuthorWorkflowOptions, AuthoredWorkflow, HostOutputTypeOptions } from "./author.js";
25
- export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, FIELD_TYPES, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
28
+ export { GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, FIELD_TYPES, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
26
29
  export type { WorkflowNodeKind, WorkflowPredicateName, FieldType } from "./vocabulary.js";
package/dist/index.js CHANGED
@@ -1,19 +1,24 @@
1
1
  export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
2
- export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, } from "./workflow.js";
2
+ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, MAP_LIMITS, } from "./workflow.js";
3
3
  export { defineJob } from "./job.js";
4
4
  export { DECISION_RECEIPT_VERSION, DECISION_INTERRUPTED, DECISION_REFUSED, DECISION_STATE_MAX_BYTES, rederiveDecision } from "./decision-receipts.js";
5
- export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
5
+ export { dryRunWorkflow, SYNTHESIS_BUDGET, SynthesisTooLarge, synthesizeInstance } from "./dry-run.js";
6
6
  export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, deriveConfidence, completeConfidence, refusedQuestions, } from "./system-one.js";
7
- export { judgeFromProvider, judgeFromProviders, checkCapabilities, DecisionProviderError, imageDimensions } from "./decision-provider.js";
7
+ export { judgeFromProvider, judgeFromProviders, checkCapabilities, chargedCost, DecisionProviderError, imageDimensions } from "./decision-provider.js";
8
+ export { evidenceOf, EVIDENCE_EXCERPT_MAX, EVIDENCE_EXCERPTS_PER_ITEM, EVIDENCE_ITEMS_MAX, EVIDENCE_TEXT_MAX, EVIDENCE_TITLE_MAX } from "./evidence.js";
8
9
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
9
10
  export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA,
10
11
  // Document helpers a host facade needs to speak about a workflow without re-implementing the walk.
11
- childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
12
- // Host-side data helpers the interpreter itself uses: the same normalization and reference shaping.
13
- buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
14
- export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
12
+ childSteps, declaredWrites, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
13
+ // The host-side normalization the interpreter itself uses.
14
+ normalizeStringNullsForSchema,
15
+ // Interpolation's placeholders in a string and its lookup order for one, for a host check of what a step reads.
16
+ placeholderValue, placeholdersOf, } from "./workflow.js";
17
+ export { compileTransform, compileTransformSyntax, deniedGlobalReferences, transformScript } from "./code-exec.js";
15
18
  export { resolveSchemaForWorkflow } from "./schema-references.js";
19
+ export { formatPointerWarning, parsePointerWarning } from "./pointer-warning.js";
20
+ export { patternRisk, PATTERN_SCREEN_LIMITS } from "./pattern-screen.js";
16
21
  export { submitParameters } from "./submit-envelope.js";
17
22
  export { getPath, predicateMatches } from "./predicates.js";
18
- export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
19
- export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, FIELD_TYPES, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
23
+ export { authorContract, renderAuthorContract, renderAuthorHostAddendum, applyHostOutputTypes, authorWorkflow, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
24
+ export { GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, FIELD_TYPES, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
@@ -0,0 +1,14 @@
1
+ /** The longest pattern read (characters), and the most quantifiers in one: a schema pattern is a few dozen of each. */
2
+ export declare const PATTERN_SCREEN_LIMITS: {
3
+ readonly chars: 4096;
4
+ readonly quantifiers: 128;
5
+ };
6
+ /** Why `pattern` may backtrack exponentially (or could not be read), or undefined when it is safe to test strings
7
+ * against. */
8
+ export declare function patternRisk(pattern: string): string | undefined;
9
+ /** Each pattern `schema` would test strings with (a `pattern`, a `patternProperties` key) that may backtrack
10
+ * exponentially, with why. */
11
+ export declare function riskyPatterns(schema: unknown): {
12
+ pattern: string;
13
+ why: string;
14
+ }[];
@@ -0,0 +1,451 @@
1
+ // A JSON-schema `pattern` read before any string is tested against it. Schema validation runs each pattern in
2
+ // JavaScript's backtracking engine (typebox compiles it as `new RegExp(pattern, "u")`), where some shapes take time
3
+ // exponential in the string's length: `^(a+)+$` on thirty a's and a "!" holds the thread for half a minute, and every
4
+ // character more doubles it. No engine here runs in linear time, so the shapes that backtrack that way are refused before
5
+ // any string is tested:
6
+ //
7
+ // - a repeated part that repeats something inside it, or holds an optional part, when one pass of the outer repeat can
8
+ // match a run of what the inner one matches (`(a+)+`, `(a?a?)+`, `(\w+\s?)*`, `(.*,){20}`): the run splits between
9
+ // the passes in exponentially many ways. A repeat whose every pass must also match something the inner one can't
10
+ // (`(-[a-z0-9]+)*`, `(?:[.-][a-z0-9]+)*`) is unambiguous and passes.
11
+ // - an alternation repeated without end (or more than 16 times) whose branches can start with the same character
12
+ // (`(a|ab)*`, `(\w|\d)+`).
13
+ // - a backreference (`(a*)\1`): the engine has no bound for it at all.
14
+ //
15
+ // It reads the pattern's own syntax (the `u` flag's), so it never runs it. A pattern it can't read, or one past
16
+ // PATTERN_SCREEN_LIMITS, is refused too: a pattern is refused unless it is read and found safe. Polynomial shapes
17
+ // (`\s*\s*\s*$`) are not refused: their time grows with a power of the length, not exponentially.
18
+ /** The longest pattern read (characters), and the most quantifiers in one: a schema pattern is a few dozen of each. */
19
+ export const PATTERN_SCREEN_LIMITS = { chars: 4_096, quantifiers: 128 };
20
+ const TOP = 0x10ffff;
21
+ function normal(ranges) {
22
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
23
+ const out = [];
24
+ for (const [lo, hi] of sorted) {
25
+ const last = out[out.length - 1];
26
+ if (last && lo <= last[1] + 1)
27
+ last[1] = Math.max(last[1], hi);
28
+ else
29
+ out.push([lo, hi]);
30
+ }
31
+ return out;
32
+ }
33
+ const union = (...sets) => normal(sets.flat());
34
+ function complement(set) {
35
+ const out = [];
36
+ let next = 0;
37
+ for (const [lo, hi] of set) {
38
+ if (lo > next)
39
+ out.push([next, lo - 1]);
40
+ next = hi + 1;
41
+ }
42
+ if (next <= TOP)
43
+ out.push([next, TOP]);
44
+ return out;
45
+ }
46
+ function meets(a, b) {
47
+ for (const [lo, hi] of a)
48
+ for (const [blo, bhi] of b)
49
+ if (lo <= bhi && blo <= hi)
50
+ return true;
51
+ return false;
52
+ }
53
+ const one = (code) => [[code, code]];
54
+ const DIGIT = [[0x30, 0x39]];
55
+ const WORD = normal([[0x30, 0x39], [0x41, 0x5a], [0x5f, 0x5f], [0x61, 0x7a]]);
56
+ const SPACE = normal([[0x09, 0x0d], [0x20, 0x20], [0xa0, 0xa0], [0x1680, 0x1680], [0x2000, 0x200a], [0x2028, 0x2029], [0x202f, 0x202f], [0x205f, 0x205f], [0x3000, 0x3000], [0xfeff, 0xfeff]]);
57
+ const ANY = [[0, TOP]];
58
+ const DOT = complement(normal([[0x0a, 0x0a], [0x0d, 0x0d], [0x2028, 0x2029]]));
59
+ const SINGLE = { t: 0x09, n: 0x0a, v: 0x0b, f: 0x0c, r: 0x0d };
60
+ const CLASS_ESCAPES = { d: DIGIT, D: complement(DIGIT), w: WORD, W: complement(WORD), s: SPACE, S: complement(SPACE) };
61
+ /** The characters a `u`-flag pattern lets an escape stand for (and `-` in a class). */
62
+ const SYNTAX = new Set([..."^$\\.*+?()[]{}|/"]);
63
+ class Unreadable extends Error {
64
+ }
65
+ /** A `u`-flag pattern's parse: alternatives, sequences, repeats, character sets, anchors, lookarounds, references. */
66
+ class Parser {
67
+ source;
68
+ i = 0;
69
+ quantifiers = 0;
70
+ cps;
71
+ constructor(source) {
72
+ this.source = source;
73
+ this.cps = [...source].map((c) => c.codePointAt(0));
74
+ }
75
+ get at() {
76
+ return this.i < this.cps.length ? String.fromCodePoint(this.cps[this.i]) : undefined;
77
+ }
78
+ take() {
79
+ const c = this.at;
80
+ if (c === undefined)
81
+ throw new Unreadable("the pattern ends early");
82
+ this.i++;
83
+ return c;
84
+ }
85
+ eat(text) {
86
+ const there = this.cps.slice(this.i, this.i + text.length).map((c) => String.fromCodePoint(c)).join("");
87
+ if (there !== text)
88
+ return false;
89
+ this.i += text.length;
90
+ return true;
91
+ }
92
+ whole() {
93
+ const re = this.alt();
94
+ if (this.i < this.cps.length)
95
+ throw new Unreadable(`unexpected "${this.at}"`);
96
+ return re;
97
+ }
98
+ alt() {
99
+ const alts = [this.seq()];
100
+ while (this.eat("|"))
101
+ alts.push(this.seq());
102
+ return alts.length === 1 ? alts[0] : { k: "alt", alts };
103
+ }
104
+ seq() {
105
+ const items = [];
106
+ while (this.at !== undefined && this.at !== "|" && this.at !== ")") {
107
+ const start = this.i;
108
+ items.push(this.quantified(this.atom(), start));
109
+ }
110
+ return items.length === 1 ? items[0] : { k: "seq", items };
111
+ }
112
+ quantified(atom, start) {
113
+ let min;
114
+ let max;
115
+ if (this.eat("*"))
116
+ [min, max] = [0, Infinity];
117
+ else if (this.eat("+"))
118
+ [min, max] = [1, Infinity];
119
+ else if (this.eat("?"))
120
+ [min, max] = [0, 1];
121
+ else if (this.at === "{") {
122
+ const match = /^\{(\d+)(,(\d*))?\}/.exec(this.cps.slice(this.i).map((c) => String.fromCodePoint(c)).join(""));
123
+ if (!match)
124
+ throw new Unreadable("a { that is no quantifier");
125
+ this.i += match[0].length;
126
+ min = Number(match[1]);
127
+ max = match[2] === undefined ? min : match[3] === "" ? Infinity : Number(match[3]);
128
+ }
129
+ else
130
+ return atom;
131
+ this.eat("?");
132
+ if (++this.quantifiers > PATTERN_SCREEN_LIMITS.quantifiers)
133
+ throw new Unreadable(`more than ${PATTERN_SCREEN_LIMITS.quantifiers} quantifiers`);
134
+ const text = this.cps.slice(start, this.i).map((c) => String.fromCodePoint(c)).join("");
135
+ return { k: "rep", body: atom, min, max, text };
136
+ }
137
+ group() {
138
+ const body = this.alt();
139
+ if (!this.eat(")"))
140
+ throw new Unreadable("a group that does not close");
141
+ return body;
142
+ }
143
+ atom() {
144
+ const c = this.take();
145
+ if (c === "(") {
146
+ if (this.eat("?:"))
147
+ return this.group();
148
+ if (this.eat("?=") || this.eat("?!") || this.eat("?<=") || this.eat("?<!"))
149
+ return { k: "zero", body: this.group() };
150
+ if (this.eat("?<")) {
151
+ while (this.at !== ">")
152
+ this.take();
153
+ this.take();
154
+ return this.group();
155
+ }
156
+ if (this.at === "?")
157
+ throw new Unreadable("an unknown group");
158
+ return this.group();
159
+ }
160
+ if (c === "^" || c === "$")
161
+ return { k: "zero" };
162
+ if (c === ".")
163
+ return { k: "set", set: DOT };
164
+ if (c === "[")
165
+ return { k: "set", set: this.cls() };
166
+ if (c === "\\")
167
+ return this.escape(false);
168
+ if (c === ")" || c === "*" || c === "+" || c === "?" || c === "{" || c === "}" || c === "]")
169
+ throw new Unreadable(`a stray "${c}"`);
170
+ return { k: "set", set: one(c.codePointAt(0)) };
171
+ }
172
+ hex(digits) {
173
+ let text = "";
174
+ for (let n = 0; n < digits; n++)
175
+ text += this.take();
176
+ if (!/^[0-9a-fA-F]+$/.test(text))
177
+ throw new Unreadable("a bad hex escape");
178
+ return parseInt(text, 16);
179
+ }
180
+ /** An escape after its backslash: a set (one character or a class), or outside a class an anchor or a reference. */
181
+ escape(inClass) {
182
+ const c = this.take();
183
+ if (CLASS_ESCAPES[c])
184
+ return { k: "set", set: CLASS_ESCAPES[c] };
185
+ if (SINGLE[c] !== undefined)
186
+ return { k: "set", set: one(SINGLE[c]) };
187
+ if (c === "b")
188
+ return inClass ? { k: "set", set: one(0x08) } : { k: "zero" };
189
+ if (c === "B" && !inClass)
190
+ return { k: "zero" };
191
+ if (c === "p" || c === "P") {
192
+ if (!this.eat("{"))
193
+ throw new Unreadable("a property escape without {");
194
+ while (this.at !== "}")
195
+ this.take();
196
+ this.take();
197
+ return { k: "set", set: ANY };
198
+ }
199
+ if (c === "k" && !inClass) {
200
+ if (!this.eat("<"))
201
+ throw new Unreadable("a named reference without <");
202
+ while (this.at !== ">")
203
+ this.take();
204
+ this.take();
205
+ return { k: "ref" };
206
+ }
207
+ if (/[1-9]/.test(c)) {
208
+ if (inClass)
209
+ throw new Unreadable("a reference in a class");
210
+ while (this.at !== undefined && /[0-9]/.test(this.at))
211
+ this.take();
212
+ return { k: "ref" };
213
+ }
214
+ if (c === "0") {
215
+ if (this.at !== undefined && /[0-9]/.test(this.at))
216
+ throw new Unreadable("an octal escape");
217
+ return { k: "set", set: one(0) };
218
+ }
219
+ if (c === "x")
220
+ return { k: "set", set: one(this.hex(2)) };
221
+ if (c === "u") {
222
+ if (this.eat("{")) {
223
+ let text = "";
224
+ while (this.at !== "}")
225
+ text += this.take();
226
+ this.take();
227
+ if (!/^[0-9a-fA-F]{1,6}$/.test(text) || parseInt(text, 16) > TOP)
228
+ throw new Unreadable("a bad code point escape");
229
+ return { k: "set", set: one(parseInt(text, 16)) };
230
+ }
231
+ const unit = this.hex(4);
232
+ // A surrogate pair written as two escapes is one character.
233
+ if (unit >= 0xd800 && unit <= 0xdbff && this.eat("\\u")) {
234
+ const low = this.hex(4);
235
+ return { k: "set", set: one(0x10000 + ((unit - 0xd800) << 10) + (low - 0xdc00)) };
236
+ }
237
+ return { k: "set", set: one(unit) };
238
+ }
239
+ if (c === "c") {
240
+ const letter = this.take();
241
+ if (!/[A-Za-z]/.test(letter))
242
+ throw new Unreadable("a bad control escape");
243
+ return { k: "set", set: one(letter.charCodeAt(0) % 32) };
244
+ }
245
+ if (SYNTAX.has(c) || (inClass && c === "-"))
246
+ return { k: "set", set: one(c.codePointAt(0)) };
247
+ throw new Unreadable(`an unknown escape \\${c}`);
248
+ }
249
+ /** A class after its [: its characters, negated when it opens with ^. */
250
+ cls() {
251
+ const negated = this.eat("^");
252
+ const parts = [];
253
+ const member = () => {
254
+ const c = this.take();
255
+ if (c === "\\")
256
+ return this.escape(true).set;
257
+ return one(c.codePointAt(0));
258
+ };
259
+ while (!this.eat("]")) {
260
+ const low = member();
261
+ if (this.at === "-" && this.cps[this.i + 1] !== undefined && String.fromCodePoint(this.cps[this.i + 1]) !== "]") {
262
+ this.take();
263
+ const high = member();
264
+ if (low.length !== 1 || high.length !== 1 || low[0][0] !== low[0][1] || high[0][0] !== high[0][1])
265
+ throw new Unreadable("a range of a class");
266
+ if (low[0][0] > high[0][0])
267
+ throw new Unreadable("a range out of order");
268
+ parts.push([[low[0][0], high[0][0]]]);
269
+ }
270
+ else
271
+ parts.push(low);
272
+ }
273
+ const set = union(...parts);
274
+ return negated ? complement(set) : set;
275
+ }
276
+ }
277
+ /** Every character `re` may consume. */
278
+ function alphabet(re) {
279
+ switch (re.k) {
280
+ case "set": return re.set;
281
+ case "seq": return union(...re.items.map(alphabet));
282
+ case "alt": return union(...re.alts.map(alphabet));
283
+ case "rep": return re.max === 0 ? [] : alphabet(re.body);
284
+ default: return [];
285
+ }
286
+ }
287
+ function nullable(re) {
288
+ switch (re.k) {
289
+ case "set": return false;
290
+ case "seq": return re.items.every(nullable);
291
+ case "alt": return re.alts.some(nullable);
292
+ case "rep": return re.min === 0 || nullable(re.body);
293
+ default: return true;
294
+ }
295
+ }
296
+ /** The characters a match of `re` may start with. */
297
+ function first(re) {
298
+ switch (re.k) {
299
+ case "set": return re.set;
300
+ case "seq": {
301
+ const sets = [];
302
+ for (const item of re.items) {
303
+ sets.push(first(item));
304
+ if (!nullable(item))
305
+ break;
306
+ }
307
+ return union(...sets);
308
+ }
309
+ case "alt": return union(...re.alts.map(first));
310
+ case "rep": return re.max === 0 ? [] : first(re.body);
311
+ default: return [];
312
+ }
313
+ }
314
+ /** Whether `re` can match a string of characters all in `chars`: not at all (0), only the empty string (1), or a
315
+ * non-empty one (2). */
316
+ function within(re, chars) {
317
+ switch (re.k) {
318
+ case "set": return meets(re.set, chars) ? 2 : 0;
319
+ case "seq": {
320
+ let best = 1;
321
+ for (const item of re.items) {
322
+ const got = within(item, chars);
323
+ if (got === 0)
324
+ return 0;
325
+ if (got === 2)
326
+ best = 2;
327
+ }
328
+ return best;
329
+ }
330
+ case "alt": return Math.max(...re.alts.map((alt) => within(alt, chars)));
331
+ case "rep": {
332
+ if (re.max === 0)
333
+ return 1;
334
+ const got = within(re.body, chars);
335
+ return got === 0 ? (re.min === 0 ? 1 : 0) : got;
336
+ }
337
+ case "ref": return 1;
338
+ default: return 1;
339
+ }
340
+ }
341
+ /** Every part of `re` below it (itself excluded), lookaround bodies included. */
342
+ function* parts(re) {
343
+ const children = re.k === "seq" ? re.items : re.k === "alt" ? re.alts : re.k === "rep" ? [re.body] : re.k === "zero" && re.body ? [re.body] : [];
344
+ for (const child of children) {
345
+ yield child;
346
+ yield* parts(child);
347
+ }
348
+ }
349
+ /** The most passes of a repeat whose alternatives start alike that is let through: its branches' tries, multiplied
350
+ * across the passes, stay bounded. */
351
+ const ALTERNATION_PASSES = 16;
352
+ const repeats = (re) => re.k === "rep" && re.max >= 2;
353
+ /** Why `pattern` may backtrack exponentially (or could not be read), or undefined when it is safe to test strings
354
+ * against. */
355
+ export function patternRisk(pattern) {
356
+ // One the engine refuses never runs: the schema's compile says so.
357
+ try {
358
+ new RegExp(pattern, "u");
359
+ }
360
+ catch {
361
+ return undefined;
362
+ }
363
+ if (pattern.length > PATTERN_SCREEN_LIMITS.chars)
364
+ return `it is longer than the ${PATTERN_SCREEN_LIMITS.chars} characters a pattern may be`;
365
+ let re;
366
+ try {
367
+ re = new Parser(pattern).whole();
368
+ }
369
+ catch (error) {
370
+ return `it could not be read (${error instanceof Unreadable ? error.message : "an unreadable pattern"})`;
371
+ }
372
+ for (const outer of [re, ...parts(re)]) {
373
+ if (outer.k === "ref")
374
+ return "it has a backreference, which can take exponential time";
375
+ if (!repeats(outer))
376
+ continue;
377
+ for (const inner of [outer.body, ...parts(outer.body)]) {
378
+ // An inner repeat of a varying count (an optional part `a?` among them), a run of whose characters one pass of the
379
+ // outer repeat can match: a run splits between the passes in exponentially many ways (`(a+)+`, `(a?a?)+`).
380
+ if (inner.k === "rep" && inner.max > inner.min && within(outer.body, alphabet(inner.body)) === 2) {
381
+ return `"${outer.text}" repeats "${inner.text}" inside a repeat that can match the same text more than one way, which can take exponential time`;
382
+ }
383
+ // Alternatives that can start alike, repeated without end (or many times): each pass may take either. A few passes
384
+ // (`(25[0-5]|2[0-4][0-9]|[0-9]{1,2})\.){3}`, an IPv4 address) try a few branches each, a bounded number in all.
385
+ if (inner.k === "alt" && outer.max > ALTERNATION_PASSES) {
386
+ const starts = inner.alts.map(first);
387
+ if (starts.some((start, a) => starts.slice(a + 1).some((other) => meets(start, other)))) {
388
+ return `"${outer.text}" repeats alternatives that can start with the same character, which can take exponential time`;
389
+ }
390
+ }
391
+ }
392
+ }
393
+ return undefined;
394
+ }
395
+ /** Keywords whose values are data, never a schema: a "pattern" key inside them is no pattern. */
396
+ const VALUE_KEYWORDS = new Set(["const", "enum", "default", "examples"]);
397
+ /** Keywords whose values map names (never keywords) to schemas. */
398
+ const NAME_MAPS = new Set(["properties", "patternProperties", "definitions", "$defs", "dependentSchemas"]);
399
+ /** Patterns already read, each with why it is refused ("" when it is not): a workflow is validated more than once. */
400
+ const verdicts = new Map();
401
+ const VERDICTS = 1_000;
402
+ /** Each pattern `schema` would test strings with (a `pattern`, a `patternProperties` key) that may backtrack
403
+ * exponentially, with why. */
404
+ export function riskyPatterns(schema) {
405
+ const found = [];
406
+ const seen = new Set();
407
+ const check = (pattern) => {
408
+ if (seen.has(pattern))
409
+ return;
410
+ seen.add(pattern);
411
+ let why = verdicts.get(pattern);
412
+ if (why === undefined) {
413
+ why = patternRisk(pattern) ?? "";
414
+ if (verdicts.size >= VERDICTS)
415
+ verdicts.clear();
416
+ verdicts.set(pattern, why);
417
+ }
418
+ if (why)
419
+ found.push({ pattern, why });
420
+ };
421
+ // Every value reached, however deep (a document's own bounds limit its depth): a pattern the walk did not reach would
422
+ // be tested unscreened. Each object once, so a value reached two ways (or a cycle a host built) is read once.
423
+ const seenObjects = new Set();
424
+ const stack = [schema];
425
+ while (stack.length) {
426
+ const value = stack.pop();
427
+ if (!value || typeof value !== "object" || seenObjects.has(value))
428
+ continue;
429
+ seenObjects.add(value);
430
+ if (Array.isArray(value)) {
431
+ stack.push(...value);
432
+ continue;
433
+ }
434
+ for (const [key, child] of Object.entries(value)) {
435
+ if (VALUE_KEYWORDS.has(key))
436
+ continue;
437
+ if (key === "pattern" && typeof child === "string")
438
+ check(child);
439
+ else if (NAME_MAPS.has(key) && child && typeof child === "object" && !Array.isArray(child)) {
440
+ for (const [name, sub] of Object.entries(child)) {
441
+ if (key === "patternProperties")
442
+ check(name);
443
+ stack.push(sub);
444
+ }
445
+ }
446
+ else
447
+ stack.push(child);
448
+ }
449
+ }
450
+ return found;
451
+ }
@@ -0,0 +1,14 @@
1
+ /** A warning's parts: the validation code, the JSON Pointer (RFC 6901) of what it is about ("" for the document), and
2
+ * the message. */
3
+ export type PointerWarning = {
4
+ code: string;
5
+ pointer: string;
6
+ message: string;
7
+ };
8
+ /** `<code> at <pointer>: <message>`, or `<code>: <message>` for the pointer "". A route branch's name may hold ": ", and
9
+ * so may a pointer through it: in the text, the pointer's ":" is written `%3A` and its "%" `%25` (as a URI fragment
10
+ * writes them), so the first ":" after " at " ends the pointer. A pointer with neither reads as it is. */
11
+ export declare function formatPointerWarning(code: string, pointer: string, message: string): string;
12
+ /** The parts of a text `formatPointerWarning` wrote, its pointer as written in the workflow, or null for any other text
13
+ * (or a value that is not a string). */
14
+ export declare function parsePointerWarning(text: unknown): PointerWarning | null;