@parcha/agentrun-dsl 0.1.0-beta.33 → 0.1.0-beta.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Typed workflows that your agent writes. It drafts a workflow, checks it, dry-runs it for free, then runs it; `@parcha/agentrun-dsl/graph` turns the workflow into its graph. The core provides the v2 workflow types, validator, interpreter, events, schema, and an offline CLI. Supply agent, judgment, and effect functions only when a workflow needs them.
4
4
 
5
- Beta, on npm under the `latest` dist-tag (`npm view @parcha/agentrun-dsl dist-tags`). Requires Node 22.19+; TypeScript consumers require TypeScript 5.4+.
5
+ Beta, on npm under the `latest` dist-tag (`npm view @parcha/agentrun-dsl dist-tags`). Requires Node 24.22.3+; TypeScript consumers require TypeScript 5.4+.
6
6
 
7
7
  ```sh
8
8
  npm install @parcha/agentrun-dsl@latest
package/dist/dry-run.d.ts CHANGED
@@ -11,7 +11,24 @@ export type DryRunResult = {
11
11
  problems: string[];
12
12
  stage?: string;
13
13
  };
14
- export declare function synthesizeInstance(schema: unknown, definitions?: Record<string, unknown>, depth?: number): unknown;
14
+ /** What one dry run may synthesize in all, across its input and every step's answer (DryRunOptions.budget), and what one
15
+ * synthesizeInstance call may when none is given: values (each array item, object, string, number...) and string
16
+ * characters. Synthesis counts each before it makes it and throws SynthesisTooLarge past either, so a schema that asks
17
+ * for a huge value (nested arrays of a large minItems, a long minLength) never allocates past the budget. */
18
+ export type SynthesisBudget = {
19
+ values: number;
20
+ chars: number;
21
+ };
22
+ /** The default: a million values and 16 million characters, far past what a real workflow's dry run builds (a few
23
+ * thousand values at most), and well within a host's memory (a few hundred MB at worst). */
24
+ export declare const SYNTHESIS_BUDGET: Readonly<SynthesisBudget>;
25
+ /** The schema asked synthesis for more than its budget: the dry run ends not run, saying so. */
26
+ export declare class SynthesisTooLarge extends Error {
27
+ name: string;
28
+ }
29
+ /** A value of `schema` (its `$ref`s read from `definitions`), synthesized within `budget` (SYNTHESIS_BUDGET when none):
30
+ * past it, SynthesisTooLarge. */
31
+ export declare function synthesizeInstance(schema: unknown, definitions?: Record<string, unknown>, depth?: number, budget?: Partial<SynthesisBudget>): unknown;
15
32
  export type DryRunOptions = {
16
33
  sop?: string;
17
34
  probeContext?: {
@@ -28,5 +45,15 @@ export type DryRunOptions = {
28
45
  * stops, as not run: synthetic answers can keep a loop going to its bound, and a map over a long list. 10,000 by
29
46
  * default. */
30
47
  maxSteps?: number;
48
+ /** What the whole dry run may synthesize (SynthesisBudget): its input and every step's answer together. Past it the dry
49
+ * run stops, as not run ("the schema is too large to synthesize"). SYNTHESIS_BUDGET by default. */
50
+ budget?: Partial<SynthesisBudget>;
51
+ /** The longest the dry run may take by the clock (ms): past it, it stops at its next node or step, as not run. Read
52
+ * from the clock at each, never from a timer, so a dry run that never yields still stops. 60,000 by default. */
53
+ deadlineMs?: number;
54
+ /** The most node visits (a loop's body each iteration, a map's body for each item, any node run), whether or not they
55
+ * ask anything, before the dry run stops, as not run: a loop whose body asks nothing is no step, so maxSteps alone
56
+ * never ends it. Ten times maxSteps by default. */
57
+ maxVisits?: number;
31
58
  };
32
59
  export declare function dryRunWorkflow(workflow: Workflow, opts?: DryRunOptions): Promise<DryRunResult>;
package/dist/dry-run.js CHANGED
@@ -13,29 +13,63 @@ function syntheticProviders(workflow) {
13
13
  const provider = (id) => ({ id, needs: [], capabilities, decide: async () => { throw new Error("A dry run answers its decisions itself."); } });
14
14
  return { providers: Object.fromEntries([...ids].map((id) => [id, provider(id)])), default: "dry-run" };
15
15
  }
16
- export function synthesizeInstance(schema, definitions = {}, depth = 0) {
16
+ /** The default: a million values and 16 million characters, far past what a real workflow's dry run builds (a few
17
+ * thousand values at most), and well within a host's memory (a few hundred MB at worst). */
18
+ export const SYNTHESIS_BUDGET = { values: 1_000_000, chars: 16_000_000 };
19
+ /** The schema asked synthesis for more than its budget: the dry run ends not run, saying so. */
20
+ export class SynthesisTooLarge extends Error {
21
+ name = "SynthesisTooLarge";
22
+ }
23
+ /** A budget's limits, each field the default unless given as a number (a field given as undefined keeps the default). */
24
+ const spendOf = (limit = {}) => ({
25
+ values: 0,
26
+ chars: 0,
27
+ limit: { values: typeof limit.values === "number" ? limit.values : SYNTHESIS_BUDGET.values, chars: typeof limit.chars === "number" ? limit.chars : SYNTHESIS_BUDGET.chars },
28
+ });
29
+ /** A literal's characters as the value it is (a const, an enum's first): its serialized size. */
30
+ const literalChars = (value) => JSON.stringify(value)?.length ?? 0;
31
+ function charge(spend, values, chars) {
32
+ spend.values += values;
33
+ spend.chars += chars;
34
+ if (spend.values > spend.limit.values || spend.chars > spend.limit.chars) {
35
+ throw new SynthesisTooLarge(`the schema is too large to synthesize: past ${spend.limit.values} values or ${spend.limit.chars} characters`);
36
+ }
37
+ }
38
+ /** A value of `schema` (its `$ref`s read from `definitions`), synthesized within `budget` (SYNTHESIS_BUDGET when none):
39
+ * past it, SynthesisTooLarge. */
40
+ export function synthesizeInstance(schema, definitions = {}, depth = 0, budget = SYNTHESIS_BUDGET) {
41
+ return synthesize(schema, definitions, depth, spendOf(budget));
42
+ }
43
+ function synthesize(schema, definitions, depth, spend) {
44
+ // Every value it makes is counted before it is made, once (a $ref, an anyOf or a oneOf is the value it leads to, not one
45
+ // of its own): past the budget it throws, having built no more than the budget.
17
46
  if (depth > 12 || !schema || typeof schema !== "object")
18
- return null;
47
+ return (charge(spend, 1, 0), null);
19
48
  const spec = schema;
20
49
  if (typeof spec.$ref === "string") {
21
50
  const match = /^#\/definitions\/(.+)$/.exec(spec.$ref);
22
- return match && definitions[match[1]] ? synthesizeInstance(definitions[match[1]], definitions, depth + 1) : null;
51
+ return match && definitions[match[1]] ? synthesize(definitions[match[1]], definitions, depth + 1, spend) : (charge(spend, 1, 0), null);
23
52
  }
53
+ // A literal is charged its serialized size: one written long in the schema does not escape the character budget.
24
54
  if (spec.const !== undefined)
25
- return spec.const;
55
+ return (charge(spend, 1, literalChars(spec.const)), spec.const);
26
56
  if (Array.isArray(spec.enum) && spec.enum.length)
27
- return spec.enum[0];
57
+ return (charge(spend, 1, literalChars(spec.enum[0])), spec.enum[0]);
28
58
  if (Array.isArray(spec.anyOf) && spec.anyOf.length) {
29
59
  const branch = spec.anyOf.find((candidate) => candidate?.type !== "null") ?? spec.anyOf[0];
30
- return synthesizeInstance(branch, definitions, depth + 1);
60
+ return synthesize(branch, definitions, depth + 1, spend);
31
61
  }
32
62
  if (Array.isArray(spec.oneOf) && spec.oneOf.length)
33
- return synthesizeInstance(spec.oneOf[0], definitions, depth + 1);
63
+ return synthesize(spec.oneOf[0], definitions, depth + 1, spend);
64
+ // The one value made below.
65
+ charge(spend, 1, 0);
34
66
  const type = Array.isArray(spec.type) ? spec.type[0] : spec.type;
35
67
  if (type === "object" || (!type && spec.properties)) {
36
68
  const out = Object.create(null);
37
69
  for (const [key, property] of Object.entries(spec.properties || {})) {
38
- out[key] = synthesizeInstance(property, definitions, depth + 1);
70
+ // Its name is built into every value made under it, and serialized with it: charged before it is added.
71
+ charge(spend, 0, key.length);
72
+ out[key] = synthesize(property, definitions, depth + 1, spend);
39
73
  }
40
74
  return { ...out };
41
75
  }
@@ -45,12 +79,17 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
45
79
  const min = Number.isInteger(spec.minItems) ? spec.minItems : 1;
46
80
  if (!spec.items)
47
81
  return [];
48
- return Array.from({ length: Math.max(1, min) }, () => synthesizeInstance(spec.items, definitions, depth + 1));
82
+ // Each item is at least one value: a length past what the budget has left is refused before the array is made.
83
+ const length = Math.max(1, min);
84
+ if (length > spend.limit.values - spend.values)
85
+ charge(spend, length, 0);
86
+ return Array.from({ length }, () => synthesize(spec.items, definitions, depth + 1, spend));
49
87
  }
50
88
  if (type === "string") {
51
89
  if (spec.maxLength === 0)
52
90
  return "";
53
91
  const min = Number.isInteger(spec.minLength) ? spec.minLength : 1;
92
+ charge(spend, 0, Math.max(1, min));
54
93
  return "x".repeat(Math.max(1, min));
55
94
  }
56
95
  if (type === "integer") {
@@ -90,6 +129,8 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
90
129
  return false;
91
130
  if (type === "null")
92
131
  return null;
132
+ // A schema synthesis cannot read: one character.
133
+ charge(spend, 0, 1);
93
134
  return "x";
94
135
  }
95
136
  function unsupportedConstructs(schema, path, found, depth = 0) {
@@ -151,10 +192,20 @@ export async function dryRunWorkflow(workflow, opts = {}) {
151
192
  scanSchemas(workflow);
152
193
  if (skipped.length)
153
194
  return { ok: true, status: "not_run", skipped };
195
+ // One budget for everything this dry run synthesizes.
196
+ const spend = spendOf(opts.budget);
154
197
  let input = opts.input ?? {};
155
198
  if (opts.input === undefined && workflow.input) {
156
199
  const schema = resolveSchemaForWorkflow(workflow, workflow.schemas[workflow.input.schemaId]);
157
- const generated = synthesizeInstance(schema, schema.definitions ?? workflow.schemas);
200
+ let generated;
201
+ try {
202
+ generated = synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend);
203
+ }
204
+ catch (error) {
205
+ if (error instanceof SynthesisTooLarge)
206
+ return { ok: true, status: "not_run", skipped: [error.message] };
207
+ throw error;
208
+ }
158
209
  if (!generated || typeof generated !== "object" || Array.isArray(generated) || !Compile(schema).Check(generated)) {
159
210
  return { ok: true, status: "not_run", skipped: ["Could not synthesize a valid input object. Supply input explicitly to dryRunWorkflow or the dry-run CLI."] };
160
211
  }
@@ -173,12 +224,43 @@ export async function dryRunWorkflow(workflow, opts = {}) {
173
224
  // Why the dry run stopped early, kept here: the interpreter may wrap what an adapter throws.
174
225
  let stopped;
175
226
  const stop = (reason) => { stopped ??= reason; throw new Error(stopped); };
227
+ /** A step's synthetic answer within the run's budget: past it, the dry run stops (the interpreter may wrap the throw). */
228
+ const synthesized = (make) => {
229
+ try {
230
+ return make();
231
+ }
232
+ catch (error) {
233
+ if (error instanceof SynthesisTooLarge)
234
+ stop(error.message);
235
+ throw error;
236
+ }
237
+ };
238
+ const deadlineMs = opts.deadlineMs ?? 60_000;
239
+ const deadline = Date.now() + deadlineMs;
240
+ const maxVisits = opts.maxVisits ?? maxSteps * 10;
241
+ let visits = 0;
242
+ const pastDeadline = () => {
243
+ if (Date.now() > deadline)
244
+ stop(`The dry run stopped past its ${deadlineMs} ms deadline.`);
245
+ };
246
+ /** A node's visit (a loop's body each iteration, a map's body for each item), counted against maxVisits and the
247
+ * deadline, so a loop whose body asks nothing (no step) still ends. Synchronous: it reads the clock, never a timer, so
248
+ * a run that never yields still stops. */
249
+ const visit = () => {
250
+ if (opts.signal?.aborted)
251
+ stop("The dry run was stopped before it finished.");
252
+ visits += 1;
253
+ if (visits > maxVisits)
254
+ stop(`The dry run stopped after ${maxVisits} node visits: on synthetic values the workflow's loops or maps go on further, asking nothing. Supply input, or lower a loop's maxIters.`);
255
+ pastDeadline();
256
+ };
176
257
  const step = async () => {
177
258
  if (opts.signal?.aborted)
178
259
  stop("The dry run was stopped before it finished.");
179
260
  steps += 1;
180
261
  if (steps > maxSteps)
181
262
  stop(`The dry run stopped after ${maxSteps} synthetic steps: on synthetic values the workflow's loops or maps go on further. Supply input, or lower a loop's maxIters.`);
263
+ pastDeadline();
182
264
  if (steps % 64 === 0) {
183
265
  await new Promise((resolve) => setTimeout(resolve, 0));
184
266
  if (opts.signal?.aborted)
@@ -188,13 +270,14 @@ export async function dryRunWorkflow(workflow, opts = {}) {
188
270
  const runCode = opts.runCode;
189
271
  try {
190
272
  const result = await runWorkflow(workflow, input, {
273
+ onVisit: () => visit(),
191
274
  sop: opts.sop,
192
275
  ...(runCode ? { runCode: async (...args) => { await step(); return runCode(...args); } } : {}),
193
276
  onEvent: (event) => { if (typeof event.label === "string")
194
277
  currentLabel = event.label; },
195
278
  runNode: async ({ schema, review }) => {
196
279
  await step();
197
- const candidate = synthesizeInstance(schema, schema.definitions ?? workflow.schemas);
280
+ const candidate = synthesized(() => synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend));
198
281
  if (review)
199
282
  await review(candidate);
200
283
  return candidate;
@@ -202,7 +285,11 @@ export async function dryRunWorkflow(workflow, opts = {}) {
202
285
  // A node that requires evidence gets a placeholder, as a provider that gives evidence would answer it.
203
286
  runJudge: async ({ questions, evidence }) => {
204
287
  await step();
205
- return { answers: synthesizeAnswers(questions), model: "synthetic", usage: null, cost_usd: null, request_sha256: "",
288
+ // Its answers are synthetic values like any step's: each charged its serialized size against the run's budget (a
289
+ // choice's first option may be a long string, and a map collects one per item).
290
+ const answers = synthesizeAnswers(questions);
291
+ synthesized(() => charge(spend, Object.keys(answers).length, literalChars(answers)));
292
+ return { answers, model: "synthetic", usage: null, cost_usd: null, request_sha256: "",
206
293
  ...(evidence === "required" ? { evidence: [{ url: "https://example.invalid/dry-run", title: null, excerpts: [], scope: "dry_run" }] } : {}) };
207
294
  },
208
295
  syntheticEffects: true,
@@ -211,7 +298,7 @@ export async function dryRunWorkflow(workflow, opts = {}) {
211
298
  await step();
212
299
  return node.via === "shell"
213
300
  ? { code: 0, stdout: "{}", stderr: "", truncated: false }
214
- : synthesizeInstance(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {});
301
+ : synthesized(() => synthesize(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {}, 0, spend));
215
302
  },
216
303
  });
217
304
  if (result.status === "escalated") {
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ 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
7
  export type { DecisionImageDigest, DecisionKind, DecisionReceipt, DecisionRule } from "./decision-receipts.js";
8
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";
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";
@@ -15,7 +15,7 @@ export { evidenceOf, EVIDENCE_EXCERPT_MAX, EVIDENCE_EXCERPTS_PER_ITEM, EVIDENCE_
15
15
  export type { DecisionProvider, DecisionCapabilities, DecisionInput, DecisionRequest, DecisionContext, DecisionEvidence, DecisionOutcome, ProviderAnswer, CostBasis, DecisionProviderErrorCode, DecisionImage, LoadImage, JudgeFromProviderOptions, } from "./decision-provider.js";
16
16
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
17
17
  export type { WorkflowInspection, WorkflowInspectionNode } from "./inspection.js";
18
- 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 { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA, childSteps, declaredWrites, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY, normalizeStringNullsForSchema, } from "./workflow.js";
19
19
  export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
20
20
  export { resolveSchemaForWorkflow } from "./schema-references.js";
21
21
  export { submitParameters } from "./submit-envelope.js";
package/dist/index.js CHANGED
@@ -2,16 +2,16 @@ export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from
2
2
  export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, } 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
7
  export { judgeFromProvider, judgeFromProviders, checkCapabilities, chargedCost, DecisionProviderError, imageDimensions } from "./decision-provider.js";
8
8
  export { evidenceOf, EVIDENCE_EXCERPT_MAX, EVIDENCE_EXCERPTS_PER_ITEM, EVIDENCE_ITEMS_MAX, EVIDENCE_TEXT_MAX, EVIDENCE_TITLE_MAX } from "./evidence.js";
9
9
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
10
10
  export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA,
11
11
  // Document helpers a host facade needs to speak about a workflow without re-implementing the walk.
12
- childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
13
- // Host-side data helpers the interpreter itself uses: the same normalization and reference shaping.
14
- buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
12
+ childSteps, declaredWrites, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
13
+ // The host-side normalization the interpreter itself uses.
14
+ normalizeStringNullsForSchema, } from "./workflow.js";
15
15
  export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
16
16
  export { resolveSchemaForWorkflow } from "./schema-references.js";
17
17
  export { submitParameters } from "./submit-envelope.js";
@@ -7,7 +7,3 @@ export declare const CALL_KEY_BYTES = 256;
7
7
  * call always has the same key, and two different wide ids share a key only on a digest collision.
8
8
  * Only keys use it: what goes back to the provider is always the id it minted. */
9
9
  export declare function callKey(callId: string): string;
10
- /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
11
- * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
12
- * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
13
- export declare function heldCallKey(callId: string, holds: (rawKey: string) => boolean): string;
@@ -15,10 +15,3 @@ export function callKey(callId) {
15
15
  const prefix = callId.slice(0, PREFIX_CHARS).replace(/[^A-Za-z0-9_.-]/g, "_");
16
16
  return `${prefix}~${createHash("sha256").update(callId).digest("hex").slice(0, DIGEST_HEX)}`;
17
17
  }
18
- /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
19
- * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
20
- * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
21
- export function heldCallKey(callId, holds) {
22
- const key = callKey(callId);
23
- return key !== callId && holds(callId) ? callId : key;
24
- }
@@ -1,4 +1,4 @@
1
- import type { RecoveryEffect, RecoveryIntent } from "./store.js";
1
+ import type { RecoveryIntent } from "./store.js";
2
2
  /** A completed tool effect a continuation may answer an exact repeat from: the external call it paid for, and its value. */
3
3
  export type InheritedReceipt = {
4
4
  id: string;
@@ -21,18 +21,6 @@ export type InheritedUnknown = {
21
21
  * an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
22
22
  * never prose. */
23
23
  export declare function returnedFailure(value: unknown): boolean;
24
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
25
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
26
- * failure. */
27
- export declare function inheritableReceipts(effects: readonly RecoveryEffect[]): InheritedReceipt[];
28
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
29
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
30
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
31
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
32
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
33
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
34
- * has none, and is matched by name and hash only. */
35
- export declare function inheritableUnknowns(effects: readonly RecoveryEffect[]): InheritedUnknown[];
36
24
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
37
25
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
38
26
  * The same key is computed for an effect from its receipt's intent. */
@@ -19,29 +19,6 @@ export function returnedFailure(value) {
19
19
  }
20
20
  return false;
21
21
  }
22
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
23
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
24
- * failure. */
25
- export function inheritableReceipts(effects) {
26
- return effects.filter((e) => e.status === "completed" && e.result && typeof e.result === "object" && e.result.intent && typeof e.result.intent.tool === "string" && !returnedFailure(e.result.value))
27
- .map((e) => {
28
- const receipt = e.result;
29
- // Keyed as a continuation's own call is: a node that reached the gateway through the fetch wrapper paid for the tool the wrapper names.
30
- const { tool, argsHash } = gatewayIntentOf(receipt.intent.tool, receipt.intent.args ?? {});
31
- return { id: e.id, name: e.name, tool, argsHash, result: receipt.value, session: e.session };
32
- });
33
- }
34
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
35
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
36
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
37
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
38
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
39
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
40
- * has none, and is matched by name and hash only. */
41
- export function inheritableUnknowns(effects) {
42
- return effects.filter((e) => e.status === "unknown").map((e) => ({ id: e.id, name: e.name, argsHash: e.argsHash, session: e.session,
43
- ...(e.intent ? { intent: { tool: e.intent.tool, argsHash: e.intent.argsHash } } : {}) }));
44
- }
45
22
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
46
23
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
47
24
  * The same key is computed for an effect from its receipt's intent. */
@@ -8,12 +8,8 @@ export { openJournal, type JournalBackend, type JournalRecord } from "./journal.
8
8
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
9
9
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
10
10
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
11
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
11
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
12
12
  export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type DecisionRequest, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
13
13
  export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
14
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
15
14
  export { effectRetryClass, transportFactOf, type TransportFact } from "./transport-facts.js";
16
- export { buildHandoff, handoffFirstTurn, type Handoff, type HandoffOptions } from "./handoff.js";
17
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
18
- export { inputProvenance, judgedRecords, type InputProvenance } from "./handoff-files.js";
19
- export { type InheritedSession, type InheritedEffect, type TranscriptMessage } from "./handoff-digest.js";
15
+ export { gatewayIntentOf, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
@@ -7,11 +7,8 @@ export { openJournal } from "./journal.js";
7
7
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
8
8
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
9
9
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
10
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
10
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
11
11
  export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
12
12
  export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
13
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
14
13
  export { effectRetryClass, transportFactOf } from "./transport-facts.js";
15
- export { buildHandoff, handoffFirstTurn } from "./handoff.js";
16
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure } from "./handoff-receipts.js";
17
- export { inputProvenance, judgedRecords } from "./handoff-files.js";
14
+ export { gatewayIntentOf, returnedFailure } from "./handoff-receipts.js";
@@ -68,8 +68,10 @@ export function withRecovery(driver, deps, options = {}) {
68
68
  throw error;
69
69
  }
70
70
  // A cut call (a cancel, the run's failure) has no outcome: a later open finds it asked and unanswered. A call
71
- // that ended on its own failed, and the next process asks again.
72
- if (!driver.signal.aborted && !params.signal?.aborted)
71
+ // that ended on its own failed, and the next process asks again; so does one that never left (`unsent`, a host's
72
+ // refusal before it sent anything), whatever stopped the run meanwhile: nothing went out to answer.
73
+ const unsent = error instanceof DecisionProviderError && error.unsent === true;
74
+ if (unsent || (!driver.signal.aborted && !params.signal?.aborted))
73
75
  driver.decisionEnded(params.executionPath, decisionId, "failed", null);
74
76
  throw error;
75
77
  }
@@ -65,7 +65,6 @@ export declare const SYSTEM_ONE_LIMITS: {
65
65
  readonly minScoreLevels: 2;
66
66
  readonly maxScoreLevels: 10;
67
67
  };
68
- export declare const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
69
68
  export type CompiledQuestions = Record<string, SystemOneQuestion>;
70
69
  export declare function compileQuestions(schema: Record<string, unknown>, definitions?: Record<string, unknown>): {
71
70
  ok: true;
@@ -1,5 +1,4 @@
1
1
  export const SYSTEM_ONE_LIMITS = { maxChoiceOptions: 240, minScoreLevels: 2, maxScoreLevels: 10 };
2
- export const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
3
2
  const CRITERIA = "criteria";
4
3
  export function compileQuestions(schema, definitions = {}) {
5
4
  const errors = [];
@@ -320,7 +320,6 @@ export type ArtifactState = {
320
320
  };
321
321
  export declare function artifactNodeIsProse(node: ArtifactNode): boolean;
322
322
  export declare function desugarWorkflow(workflow: Workflow): Workflow;
323
- export declare function terminalArtifactType(workflow: Workflow): string | null;
324
323
  /** A predicate a `call` evaluates against ITS OWN RESULT: paths are result-relative. */
325
324
  export type CallPredicate = MechanicalPredicate;
326
325
  export type PollClause = {
@@ -628,6 +627,9 @@ export type WorkflowDeps = {
628
627
  sop?: string;
629
628
  skill?: string;
630
629
  signal?: AbortSignal;
630
+ /** Called at each node's visit, before it runs (a loop's body each iteration, a map's body for each item): a host that
631
+ * bounds the work a run does (a dry run's steps and deadline) counts it here, and throws to stop the run. */
632
+ onVisit?: (node: WorkflowNode) => void;
631
633
  /** Best-effort observation only: thrown errors and rejected promises are ignored.
632
634
  * Observers are never awaited. Use required checkpoints for durable lifecycle gates. */
633
635
  onEvent?: (event: WorkflowEvent) => void;
@@ -664,14 +666,6 @@ export declare class EffectFailure extends Error {
664
666
  cause?: unknown;
665
667
  });
666
668
  }
667
- export declare function parseCsvRows(text: string): string[][];
668
- export declare function buildReferenceContext(files: Record<string, string>): {
669
- references: Record<string, string>;
670
- references_parsed: Record<string, {
671
- header: string[];
672
- rows: string[][];
673
- }>;
674
- };
675
669
  export declare function normalizeStringNullsForSchema(value: unknown, schema: Record<string, unknown> | undefined, depth?: number, root?: Record<string, unknown> | undefined): unknown;
676
670
  export declare function workflowSha256(workflow: Workflow): string;
677
671
  /** Bound the complete document before any recursive schema or semantic traversal. Shared
package/dist/workflow.js CHANGED
@@ -44,13 +44,6 @@ export function desugarWorkflow(workflow) {
44
44
  return workflow;
45
45
  return { ...workflow, root: visit(workflow.root) };
46
46
  }
47
- export function terminalArtifactType(workflow) {
48
- const steps = workflow?.root?.node === "chain" ? workflow.root.steps || [] : [workflow?.root];
49
- const last = steps[steps.length - 1];
50
- if (!last || last.node !== "artifact")
51
- return null;
52
- return last.type;
53
- }
54
47
  export const SHELL_RESULT_SCHEMA = {
55
48
  type: "object",
56
49
  required: ["code", "stdout", "stderr"],
@@ -269,63 +262,6 @@ function resultPathMissing(shape, dotted) {
269
262
  }
270
263
  return false;
271
264
  }
272
- export function parseCsvRows(text) {
273
- const rows = [];
274
- let field = "", row = [], inQuotes = false;
275
- for (let i = 0; i < text.length; i += 1) {
276
- const ch = text[i];
277
- if (inQuotes) {
278
- if (ch === '"' && text[i + 1] === '"') {
279
- field += '"';
280
- i += 1;
281
- }
282
- else if (ch === '"')
283
- inQuotes = false;
284
- else
285
- field += ch;
286
- }
287
- else if (ch === '"')
288
- inQuotes = true;
289
- else if (ch === ",") {
290
- row.push(field);
291
- field = "";
292
- }
293
- else if (ch === "\n" || ch === "\r") {
294
- if (ch === "\r" && text[i + 1] === "\n")
295
- i += 1;
296
- row.push(field);
297
- field = "";
298
- if (row.some((c) => c.trim() !== ""))
299
- rows.push(row);
300
- row = [];
301
- }
302
- else
303
- field += ch;
304
- }
305
- if (field !== "" || row.length) {
306
- row.push(field);
307
- if (row.some((c) => c.trim() !== ""))
308
- rows.push(row);
309
- }
310
- return rows;
311
- }
312
- export function buildReferenceContext(files) {
313
- // Null prototypes: reference filenames are external data. On a plain object a name like
314
- // "__proto__" hits the prototype SETTER on assignment — the file silently vanishes from
315
- // the map (and worse shapes pollute it). A null-prototype object stores it as an ordinary
316
- // own key, so every filename round-trips.
317
- const references = Object.create(null);
318
- const referencesParsed = Object.create(null);
319
- for (const [name, body] of Object.entries(files)) {
320
- references[name] = body;
321
- if (name.toLowerCase().endsWith(".csv")) {
322
- const rows = parseCsvRows(body);
323
- if (rows.length)
324
- referencesParsed[name] = { header: rows[0], rows: rows.slice(1) };
325
- }
326
- }
327
- return { references, references_parsed: referencesParsed };
328
- }
329
265
  /** Whether a field's schema lists the value itself: its own `const`, or a member of its own `enum`, or the same in the
330
266
  * schema a local `$ref` names in the root schema's `definitions` or `$defs`, or in any `anyOf` or `oneOf` branch, at any
331
267
  * depth. A schema's own listed values count beside its `$ref`, never in place of it. */
@@ -2764,6 +2700,7 @@ function forwardObserver(observer, transform) {
2764
2700
  return forwarded;
2765
2701
  }
2766
2702
  async function runNodeOnState(node, state, workflow, deps) {
2703
+ deps.onVisit?.(node);
2767
2704
  deps = withExecutionLocation(deps);
2768
2705
  const observer = deps.onEvent;
2769
2706
  if (observer && !guardedObservers.has(observer)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-dsl",
3
- "version": "0.1.0-beta.33",
3
+ "version": "0.1.0-beta.35",
4
4
  "description": "Composable, typed workflows for agents",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -47,7 +47,7 @@
47
47
  "skills"
48
48
  ],
49
49
  "engines": {
50
- "node": ">=24.11.0"
50
+ "node": ">=24.22.3"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsc -p tsconfig.json",
@@ -1,34 +0,0 @@
1
- import { EffectFailure, type CallRetryClass, type EffectFailureCode } from "../workflow.js";
2
- /** A failed effect: its closed code, the prose for the reader, and what the host observed
3
- * (`detail`: the deadline, the elapsed time, the output tail, the filed output) which the
4
- * interpreter writes onto the attempt's `effect.failed` event. The retry class is the transport's
5
- * when it gave one, else the code's. */
6
- export declare class TypedEffectFailure extends EffectFailure {
7
- readonly code: EffectFailureCode;
8
- constructor(code: EffectFailureCode, message: string, options?: {
9
- detail?: Record<string, unknown>;
10
- cause?: unknown;
11
- retryClass?: CallRetryClass | null;
12
- });
13
- }
14
- /** A dispatch that succeeded around a failed tool: the transport answered with the tool's own failure
15
- * envelope as its text. The envelope is the effect's failure, never its result. */
16
- export declare class EffectEnvelopeFailure extends Error {
17
- readonly tool: string;
18
- readonly envelope: string;
19
- constructor(tool: string, envelope: string);
20
- }
21
- /** A thrown error at an effect boundary, as a TypedEffectFailure. A TypedEffectFailure passes through; a
22
- * tool the host did not grant (`notGranted` names it) is effect_not_granted; an unknown transport
23
- * (`via` outside the interpreter's list) is effect_unknown_transport; a tool's failure envelope is
24
- * effect_transport; otherwise the error's typed transport facts decide: a deadline (a TimeoutError, an
25
- * AbortError, a 408, an idle cut, a timed-out connect) is effect_timeout, any other typed fact (a
26
- * status, a system code, an error class) is effect_transport with the retry class those facts earn
27
- * (effectRetryClass), and an error with no typed fact came through no transport that can be named:
28
- * effect_unknown_transport. The message is carried for the reader and never read. */
29
- export declare function classifyEffectFailure(error: unknown, at: {
30
- label: string;
31
- via: string;
32
- }, options?: {
33
- notGranted?: (error: unknown) => string | undefined;
34
- }): TypedEffectFailure;