@anureo/workflow 0.3.0 → 0.3.2

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.
Files changed (63) hide show
  1. package/README.md +96 -70
  2. package/package.json +18 -16
  3. package/src/agent-adapters.test.ts +121 -0
  4. package/src/agent-execution.ts +220 -0
  5. package/src/agent.test.ts +470 -0
  6. package/src/agent.ts +136 -0
  7. package/src/fixtures/workflow-crash.ts +69 -0
  8. package/src/index.ts +9 -0
  9. package/src/output-schema.test.ts +159 -0
  10. package/src/output-schema.ts +237 -0
  11. package/src/parallel.test.ts +96 -0
  12. package/src/parallel.ts +33 -0
  13. package/src/persistence/checkpoint-files.ts +83 -0
  14. package/src/persistence/journal.ts +132 -0
  15. package/src/persistence/json.ts +83 -0
  16. package/src/persistence/records.ts +103 -0
  17. package/src/persistence/replay.ts +93 -0
  18. package/src/persistence/store.ts +315 -0
  19. package/src/pipeline.test.ts +201 -0
  20. package/src/pipeline.ts +99 -0
  21. package/src/test-helpers.ts +23 -0
  22. package/src/workflow-state.ts +131 -0
  23. package/src/workflow-types.ts +38 -0
  24. package/src/workflow.test.ts +503 -0
  25. package/src/workflow.ts +112 -0
  26. package/tsconfig.json +13 -0
  27. package/LICENSE +0 -201
  28. package/src/agent-outcome.d.ts +0 -15
  29. package/src/agent-outcome.js +0 -28
  30. package/src/agent.d.ts +0 -49
  31. package/src/agent.js +0 -206
  32. package/src/index.d.ts +0 -6
  33. package/src/index.js +0 -5
  34. package/src/output-schema.d.ts +0 -27
  35. package/src/output-schema.js +0 -192
  36. package/src/parallel.d.ts +0 -18
  37. package/src/parallel.js +0 -25
  38. package/src/persistence/atomic.d.ts +0 -9
  39. package/src/persistence/atomic.js +0 -48
  40. package/src/persistence/journal.d.ts +0 -54
  41. package/src/persistence/journal.js +0 -106
  42. package/src/persistence/json.d.ts +0 -17
  43. package/src/persistence/json.js +0 -75
  44. package/src/persistence/read-json.d.ts +0 -11
  45. package/src/persistence/read-json.js +0 -46
  46. package/src/persistence/records.d.ts +0 -92
  47. package/src/persistence/records.js +0 -70
  48. package/src/persistence/replay.d.ts +0 -11
  49. package/src/persistence/replay.js +0 -79
  50. package/src/persistence/store.d.ts +0 -45
  51. package/src/persistence/store.js +0 -238
  52. package/src/pipeline.d.ts +0 -41
  53. package/src/pipeline.js +0 -24
  54. package/src/run-context.d.ts +0 -16
  55. package/src/run-context.js +0 -13
  56. package/src/test-helpers.d.ts +0 -11
  57. package/src/test-helpers.js +0 -21
  58. package/src/workflow-state.d.ts +0 -44
  59. package/src/workflow-state.js +0 -96
  60. package/src/workflow-types.d.ts +0 -39
  61. package/src/workflow-types.js +0 -0
  62. package/src/workflow.d.ts +0 -17
  63. package/src/workflow.js +0 -104
@@ -0,0 +1,69 @@
1
+ import { mock } from 'bun:test'
2
+ import * as fs from 'node:fs/promises'
3
+ import { createClient, HarnessSdkError } from '@anureo/sdk'
4
+ import { createScriptedAdapter } from '@anureo/conformance'
5
+ import type { JournalEvent } from '../persistence/records'
6
+
7
+ const [directory, phase] = process.argv.slice(2) as [string, string]
8
+ const originalRename = fs.rename
9
+ // workflow.test.ts spawns a fresh process per crash point. Install the mock before
10
+ // importing workflow so atomic publication uses the injected rename in this process.
11
+ mock.module('node:fs/promises', () => ({ ...fs, rename: renameAtCrashBoundary }))
12
+ const { workflow, agent } = await import('../index')
13
+
14
+ const adapter = createScriptedAdapter({
15
+ async execute(call) {
16
+ if (phase === 'unpublished-unknown' && call.method === 'input/submit' && 'submissionId' in call.params) {
17
+ throw new HarnessSdkError('NATIVE_FAILED', 'unknown', false, true)
18
+ }
19
+ if (phase === 'after-later-result' && call.method === 'input/submit' && 'input' in call.params
20
+ && call.params.input.some(part => part.type === 'text' && part.text === 'work')) {
21
+ // Hold the first call at started while the second reaches durable completion.
22
+ await new Promise<never>(() => {})
23
+ }
24
+ return undefined
25
+ },
26
+ })
27
+ const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
28
+ try {
29
+ await workflow({ directory, name: 'crash-test', revision: '1', input: {}, runId: 'crashed',
30
+ resumeFrom: phase === 'after-retry' ? 'source' : undefined }, async () => {
31
+ if (phase === 'after-retry') {
32
+ await agent('prefix', { client, cwd: directory })
33
+ await agent('work', { client, cwd: directory })
34
+ process.kill(process.pid, 'SIGKILL')
35
+ }
36
+ const first = agent('work', { client, cwd: directory })
37
+ if (phase !== 'after-later-result') return first
38
+ await agent('later', { client, cwd: directory })
39
+ process.kill(process.pid, 'SIGKILL')
40
+ return first
41
+ })
42
+ } catch (error) {
43
+ const codes = error instanceof HarnessSdkError ? error.details?.failureCodes : undefined
44
+ if (phase !== 'unpublished-unknown' || !(error instanceof HarnessSdkError)
45
+ || !error.outcomeUnknown || !Array.isArray(codes) || !codes.includes('WORKFLOW_STORAGE_FAILED')) throw error
46
+ } finally {
47
+ await client.dispose()
48
+ }
49
+
50
+ /** Replace fs.rename for atomicPublish. Kill the process before the selected rename can
51
+ * publish the started marker, agent result or completed manifest. Unselected renames
52
+ * use the original operation and propagate its failures. */
53
+ async function renameAtCrashBoundary(from: string, to: string): Promise<void> {
54
+ const target = to.replaceAll('\\', '/')
55
+ if (target.endsWith('/journal.json')) {
56
+ const pending = JSON.parse(await fs.readFile(from, 'utf8')) as JournalEvent[]
57
+ const event = pending.at(-1)
58
+ if ((phase === 'before-started' && event?.type === 'started')
59
+ || (phase === 'after-execute' && event?.type === 'result')) process.kill(process.pid, 'SIGKILL')
60
+ if (phase === 'unpublished-unknown' && event?.type === 'failed' && event.outcomeUnknown) {
61
+ throw new Error('Injected journal replacement failure')
62
+ }
63
+ }
64
+ if (phase === 'before-final' && target.endsWith('/run.json')) {
65
+ const value = JSON.parse(await fs.readFile(from, 'utf8'))
66
+ if (value.status === 'completed') process.kill(process.pid, 'SIGKILL')
67
+ }
68
+ await originalRename(from, to)
69
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ /** Application entry point for agent execution, concurrent composition, and durable runs. */
2
+ export { agent } from './agent'
3
+ export type { AgentOptions } from './agent-execution'
4
+
5
+ export { parallel } from './parallel'
6
+ export { pipeline } from './pipeline'
7
+
8
+ export { workflow } from './workflow'
9
+ export type { WorkflowContext, WorkflowOptions, WorkflowResult } from './workflow-types'
@@ -0,0 +1,159 @@
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: '/count', 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('raw JSON issues identify missing and extra fields with escaped pointer segments', async () => {
79
+ const output = prepareOutputSchema(z.object({ nested: z.object({ 'a/b': z.number(), 'a~b': z.number() }) }))
80
+ await expect(output.parse('{"nested":{"extra~/":"private value"}}')).rejects.toMatchObject({
81
+ code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
82
+ details: { issues: [
83
+ { path: '/nested/a~1b', code: 'required' },
84
+ { path: '/nested/a~0b', code: 'required' },
85
+ { path: '/nested/extra~0~1', code: 'additionalProperties' },
86
+ ] },
87
+ })
88
+ })
89
+
90
+ test('missing and malformed output remain distinct failures without recovering prose', async () => {
91
+ const output = prepareOutputSchema(z.object({ count: z.number() }))
92
+ await expect(output.parse(' ')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_MISSING' })
93
+ for (const text of ['not json', '```json\n{"count":1}\n```', '{"count":1}\n{"count":2}']) {
94
+ await expect(output.parse(text)).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_NOT_JSON' })
95
+ }
96
+ })
97
+
98
+ test('sync and async refinements and formats validate locally and sanitize custom diagnostics', async () => {
99
+ const local = z.object({ count: z.number(), email: z.email() })
100
+ .refine(value => value.count > 0, 'private-message')
101
+ .superRefine(async (value, context) => { if (value.count > 10) context.addIssue({ code: 'custom', message: 'private-refinement' }) })
102
+ const output = prepareOutputSchema(local)
103
+ expect(await output.parse('{"count":3,"email":"me@example.com"}')).toEqual({ count: 3, email: 'me@example.com' })
104
+ for (const count of [-1, 11]) {
105
+ let failure: unknown
106
+ try {
107
+ await output.parse(JSON.stringify({ count, email: 'me@example.com' }))
108
+ } catch (error) {
109
+ failure = error
110
+ }
111
+ expect(failure).toMatchObject({
112
+ code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
113
+ outcomeUnknown: false,
114
+ details: { issues: [{ path: [], code: 'custom' }] },
115
+ })
116
+ expect(JSON.stringify(failure)).not.toContain('private-')
117
+ }
118
+ await expect(output.parse('{"count":1,"email":"bad"}')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID' })
119
+ const throwing = prepareOutputSchema(z.object({ a: z.string() }).refine(async () => { throw new Error('private exception') }))
120
+ await expect(throwing.parse('{"a":"ok"}')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED' })
121
+ })
122
+
123
+ test('definite generated contradictions and external references are rejected', () => {
124
+ const cases: Array<{ schema: z.ZodObject; rule: string }> = [
125
+ { schema: z.object({ a: z.string().meta({ minLength: 5, maxLength: 1 }) }), rule: 'unsatisfiableBounds' },
126
+ { schema: z.object({ a: z.number().meta({ minimum: 5, maximum: 1 }) }), rule: 'unsatisfiableBounds' },
127
+ { schema: z.object({ a: z.number().meta({ minimum: 1, exclusiveMaximum: 1 }) }), rule: 'unsatisfiableBounds' },
128
+ { schema: z.object({ a: z.array(z.string()).meta({ minItems: 3, maxItems: 1 }) }), rule: 'unsatisfiableBounds' },
129
+ { schema: z.object({ a: z.string().meta({ $ref: 'https://private.example/schema' }) }), rule: 'externalOrAsyncSchema' },
130
+ { schema: z.object({ a: z.string() }).meta({ required: ['missing'] }), rule: 'optionalProperty' },
131
+ {
132
+ schema: z.object({}).meta({ required: ['missing'], patternProperties: { '^allowed$': { type: 'string' } } }),
133
+ rule: 'unsatisfiableRequired',
134
+ },
135
+ ]
136
+ for (const { schema, rule } of cases) {
137
+ expect(() => prepareOutputSchema(schema)).toThrow(expect.objectContaining({ code: 'INVALID_PARAMS', details: { rule } }))
138
+ }
139
+ // Numeric bounds do not contradict a string instance.
140
+ expect(prepareOutputSchema(z.object({ a: z.string().meta({ minimum: 5, maximum: 1 }) })).schema.type).toBe('object')
141
+ expect(prepareOutputSchema(z.object({}).meta({ required: ['allowed'], patternProperties: { '^allowed$': { type: 'string' } } })).schema.type).toBe('object')
142
+ })
143
+
144
+ test('user schema callbacks cannot expose their exception or claim execution uncertainty before submission', () => {
145
+ const schema = z.object({ a: z.lazy(() => { throw new HarnessSdkError('PRIVATE_NATIVE_ERROR', 'private value', true, true) }) })
146
+ let failure: unknown
147
+ try {
148
+ prepareOutputSchema(schema)
149
+ } catch (cause) {
150
+ failure = cause
151
+ }
152
+ expect(failure).toMatchObject({
153
+ code: 'INVALID_PARAMS',
154
+ retryable: false,
155
+ outcomeUnknown: false,
156
+ details: { rule: 'invalidOrUnrepresentableSchema' },
157
+ })
158
+ expect(String(failure)).not.toContain('private value')
159
+ })
@@ -0,0 +1,237 @@
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
+ * 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 })
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 {
119
+ const seen = new WeakSet<object>()
120
+ const nonportableTypes = new Set(['optional', 'record', 'tuple', 'pipe', 'transform', 'catch', 'prefault',
121
+ '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 {
124
+ if (!value || typeof value !== 'object' || seen.has(value)) return
125
+ 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)
140
+ }
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)
163
+ }
164
+ }
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
+ }
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')
226
+ }
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
+ }
@@ -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
@@ -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
+ }