@anureo/workflow 0.3.0 → 0.3.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/README.md +96 -70
- package/package.json +17 -16
- package/src/agent-adapters.test.ts +121 -0
- package/src/agent-execution.ts +201 -0
- package/src/agent.test.ts +333 -0
- package/src/agent.ts +135 -0
- package/src/fixtures/workflow-crash.ts +53 -0
- package/src/index.ts +9 -0
- package/src/output-schema.test.ts +147 -0
- package/src/output-schema.ts +231 -0
- package/src/parallel.test.ts +96 -0
- package/src/parallel.ts +33 -0
- package/src/persistence/checkpoint-files.ts +82 -0
- package/src/persistence/journal.ts +111 -0
- package/src/persistence/json.ts +83 -0
- package/src/persistence/records.ts +97 -0
- package/src/persistence/replay.ts +91 -0
- package/src/persistence/store.ts +286 -0
- package/src/pipeline.test.ts +201 -0
- package/src/pipeline.ts +99 -0
- package/src/test-helpers.ts +23 -0
- package/src/workflow-state.ts +130 -0
- package/src/workflow-types.ts +38 -0
- package/src/workflow.test.ts +376 -0
- package/src/workflow.ts +112 -0
- package/tsconfig.json +13 -0
- package/LICENSE +0 -201
- package/src/agent-outcome.d.ts +0 -15
- package/src/agent-outcome.js +0 -28
- package/src/agent.d.ts +0 -49
- package/src/agent.js +0 -206
- package/src/index.d.ts +0 -6
- package/src/index.js +0 -5
- package/src/output-schema.d.ts +0 -27
- package/src/output-schema.js +0 -192
- package/src/parallel.d.ts +0 -18
- package/src/parallel.js +0 -25
- package/src/persistence/atomic.d.ts +0 -9
- package/src/persistence/atomic.js +0 -48
- package/src/persistence/journal.d.ts +0 -54
- package/src/persistence/journal.js +0 -106
- package/src/persistence/json.d.ts +0 -17
- package/src/persistence/json.js +0 -75
- package/src/persistence/read-json.d.ts +0 -11
- package/src/persistence/read-json.js +0 -46
- package/src/persistence/records.d.ts +0 -92
- package/src/persistence/records.js +0 -70
- package/src/persistence/replay.d.ts +0 -11
- package/src/persistence/replay.js +0 -79
- package/src/persistence/store.d.ts +0 -45
- package/src/persistence/store.js +0 -238
- package/src/pipeline.d.ts +0 -41
- package/src/pipeline.js +0 -24
- package/src/run-context.d.ts +0 -16
- package/src/run-context.js +0 -13
- package/src/test-helpers.d.ts +0 -11
- package/src/test-helpers.js +0 -21
- package/src/workflow-state.d.ts +0 -44
- package/src/workflow-state.js +0 -96
- package/src/workflow-types.d.ts +0 -39
- package/src/workflow-types.js +0 -0
- package/src/workflow.d.ts +0 -17
- package/src/workflow.js +0 -104
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { validateJsonSchema } from '@anureo/protocol'
|
|
4
|
+
import { HarnessSdkError } from '@anureo/sdk'
|
|
5
|
+
import { compileOutputSchema } from '../../adapter/claude/src/output-schema'
|
|
6
|
+
import { prepareOutputSchema } from './output-schema'
|
|
7
|
+
|
|
8
|
+
const findings = z.strictObject({ issues: z.array(z.string()), state: z.enum(['ready', 'done']), note: z.string().nullable() })
|
|
9
|
+
|
|
10
|
+
test('one Zod schema generates compatible JSON Schema and validates typed results', async () => {
|
|
11
|
+
const output = prepareOutputSchema(findings)
|
|
12
|
+
const good: z.output<typeof findings> = { issues: ['one'], state: 'ready', note: null }
|
|
13
|
+
const bad = { ...good, issues: [1] }
|
|
14
|
+
expect(output.schema.$schema).toBeUndefined()
|
|
15
|
+
expect(output.schema).toMatchObject({ type: 'object', required: ['issues', 'state', 'note'], additionalProperties: false })
|
|
16
|
+
expect(validateJsonSchema(output.schema, good)).toBe(true)
|
|
17
|
+
expect(validateJsonSchema(output.schema, bad)).toBe(false)
|
|
18
|
+
const native = compileOutputSchema(output.schema)
|
|
19
|
+
expect(native.validate(good)).toBe(true)
|
|
20
|
+
expect(native.validate(bad)).toBe(false)
|
|
21
|
+
expect(await output.parse(JSON.stringify(good))).toEqual(good)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
test('nested unions and recursive local references retain positive and negative validation', async () => {
|
|
25
|
+
const tree = z.object({
|
|
26
|
+
name: z.string(),
|
|
27
|
+
get children(): z.ZodArray<typeof tree> { return z.array(tree) },
|
|
28
|
+
value: z.union([z.string(), z.number()]),
|
|
29
|
+
})
|
|
30
|
+
const output = prepareOutputSchema(tree)
|
|
31
|
+
const good = { name: 'root', children: [{ name: 'child', children: [], value: 'ok' }], value: 1 }
|
|
32
|
+
expect(compileOutputSchema(output.schema).validate(good)).toBe(true)
|
|
33
|
+
expect(validateJsonSchema(output.schema, good)).toBe(true)
|
|
34
|
+
expect(await output.parse(JSON.stringify(good))).toEqual(good)
|
|
35
|
+
await expect(output.parse(JSON.stringify({ ...good, children: [{ ...good, name: 4 }] }))).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID' })
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
test.each([
|
|
39
|
+
['raw JSON Schema', { type: 'object', properties: {} }],
|
|
40
|
+
['null', null], ['boolean', true], ['array', []], ['string root', z.string()],
|
|
41
|
+
['array root', z.array(z.string())], ['root union', z.union([z.object({ a: z.string() }), z.object({ b: z.string() })])],
|
|
42
|
+
['optional', z.object({ a: z.string().optional() })],
|
|
43
|
+
['loose', z.looseObject({ a: z.string() })], ['record', z.object({ a: z.record(z.string(), z.string()) })],
|
|
44
|
+
['tuple', z.object({ a: z.tuple([z.string(), z.number()]) })],
|
|
45
|
+
['coercion', z.object({ a: z.coerce.number() })], ['transform', z.object({ a: z.string().transform(x => x.length) })],
|
|
46
|
+
['output pipe', z.object({ a: z.string().transform(x => x.length).pipe(z.number()) })],
|
|
47
|
+
['preprocess', z.object({ a: z.preprocess(x => x, z.string()) })],
|
|
48
|
+
['catch', z.object({ a: z.string().catch('fallback') })], ['prefault', z.object({ a: z.string().prefault('fallback') })],
|
|
49
|
+
['trim overwrite', z.object({ a: z.string().trim() })], ['date', z.object({ a: z.date() })],
|
|
50
|
+
['bigint', z.object({ a: z.bigint() })], ['map', z.object({ a: z.map(z.string(), z.string()) })],
|
|
51
|
+
['set', z.object({ a: z.set(z.string()) })], ['custom', z.object({ a: z.custom<string>() })],
|
|
52
|
+
['metadata cannot hide a date', z.object({ a: z.date().meta({ type: 'string' }) })],
|
|
53
|
+
['lazy transform', z.object({ a: z.lazy(() => z.coerce.string()) })],
|
|
54
|
+
])('rejects %s before execution', (_label, schema) => {
|
|
55
|
+
expect(() => prepareOutputSchema(schema as z.ZodObject)).toThrow(expect.objectContaining({ code: 'INVALID_PARAMS', outcomeUnknown: false }))
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
test('schema-like keys in business enum and default data are not treated as schema nodes', async () => {
|
|
59
|
+
const schema = z.object({ value: z.enum(['object', 'array']), data: z.object({ type: z.literal('object'), $ref: z.literal('https://business') }).default({ type: 'object', $ref: 'https://business' }) })
|
|
60
|
+
const value: z.output<typeof schema> = { value: 'object', data: { type: 'object', $ref: 'https://business' } }
|
|
61
|
+
expect(await prepareOutputSchema(schema).parse(JSON.stringify(value))).toEqual(value)
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
test('raw JSON is validated before Zod can strip extra fields or supply defaults', async () => {
|
|
65
|
+
const output = prepareOutputSchema(z.object({ count: z.number().default(3) }))
|
|
66
|
+
expect(await output.parse('{"count":4}')).toEqual({ count: 4 })
|
|
67
|
+
await expect(output.parse('{}')).rejects.toMatchObject({
|
|
68
|
+
code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
|
|
69
|
+
retryable: false,
|
|
70
|
+
outcomeUnknown: false,
|
|
71
|
+
details: { issues: [{ path: '', code: 'required' }] },
|
|
72
|
+
})
|
|
73
|
+
for (const text of ['{"count":4,"extra":1}', '{"count":"4"}', 'null', '[]']) {
|
|
74
|
+
await expect(output.parse(text)).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', retryable: false, outcomeUnknown: false })
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test('missing and malformed output remain distinct failures without recovering prose', async () => {
|
|
79
|
+
const output = prepareOutputSchema(z.object({ count: z.number() }))
|
|
80
|
+
await expect(output.parse(' ')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_MISSING' })
|
|
81
|
+
for (const text of ['not json', '```json\n{"count":1}\n```', '{"count":1}\n{"count":2}']) {
|
|
82
|
+
await expect(output.parse(text)).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_NOT_JSON' })
|
|
83
|
+
}
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
test('sync and async refinements and formats validate locally and sanitize custom diagnostics', async () => {
|
|
87
|
+
const local = z.object({ count: z.number(), email: z.email() })
|
|
88
|
+
.refine(value => value.count > 0, 'private-message')
|
|
89
|
+
.superRefine(async (value, context) => { if (value.count > 10) context.addIssue({ code: 'custom', message: 'private-refinement' }) })
|
|
90
|
+
const output = prepareOutputSchema(local)
|
|
91
|
+
expect(await output.parse('{"count":3,"email":"me@example.com"}')).toEqual({ count: 3, email: 'me@example.com' })
|
|
92
|
+
for (const count of [-1, 11]) {
|
|
93
|
+
let failure: unknown
|
|
94
|
+
try {
|
|
95
|
+
await output.parse(JSON.stringify({ count, email: 'me@example.com' }))
|
|
96
|
+
} catch (error) {
|
|
97
|
+
failure = error
|
|
98
|
+
}
|
|
99
|
+
expect(failure).toMatchObject({
|
|
100
|
+
code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
|
|
101
|
+
outcomeUnknown: false,
|
|
102
|
+
details: { issues: [{ path: [], code: 'custom' }] },
|
|
103
|
+
})
|
|
104
|
+
expect(JSON.stringify(failure)).not.toContain('private-')
|
|
105
|
+
}
|
|
106
|
+
await expect(output.parse('{"count":1,"email":"bad"}')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID' })
|
|
107
|
+
const throwing = prepareOutputSchema(z.object({ a: z.string() }).refine(async () => { throw new Error('private exception') }))
|
|
108
|
+
await expect(throwing.parse('{"a":"ok"}')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED' })
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
test('definite generated contradictions and external references are rejected', () => {
|
|
112
|
+
const cases: Array<{ schema: z.ZodObject; rule: string }> = [
|
|
113
|
+
{ schema: z.object({ a: z.string().meta({ minLength: 5, maxLength: 1 }) }), rule: 'unsatisfiableBounds' },
|
|
114
|
+
{ schema: z.object({ a: z.number().meta({ minimum: 5, maximum: 1 }) }), rule: 'unsatisfiableBounds' },
|
|
115
|
+
{ schema: z.object({ a: z.number().meta({ minimum: 1, exclusiveMaximum: 1 }) }), rule: 'unsatisfiableBounds' },
|
|
116
|
+
{ schema: z.object({ a: z.array(z.string()).meta({ minItems: 3, maxItems: 1 }) }), rule: 'unsatisfiableBounds' },
|
|
117
|
+
{ schema: z.object({ a: z.string().meta({ $ref: 'https://private.example/schema' }) }), rule: 'externalOrAsyncSchema' },
|
|
118
|
+
{ schema: z.object({ a: z.string() }).meta({ required: ['missing'] }), rule: 'optionalProperty' },
|
|
119
|
+
{
|
|
120
|
+
schema: z.object({}).meta({ required: ['missing'], patternProperties: { '^allowed$': { type: 'string' } } }),
|
|
121
|
+
rule: 'unsatisfiableRequired',
|
|
122
|
+
},
|
|
123
|
+
]
|
|
124
|
+
for (const { schema, rule } of cases) {
|
|
125
|
+
expect(() => prepareOutputSchema(schema)).toThrow(expect.objectContaining({ code: 'INVALID_PARAMS', details: { rule } }))
|
|
126
|
+
}
|
|
127
|
+
// Numeric bounds do not contradict a string instance.
|
|
128
|
+
expect(prepareOutputSchema(z.object({ a: z.string().meta({ minimum: 5, maximum: 1 }) })).schema.type).toBe('object')
|
|
129
|
+
expect(prepareOutputSchema(z.object({}).meta({ required: ['allowed'], patternProperties: { '^allowed$': { type: 'string' } } })).schema.type).toBe('object')
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
test('user schema callbacks cannot expose their exception or claim execution uncertainty before submission', () => {
|
|
133
|
+
const schema = z.object({ a: z.lazy(() => { throw new HarnessSdkError('PRIVATE_NATIVE_ERROR', 'private value', true, true) }) })
|
|
134
|
+
let failure: unknown
|
|
135
|
+
try {
|
|
136
|
+
prepareOutputSchema(schema)
|
|
137
|
+
} catch (cause) {
|
|
138
|
+
failure = cause
|
|
139
|
+
}
|
|
140
|
+
expect(failure).toMatchObject({
|
|
141
|
+
code: 'INVALID_PARAMS',
|
|
142
|
+
retryable: false,
|
|
143
|
+
outcomeUnknown: false,
|
|
144
|
+
details: { rule: 'invalidOrUnrepresentableSchema' },
|
|
145
|
+
})
|
|
146
|
+
expect(String(failure)).not.toContain('private value')
|
|
147
|
+
})
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import Ajv, { type ValidateFunction } from 'ajv'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { HarnessSdkError } from '@anureo/sdk'
|
|
4
|
+
import type { JsonObject } from '@anureo/protocol'
|
|
5
|
+
|
|
6
|
+
/** Package-internal schema and parser for agent execution and journal replay. */
|
|
7
|
+
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
|
+
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
|
+
parse(text: string): Promise<z.output<S>>
|
|
24
|
+
}
|
|
25
|
+
|
|
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
|
+
* memoizedAgent prepares the pair before reserving a journal key and uses it for typed replay.
|
|
32
|
+
* executeAgent prepares its own pair before opening a session. On a journal miss this happens
|
|
33
|
+
* after the started record is published and dispatch is rechecked.
|
|
34
|
+
*/
|
|
35
|
+
export function prepareOutputSchema<S extends z.ZodObject>(source: S): AgentOutputSchema<S> {
|
|
36
|
+
const { schema, validate } = compilePortableSchema(source)
|
|
37
|
+
return {
|
|
38
|
+
schema,
|
|
39
|
+
async parse(text) {
|
|
40
|
+
const value = parseRawOutput(text, validate)
|
|
41
|
+
let parsed: z.ZodSafeParseResult<z.output<S>>
|
|
42
|
+
try {
|
|
43
|
+
parsed = await source.safeParseAsync(value)
|
|
44
|
+
} catch {
|
|
45
|
+
throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED')
|
|
46
|
+
}
|
|
47
|
+
if (!parsed.success) {
|
|
48
|
+
throw outputMismatch(parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })))
|
|
49
|
+
}
|
|
50
|
+
return parsed.data
|
|
51
|
+
},
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Decode a single JSON object and check its raw fields before parse awaits Zod.
|
|
57
|
+
* Throw the missing, malformed or invalid output error synchronously, copying any available
|
|
58
|
+
* Ajv issue paths and codes into the invalid output error.
|
|
59
|
+
*/
|
|
60
|
+
function parseRawOutput(text: string, validate: ValidateFunction): unknown {
|
|
61
|
+
if (!text.trim()) throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_MISSING')
|
|
62
|
+
let value: unknown
|
|
63
|
+
try {
|
|
64
|
+
value = JSON.parse(text)
|
|
65
|
+
} catch {
|
|
66
|
+
throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_NOT_JSON')
|
|
67
|
+
}
|
|
68
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || !validate(value)) {
|
|
69
|
+
const issues = validate.errors?.map(error => ({ path: error.instancePath, code: error.keyword })) ?? []
|
|
70
|
+
throw outputMismatch(issues)
|
|
71
|
+
}
|
|
72
|
+
return value
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Use the same failure envelope for Ajv and Zod with only issue paths and codes. */
|
|
76
|
+
function outputMismatch(issues: Array<{ path: string | PropertyKey[]; code: string }>): HarnessSdkError {
|
|
77
|
+
return new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_INVALID', 'Agent output does not match its schema', false, false, { issues })
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Give prepareOutputSchema a detached draft-07 schema and a synchronous validator. Check the
|
|
82
|
+
* Zod source before conversion, then check the emitted schema before compiling it with Ajv.
|
|
83
|
+
* Preserve preflight rule codes and replace unexpected conversion, callback or Ajv exceptions
|
|
84
|
+
* with INVALID_PARAMS. Ajv checks fields as supplied and leaves format assertions to Zod.
|
|
85
|
+
*/
|
|
86
|
+
function compilePortableSchema(source: z.ZodObject): { schema: JsonObject; validate: ValidateFunction } {
|
|
87
|
+
if (!(source instanceof z.ZodObject)) rejectSchema('objectRootRequired')
|
|
88
|
+
try {
|
|
89
|
+
checkPortableZodSource(source)
|
|
90
|
+
const schema = structuredClone(z.toJSONSchema(source, {
|
|
91
|
+
target: 'draft-7',
|
|
92
|
+
io: 'output',
|
|
93
|
+
unrepresentable: 'throw',
|
|
94
|
+
})) as JsonObject
|
|
95
|
+
delete schema.$schema
|
|
96
|
+
if (schema.type !== 'object') rejectSchema('objectRootRequired')
|
|
97
|
+
checkPortableJsonSchema(schema)
|
|
98
|
+
const validate = new Ajv({
|
|
99
|
+
allErrors: true,
|
|
100
|
+
validateFormats: false,
|
|
101
|
+
multipleOfPrecision: 6,
|
|
102
|
+
logger: false,
|
|
103
|
+
}).compile(schema)
|
|
104
|
+
return { schema, validate }
|
|
105
|
+
} catch (cause) {
|
|
106
|
+
if (cause instanceof SchemaParameterError) throw cause
|
|
107
|
+
rejectSchema('invalidOrUnrepresentableSchema')
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Reject conversions and nonportable types in the source graph before Zod's output-mode converter can hide them. */
|
|
112
|
+
function checkPortableZodSource(root: z.ZodObject): void {
|
|
113
|
+
const seen = new WeakSet<object>()
|
|
114
|
+
const nonportableTypes = new Set(['optional', 'record', 'tuple', 'pipe', 'transform', 'catch', 'prefault',
|
|
115
|
+
'date', 'bigint', 'symbol', 'map', 'set', 'nan', 'undefined', 'void', 'custom', 'function', 'promise', 'file'])
|
|
116
|
+
/** Follow definition fields once per node, including lazy schemas. Getter failures reach compilePortableSchema. */
|
|
117
|
+
function visitZodNode(value: unknown): void {
|
|
118
|
+
if (!value || typeof value !== 'object' || seen.has(value)) return
|
|
119
|
+
seen.add(value)
|
|
120
|
+
if (!(value instanceof z.ZodType)) {
|
|
121
|
+
for (const child of Object.values(value)) visitZodNode(child)
|
|
122
|
+
return
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const def = value._zod.def
|
|
126
|
+
if (nonportableTypes.has(def.type) || ('coerce' in def && def.coerce)) {
|
|
127
|
+
rejectSchema('valueConversionOrNonportableType')
|
|
128
|
+
}
|
|
129
|
+
if (def.checks?.some(check => check._zod.def.check === 'overwrite')) rejectSchema('valueConversion')
|
|
130
|
+
if (value instanceof z.ZodLazy) visitZodNode(value._zod.def.getter())
|
|
131
|
+
// Skip the checks list when walking child schemas because refinements can be ZodCustom instances.
|
|
132
|
+
for (const [key, child] of Object.entries(def)) {
|
|
133
|
+
if (key !== 'checks') visitZodNode(child)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
visitZodNode(root)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Reject portability violations before Ajv compiles the generated schema. Follow only
|
|
141
|
+
* subschema keywords because examples, defaults and enum values may contain schema-like keys.
|
|
142
|
+
*/
|
|
143
|
+
function checkPortableJsonSchema(node: unknown): void {
|
|
144
|
+
if (!node || typeof node !== 'object' || Array.isArray(node)) return
|
|
145
|
+
const schema = node as JsonObject
|
|
146
|
+
if (schema.$async || (typeof schema.$ref === 'string' && !schema.$ref.startsWith('#'))) {
|
|
147
|
+
rejectSchema('externalOrAsyncSchema')
|
|
148
|
+
}
|
|
149
|
+
checkObjectProperties(schema)
|
|
150
|
+
if (Array.isArray(schema.items) || schema.prefixItems) rejectSchema('tuple')
|
|
151
|
+
checkSchemaBounds(schema)
|
|
152
|
+
|
|
153
|
+
for (const key of ['properties', 'patternProperties', 'definitions', '$defs', 'dependentSchemas']) {
|
|
154
|
+
const children = schema[key]
|
|
155
|
+
if (children && typeof children === 'object' && !Array.isArray(children)) {
|
|
156
|
+
Object.values(children).forEach(checkPortableJsonSchema)
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
for (const key of ['allOf', 'anyOf', 'oneOf']) {
|
|
160
|
+
const children = schema[key]
|
|
161
|
+
if (Array.isArray(children)) children.forEach(checkPortableJsonSchema)
|
|
162
|
+
}
|
|
163
|
+
for (const key of ['items', 'contains', 'additionalProperties', 'propertyNames', 'not', 'if', 'then', 'else']) {
|
|
164
|
+
checkPortableJsonSchema(schema[key])
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Check closure and requiredness before testing whether explicit properties or patterns admit each required key. */
|
|
169
|
+
function checkObjectProperties(schema: JsonObject): void {
|
|
170
|
+
if (schema.type !== 'object' && !(Array.isArray(schema.type) && schema.type.includes('object'))) return
|
|
171
|
+
if (schema.additionalProperties !== false) rejectSchema('openObject')
|
|
172
|
+
const properties = schema.properties as JsonObject | undefined
|
|
173
|
+
const requiredKeys = Array.isArray(schema.required) ? schema.required : undefined
|
|
174
|
+
const required = new Set(requiredKeys)
|
|
175
|
+
if (properties && Object.keys(properties).some(key => !required.has(key))) rejectSchema('optionalProperty')
|
|
176
|
+
|
|
177
|
+
const patterns = schema.patternProperties && typeof schema.patternProperties === 'object'
|
|
178
|
+
? Object.keys(schema.patternProperties).map(pattern => new RegExp(pattern, 'u'))
|
|
179
|
+
: []
|
|
180
|
+
const impossibleRequiredKey = requiredKeys?.some(key =>
|
|
181
|
+
typeof key === 'string' && !Object.hasOwn(properties ?? {}, key) && !patterns.some(pattern => pattern.test(key)),
|
|
182
|
+
)
|
|
183
|
+
if (impossibleRequiredKey) {
|
|
184
|
+
rejectSchema('unsatisfiableRequired')
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Check bounds for the declared type because other types' keywords do not constrain the instance. */
|
|
189
|
+
function checkSchemaBounds(schema: JsonObject): void {
|
|
190
|
+
switch (schema.type) {
|
|
191
|
+
case 'string': return checkSizeBounds(schema.minLength, schema.maxLength)
|
|
192
|
+
case 'array': return checkSizeBounds(schema.minItems, schema.maxItems)
|
|
193
|
+
case 'object': return checkSizeBounds(schema.minProperties, schema.maxProperties)
|
|
194
|
+
case 'number':
|
|
195
|
+
case 'integer': return checkNumericBounds(schema)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Reject contradictory sizes. Ajv checks the validity of the individual keyword values. */
|
|
200
|
+
function checkSizeBounds(lower: unknown, upper: unknown): void {
|
|
201
|
+
if (typeof lower === 'number' && typeof upper === 'number' && lower > upper) {
|
|
202
|
+
rejectSchema('unsatisfiableBounds')
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Reject crossed bounds or a shared endpoint excluded by either bound. */
|
|
207
|
+
function checkNumericBounds(schema: JsonObject): void {
|
|
208
|
+
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum } = schema
|
|
209
|
+
const lower = Math.max(
|
|
210
|
+
typeof minimum === 'number' ? minimum : -Infinity,
|
|
211
|
+
typeof exclusiveMinimum === 'number' ? exclusiveMinimum : -Infinity,
|
|
212
|
+
)
|
|
213
|
+
const upper = Math.min(
|
|
214
|
+
typeof maximum === 'number' ? maximum : Infinity,
|
|
215
|
+
typeof exclusiveMaximum === 'number' ? exclusiveMaximum : Infinity,
|
|
216
|
+
)
|
|
217
|
+
const equalBoundsExcludeValue = lower === upper && (exclusiveMinimum === lower || exclusiveMaximum === upper)
|
|
218
|
+
if (lower > upper || equalBoundsExcludeValue) {
|
|
219
|
+
rejectSchema('unsatisfiableBounds')
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Distinguish preflight rule failures from exceptions raised during conversion or compilation. */
|
|
224
|
+
class SchemaParameterError extends HarnessSdkError {
|
|
225
|
+
constructor(rule: string) { super('INVALID_PARAMS', 'Unsupported agent output schema', false, false, { rule }) }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Stop preflight with the rule code compilePortableSchema can carry through sanitization. */
|
|
229
|
+
function rejectSchema(rule: string): never {
|
|
230
|
+
throw new SchemaParameterError(rule)
|
|
231
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { parallel } from './index'
|
|
3
|
+
|
|
4
|
+
test('starts all callbacks concurrently and preserves input order', async () => {
|
|
5
|
+
let finishFirst!: (value: string) => void
|
|
6
|
+
let finishSecond!: (value: number) => void
|
|
7
|
+
const started: string[] = []
|
|
8
|
+
const result = parallel([
|
|
9
|
+
() => { started.push('first'); return new Promise<string>(resolve => { finishFirst = resolve }) },
|
|
10
|
+
() => { started.push('second'); return new Promise<number>(resolve => { finishSecond = resolve }) },
|
|
11
|
+
])
|
|
12
|
+
expect(started).toEqual(['first', 'second'])
|
|
13
|
+
finishSecond(42)
|
|
14
|
+
finishFirst('done')
|
|
15
|
+
expect(await result).toEqual(['done', 42])
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
test('accepts synchronous results, readonly tuples, and empty batches', async () => {
|
|
19
|
+
expect(await parallel([() => 1, () => Promise.resolve('two'), () => true] as const)).toEqual([1, 'two', true])
|
|
20
|
+
expect(await parallel([])).toEqual([])
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
test('synchronous failure does not prevent later callbacks from starting', async () => {
|
|
24
|
+
const failure = new Error('failed')
|
|
25
|
+
let started = false
|
|
26
|
+
const result = parallel([
|
|
27
|
+
() => { throw failure },
|
|
28
|
+
() => { started = true; return 'other' },
|
|
29
|
+
])
|
|
30
|
+
expect(await result).toEqual([null, 'other'])
|
|
31
|
+
expect(started).toBe(true)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
test('a failed callback becomes null and the batch still waits for its pending sibling', async () => {
|
|
35
|
+
let finish!: (value: string) => void
|
|
36
|
+
let completed = false
|
|
37
|
+
const sibling = new Promise<string>(resolve => {
|
|
38
|
+
finish = resolve
|
|
39
|
+
}).then(value => {
|
|
40
|
+
completed = true
|
|
41
|
+
return value
|
|
42
|
+
})
|
|
43
|
+
const failure = new Error('failed')
|
|
44
|
+
let settled = false
|
|
45
|
+
const result = parallel([
|
|
46
|
+
() => Promise.reject(failure),
|
|
47
|
+
() => sibling,
|
|
48
|
+
]).then(values => {
|
|
49
|
+
settled = true
|
|
50
|
+
return values
|
|
51
|
+
})
|
|
52
|
+
await Promise.resolve()
|
|
53
|
+
await Promise.resolve()
|
|
54
|
+
expect(settled).toBe(false)
|
|
55
|
+
expect(completed).toBe(false)
|
|
56
|
+
finish('still running')
|
|
57
|
+
expect(await sibling).toBe('still running')
|
|
58
|
+
expect(await result).toEqual([null, 'still running'])
|
|
59
|
+
expect(completed).toBe(true)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test('preserves null and other falsy results', async () => {
|
|
63
|
+
expect(await parallel([() => null, () => 0, () => false, () => '', () => undefined])).toEqual([null, 0, false, '', undefined])
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
test('validates every entry before starting any callbacks', async () => {
|
|
67
|
+
let started = false
|
|
68
|
+
// @ts-expect-error invalid JavaScript input must be rejected before any task starts
|
|
69
|
+
await expect(parallel([() => { started = true }, Promise.resolve('already started')])).rejects.toBeInstanceOf(TypeError)
|
|
70
|
+
expect(started).toBe(false)
|
|
71
|
+
// @ts-expect-error array-like objects are not arrays
|
|
72
|
+
await expect(parallel({ map: () => [] })).rejects.toBeInstanceOf(TypeError)
|
|
73
|
+
// @ts-expect-error missing argument
|
|
74
|
+
await expect(parallel()).rejects.toBeInstanceOf(TypeError)
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('snapshots the callbacks before one callback mutates the input array', async () => {
|
|
78
|
+
const callbacks = [() => { callbacks[1] = () => 99; return 1 }, () => 2]
|
|
79
|
+
expect(await parallel(callbacks)).toEqual([1, 2])
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
/** Compile-only assertions for positional inference and nullable failures; never invoked at runtime. */
|
|
83
|
+
function checkTypes() {
|
|
84
|
+
const values = parallel([() => 1, async () => 'two', () => true])
|
|
85
|
+
const tuple: Promise<[number | null, string | null, boolean | null]> = values
|
|
86
|
+
// @ts-expect-error the first task returns a number
|
|
87
|
+
const wrong: Promise<[string | null, string | null, boolean | null]> = values
|
|
88
|
+
// @ts-expect-error callback failures can produce null at every position
|
|
89
|
+
const missingNull: Promise<[number, string, boolean]> = values
|
|
90
|
+
const empty: Promise<[]> = parallel([])
|
|
91
|
+
const callbacks: ReadonlyArray<() => Promise<number>> = [async () => 1]
|
|
92
|
+
const array: Promise<(number | null)[]> = parallel(callbacks)
|
|
93
|
+
const readonlyTuple: Promise<[number | null, string | null]> = parallel([() => 1, async () => 'two'] as const)
|
|
94
|
+
void tuple; void wrong; void missingNull; void empty; void array; void readonlyTuple
|
|
95
|
+
}
|
|
96
|
+
void checkTypes
|
package/src/parallel.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
*/
|
|
15
|
+
export async function parallel<const Tasks extends readonly (() => unknown)[]>(
|
|
16
|
+
tasks: Tasks,
|
|
17
|
+
): Promise<ParallelResults<Tasks>> {
|
|
18
|
+
if (!Array.isArray(tasks)) throw new TypeError('parallel expects an array of functions')
|
|
19
|
+
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
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// 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
|
|
33
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { constants } from 'node:fs'
|
|
3
|
+
import { lstat, open, rename, unlink } from 'node:fs/promises'
|
|
4
|
+
import { dirname } from 'node:path'
|
|
5
|
+
import { HarnessSdkError } from '@anureo/sdk'
|
|
6
|
+
import { canonicalJson, type JsonValue } from './json'
|
|
7
|
+
import { invalidCheckpoint } from './records'
|
|
8
|
+
|
|
9
|
+
/** Flush directory-entry changes and close the directory handle. I/O failures reject.
|
|
10
|
+
* On Windows this resolves without a flush because Node does not provide directory fsync. */
|
|
11
|
+
export async function syncDirectory(path: string): Promise<void> {
|
|
12
|
+
if (process.platform === 'win32') return
|
|
13
|
+
const directory = await open(path, 'r')
|
|
14
|
+
try { await directory.sync() } finally { await directory.close() }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Publish one complete checkpoint by renaming a flushed sibling temporary file, then flush
|
|
18
|
+
* its parent directory where supported. FileRunHandle and AgentJournal serialize their own
|
|
19
|
+
* writes because a rename alone cannot prevent an older snapshot from overwriting a newer one.
|
|
20
|
+
* The caller creates the parent. Invalid JSON rejects before any file I/O.
|
|
21
|
+
* A directory flush can fail after replacement.
|
|
22
|
+
* If temporary-file cleanup fails, the rejection includes both failures. */
|
|
23
|
+
export async function atomicPublish(path: string, value: unknown): Promise<void> {
|
|
24
|
+
const text = `${canonicalJson(value)}\n`
|
|
25
|
+
const temporary = `${path}.${randomUUID()}.tmp`
|
|
26
|
+
// An exclusive open establishes ownership. Cleanup must leave an existing file alone.
|
|
27
|
+
const file = await open(temporary, 'wx', 0o600)
|
|
28
|
+
try {
|
|
29
|
+
try {
|
|
30
|
+
await file.writeFile(text, 'utf8')
|
|
31
|
+
await file.sync()
|
|
32
|
+
} finally {
|
|
33
|
+
await file.close()
|
|
34
|
+
}
|
|
35
|
+
await rename(temporary, path)
|
|
36
|
+
} catch (cause) {
|
|
37
|
+
try {
|
|
38
|
+
await unlink(temporary)
|
|
39
|
+
} catch (cleanup) {
|
|
40
|
+
throw new AggregateError([cause, cleanup], 'Atomic publish failed')
|
|
41
|
+
}
|
|
42
|
+
throw cause
|
|
43
|
+
}
|
|
44
|
+
await syncDirectory(dirname(path))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Read strict JSON from a regular file and always close its descriptor. Check the final
|
|
48
|
+
* component with lstat and verify the opened inode to catch replacement during open.
|
|
49
|
+
* Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
|
|
50
|
+
* filesystem failures and validates the returned value against the checkpoint schema. */
|
|
51
|
+
export async function readJson(path: string): Promise<JsonValue> {
|
|
52
|
+
const before = await lstat(path)
|
|
53
|
+
if (!before.isFile()) return invalidCheckpoint()
|
|
54
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
|
|
55
|
+
try {
|
|
56
|
+
const current = await file.stat()
|
|
57
|
+
if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino) return invalidCheckpoint()
|
|
58
|
+
return parseCheckpointJson(await file.readFile('utf8'))
|
|
59
|
+
} finally {
|
|
60
|
+
await file.close()
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Normalize failures caught by openFileRun, FileRunHandle and AgentJournal.append.
|
|
65
|
+
* Preserve SDK errors by identity; report other failures as WORKFLOW_STORAGE_FAILED
|
|
66
|
+
* without passing filesystem diagnostics to workflow consumers. */
|
|
67
|
+
export function storageError(cause: unknown): HarnessSdkError {
|
|
68
|
+
if (cause instanceof HarnessSdkError) return cause
|
|
69
|
+
return new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Map malformed or nonrepresentable JSON to checkpoint corruption before schema validation.
|
|
73
|
+
* JSON.parse alone accepts number literals that overflow to Infinity. */
|
|
74
|
+
function parseCheckpointJson(text: string): JsonValue {
|
|
75
|
+
try {
|
|
76
|
+
const value = JSON.parse(text) as JsonValue
|
|
77
|
+
canonicalJson(value)
|
|
78
|
+
return value
|
|
79
|
+
} catch {
|
|
80
|
+
return invalidCheckpoint()
|
|
81
|
+
}
|
|
82
|
+
}
|