@anureo/workflow 0.3.4 → 0.3.7
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 +102 -82
- package/package.json +9 -8
- package/src/agent-adapters.test.ts +121 -0
- package/src/agent-execution.ts +228 -0
- package/src/agent.test.ts +237 -51
- package/src/agent.ts +61 -92
- package/src/fixtures/workflow-crash.ts +54 -17
- package/src/index.ts +6 -2
- package/src/journal-call.test.ts +2 -10
- package/src/journal-call.ts +44 -32
- package/src/output-schema.test.ts +45 -12
- package/src/output-schema.ts +208 -96
- package/src/parallel.test.ts +1 -0
- package/src/parallel.ts +26 -8
- package/src/persistence/checkpoint-files.ts +83 -0
- package/src/persistence/journal.ts +98 -82
- package/src/persistence/json.ts +58 -32
- package/src/persistence/records.ts +82 -56
- package/src/persistence/replay.ts +74 -30
- package/src/persistence/store.ts +260 -120
- package/src/pipeline.test.ts +19 -0
- package/src/pipeline.ts +69 -23
- package/src/test-helpers.ts +24 -0
- package/src/workflow-state.ts +72 -18
- package/src/workflow-types.ts +20 -2
- package/src/workflow.test.ts +204 -97
- package/src/workflow.ts +88 -30
- package/src/agent-outcome.ts +0 -21
- package/src/agent-pi.test.ts +0 -21
- package/src/native.test.ts +0 -71
- package/src/persistence/atomic.ts +0 -32
- package/src/run-context.ts +0 -19
package/src/output-schema.ts
CHANGED
|
@@ -3,123 +3,235 @@ 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. */
|
|
6
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
|
+
*/
|
|
7
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
|
+
*/
|
|
8
23
|
parse(text: string): Promise<z.output<S>>
|
|
9
24
|
}
|
|
10
25
|
|
|
11
|
-
|
|
12
|
-
|
|
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
|
+
}
|
|
13
51
|
}
|
|
14
52
|
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
17
79
|
}
|
|
18
80
|
|
|
19
|
-
/**
|
|
20
|
-
function
|
|
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 })
|
|
84
|
+
}
|
|
85
|
+
|
|
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
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
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 {
|
|
21
119
|
const seen = new WeakSet<object>()
|
|
22
|
-
const
|
|
120
|
+
const nonportableTypes = new Set(['optional', 'record', 'tuple', 'pipe', 'transform', 'catch', 'prefault',
|
|
23
121
|
'date', 'bigint', 'symbol', 'map', 'set', 'nan', 'undefined', 'void', 'custom', 'function', 'promise', 'file'])
|
|
24
|
-
|
|
122
|
+
/** Follow definition fields once per node, including lazy schemas. Getter failures reach compilePortableSchema. */
|
|
123
|
+
function visitZodNode(value: unknown): void {
|
|
25
124
|
if (!value || typeof value !== 'object' || seen.has(value)) return
|
|
26
125
|
seen.add(value)
|
|
27
|
-
if (value instanceof z.ZodType) {
|
|
28
|
-
const
|
|
29
|
-
|
|
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)
|
|
126
|
+
if (!(value instanceof z.ZodType)) {
|
|
127
|
+
for (const child of Object.values(value)) visitZodNode(child)
|
|
128
|
+
return
|
|
36
129
|
}
|
|
37
|
-
}
|
|
38
|
-
visit(root)
|
|
39
|
-
}
|
|
40
130
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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')
|
|
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')
|
|
131
|
+
const def = value._zod.def
|
|
132
|
+
if (nonportableTypes.has(def.type) || ('coerce' in def && def.coerce)) {
|
|
133
|
+
rejectSchema('valueConversionOrNonportableType')
|
|
76
134
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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)
|
|
80
140
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
141
|
+
}
|
|
142
|
+
visitZodNode(root)
|
|
143
|
+
}
|
|
144
|
+
|
|
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)
|
|
84
163
|
}
|
|
85
|
-
for (const key of ['items', 'contains', 'additionalProperties', 'propertyNames', 'not', 'if', 'then', 'else']) visit(schema[key])
|
|
86
164
|
}
|
|
87
|
-
|
|
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
|
+
}
|
|
88
172
|
}
|
|
89
173
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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')
|
|
104
191
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
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')
|
|
209
|
+
}
|
|
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')
|
|
124
226
|
}
|
|
125
227
|
}
|
|
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
|
+
}
|
package/src/parallel.test.ts
CHANGED
|
@@ -79,6 +79,7 @@ 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. */
|
|
82
83
|
function checkTypes() {
|
|
83
84
|
const values = parallel([() => 1, async () => 'two', () => true])
|
|
84
85
|
const tuple: Promise<[number | null, string | null, boolean | null]> = values
|
package/src/parallel.ts
CHANGED
|
@@ -1,15 +1,33 @@
|
|
|
1
|
-
/**
|
|
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
|
+
*/
|
|
2
15
|
export async function parallel<const Tasks extends readonly (() => unknown)[]>(
|
|
3
16
|
tasks: Tasks,
|
|
4
|
-
): Promise<
|
|
17
|
+
): Promise<ParallelResults<Tasks>> {
|
|
5
18
|
if (!Array.isArray(tasks)) throw new TypeError('parallel expects an array of functions')
|
|
6
19
|
const callbacks = [...tasks]
|
|
7
|
-
for (const
|
|
8
|
-
if (typeof
|
|
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
|
+
}
|
|
9
24
|
}
|
|
10
25
|
// An async wrapper captures synchronous throws without skipping later callbacks.
|
|
11
|
-
const
|
|
12
|
-
return
|
|
13
|
-
|
|
14
|
-
|
|
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
|
|
15
33
|
}
|
|
@@ -0,0 +1,83 @@
|
|
|
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
|
+
* The optional callback observes replacement before the directory flush, which can still fail.
|
|
22
|
+
* If temporary-file cleanup fails, the rejection includes both failures. */
|
|
23
|
+
export async function atomicPublish(path: string, value: unknown, onReplace?: () => void): 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
|
+
onReplace?.()
|
|
45
|
+
await syncDirectory(dirname(path))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Read strict JSON from a regular file and always close its descriptor. Check the final
|
|
49
|
+
* component with lstat and verify the opened inode to catch replacement during open.
|
|
50
|
+
* Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
|
|
51
|
+
* filesystem failures and validates the returned value against the checkpoint schema. */
|
|
52
|
+
export async function readJson(path: string): Promise<JsonValue> {
|
|
53
|
+
const before = await lstat(path)
|
|
54
|
+
if (!before.isFile()) return invalidCheckpoint()
|
|
55
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
|
|
56
|
+
try {
|
|
57
|
+
const current = await file.stat()
|
|
58
|
+
if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino) return invalidCheckpoint()
|
|
59
|
+
return parseCheckpointJson(await file.readFile('utf8'))
|
|
60
|
+
} finally {
|
|
61
|
+
await file.close()
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Normalize failures caught by openFileRun, FileRunHandle and AgentJournal.append.
|
|
66
|
+
* Preserve SDK errors by identity; report other failures as WORKFLOW_STORAGE_FAILED
|
|
67
|
+
* without passing filesystem diagnostics to workflow consumers. */
|
|
68
|
+
export function storageError(cause: unknown): HarnessSdkError {
|
|
69
|
+
if (cause instanceof HarnessSdkError) return cause
|
|
70
|
+
return new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Map malformed or nonrepresentable JSON to checkpoint corruption before schema validation.
|
|
74
|
+
* JSON.parse alone accepts number literals that overflow to Infinity. */
|
|
75
|
+
function parseCheckpointJson(text: string): JsonValue {
|
|
76
|
+
try {
|
|
77
|
+
const value = JSON.parse(text) as JsonValue
|
|
78
|
+
canonicalJson(value)
|
|
79
|
+
return value
|
|
80
|
+
} catch {
|
|
81
|
+
return invalidCheckpoint()
|
|
82
|
+
}
|
|
83
|
+
}
|