@parcha/agentrun-dsl 0.1.0-beta.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ AgentRun
2
+ Copyright 2026 Parcha Labs, Inc.
package/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # @parcha/agentrun-dsl
2
+
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
+
5
+ This is an unpublished `0.1.0-beta.1` candidate. Requires Node 22.19+; TypeScript consumers require TypeScript 5.4+.
6
+
7
+ ```js
8
+ import { runTriageDemo } from '@parcha/agentrun-dsl/demo';
9
+ const { result } = await runTriageDemo('billing');
10
+ console.log(result.output); // { queue: 'billing', priority: 'normal' }
11
+ ```
12
+
13
+ The demo runs real control flow with scripted judgments. `ambiguous` escalates. No model SDK or API key is required by the core. Optional `@parcha/agentrun-jev` and `@parcha/agentrun-pi` adapters add live judgments and agent steps.
14
+
15
+ The `agentrun` CLI provides `demo`, `example`, `inspect`, `validate`, `dry-run`, and deterministic `run`. `inspect workflow.json [--json]` displays structure without executing code. Validation/run require `--trusted` because workflow JavaScript can execute, including during validation. This package is not an isolation boundary.
16
+
17
+ `runWorkflow(workflow, input, deps)` returns a complete schema-validated output or an escalation; its TypeScript output type is `unknown`. `defineWorkflow` binds Standard JSON Schema contracts, including supported Zod schemas, to a frozen v2 document; `runTypedWorkflow` infers those input/output types and delegates to the same interpreter. Intermediate state paths remain runtime-validated. Execution and verification failures throw. Hosts own tools, durable storage, file delivery, idempotency, recovery, and activation.
18
+
19
+ Raw JSON schemas retain `unknown` boundary types. Zod transforms, refinements, defaults and coercion are rejected rather than silently dropped. The core does not depend on Zod at runtime. Other Standard JSON Schema providers must faithfully represent their contracts. Typed execution accepts the original `defineWorkflow` result; copied or deserialized documents use `runWorkflow`.
20
+
21
+ ## Public API
22
+
23
+ The package root exports a deliberate API. The beta retains agent, structured-output, report, artifact, effect, child-workflow and focused-evaluation paths. Hosts supply their adapters and policy; a workflow cannot grant itself tool permissions.
24
+
25
+ | Group | Exports and purpose |
26
+ | --- | --- |
27
+ | Typed authoring | `defineWorkflow`, `runTypedWorkflow`, `WorkflowSchemaConversionError`; `StandardJSONSchema`, `AuthoringSchema`, `TypedWorkflow`, `WorkflowInput`, `WorkflowOutput`, `TypedWorkflowRunResult`. |
28
+ | Structural inspection | `inspectWorkflow`, `formatWorkflowTree`; `WorkflowInspection`, `WorkflowInspectionNode`. Reads structure and capability requirements; does not perform semantic validation or run code probes. |
29
+ | Run and inspect | `runWorkflow`, `validateWorkflow`, `workflowSha256`, `dryRunWorkflow`; core contracts `Workflow`, `WorkflowNode`, `WorkflowDeps`, `WorkflowRunResult`, plus the named node, predicate, effect, effort and result types. |
30
+ | Recognize outcomes | `WorkflowInvalidError`, `WorkflowInputInvalidError`, `WorkflowOutputInvalidError`, `WorkflowVerificationError`, `EffectFailure`, `EffectDeadlineExceededError`, `EffectOutcomeUnknownError`, `EscalationSignal`. A concurrent failure may contain typed outcomes in `AggregateError.errors`; inspect them before deciding whether an effect is safe to retry. |
31
+ | Build judgment adapters | `compileQuestions`, `validateAnswers`, `answersToValue`, `answersSidecar`, `answerConfidence`, `SYSTEM_ONE_LIMITS`, `SystemOneError`; `SystemOneQuestion`, `SystemOneAnswer`, `SystemOneResult`, `SystemOneRetryClass`, `CompiledQuestions`, `AnswersSidecar`. |
32
+ | Integrate a host | `runWorkflowSlice`, `assertWorkflowCapabilities`, `desugarWorkflow`, `resolveSchemaForWorkflow`, `stageSchemaForNode`, `submissionSchemaForNode`, `mergeStageDelta`, `REPORT_SCHEMA`, `SHELL_RESULT_SCHEMA`, `getPath`, `predicateMatches`. |
33
+ | Test without a model | `synthesizeInstance`, `synthesizeAnswers`, `DryRunOptions`, `DryRunResult`. Synthetic answers exercise execution mechanics; they do not establish judgment quality. |
34
+
35
+ `runWorkflowSlice` runs selected root steps against supplied state and optional seed data. It returns the slice state without checking the full workflow's terminal output contract. Use `runWorkflow` for a complete run. `getPath` reads dot-separated record keys, returning `undefined` when the path leaves an object. `predicateMatches` evaluates mechanical predicates only; use `field_equals` with an explicit path for a stored label.
36
+
37
+ The schema helpers resolve the owning workflow's schema catalog; `stageSchemaForNode` and `submissionSchemaForNode` name the same submission contract. `mergeStageDelta` stores declared submission fields under the node's output key; callers must validate the submission first. Internal traversal, compilation, CSV, reference-file and input-normalization helpers are not package-root APIs.
38
+
39
+ The separate `@parcha/agentrun-dsl/demo` entrypoint provides the support-triage example. `@parcha/agentrun-dsl/schema` provides the generated workflow JSON Schema.
40
+
41
+ Children can contain maps, loops, routes, parallel branches and other children, and appear inside those structures. Their input/state and schema catalogs stay isolated; terminal report/artifact delivery remains parent-owned. New composed structures require path-aware recovery stores when recovery is enabled. `executionPath` is supplied to adapters, events and checkpoint/recovery hooks. Existing host validators and durable-cursor limits remain authoritative.
42
+
43
+ ## Bounds
44
+
45
+ These are the current beta's validation limits. Hosts may impose tighter budgets; the bounds below are not configurable unless an override is named.
46
+
47
+ | Setting | Bound |
48
+ | --- | --- |
49
+ | Document traversal | At most 100,000 visited values and 128 levels of object nesting; cycles, accessors and proxies rejected |
50
+ | `loop.maxIters` | Integer 1–20 |
51
+ | `verify.maxDrives` | Integer 1–4; default 2 |
52
+ | `call.deadline_s` | Greater than 0 and at most 3,600 seconds |
53
+ | `call.retry.attempts` | Integer 1–5, including the first attempt |
54
+ | `call.poll.interval_s` | 0.1–300 seconds |
55
+ | `call.poll.deadline_s` | At least the call deadline and at most 7,200 seconds |
56
+ | Choice options / route branches | At most 240; `pick.allowNone` reserves one option |
57
+ | Score rubric | 2–10 levels, indexed from 0 |
58
+ | Questions per judgment request | Default 256; override with host-owned `WorkflowDeps.maxQuestionsPerRequest` |
59
+ | Jev context | Selected provider's token limits; an adapter host may configure an additional byte guard |
60
+
61
+ The question-count guard applies after collection expansion, including `sift` items multiplied by their questions. It is a host budget guard, not a claim about a provider's service limit.
62
+
63
+ `System One` names TypeSafe's typed-question interface used by the judgment types. A `noul` answer is a truth probability from 0 to 1; `answersToValue` turns values at least 0.5 into `true`. Choice and score confidence comes from the adapter response; Noul confidence is `2 × |probability − 0.5|`. Neither is a calibration guarantee.
64
+
65
+ ## License
66
+
67
+ Apache-2.0. See the included LICENSE and NOTICE files.
@@ -0,0 +1,72 @@
1
+ import { type Workflow, type WorkflowDeps, type WorkflowNode, type WorkflowRunResult } from "./workflow.js";
2
+ /** Structural Standard JSON Schema v1 interface. Compatible schema libraries need no
3
+ * AgentRun adapter or runtime dependency. See https://standardschema.dev/json-schema. */
4
+ export interface StandardJSONSchema<Input = unknown, Output = Input> {
5
+ readonly "~standard": {
6
+ readonly version: 1;
7
+ readonly vendor: string;
8
+ readonly types?: {
9
+ readonly input: Input;
10
+ readonly output: Output;
11
+ };
12
+ readonly jsonSchema: {
13
+ readonly input: (options: {
14
+ readonly target: string;
15
+ readonly libraryOptions?: Record<string, unknown>;
16
+ }) => Record<string, unknown>;
17
+ readonly output: (options: {
18
+ readonly target: string;
19
+ readonly libraryOptions?: Record<string, unknown>;
20
+ }) => Record<string, unknown>;
21
+ };
22
+ };
23
+ }
24
+ export type AuthoringSchema = StandardJSONSchema | Record<string, unknown>;
25
+ type SchemaInput<S> = S extends StandardJSONSchema ? NonNullable<S["~standard"]["types"]>["input"] : unknown;
26
+ type SchemaOutput<S> = S extends StandardJSONSchema ? NonNullable<S["~standard"]["types"]>["output"] : unknown;
27
+ declare const workflowTypes: unique symbol;
28
+ export type TypedWorkflow<Input, Output> = Workflow & {
29
+ readonly [workflowTypes]: {
30
+ readonly input: Input;
31
+ readonly output: Output;
32
+ };
33
+ };
34
+ export type WorkflowInput<W extends TypedWorkflow<unknown, unknown>> = W[typeof workflowTypes]["input"];
35
+ export type WorkflowOutput<W extends TypedWorkflow<unknown, unknown>> = W[typeof workflowTypes]["output"];
36
+ export type TypedWorkflowRunResult<Output> = (Omit<Extract<WorkflowRunResult, {
37
+ status: "complete";
38
+ }>, "output"> & {
39
+ output: Output;
40
+ }) | Extract<WorkflowRunResult, {
41
+ status: "escalated";
42
+ }>;
43
+ export declare class WorkflowSchemaConversionError extends Error {
44
+ readonly schemaId: string;
45
+ readonly code = "schema_conversion_failed";
46
+ constructor(schemaId: string, cause: unknown);
47
+ }
48
+ type Definition<S extends Record<string, AuthoringSchema>, I extends keyof S & string, O extends keyof S & string> = {
49
+ name: string;
50
+ schemas: S;
51
+ input: I;
52
+ output: {
53
+ schema: O;
54
+ path?: string;
55
+ };
56
+ } & ({
57
+ steps: WorkflowNode[];
58
+ root?: never;
59
+ } | {
60
+ root: WorkflowNode;
61
+ steps?: never;
62
+ });
63
+ /** Author with schema libraries; execute the same JSON language as every other host.
64
+ * Input uses the provider's input JSON Schema, all other schemas its output JSON Schema.
65
+ * These are JSON contracts, NOT schema-library parsers: transforms, coercion, defaults,
66
+ * and arbitrary refinements are not executed. Known lossy Zod constructs are rejected;
67
+ * other providers must supply faithful JSON contracts through their converter.
68
+ * Raw JSON schemas (including Jev criteria) remain supported and infer unknown.
69
+ * Node references and state paths remain runtime-validated, not statically inferred. */
70
+ export declare function defineWorkflow<const S extends Record<string, AuthoringSchema>, I extends keyof S & string, O extends keyof S & string>(definition: Definition<S, I, O>): TypedWorkflow<SchemaInput<S[I]>, SchemaOutput<S[O]>>;
71
+ export declare function runTypedWorkflow<W extends TypedWorkflow<unknown, unknown>>(workflow: W, input: NoInfer<WorkflowInput<W>>, deps: WorkflowDeps): Promise<TypedWorkflowRunResult<WorkflowOutput<W>>>;
72
+ export {};
@@ -0,0 +1,138 @@
1
+ import { runWorkflow, validateWorkflow, resolveSchemaForWorkflow, WorkflowInvalidError, } from "./workflow.js";
2
+ import { isDeepStrictEqual, types as utilTypes } from "node:util";
3
+ import { assertZodJsonContract } from "./zod-json-contract.js";
4
+ const authoredWorkflows = new WeakSet();
5
+ export class WorkflowSchemaConversionError extends Error {
6
+ schemaId;
7
+ code = "schema_conversion_failed";
8
+ constructor(schemaId, cause) {
9
+ super(`schema "${schemaId}" cannot be represented as JSON Schema: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
10
+ this.schemaId = schemaId;
11
+ this.name = "WorkflowSchemaConversionError";
12
+ }
13
+ }
14
+ /** Author with schema libraries; execute the same JSON language as every other host.
15
+ * Input uses the provider's input JSON Schema, all other schemas its output JSON Schema.
16
+ * These are JSON contracts, NOT schema-library parsers: transforms, coercion, defaults,
17
+ * and arbitrary refinements are not executed. Known lossy Zod constructs are rejected;
18
+ * other providers must supply faithful JSON contracts through their converter.
19
+ * Raw JSON schemas (including Jev criteria) remain supported and infer unknown.
20
+ * Node references and state paths remain runtime-validated, not statically inferred. */
21
+ export function defineWorkflow(definition) {
22
+ const schemas = {};
23
+ for (const [id, source] of Object.entries(definition.schemas)) {
24
+ try {
25
+ let schema = source;
26
+ if (source && typeof source === "object" && "~standard" in source) {
27
+ const standard = source["~standard"];
28
+ if (standard.version !== 1 || typeof standard.vendor !== "string" || !standard.jsonSchema) {
29
+ throw new Error("expected Standard JSON Schema v1 conversion methods");
30
+ }
31
+ if (standard.vendor === "zod")
32
+ assertZodJsonContract(source, id === definition.input);
33
+ const input = standard.jsonSchema.input({ target: "draft-07" });
34
+ const output = standard.jsonSchema.output({ target: "draft-07" });
35
+ schema = id === definition.input ? input : output;
36
+ if (id === definition.input && id === definition.output.schema) {
37
+ if (!isDeepStrictEqual(input, output)) {
38
+ throw new Error("input and output conversions differ; declare separate input and output schema entries");
39
+ }
40
+ }
41
+ }
42
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
43
+ throw new Error("expected a JSON Schema object");
44
+ Object.defineProperty(schemas, id, { value: cloneJson(schema), enumerable: true, writable: true, configurable: true });
45
+ }
46
+ catch (error) {
47
+ throw new WorkflowSchemaConversionError(id, error);
48
+ }
49
+ }
50
+ const document = cloneJson({
51
+ v: 2,
52
+ name: definition.name,
53
+ schemas,
54
+ input: { schemaId: definition.input },
55
+ output: { schemaId: definition.output.schema, ...(definition.output.path === undefined ? {} : { path: definition.output.path }) },
56
+ root: definition.root ?? { node: "chain", steps: definition.steps },
57
+ });
58
+ const result = validateWorkflow(document);
59
+ if (!result.ok)
60
+ throw new WorkflowInvalidError(document.name, result.errors);
61
+ const inputSchema = resolveSchemaForWorkflow(document, document.schemas[definition.input]);
62
+ if (!objectContract(inputSchema)) {
63
+ throw new WorkflowSchemaConversionError(definition.input, new Error("workflow input must be constrained to JSON objects; declare type: object or object-only schema alternatives"));
64
+ }
65
+ freezeJson(document);
66
+ authoredWorkflows.add(document);
67
+ return document;
68
+ }
69
+ function objectContract(value) {
70
+ if (!value || typeof value !== "object" || Array.isArray(value))
71
+ return false;
72
+ const schema = value;
73
+ if (schema.type === "object" || Array.isArray(schema.type) && schema.type.length === 1 && schema.type[0] === "object")
74
+ return true;
75
+ for (const key of ["anyOf", "oneOf"]) {
76
+ if (Array.isArray(schema[key]) && schema[key].length > 0 && schema[key].every(objectContract))
77
+ return true;
78
+ }
79
+ return Array.isArray(schema.allOf) && schema.allOf.some(objectContract);
80
+ }
81
+ export async function runTypedWorkflow(workflow, input, deps) {
82
+ // A TypeScript object spread preserves phantom properties even when callers
83
+ // replace a schema. Only the immutable definition we checked owns these types.
84
+ if (!authoredWorkflows.has(workflow)) {
85
+ throw new Error("runTypedWorkflow requires the original document returned by defineWorkflow; use runWorkflow for copied or imported JSON");
86
+ }
87
+ return await runWorkflow(workflow, input, deps);
88
+ }
89
+ function cloneJson(value) {
90
+ return copyJson(value, new Set(), { entries: 0 }, 0);
91
+ }
92
+ function copyJson(value, ancestors, budget, depth) {
93
+ if (++budget.entries > 100_000)
94
+ throw new Error("workflow document exceeds 100000 expanded values");
95
+ if (depth > 128)
96
+ throw new Error("workflow document exceeds nesting depth 128");
97
+ if (value === null || typeof value === "string" || typeof value === "boolean")
98
+ return value;
99
+ if (typeof value === "number" && Number.isFinite(value))
100
+ return value;
101
+ if (typeof value !== "object" || value === null)
102
+ throw new Error("workflow documents must contain only finite JSON values");
103
+ if (utilTypes.isProxy(value))
104
+ throw new Error("workflow documents must not contain proxies");
105
+ if (ancestors.has(value))
106
+ throw new Error("workflow documents must not contain cycles");
107
+ const prototype = Object.getPrototypeOf(value);
108
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
109
+ throw new Error("workflow documents must contain plain JSON objects");
110
+ if (Object.getOwnPropertySymbols(value).length)
111
+ throw new Error("workflow documents must not contain symbol properties");
112
+ // Conversion libraries may attach non-enumerable Standard Schema methods to
113
+ // the result. They are not JSON fields and never enter the emitted document.
114
+ const descriptors = Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([, descriptor]) => descriptor.enumerable);
115
+ if (descriptors.some(([, descriptor]) => descriptor.get || descriptor.set))
116
+ throw new Error("workflow documents must not contain accessors");
117
+ if (budget.entries + descriptors.length > 100_000)
118
+ throw new Error("workflow document exceeds 100000 expanded values");
119
+ if (Array.isArray(value) && budget.entries + value.length > 100_000)
120
+ throw new Error("workflow document exceeds 100000 expanded values");
121
+ ancestors.add(value);
122
+ try {
123
+ if (Array.isArray(value)) {
124
+ return Array.from({ length: value.length }, (_, index) => copyJson(Object.getOwnPropertyDescriptor(value, String(index))?.value, ancestors, budget, depth + 1));
125
+ }
126
+ return Object.fromEntries(descriptors.map(([key, descriptor]) => [key, copyJson(descriptor.value, ancestors, budget, depth + 1)]));
127
+ }
128
+ finally {
129
+ ancestors.delete(value);
130
+ }
131
+ }
132
+ function freezeJson(value) {
133
+ if (!value || typeof value !== "object" || Object.isFrozen(value))
134
+ return;
135
+ for (const child of Object.values(value))
136
+ freezeJson(child);
137
+ Object.freeze(value);
138
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import { relative, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { runWorkflow, validateWorkflow } from "./workflow.js";
6
+ import { dryRunWorkflow } from "./dry-run.js";
7
+ import { demoScenarios, runTriageDemo, supportTriage } from "./demo.js";
8
+ import { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
9
+ const help = `AgentRun DSL — build, test, and run agent workflows
10
+
11
+ agentrun demo [--scenario billing|technical|ambiguous] [--json]
12
+ agentrun example [file.json] Write the demo workflow (never overwrite)
13
+ agentrun inspect workflow.json [--json] Show structure without executing code
14
+ agentrun validate workflow.json [input.json] --trusted
15
+ agentrun dry-run workflow.json [input.json] --trusted
16
+ agentrun run workflow.json input.json --trusted
17
+
18
+ demo runs the real interpreter with scripted judgments, without a key or network.
19
+ run supports deterministic workflows; use the JavaScript API to supply agent,
20
+ Jev, or effect adapters. --trusted acknowledges that authored code may execute
21
+ during validation and running. Only use workflows you trust; this is not a sandbox.
22
+ validate checks a supplied input against the workflow's input contract.
23
+ dry-run uses supplied input, or synthesizes it from the declared input schema.
24
+ Without an input schema, dry-run starts with an empty input object.
25
+ `;
26
+ async function main(args) {
27
+ const [command] = args;
28
+ if (!command || command === "--help" || command === "help" || command === "-h") {
29
+ console.log(help);
30
+ return;
31
+ }
32
+ if (command === "demo") {
33
+ let scenario = "billing";
34
+ let scenarioProvided = false;
35
+ let json = false;
36
+ const usage = "Usage: agentrun demo [--scenario billing|technical|ambiguous] [--json]";
37
+ for (let i = 1; i < args.length; i++) {
38
+ const arg = args[i];
39
+ if (arg === "--json") {
40
+ json = true;
41
+ continue;
42
+ }
43
+ if (arg !== "--scenario")
44
+ throw new Error(`Unexpected demo argument "${arg}". ${usage}`);
45
+ if (scenarioProvided)
46
+ throw new Error(`Pass --scenario only once. ${usage}`);
47
+ const value = args[++i];
48
+ if (!value || value.startsWith("--"))
49
+ throw new Error(`--scenario needs a value. ${usage}`);
50
+ if (!Object.prototype.hasOwnProperty.call(demoScenarios, value))
51
+ throw new Error(`Unknown scenario "${value}". Choose billing, technical, or ambiguous.`);
52
+ scenario = value;
53
+ scenarioProvided = true;
54
+ }
55
+ const demo = await runTriageDemo(scenario);
56
+ if (json)
57
+ console.log(JSON.stringify(demo, null, 2));
58
+ else {
59
+ console.log("AgentRun · real control flow, scripted judgments\n");
60
+ console.log(`Ticket: ${demo.input.ticket}\n`);
61
+ for (const event of demo.events)
62
+ console.log(` ${event.label} · ${event.type}`);
63
+ console.log(`\nStatus: ${demo.result.status}`);
64
+ console.log(JSON.stringify(demo.result.status === "complete" ? demo.result.output : demo.result.escalation, null, 2));
65
+ const cliPath = relative(process.cwd(), fileURLToPath(import.meta.url));
66
+ const quotedPath = `'${cliPath.replace(/'/g, "'\\''")}'`;
67
+ console.log(`\nSave this workflow: node ${quotedPath} example workflow.json`);
68
+ }
69
+ return;
70
+ }
71
+ if (command === "example") {
72
+ const target = resolve(args[1] || "workflow.json");
73
+ await writeFile(target, `${JSON.stringify(supportTriage, null, 2)}\n`, { flag: "wx" });
74
+ console.log(`Wrote ${target}`);
75
+ return;
76
+ }
77
+ if (command === "inspect") {
78
+ const positional = args.slice(1).filter(arg => arg !== "--json");
79
+ if (positional.length !== 1 || positional[0].startsWith("--"))
80
+ throw new Error("Usage: agentrun inspect workflow.json [--json]");
81
+ const inspection = inspectWorkflow(JSON.parse(await readFile(resolve(positional[0]), "utf8")));
82
+ console.log(args.includes("--json") ? JSON.stringify(inspection, null, 2) : formatWorkflowTree(inspection));
83
+ return;
84
+ }
85
+ if (!["validate", "dry-run", "run"].includes(command))
86
+ throw new Error(`Unknown command "${command}". Use agentrun --help.`);
87
+ if (!args.includes("--trusted"))
88
+ throw new Error("Pass --trusted only after reviewing the workflow. Authored JavaScript may execute, including during validation.");
89
+ const positional = args.slice(1).filter(arg => arg !== "--trusted");
90
+ const unknown = positional.find(arg => arg.startsWith("--"));
91
+ if (unknown)
92
+ throw new Error(`Unknown option "${unknown}". Use agentrun --help.`);
93
+ if (!positional[0])
94
+ throw new Error("Provide a workflow JSON file.");
95
+ if (positional.length > 2)
96
+ throw new Error(`Usage: agentrun ${command} workflow.json ${command === "run" ? "input.json" : "[input.json]"} --trusted`);
97
+ if (command === "run" && !positional[1])
98
+ throw new Error("Provide an input JSON file.");
99
+ const workflow = JSON.parse(await readFile(resolve(positional[0]), "utf8"));
100
+ let input;
101
+ if (positional[1]) {
102
+ let parsed;
103
+ try {
104
+ parsed = JSON.parse(await readFile(resolve(positional[1]), "utf8"));
105
+ }
106
+ catch (error) {
107
+ throw new Error(`Cannot read input JSON file "${positional[1]}": ${error instanceof Error ? error.message : String(error)}`);
108
+ }
109
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
110
+ throw new Error("Input JSON must be an object.");
111
+ input = parsed;
112
+ }
113
+ if (command === "validate") {
114
+ const result = validateWorkflow(workflow, input === undefined ? undefined : { input });
115
+ console.log(JSON.stringify(result, null, 2));
116
+ if (!result.ok)
117
+ process.exitCode = 1;
118
+ }
119
+ else if (command === "dry-run") {
120
+ const result = await dryRunWorkflow(workflow, input === undefined ? undefined : { input });
121
+ console.log(JSON.stringify(result, null, 2));
122
+ if (!result.ok)
123
+ process.exitCode = 1;
124
+ }
125
+ else {
126
+ const result = await runWorkflow(workflow, input, {});
127
+ console.log(JSON.stringify(result, null, 2));
128
+ if (result.status !== "complete")
129
+ process.exitCode = 2;
130
+ }
131
+ }
132
+ main(process.argv.slice(2)).catch(error => {
133
+ console.error(error instanceof Error ? error.message : "Workflow failed.");
134
+ process.exitCode = 1;
135
+ });
@@ -0,0 +1,4 @@
1
+ /** Parse the same expression as trusted execution, without evaluating it or calling its body.
2
+ * Syntax validity does not prove that the expression produces a function or a valid patch. */
3
+ export declare function compileTransformSyntax(src: string): void;
4
+ export declare function compileTransform(src: string): (value: any, ctx?: any) => any;