@anureo/workflow 0.3.2 → 0.3.4

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.
@@ -3,235 +3,123 @@ import { z } from 'zod'
3
3
  import { HarnessSdkError } from '@anureo/sdk'
4
4
  import type { JsonObject } from '@anureo/protocol'
5
5
 
6
- /** Package-internal schema and parser for agent execution and journal replay. */
7
6
  export interface AgentOutputSchema<S extends z.ZodObject = z.ZodObject> {
8
- /**
9
- * Closed draft-07 object schema. agentSubmission sends it or embeds it in the JSON-text
10
- * prompt, and memoizedAgent includes it in the journal key.
11
- */
12
7
  schema: JsonObject
13
- /**
14
- * Validate a complete JSON object before Zod can strip extra fields or fill omitted fields.
15
- * Resolve with the typed value after local Zod checks, including async refinements.
16
- * Blank text, malformed JSON and schema mismatches reject with AGENT_STRUCTURED_OUTPUT_MISSING,
17
- * AGENT_STRUCTURED_OUTPUT_NOT_JSON and AGENT_STRUCTURED_OUTPUT_INVALID, respectively. Exceptions
18
- * from Zod reject with AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED and omit the original cause.
19
- * observeAgentTurn awaits this parser after a completed turn and captures rejections so
20
- * executeAgent can release the session before settlement. For a typed cache hit,
21
- * replayAgentResult passes the saved value as canonical JSON and propagates the outcome.
22
- */
23
8
  parse(text: string): Promise<z.output<S>>
24
9
  }
25
10
 
26
- /**
27
- * Prepare a portable Zod object as a draft-07 schema and a parser for its inferred output.
28
- * Require closed objects and required JSON fields, including fields with JSON-compatible defaults.
29
- * Conversion schemas and other unsupported shapes synchronously throw INVALID_PARAMS with a
30
- * rule code in details.rule.
31
- * prepareAgentCall prepares the pair at invocation for fresh execution and typed replay.
32
- */
33
- export function prepareOutputSchema<S extends z.ZodObject>(source: S): AgentOutputSchema<S> {
34
- const { schema, validate } = compilePortableSchema(source)
35
- return {
36
- schema,
37
- async parse(text) {
38
- const value = parseRawOutput(text, validate)
39
- let parsed: z.ZodSafeParseResult<z.output<S>>
40
- try {
41
- parsed = await source.safeParseAsync(value)
42
- } catch {
43
- throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED')
44
- }
45
- if (!parsed.success) {
46
- throw outputMismatch(parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })))
47
- }
48
- return parsed.data
49
- },
50
- }
51
- }
52
-
53
- /**
54
- * Decode a single JSON object and check its raw fields before parse awaits Zod.
55
- * Throw the missing, malformed or invalid output error synchronously, copying any available
56
- * Ajv issue paths and codes into the invalid output error.
57
- */
58
- function parseRawOutput(text: string, validate: ValidateFunction): unknown {
59
- if (!text.trim()) throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_MISSING')
60
- let value: unknown
61
- try {
62
- value = JSON.parse(text)
63
- } catch {
64
- throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_NOT_JSON')
65
- }
66
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw outputMismatch([])
67
- if (!validate(value)) {
68
- const issues = validate.errors?.map(({ instancePath, keyword, params }) => {
69
- const property = keyword === 'required' ? params.missingProperty
70
- : keyword === 'additionalProperties' ? params.additionalProperty : undefined
71
- const path = typeof property === 'string'
72
- ? `${instancePath}/${property.replace(/~/g, '~0').replace(/\//g, '~1')}`
73
- : instancePath
74
- return { path, code: keyword }
75
- }) ?? []
76
- throw outputMismatch(issues)
77
- }
78
- return value
79
- }
80
-
81
- /** Use the same failure envelope for Ajv and Zod with only issue paths and codes. */
82
- function outputMismatch(issues: Array<{ path: string | PropertyKey[]; code: string }>): HarnessSdkError {
83
- return new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_INVALID', 'Agent output does not match its schema', false, false, { issues })
11
+ class SchemaParameterError extends HarnessSdkError {
12
+ constructor(rule: string) { super('INVALID_PARAMS', 'Unsupported agent output schema', false, false, { rule }) }
84
13
  }
85
14
 
86
- /**
87
- * Give prepareOutputSchema a detached draft-07 schema and a synchronous validator. Check the
88
- * Zod source before conversion, then check the emitted schema before compiling it with Ajv.
89
- * Preserve preflight rule codes and replace unexpected conversion, callback or Ajv exceptions
90
- * with INVALID_PARAMS. Ajv checks fields as supplied and leaves format assertions to Zod.
91
- */
92
- function compilePortableSchema(source: z.ZodObject): { schema: JsonObject; validate: ValidateFunction } {
93
- if (!(source instanceof z.ZodObject)) rejectSchema('objectRootRequired')
94
- try {
95
- checkPortableZodSource(source)
96
- const schema = structuredClone(z.toJSONSchema(source, {
97
- target: 'draft-7',
98
- io: 'output',
99
- unrepresentable: 'throw',
100
- })) as JsonObject
101
- delete schema.$schema
102
- if (schema.type !== 'object') rejectSchema('objectRootRequired')
103
- checkPortableJsonSchema(schema)
104
- const validate = new Ajv({
105
- allErrors: true,
106
- validateFormats: false,
107
- multipleOfPrecision: 6,
108
- logger: false,
109
- }).compile(schema)
110
- return { schema, validate }
111
- } catch (cause) {
112
- if (cause instanceof SchemaParameterError) throw cause
113
- rejectSchema('invalidOrUnrepresentableSchema')
114
- }
15
+ function invalid(rule: string): never {
16
+ throw new SchemaParameterError(rule)
115
17
  }
116
18
 
117
- /** Reject conversions and nonportable types in the source graph before Zod's output-mode converter can hide them. */
118
- function checkPortableZodSource(root: z.ZodObject): void {
19
+ /** Zod's converter can hide input-side transforms in output mode. Check the original graph too. */
20
+ function checkZod(root: z.ZodObject): void {
119
21
  const seen = new WeakSet<object>()
120
- const nonportableTypes = new Set(['optional', 'record', 'tuple', 'pipe', 'transform', 'catch', 'prefault',
22
+ const rejected = new Set(['optional', 'record', 'tuple', 'pipe', 'transform', 'catch', 'prefault',
121
23
  'date', 'bigint', 'symbol', 'map', 'set', 'nan', 'undefined', 'void', 'custom', 'function', 'promise', 'file'])
122
- /** Follow definition fields once per node, including lazy schemas. Getter failures reach compilePortableSchema. */
123
- function visitZodNode(value: unknown): void {
24
+ function visit(value: unknown): void {
124
25
  if (!value || typeof value !== 'object' || seen.has(value)) return
125
26
  seen.add(value)
126
- if (!(value instanceof z.ZodType)) {
127
- for (const child of Object.values(value)) visitZodNode(child)
128
- return
129
- }
130
-
131
- const def = value._zod.def
132
- if (nonportableTypes.has(def.type) || ('coerce' in def && def.coerce)) {
133
- rejectSchema('valueConversionOrNonportableType')
134
- }
135
- if (def.checks?.some(check => check._zod.def.check === 'overwrite')) rejectSchema('valueConversion')
136
- if (value instanceof z.ZodLazy) visitZodNode(value._zod.def.getter())
137
- // Skip the checks list when walking child schemas because refinements can be ZodCustom instances.
138
- for (const [key, child] of Object.entries(def)) {
139
- if (key !== 'checks') visitZodNode(child)
27
+ if (value instanceof z.ZodType) {
28
+ const def = value._zod.def
29
+ if (rejected.has(def.type) || ('coerce' in def && def.coerce)) invalid('valueConversionOrNonportableType')
30
+ if (def.checks?.some(check => check._zod.def.check === 'overwrite')) invalid('valueConversion')
31
+ if (value instanceof z.ZodLazy) visit(value._zod.def.getter())
32
+ // Refinement checks can themselves be ZodCustom instances; they validate, not convert.
33
+ for (const [key, child] of Object.entries(def)) if (key !== 'checks') visit(child)
34
+ } else {
35
+ for (const child of Object.values(value)) visit(child)
140
36
  }
141
37
  }
142
- visitZodNode(root)
38
+ visit(root)
143
39
  }
144
40
 
145
- /**
146
- * Reject portability violations before Ajv compiles the generated schema. Follow only
147
- * subschema keywords because examples, defaults and enum values may contain schema-like keys.
148
- */
149
- function checkPortableJsonSchema(node: unknown): void {
150
- if (!node || typeof node !== 'object' || Array.isArray(node)) return
151
- const schema = node as JsonObject
152
- if (schema.$async || (typeof schema.$ref === 'string' && !schema.$ref.startsWith('#'))) {
153
- rejectSchema('externalOrAsyncSchema')
154
- }
155
- checkObjectProperties(schema)
156
- if (Array.isArray(schema.items) || schema.prefixItems) rejectSchema('tuple')
157
- checkSchemaBounds(schema)
158
-
159
- for (const key of ['properties', 'patternProperties', 'definitions', '$defs', 'dependentSchemas']) {
160
- const children = schema[key]
161
- if (children && typeof children === 'object' && !Array.isArray(children)) {
162
- Object.values(children).forEach(checkPortableJsonSchema)
41
+ /** Walk schema locations, never examples/defaults/enum data that may contain schema-like keys. */
42
+ function checkJsonSchema(root: JsonObject): void {
43
+ function visit(node: unknown): void {
44
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return
45
+ const schema = node as JsonObject
46
+ if (schema.$async || (typeof schema.$ref === 'string' && !schema.$ref.startsWith('#'))) invalid('externalOrAsyncSchema')
47
+ if (schema.type === 'object' || (Array.isArray(schema.type) && schema.type.includes('object'))) {
48
+ if (schema.additionalProperties !== false) invalid('openObject')
49
+ const properties = schema.properties as JsonObject | undefined
50
+ const required = new Set(Array.isArray(schema.required) ? schema.required : [])
51
+ if (properties && Object.keys(properties).some(key => !required.has(key))) invalid('optionalProperty')
52
+ const patterns = schema.patternProperties && typeof schema.patternProperties === 'object'
53
+ ? Object.keys(schema.patternProperties).map(pattern => new RegExp(pattern, 'u')) : []
54
+ if (Array.isArray(schema.required) && schema.required.some(key => typeof key === 'string'
55
+ && !Object.hasOwn(properties ?? {}, key) && !patterns.some(pattern => pattern.test(key)))) invalid('unsatisfiableRequired')
163
56
  }
57
+ if (Array.isArray(schema.items) || schema.prefixItems) invalid('tuple')
58
+ const type = schema.type
59
+ const pairs: Array<[string, string]> = type === 'string' ? [['minLength', 'maxLength']] : type === 'array' ? [['minItems', 'maxItems']]
60
+ : type === 'object' ? [['minProperties', 'maxProperties']] : []
61
+ for (const [min, max] of pairs) {
62
+ const lower = schema[min], upper = schema[max]
63
+ if (typeof lower === 'number' && typeof upper === 'number' && lower > upper) invalid('unsatisfiableBounds')
64
+ }
65
+ if (type === 'number' || type === 'integer') {
66
+ const minimum = typeof schema.minimum === 'number' ? schema.minimum : -Infinity
67
+ const exclusiveMinimum = typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : -Infinity
68
+ const lower = Math.max(minimum, exclusiveMinimum)
69
+ const maximum = typeof schema.maximum === 'number' ? schema.maximum : Infinity
70
+ const exclusiveMaximum = typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : Infinity
71
+ const upper = Math.min(maximum, exclusiveMaximum)
72
+ const boundsCrossed = lower > upper
73
+ const equalBoundsExcludeValue = lower === upper
74
+ && (schema.exclusiveMinimum === lower || schema.exclusiveMaximum === upper)
75
+ if (boundsCrossed || equalBoundsExcludeValue) invalid('unsatisfiableBounds')
76
+ }
77
+ for (const key of ['properties', 'patternProperties', 'definitions', '$defs', 'dependentSchemas']) {
78
+ const children = schema[key]
79
+ if (children && typeof children === 'object' && !Array.isArray(children)) Object.values(children).forEach(visit)
80
+ }
81
+ for (const key of ['allOf', 'anyOf', 'oneOf']) {
82
+ const children = schema[key]
83
+ if (Array.isArray(children)) children.forEach(visit)
84
+ }
85
+ for (const key of ['items', 'contains', 'additionalProperties', 'propertyNames', 'not', 'if', 'then', 'else']) visit(schema[key])
164
86
  }
165
- for (const key of ['allOf', 'anyOf', 'oneOf']) {
166
- const children = schema[key]
167
- if (Array.isArray(children)) children.forEach(checkPortableJsonSchema)
168
- }
169
- for (const key of ['items', 'contains', 'additionalProperties', 'propertyNames', 'not', 'if', 'then', 'else']) {
170
- checkPortableJsonSchema(schema[key])
171
- }
172
- }
173
-
174
- /** Check closure and requiredness before testing whether explicit properties or patterns admit each required key. */
175
- function checkObjectProperties(schema: JsonObject): void {
176
- if (schema.type !== 'object' && !(Array.isArray(schema.type) && schema.type.includes('object'))) return
177
- if (schema.additionalProperties !== false) rejectSchema('openObject')
178
- const properties = schema.properties as JsonObject | undefined
179
- const requiredKeys = Array.isArray(schema.required) ? schema.required : undefined
180
- const required = new Set(requiredKeys)
181
- if (properties && Object.keys(properties).some(key => !required.has(key))) rejectSchema('optionalProperty')
182
-
183
- const patterns = schema.patternProperties && typeof schema.patternProperties === 'object'
184
- ? Object.keys(schema.patternProperties).map(pattern => new RegExp(pattern, 'u'))
185
- : []
186
- const impossibleRequiredKey = requiredKeys?.some(key =>
187
- typeof key === 'string' && !Object.hasOwn(properties ?? {}, key) && !patterns.some(pattern => pattern.test(key)),
188
- )
189
- if (impossibleRequiredKey) {
190
- rejectSchema('unsatisfiableRequired')
191
- }
192
- }
193
-
194
- /** Check bounds for the declared type because other types' keywords do not constrain the instance. */
195
- function checkSchemaBounds(schema: JsonObject): void {
196
- switch (schema.type) {
197
- case 'string': return checkSizeBounds(schema.minLength, schema.maxLength)
198
- case 'array': return checkSizeBounds(schema.minItems, schema.maxItems)
199
- case 'object': return checkSizeBounds(schema.minProperties, schema.maxProperties)
200
- case 'number':
201
- case 'integer': return checkNumericBounds(schema)
202
- }
87
+ visit(root)
203
88
  }
204
89
 
205
- /** Reject contradictory sizes. Ajv checks the validity of the individual keyword values. */
206
- function checkSizeBounds(lower: unknown, upper: unknown): void {
207
- if (typeof lower === 'number' && typeof upper === 'number' && lower > upper) {
208
- rejectSchema('unsatisfiableBounds')
90
+ export function prepareOutputSchema<S extends z.ZodObject>(source: S): AgentOutputSchema<S> {
91
+ if (!(source instanceof z.ZodObject)) invalid('objectRootRequired')
92
+ let schema: JsonObject
93
+ let validate: ValidateFunction
94
+ try {
95
+ checkZod(source)
96
+ schema = structuredClone(z.toJSONSchema(source, { target: 'draft-7', io: 'output', unrepresentable: 'throw' })) as JsonObject
97
+ delete schema.$schema
98
+ if (schema.type !== 'object') invalid('objectRootRequired')
99
+ checkJsonSchema(schema)
100
+ validate = new Ajv({ allErrors: true, validateFormats: false, multipleOfPrecision: 6, logger: false }).compile(schema)
101
+ } catch (cause) {
102
+ if (cause instanceof SchemaParameterError) throw cause
103
+ invalid('invalidOrUnrepresentableSchema')
209
104
  }
210
- }
211
-
212
- /** Reject crossed bounds or a shared endpoint excluded by either bound. */
213
- function checkNumericBounds(schema: JsonObject): void {
214
- const { minimum, maximum, exclusiveMinimum, exclusiveMaximum } = schema
215
- const lower = Math.max(
216
- typeof minimum === 'number' ? minimum : -Infinity,
217
- typeof exclusiveMinimum === 'number' ? exclusiveMinimum : -Infinity,
218
- )
219
- const upper = Math.min(
220
- typeof maximum === 'number' ? maximum : Infinity,
221
- typeof exclusiveMaximum === 'number' ? exclusiveMaximum : Infinity,
222
- )
223
- const equalBoundsExcludeValue = lower === upper && (exclusiveMinimum === lower || exclusiveMaximum === upper)
224
- if (lower > upper || equalBoundsExcludeValue) {
225
- rejectSchema('unsatisfiableBounds')
105
+ return {
106
+ schema,
107
+ async parse(text) {
108
+ if (!text.trim()) throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_MISSING')
109
+ let value: unknown
110
+ try { value = JSON.parse(text) } catch { throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_NOT_JSON') }
111
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !validate(value)) {
112
+ throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_INVALID', 'Agent output does not match its schema', false, false,
113
+ { issues: validate.errors?.map(error => ({ path: error.instancePath, code: error.keyword })) ?? [] })
114
+ }
115
+ // User refinements may throw independently of an ordinary validation mismatch.
116
+ let parsed: z.ZodSafeParseResult<z.output<S>>
117
+ try { parsed = await source.safeParseAsync(value) } catch {
118
+ throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED')
119
+ }
120
+ if (!parsed.success) throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_INVALID', 'Agent output does not match its schema', false, false,
121
+ { issues: parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })) })
122
+ return parsed.data
123
+ },
226
124
  }
227
125
  }
228
-
229
- /** Distinguish preflight rule failures from exceptions raised during conversion or compilation. */
230
- class SchemaParameterError extends HarnessSdkError {
231
- constructor(rule: string) { super('INVALID_PARAMS', 'Unsupported agent output schema', false, false, { rule }) }
232
- }
233
-
234
- /** Stop preflight with the rule code compilePortableSchema can carry through sanitization. */
235
- function rejectSchema(rule: string): never {
236
- throw new SchemaParameterError(rule)
237
- }
@@ -79,7 +79,6 @@ test('snapshots the callbacks before one callback mutates the input array', asyn
79
79
  expect(await parallel(callbacks)).toEqual([1, 2])
80
80
  })
81
81
 
82
- /** Compile-only assertions for positional inference and nullable failures; never invoked at runtime. */
83
82
  function checkTypes() {
84
83
  const values = parallel([() => 1, async () => 'two', () => true])
85
84
  const tuple: Promise<[number | null, string | null, boolean | null]> = values
package/src/parallel.ts CHANGED
@@ -1,33 +1,15 @@
1
- /**
2
- * Start a batch of zero-argument callbacks and collect their awaited results in input order.
3
- * After validation, invoke the callbacks in array order before returning the promise. Wait for
4
- * every callback result to settle before resolving. Tuple inputs preserve the awaited type at each position,
5
- * and an empty batch resolves to `[]`.
6
- *
7
- * A synchronous throw or rejection produces `null` at that position, just like an explicit `null`
8
- * result. Other falsy values are preserved. Handle errors inside a callback to retain the original
9
- * cause. The caller owns concurrency limits, cancellation, retries and resource cleanup, and each
10
- * callback should return the work the batch needs to await.
11
- *
12
- * The function snapshots the task array and rejects with `TypeError` for a non-array argument
13
- * or a non-function entry before invoking any callback.
14
- */
1
+ /** Await every callback and preserve input positions, using null for failed tasks. */
15
2
  export async function parallel<const Tasks extends readonly (() => unknown)[]>(
16
3
  tasks: Tasks,
17
- ): Promise<ParallelResults<Tasks>> {
4
+ ): Promise<{ -readonly [K in keyof Tasks]: Awaited<ReturnType<Tasks[K]>> | null }> {
18
5
  if (!Array.isArray(tasks)) throw new TypeError('parallel expects an array of functions')
19
6
  const callbacks = [...tasks]
20
- for (const callback of callbacks) {
21
- if (typeof callback !== 'function') {
22
- throw new TypeError('parallel expects functions, not promises; wrap each call in () => task()')
23
- }
7
+ for (const task of callbacks) {
8
+ if (typeof task !== 'function') throw new TypeError('parallel expects functions, not promises; wrap each call in () => task()')
24
9
  }
25
10
  // An async wrapper captures synchronous throws without skipping later callbacks.
26
- const settledCallbacks = await Promise.allSettled(callbacks.map(async callback => callback()))
27
- return settledCallbacks.map(result => result.status === 'fulfilled' ? result.value : null) as ParallelResults<Tasks>
28
- }
29
-
30
- /** Preserve each callback's awaited type and allow a failed callback to yield null in any slot. */
31
- type ParallelResults<Tasks extends readonly (() => unknown)[]> = {
32
- -readonly [K in keyof Tasks]: Awaited<ReturnType<Tasks[K]>> | null
11
+ const results = await Promise.allSettled(callbacks.map(async task => task()))
12
+ return results.map(result => result.status === 'fulfilled' ? result.value : null) as {
13
+ -readonly [K in keyof Tasks]: Awaited<ReturnType<Tasks[K]>> | null
14
+ }
33
15
  }
@@ -0,0 +1,32 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { open, rename, unlink } from 'node:fs/promises'
3
+ import { dirname } from 'node:path'
4
+ import { canonicalJson } from './json'
5
+
6
+ /** Windows supports file flushes, but Node does not provide directory fsync there. */
7
+ export async function syncDirectory(path: string): Promise<void> {
8
+ if (process.platform === 'win32') return
9
+ const directory = await open(path, 'r')
10
+ try { await directory.sync() } finally { await directory.close() }
11
+ }
12
+
13
+ export async function atomicPublish(path: string, value: unknown): Promise<void> {
14
+ const text = `${canonicalJson(value)}\n`
15
+ const temporary = `${path}.${randomUUID()}.tmp`
16
+ let temporaryExists = false
17
+ try {
18
+ const file = await open(temporary, 'wx', 0o600)
19
+ temporaryExists = true
20
+ try { await file.writeFile(text, 'utf8'); await file.sync() }
21
+ finally { await file.close() }
22
+ await rename(temporary, path)
23
+ temporaryExists = false
24
+ await syncDirectory(dirname(path))
25
+ } catch (cause) {
26
+ if (temporaryExists) {
27
+ try { await unlink(temporary) }
28
+ catch (cleanup) { throw new AggregateError([cause, cleanup], 'Atomic publish failed') }
29
+ }
30
+ throw cause
31
+ }
32
+ }