@anureo/workflow 0.0.0-stage → 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 +198 -2
- package/package.json +37 -4
- 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
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { pipeline } from './index'
|
|
3
|
+
|
|
4
|
+
test('a fast item reaches the next stage without waiting for a slow item', async () => {
|
|
5
|
+
let releaseSlow!: () => void
|
|
6
|
+
let reachedFast!: () => void
|
|
7
|
+
const slow = new Promise<void>(resolve => { releaseSlow = resolve })
|
|
8
|
+
const fast = new Promise<void>(resolve => { reachedFast = resolve })
|
|
9
|
+
const result = pipeline(
|
|
10
|
+
['fast', 'slow'],
|
|
11
|
+
async value => { if (value === 'slow') await slow; return { value } },
|
|
12
|
+
value => { if (value.value === 'fast') reachedFast(); return value.value.toUpperCase() },
|
|
13
|
+
)
|
|
14
|
+
await fast
|
|
15
|
+
releaseSlow()
|
|
16
|
+
expect(await result).toEqual(['FAST', 'SLOW'])
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
test('supports multiple asynchronous type transitions', async () => {
|
|
20
|
+
expect(await pipeline(
|
|
21
|
+
['one', 'four'],
|
|
22
|
+
value => ({ length: value.length }),
|
|
23
|
+
async value => value.length,
|
|
24
|
+
value => value > 3,
|
|
25
|
+
async value => value ? new Date(0) : null,
|
|
26
|
+
)).toEqual([null, new Date(0)])
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
test('supports one stage, empty input, and ordinary object identity', async () => {
|
|
30
|
+
const map = new Map([['key', 1]])
|
|
31
|
+
const values = await pipeline([map], value => value)
|
|
32
|
+
expect(values[0]).toBe(map)
|
|
33
|
+
expect(await pipeline([] as number[], value => value + 1)).toEqual([])
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test('supports arbitrarily long chains of typed stage functions', async () => {
|
|
37
|
+
const increment = (value: number) => value + 1
|
|
38
|
+
expect(await pipeline([0], increment, increment, increment, increment, increment, increment, increment, increment)).toEqual([8])
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
test('a failed item skips its remaining stages while other items continue', async () => {
|
|
42
|
+
const failure = new Error('bad item')
|
|
43
|
+
let release!: () => void
|
|
44
|
+
let completed!: () => void
|
|
45
|
+
const gate = new Promise<void>(resolve => { release = resolve })
|
|
46
|
+
const sibling = new Promise<void>(resolve => { completed = resolve })
|
|
47
|
+
const finalItems: number[] = []
|
|
48
|
+
let settled = false
|
|
49
|
+
const result = pipeline(
|
|
50
|
+
[1, 2],
|
|
51
|
+
async value => { if (value === 1) throw failure; await gate; return value },
|
|
52
|
+
value => { finalItems.push(value); completed(); return value },
|
|
53
|
+
).then(values => { settled = true; return values })
|
|
54
|
+
// Give the failed item's rejection handling a chance to advance before checking
|
|
55
|
+
// that the sibling blocked on gate keeps the pipeline pending. These two yields
|
|
56
|
+
// provide bounded scheduling progress, without guaranteeing failure handling is complete.
|
|
57
|
+
await Promise.resolve()
|
|
58
|
+
await Promise.resolve()
|
|
59
|
+
expect(settled).toBe(false)
|
|
60
|
+
expect(finalItems).toEqual([])
|
|
61
|
+
release()
|
|
62
|
+
await sibling
|
|
63
|
+
expect(finalItems).toEqual([2])
|
|
64
|
+
expect(await result).toEqual([null, 2])
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test('passes the previous result, original item and index to every stage', async () => {
|
|
68
|
+
const first = Promise.resolve('first')
|
|
69
|
+
const second = Promise.resolve('second')
|
|
70
|
+
const originals = [first, second] as const
|
|
71
|
+
const seen: unknown[][] = []
|
|
72
|
+
const result = await pipeline(
|
|
73
|
+
originals,
|
|
74
|
+
(value, original, index) => {
|
|
75
|
+
expect(original).toBe(originals[index]!)
|
|
76
|
+
seen.push([value, index])
|
|
77
|
+
return value.length
|
|
78
|
+
},
|
|
79
|
+
async (length, original, index) => {
|
|
80
|
+
expect(original).toBe(originals[index]!)
|
|
81
|
+
return { length, item: await original, index }
|
|
82
|
+
},
|
|
83
|
+
)
|
|
84
|
+
expect(seen).toEqual([['first', 0], ['second', 1]])
|
|
85
|
+
expect(result).toEqual([{ length: 5, item: 'first', index: 0 }, { length: 6, item: 'second', index: 1 }])
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test('snapshots input entries and indices before starting any item chain', async () => {
|
|
89
|
+
const resolved = Promise.resolve('first')
|
|
90
|
+
const first: PromiseLike<string> = {
|
|
91
|
+
get then() {
|
|
92
|
+
// Awaiting this entry reads `then` while the other item chains are still being started.
|
|
93
|
+
items.splice(1, 1, Promise.resolve('replacement'))
|
|
94
|
+
return resolved.then.bind(resolved)
|
|
95
|
+
},
|
|
96
|
+
}
|
|
97
|
+
const second = Promise.resolve('second')
|
|
98
|
+
const items = [first, second]
|
|
99
|
+
const results = await pipeline(items, (value, original, index) => ({ value, original, index }))
|
|
100
|
+
|
|
101
|
+
expect(results.map(result => result && [result.value, result.index])).toEqual([['first', 0], ['second', 1]])
|
|
102
|
+
expect(results[0]?.original).toBe(first)
|
|
103
|
+
expect(results[1]?.original).toBe(second)
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
test('null input or stage results skip later stages while other falsy values continue', async () => {
|
|
107
|
+
const entered: unknown[] = []
|
|
108
|
+
const next: unknown[] = []
|
|
109
|
+
const result = await pipeline(
|
|
110
|
+
[null, 0, false, '', undefined, 'drop'],
|
|
111
|
+
value => { entered.push(value); return value === 'drop' ? null : value },
|
|
112
|
+
value => { next.push(value); return value },
|
|
113
|
+
)
|
|
114
|
+
expect(result).toEqual([null, 0, false, '', undefined, null])
|
|
115
|
+
expect(entered).toEqual([0, false, '', undefined, 'drop'])
|
|
116
|
+
expect(next).toEqual([0, false, '', undefined])
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
test('isolates rejected input promises and synchronous stage failures', async () => {
|
|
120
|
+
const entered: number[] = []
|
|
121
|
+
expect(await pipeline(
|
|
122
|
+
[Promise.reject(new Error('input')), Promise.resolve(1), Promise.resolve(2)],
|
|
123
|
+
value => { entered.push(value); if (value === 1) throw new Error('stage'); return value * 10 },
|
|
124
|
+
)).toEqual([null, null, 20])
|
|
125
|
+
expect(entered).toEqual([1, 2])
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
test('zero stages await input values and convert input rejection to null', async () => {
|
|
129
|
+
expect(await pipeline([Promise.resolve(1), Promise.reject(new Error('failed')), null, 0, undefined])).toEqual([1, null, null, 0, undefined])
|
|
130
|
+
expect(await pipeline([])).toEqual([])
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
test('validates arrays and all stages before processing nonempty input', async () => {
|
|
134
|
+
let started = false
|
|
135
|
+
// @ts-expect-error invalid stage from a JavaScript caller
|
|
136
|
+
await expect(pipeline([1], () => { started = true }, undefined)).rejects.toBeInstanceOf(TypeError)
|
|
137
|
+
expect(started).toBe(false)
|
|
138
|
+
// @ts-expect-error array-like objects are not arrays
|
|
139
|
+
await expect(pipeline({ map: () => [] })).rejects.toBeInstanceOf(TypeError)
|
|
140
|
+
// @ts-expect-error missing input
|
|
141
|
+
await expect(pipeline()).rejects.toBeInstanceOf(TypeError)
|
|
142
|
+
// @ts-expect-error empty inputs return before validating stages, matching the reference
|
|
143
|
+
expect(await pipeline([], undefined)).toEqual([])
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
/** Compile-only assertions for stage compatibility, context and nullable results; never invoked at runtime. */
|
|
147
|
+
function checkTypes() {
|
|
148
|
+
const firstStage = (value: string) => value.length
|
|
149
|
+
const secondStage = (value: number) => value > 0
|
|
150
|
+
const namedStages: Promise<(boolean | null)[]> = pipeline(['x'], firstStage, secondStage)
|
|
151
|
+
const increment = (value: number) => value + 1
|
|
152
|
+
const longChain: Promise<(number | null)[]> = pipeline([0], increment, increment, increment, increment, increment, increment, increment)
|
|
153
|
+
// @ts-expect-error the last named stage cannot consume the preceding number
|
|
154
|
+
pipeline([0], increment, increment, increment, increment, increment, increment, (value: string) => value)
|
|
155
|
+
const result = pipeline(
|
|
156
|
+
['file.ts'],
|
|
157
|
+
file => ({ file, valid: true }),
|
|
158
|
+
async review => review.valid,
|
|
159
|
+
valid => valid ? 1 : 0,
|
|
160
|
+
)
|
|
161
|
+
const values: Promise<(number | null)[]> = result
|
|
162
|
+
// @ts-expect-error the last stage returns numbers
|
|
163
|
+
const wrong: Promise<(string | null)[]> = result
|
|
164
|
+
// @ts-expect-error failure or an earlier null result can skip the final stage
|
|
165
|
+
const missingNull: Promise<number[]> = result
|
|
166
|
+
// @ts-expect-error stage two expects a string but stage one produces a number
|
|
167
|
+
pipeline(['x'], value => value.length, (value: string) => value.toUpperCase())
|
|
168
|
+
// @ts-expect-error first stage must accept the input item type
|
|
169
|
+
pipeline([1], (value: string) => value)
|
|
170
|
+
const zero: Promise<(number | null)[]> = pipeline([Promise.resolve(1)])
|
|
171
|
+
const empty: Promise<null[]> = pipeline([])
|
|
172
|
+
const context = pipeline([Promise.resolve('x')], (value, original, index) => {
|
|
173
|
+
const text: string = value
|
|
174
|
+
const input: Promise<string> = original
|
|
175
|
+
const position: number = index
|
|
176
|
+
void input
|
|
177
|
+
return text.length + position
|
|
178
|
+
}, (value, original, index) => {
|
|
179
|
+
const length: number = value
|
|
180
|
+
const input: Promise<string> = original
|
|
181
|
+
void input
|
|
182
|
+
return length + index
|
|
183
|
+
})
|
|
184
|
+
const nullable: Promise<(number | null)[]> = pipeline([1], () => Math.random() ? null : 1, value => {
|
|
185
|
+
const number: number = value
|
|
186
|
+
return number + 1
|
|
187
|
+
})
|
|
188
|
+
pipeline([undefined as number | undefined | null], value => {
|
|
189
|
+
const allowed: number | undefined = value
|
|
190
|
+
// @ts-expect-error undefined is passed to stages normally
|
|
191
|
+
const required: number = value
|
|
192
|
+
void required
|
|
193
|
+
return allowed
|
|
194
|
+
})
|
|
195
|
+
const six = pipeline(['x'], value => value.length, value => value > 0,
|
|
196
|
+
value => ({ valid: value }), value => value.valid ? 'yes' : 'no',
|
|
197
|
+
(value, original, index) => value.length + original.length + index, value => value > 0)
|
|
198
|
+
const sixResult: Promise<(boolean | null)[]> = six
|
|
199
|
+
void values; void wrong; void missingNull; void namedStages; void longChain; void zero; void empty; void context; void nullable; void sixResult
|
|
200
|
+
}
|
|
201
|
+
void checkTypes
|
package/src/pipeline.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run each input through sequential stages at its own pace. Each stage receives the awaited input
|
|
3
|
+
* or prior result, the original array entry as supplied and its zero-based index in the snapshot.
|
|
4
|
+
* Inline stages infer their input types through six stages. Longer chains can use typed functions
|
|
5
|
+
* that accept the preceding stage's awaited result with `null` excluded.
|
|
6
|
+
*
|
|
7
|
+
* The promise resolves after all item chains settle and returns their final values in input order.
|
|
8
|
+
* An input or stage that resolves to `null` or rejects ends that item's chain with `null`.
|
|
9
|
+
* A synchronous stage throw has the same effect. Sibling chains continue after a failure,
|
|
10
|
+
* and other falsy values advance normally. With zero stages, return awaited inputs with
|
|
11
|
+
* rejections as `null`.
|
|
12
|
+
*
|
|
13
|
+
* Handle input and stage failures before they reach the pipeline to retain the original cause.
|
|
14
|
+
* The caller owns concurrency limits, cancellation, retries and resource cleanup for input
|
|
15
|
+
* work and stages. Return the work each stage needs the pipeline to await.
|
|
16
|
+
*
|
|
17
|
+
* A non-array input rejects with `TypeError`. The function snapshots the array and resolves to `[]`
|
|
18
|
+
* for an empty snapshot. For nonempty input, a non-function stage rejects with `TypeError` before
|
|
19
|
+
* item processing starts.
|
|
20
|
+
*/
|
|
21
|
+
export function pipeline<Input>(items: readonly Input[]): Promise<(Awaited<Input> | null)[]>
|
|
22
|
+
export function pipeline<A, B>(items: readonly A[], first: Stage<A, A, B>): Promise<(Awaited<B> | null)[]>
|
|
23
|
+
export function pipeline<A, B, C>(
|
|
24
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
25
|
+
): Promise<(Awaited<C> | null)[]>
|
|
26
|
+
export function pipeline<A, B, C, D>(
|
|
27
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
28
|
+
third: Stage<C, A, D>,
|
|
29
|
+
): Promise<(Awaited<D> | null)[]>
|
|
30
|
+
export function pipeline<A, B, C, D, E>(
|
|
31
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
32
|
+
third: Stage<C, A, D>, fourth: Stage<D, A, E>,
|
|
33
|
+
): Promise<(Awaited<E> | null)[]>
|
|
34
|
+
export function pipeline<A, B, C, D, E, F>(
|
|
35
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
36
|
+
third: Stage<C, A, D>, fourth: Stage<D, A, E>, fifth: Stage<E, A, F>,
|
|
37
|
+
): Promise<(Awaited<F> | null)[]>
|
|
38
|
+
export function pipeline<A, B, C, D, E, F, G>(
|
|
39
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
40
|
+
third: Stage<C, A, D>, fourth: Stage<D, A, E>,
|
|
41
|
+
fifth: Stage<E, A, F>, sixth: Stage<F, A, G>,
|
|
42
|
+
): Promise<(Awaited<G> | null)[]>
|
|
43
|
+
/**
|
|
44
|
+
* Run a nonempty chain of typed stages, checking each stage against its predecessor. Resolve
|
|
45
|
+
* with the last stage's awaited results in input order, using `null` for failed or skipped items.
|
|
46
|
+
*/
|
|
47
|
+
export function pipeline<Input, Outputs extends readonly unknown[]>(
|
|
48
|
+
items: readonly Input[],
|
|
49
|
+
...stages: Stages<Input, Outputs> & { 0: Stage<Input, Input, unknown> }
|
|
50
|
+
): Promise<(LastAwaitedOutput<Outputs> | null)[]>
|
|
51
|
+
export async function pipeline(
|
|
52
|
+
items: readonly unknown[],
|
|
53
|
+
...stages: Stage<never, never, unknown>[]
|
|
54
|
+
): Promise<unknown[]> {
|
|
55
|
+
if (!Array.isArray(items)) throw new TypeError('pipeline expects an array as the first argument')
|
|
56
|
+
const inputs = [...items]
|
|
57
|
+
if (!inputs.length) return []
|
|
58
|
+
if (stages.some(stage => typeof stage !== 'function')) throw new TypeError('pipeline stages must be functions')
|
|
59
|
+
// The overloads check compatibility between adjacent stages. The runner only needs their order.
|
|
60
|
+
const orderedStages = stages as unknown as readonly Stage<unknown, unknown, unknown>[]
|
|
61
|
+
const settledItems = await Promise.allSettled(
|
|
62
|
+
inputs.map((originalItem, index) => runItem(originalItem, index, orderedStages)),
|
|
63
|
+
)
|
|
64
|
+
return settledItems.map(result => result.status === 'fulfilled' ? result.value : null)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Advance one pipeline item by awaiting its input and each stage in turn. Pass the original
|
|
69
|
+
* entry and snapshot index to every stage, and return early on `null`. Input rejections and
|
|
70
|
+
* stage errors reject this chain so `pipeline` can collect `null` at the item's original position.
|
|
71
|
+
*/
|
|
72
|
+
async function runItem(
|
|
73
|
+
originalItem: unknown,
|
|
74
|
+
index: number,
|
|
75
|
+
stages: readonly Stage<unknown, unknown, unknown>[],
|
|
76
|
+
): Promise<unknown> {
|
|
77
|
+
let value = await originalItem
|
|
78
|
+
for (const stage of stages) {
|
|
79
|
+
if (value === null) return null
|
|
80
|
+
value = await stage(value, originalItem, index)
|
|
81
|
+
}
|
|
82
|
+
return value
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Align each stage with its predecessor's output by prepending the original input type. */
|
|
86
|
+
type PreviousStageOutput<Input, Outputs extends readonly unknown[], K> =
|
|
87
|
+
K extends '0' ? Input : [Input, ...Outputs][K & keyof [Input, ...Outputs]]
|
|
88
|
+
|
|
89
|
+
/** Check each variadic stage against the preceding output while retaining the original input context. */
|
|
90
|
+
type Stages<Input, Outputs extends readonly unknown[]> = {
|
|
91
|
+
[K in keyof Outputs]: Stage<PreviousStageOutput<Input, Outputs, K>, Input, Outputs[K]>
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Infer the pipeline's resolved value type from the final stage of a typed chain. */
|
|
95
|
+
type LastAwaitedOutput<Outputs extends readonly unknown[]> =
|
|
96
|
+
Outputs extends readonly [...unknown[], infer Output] ? Awaited<Output> : never
|
|
97
|
+
|
|
98
|
+
/** Exclude only null from a stage's awaited input because null short-circuits the item at runtime. */
|
|
99
|
+
type Stage<Previous, Input, Output> = (value: Exclude<Awaited<Previous>, null>, originalItem: Input, index: number) => Output
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Scripted client setup shared by workflow tests; each suite retains its own disposal registry.
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { createClient, type Client } from '@anureo/sdk'
|
|
4
|
+
import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Give the agent and workflow suites a factory for initialized scripted clients. Register each
|
|
8
|
+
* initialized client in the caller's registry. Both suites dispose those clients in afterEach.
|
|
9
|
+
* Initialization failures reject before registration.
|
|
10
|
+
*/
|
|
11
|
+
export function createFixture(clients: Client[]) {
|
|
12
|
+
/**
|
|
13
|
+
* Forward optional hook and capability overrides to the scripted adapter. Return the initialized
|
|
14
|
+
* client and adapter for dispatch assertions. Give each fixture a distinct runtime identity so
|
|
15
|
+
* journal replay can distinguish clients.
|
|
16
|
+
*/
|
|
17
|
+
return async function fixture(options?: FakeAdapterOptions) {
|
|
18
|
+
const adapter = createScriptedAdapter(options)
|
|
19
|
+
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
|
|
20
|
+
clients.push(client)
|
|
21
|
+
return { client, adapter }
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { HarnessSdkError, sdkError } from '@anureo/sdk'
|
|
3
|
+
import type { AgentJournal } from './persistence/journal'
|
|
4
|
+
import type { StoredFailure } from './persistence/records'
|
|
5
|
+
|
|
6
|
+
/** Internal run context installed for the workflow body and inherited by agent calls. */
|
|
7
|
+
export interface RunContext {
|
|
8
|
+
/** Source replay and target journal used by memoizedAgent. */
|
|
9
|
+
readonly journal: AgentJournal
|
|
10
|
+
/** Admission, pending work and failure state shared with workflow. */
|
|
11
|
+
readonly state: RunState
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Invoke completeRun's callback with context inherited by asynchronous descendants. The caller
|
|
15
|
+
* receives the callback promise or a synchronous throw and owns closing admission and draining work. */
|
|
16
|
+
export function runWith<T>(context: RunContext, body: () => Promise<T>): Promise<T> {
|
|
17
|
+
return storage.run(context, body)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Read the current async context so agent can choose journaled or ordinary execution.
|
|
21
|
+
* Async descendants can retain a closed context. RunState.track then rejects admission. */
|
|
22
|
+
export function currentRun(): RunContext | undefined {
|
|
23
|
+
return storage.getStore()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Project abortRun's failure into manifest metadata, excluding diagnostic messages and details. */
|
|
27
|
+
export function storedFailure(error: HarnessSdkError): StoredFailure {
|
|
28
|
+
return {
|
|
29
|
+
code: error.code,
|
|
30
|
+
retryable: error.retryable,
|
|
31
|
+
outcomeUnknown: error.outcomeUnknown,
|
|
32
|
+
cleanupFailed: cleanupFailed(error),
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Tell memoizedAgent and RunState.track when a failure must stop later dispatch even if caught.
|
|
37
|
+
* Uncertain execution, failed cleanup and broken persistence cannot safely continue the run. */
|
|
38
|
+
export function isFatal(error: HarnessSdkError): boolean {
|
|
39
|
+
return error.outcomeUnknown || cleanupFailed(error)
|
|
40
|
+
|| error.code === 'WORKFLOW_STORAGE_FAILED'
|
|
41
|
+
|| error.code === 'WORKFLOW_CHECKPOINT_INVALID'
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Internal admission and settlement state shared by workflow and its journaled agent calls.
|
|
45
|
+
* Ordinary step failures mark completion incomplete; sticky failures reject the run and block dispatch.
|
|
46
|
+
* workflow's completion and abort phases close admission and drain registered work. */
|
|
47
|
+
export class RunState {
|
|
48
|
+
/** Preserve a failure for workflow's rejection and prevent later dispatch. Active work keeps settling. */
|
|
49
|
+
stop(error: HarnessSdkError): void { this.stops.add(error) }
|
|
50
|
+
|
|
51
|
+
/** Record a normalized storage failure when abortRun cannot publish or workflow cannot release the handle. */
|
|
52
|
+
noteStorageFailure(): void { this.stop(new HarnessSdkError('WORKFLOW_STORAGE_FAILED')) }
|
|
53
|
+
|
|
54
|
+
/** Return the first sticky code and message with all recorded codes, uncertainty and cleanup evidence.
|
|
55
|
+
* abortRun snapshots this for failure publication. workflow reads it again after lock release. */
|
|
56
|
+
get failure(): HarnessSdkError | undefined {
|
|
57
|
+
const failures = [...this.stops]
|
|
58
|
+
const first = failures[0]
|
|
59
|
+
if (!first) return undefined
|
|
60
|
+
return new HarnessSdkError(first.code, first.message, false,
|
|
61
|
+
failures.some(error => error.outcomeUnknown), {
|
|
62
|
+
failureCodes: [...new Set(failures.map(error => error.code))],
|
|
63
|
+
cleanupFailed: failures.some(cleanupFailed),
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Publication status for workflow when no sticky failure remains to reject the run. */
|
|
68
|
+
get status(): 'completed' | 'incomplete' {
|
|
69
|
+
return this.incomplete ? 'incomplete' : 'completed'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Mark a drop from executeJournaledAgent or a rejection observed by track incomplete.
|
|
73
|
+
* Fatality is checked separately. */
|
|
74
|
+
noteIncomplete(): void { this.incomplete = true }
|
|
75
|
+
|
|
76
|
+
/** Throw the sticky aggregate. track checks this before starting registered work, and
|
|
77
|
+
* executeJournaledAgent checks again after publishing started because another call may have
|
|
78
|
+
* stopped dispatch during that await. */
|
|
79
|
+
assertDispatch(): void {
|
|
80
|
+
const failure = this.failure
|
|
81
|
+
if (failure) throw failure
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Invoke memoizedAgent's operation immediately and register it for workflow's drain.
|
|
85
|
+
* Closed admission returns a WORKFLOW_CLOSED rejection without invoking the operation.
|
|
86
|
+
* Sticky failures and synchronous operation throws become rejected promises. Return the work
|
|
87
|
+
* promise and register a separate observer so catching its rejection cannot hide incomplete
|
|
88
|
+
* work or fatal failures from workflow. */
|
|
89
|
+
track<T>(operation: () => Promise<T>): Promise<T> {
|
|
90
|
+
if (!this.accepting) return Promise.reject(new HarnessSdkError('WORKFLOW_CLOSED'))
|
|
91
|
+
let work: Promise<T>
|
|
92
|
+
try {
|
|
93
|
+
this.assertDispatch()
|
|
94
|
+
work = operation()
|
|
95
|
+
} catch (cause) {
|
|
96
|
+
work = Promise.reject(cause)
|
|
97
|
+
}
|
|
98
|
+
const observed = work.then(() => {}, cause => {
|
|
99
|
+
this.noteIncomplete()
|
|
100
|
+
const error = sdkError(cause, 'WORKFLOW_STEP_FAILED')
|
|
101
|
+
if (isFatal(error)) this.stop(error)
|
|
102
|
+
})
|
|
103
|
+
this.pending.add(observed)
|
|
104
|
+
void observed.then(() => { this.pending.delete(observed) })
|
|
105
|
+
return work
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Stop admitting agent work synchronously, then await all work already registered by track.
|
|
109
|
+
* completeRun calls this before publication, and abortRun uses it on failure. Work continues
|
|
110
|
+
* settling without cancellation. The observers record operation rejections in run state. */
|
|
111
|
+
async closeAndDrain(): Promise<void> {
|
|
112
|
+
this.accepting = false
|
|
113
|
+
await Promise.all([...this.pending])
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private accepting = true
|
|
117
|
+
private pending = new Set<Promise<void>>()
|
|
118
|
+
private stops = new Set<HarnessSdkError>()
|
|
119
|
+
private incomplete = false
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const storage = new AsyncLocalStorage<RunContext>()
|
|
123
|
+
|
|
124
|
+
/** Recognize SDK resource-release errors and explicit cleanup evidence on another failure.
|
|
125
|
+
* isFatal, storedFailure and RunState.failure share this rule for dispatch and reporting. */
|
|
126
|
+
function cleanupFailed(error: HarnessSdkError): boolean {
|
|
127
|
+
return error.code === 'RESOURCE_RELEASE_FAILED'
|
|
128
|
+
|| error.details?.cleanupFailed === true
|
|
129
|
+
|| (Array.isArray(error.details?.cleanupErrors) && error.details.cleanupErrors.length > 0)
|
|
130
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Identify a new durable run and optionally supply a compatible source journal for replay. */
|
|
2
|
+
export interface WorkflowOptions<Input> {
|
|
3
|
+
/** Nonempty workflow name. Resume requires the same name in the source manifest. */
|
|
4
|
+
name: string
|
|
5
|
+
/** Nonempty application-managed revision. A changed revision prevents resuming older runs. */
|
|
6
|
+
revision: string
|
|
7
|
+
/** Nonempty storage root. Relative paths are resolved against the process working directory. */
|
|
8
|
+
directory: string
|
|
9
|
+
/** New target directory name, defaulting to a random UUID. Use a nonblank single path
|
|
10
|
+
* component of at most 255 UTF-8 bytes. Control characters, separators, `.` and `..` are
|
|
11
|
+
* invalid. A locked or nonempty target directory rejects. */
|
|
12
|
+
runId?: string
|
|
13
|
+
/** Strict JSON input. The body receives a deeply frozen copy. */
|
|
14
|
+
input: Input
|
|
15
|
+
/** Omit for a fresh journal. A string selects a run under `directory`. An object supplies the
|
|
16
|
+
* source's storage root and ID explicitly. The source must be inactive, compatible by name and
|
|
17
|
+
* revision, and separate from the target tree. The new run copies its journal before invoking the body. */
|
|
18
|
+
resumeFrom?: string | { directory: string; runId: string }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Body inputs available after the initial manifest has been published. */
|
|
22
|
+
export interface WorkflowContext<Input> {
|
|
23
|
+
/** Identity of the new run, including when replaying a source journal. */
|
|
24
|
+
readonly runId: string
|
|
25
|
+
/** Isolated, deeply frozen JSON copy of the input supplied for this invocation. */
|
|
26
|
+
readonly input: Input
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Published body result returned after registered agent work settles and the writer lock is released. */
|
|
30
|
+
export interface WorkflowResult<Result> {
|
|
31
|
+
/** Identity of the run that published this result. */
|
|
32
|
+
runId: string
|
|
33
|
+
/** Incomplete if registered agent work rejected or was dropped and the workflow could still
|
|
34
|
+
* publish a result. Fatal agent failures reject the workflow promise. */
|
|
35
|
+
status: 'completed' | 'incomplete'
|
|
36
|
+
/** JSON copy of the awaited body return value. */
|
|
37
|
+
result: Result
|
|
38
|
+
}
|