@anureo/workflow 0.3.1 → 0.3.3
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 +94 -96
- package/package.json +8 -8
- package/src/agent-mcp.test.ts +19 -0
- package/src/agent-outcome.ts +21 -0
- package/src/agent-pi.test.ts +21 -0
- package/src/agent.test.ts +51 -100
- package/src/agent.ts +81 -106
- package/src/fixtures/workflow-crash.ts +12 -33
- package/src/index.ts +5 -6
- package/src/journal-call.test.ts +68 -0
- package/src/journal-call.ts +93 -0
- package/src/native.test.ts +71 -0
- package/src/output-schema.test.ts +12 -33
- package/src/output-schema.ts +96 -202
- package/src/parallel.test.ts +0 -1
- package/src/parallel.ts +8 -26
- package/src/persistence/atomic.ts +32 -0
- package/src/persistence/journal.ts +88 -79
- package/src/persistence/json.ts +32 -58
- package/src/persistence/records.ts +54 -74
- package/src/persistence/replay.ts +30 -72
- package/src/persistence/store.ts +119 -229
- package/src/pipeline.test.ts +0 -19
- package/src/pipeline.ts +23 -69
- package/src/run-context.ts +19 -0
- package/src/workflow-state.ts +18 -71
- package/src/workflow-types.ts +2 -20
- package/src/workflow.test.ts +87 -55
- package/src/workflow.ts +30 -88
- package/src/agent-adapters.test.ts +0 -121
- package/src/agent-execution.ts +0 -201
- package/src/persistence/checkpoint-files.ts +0 -82
- package/src/test-helpers.ts +0 -23
package/src/workflow-state.ts
CHANGED
|
@@ -1,58 +1,31 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
1
|
import { HarnessSdkError, sdkError } from '@anureo/sdk'
|
|
3
|
-
import type {
|
|
4
|
-
import type { StoredFailure } from './persistence/records'
|
|
2
|
+
import type { StoredFailure } from './persistence/store'
|
|
5
3
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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()
|
|
4
|
+
export function cleanupFailed(error: HarnessSdkError): boolean {
|
|
5
|
+
return error.code === 'RESOURCE_RELEASE_FAILED'
|
|
6
|
+
|| error.details?.cleanupFailed === true
|
|
7
|
+
|| (Array.isArray(error.details?.cleanupErrors) && error.details.cleanupErrors.length > 0)
|
|
24
8
|
}
|
|
25
9
|
|
|
26
|
-
/** Project abortRun's failure into manifest metadata, excluding diagnostic messages and details. */
|
|
27
10
|
export function storedFailure(error: HarnessSdkError): StoredFailure {
|
|
28
|
-
return {
|
|
29
|
-
|
|
30
|
-
retryable: error.retryable,
|
|
31
|
-
outcomeUnknown: error.outcomeUnknown,
|
|
32
|
-
cleanupFailed: cleanupFailed(error),
|
|
33
|
-
}
|
|
11
|
+
return { code: error.code, retryable: error.retryable,
|
|
12
|
+
outcomeUnknown: error.outcomeUnknown, cleanupFailed: cleanupFailed(error) }
|
|
34
13
|
}
|
|
35
14
|
|
|
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
15
|
export function isFatal(error: HarnessSdkError): boolean {
|
|
39
16
|
return error.outcomeUnknown || cleanupFailed(error)
|
|
40
17
|
|| error.code === 'WORKFLOW_STORAGE_FAILED'
|
|
41
18
|
|| error.code === 'WORKFLOW_CHECKPOINT_INVALID'
|
|
42
19
|
}
|
|
43
20
|
|
|
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
21
|
export class RunState {
|
|
48
|
-
|
|
49
|
-
|
|
22
|
+
private accepting = true
|
|
23
|
+
private pending = new Set<Promise<void>>()
|
|
24
|
+
private stops = new Set<HarnessSdkError>()
|
|
25
|
+
private rejected = 0
|
|
50
26
|
|
|
51
|
-
|
|
52
|
-
noteStorageFailure(): void { this.stop(new HarnessSdkError('WORKFLOW_STORAGE_FAILED')) }
|
|
27
|
+
stop(error: HarnessSdkError): void { this.stops.add(error) }
|
|
53
28
|
|
|
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
29
|
get failure(): HarnessSdkError | undefined {
|
|
57
30
|
const failures = [...this.stops]
|
|
58
31
|
const first = failures[0]
|
|
@@ -64,28 +37,20 @@ export class RunState {
|
|
|
64
37
|
})
|
|
65
38
|
}
|
|
66
39
|
|
|
67
|
-
/** Publication status for workflow when no sticky failure remains to reject the run. */
|
|
68
40
|
get status(): 'completed' | 'incomplete' {
|
|
69
|
-
return this.
|
|
41
|
+
return this.rejected ? 'incomplete' : 'completed'
|
|
70
42
|
}
|
|
71
43
|
|
|
72
|
-
/**
|
|
73
|
-
*
|
|
74
|
-
noteIncomplete(): void { this.
|
|
44
|
+
/** Records a settled-but-unsuccessful outcome (for example a dropped agent)
|
|
45
|
+
* that does not reject the body but still marks the run incomplete. */
|
|
46
|
+
noteIncomplete(): void { this.rejected++ }
|
|
75
47
|
|
|
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
48
|
assertDispatch(): void {
|
|
80
49
|
const failure = this.failure
|
|
81
50
|
if (failure) throw failure
|
|
82
51
|
}
|
|
83
52
|
|
|
84
|
-
/**
|
|
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. */
|
|
53
|
+
/** Registers in-flight work so body completion waits for it; late calls reject. */
|
|
89
54
|
track<T>(operation: () => Promise<T>): Promise<T> {
|
|
90
55
|
if (!this.accepting) return Promise.reject(new HarnessSdkError('WORKFLOW_CLOSED'))
|
|
91
56
|
let work: Promise<T>
|
|
@@ -96,7 +61,7 @@ export class RunState {
|
|
|
96
61
|
work = Promise.reject(cause)
|
|
97
62
|
}
|
|
98
63
|
const observed = work.then(() => {}, cause => {
|
|
99
|
-
this.
|
|
64
|
+
this.rejected++
|
|
100
65
|
const error = sdkError(cause, 'WORKFLOW_STEP_FAILED')
|
|
101
66
|
if (isFatal(error)) this.stop(error)
|
|
102
67
|
})
|
|
@@ -105,26 +70,8 @@ export class RunState {
|
|
|
105
70
|
return work
|
|
106
71
|
}
|
|
107
72
|
|
|
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
73
|
async closeAndDrain(): Promise<void> {
|
|
112
74
|
this.accepting = false
|
|
113
75
|
await Promise.all([...this.pending])
|
|
114
76
|
}
|
|
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
77
|
}
|
package/src/workflow-types.ts
CHANGED
|
@@ -1,38 +1,20 @@
|
|
|
1
|
-
/** Identify a new durable run and optionally supply a compatible source journal for replay. */
|
|
2
1
|
export interface WorkflowOptions<Input> {
|
|
3
|
-
/** Nonempty workflow name. Resume requires the same name in the source manifest. */
|
|
4
2
|
name: string
|
|
5
|
-
/** Nonempty application-managed revision. A changed revision prevents resuming older runs. */
|
|
6
3
|
revision: string
|
|
7
|
-
/**
|
|
8
|
-
directory
|
|
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. */
|
|
4
|
+
/** Run directory for the journal and manifest; omit for a memory-only run that cannot be resumed after exit. */
|
|
5
|
+
directory?: string
|
|
12
6
|
runId?: string
|
|
13
|
-
/** Strict JSON input. The body receives a deeply frozen copy. */
|
|
14
7
|
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
8
|
resumeFrom?: string | { directory: string; runId: string }
|
|
19
9
|
}
|
|
20
10
|
|
|
21
|
-
/** Body inputs available after the initial manifest has been published. */
|
|
22
11
|
export interface WorkflowContext<Input> {
|
|
23
|
-
/** Identity of the new run, including when replaying a source journal. */
|
|
24
12
|
readonly runId: string
|
|
25
|
-
/** Isolated, deeply frozen JSON copy of the input supplied for this invocation. */
|
|
26
13
|
readonly input: Input
|
|
27
14
|
}
|
|
28
15
|
|
|
29
|
-
/** Published body result returned after registered agent work settles and the writer lock is released. */
|
|
30
16
|
export interface WorkflowResult<Result> {
|
|
31
|
-
/** Identity of the run that published this result. */
|
|
32
17
|
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
18
|
status: 'completed' | 'incomplete'
|
|
36
|
-
/** JSON copy of the awaited body return value. */
|
|
37
19
|
result: Result
|
|
38
20
|
}
|
package/src/workflow.test.ts
CHANGED
|
@@ -1,46 +1,47 @@
|
|
|
1
|
-
import { createFixture } from './test-helpers'
|
|
2
1
|
import { afterEach, expect, test } from 'bun:test'
|
|
3
2
|
import { randomUUID } from 'node:crypto'
|
|
4
|
-
import { mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { mkdir, mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises'
|
|
5
4
|
import { tmpdir } from 'node:os'
|
|
6
5
|
import { join } from 'node:path'
|
|
7
6
|
import { fileURLToPath } from 'node:url'
|
|
8
|
-
import { createClient, HarnessSdkError, type Client } from '@anureo/sdk'
|
|
9
|
-
import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
|
|
7
|
+
import { createClient, HarnessSdkError, type Client, type ClientOptions, type SessionEventSink } from '@anureo/sdk'
|
|
8
|
+
import { createScriptedAdapter, type FakeAdapterOptions, type FakeCall } from '@anureo/conformance'
|
|
10
9
|
import type { HarnessError } from '@anureo/protocol'
|
|
11
10
|
import { z } from 'zod'
|
|
12
|
-
import { workflow, parallel, agent, type WorkflowOptions } from './index'
|
|
11
|
+
import { workflow, pipeline, parallel, agent, type WorkflowOptions } from './index'
|
|
13
12
|
import { canonicalJson, digest } from './persistence/json'
|
|
14
13
|
|
|
15
14
|
const clients: Client[] = []
|
|
16
|
-
const fixture = createFixture(clients)
|
|
17
15
|
const roots: string[] = []
|
|
18
16
|
afterEach(async () => {
|
|
19
17
|
await Promise.all(clients.splice(0).map(client => client.dispose()))
|
|
20
18
|
await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true })))
|
|
21
19
|
})
|
|
22
|
-
/** Create isolated run storage; afterEach removes it after disposing the test's clients. */
|
|
23
20
|
async function setup() {
|
|
24
21
|
const directory = await mkdtemp(join(tmpdir(), 'anureo-workflow-'))
|
|
25
22
|
roots.push(directory)
|
|
26
23
|
return { directory, name: 'test', revision: '1', input: {} }
|
|
27
24
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
async function fixture(options?: FakeAdapterOptions, clientOptions?: Partial<Pick<ClientOptions, 'identity' | 'hooks'>>) {
|
|
26
|
+
const adapter = createScriptedAdapter(options)
|
|
27
|
+
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() }, ...clientOptions })
|
|
28
|
+
clients.push(client)
|
|
29
|
+
return { client, adapter }
|
|
30
|
+
}
|
|
31
|
+
/** Emits a failed terminal turn outcome, mirroring native failures. */
|
|
31
32
|
function failingExecute(error: HarnessError): NonNullable<FakeAdapterOptions['execute']> {
|
|
32
33
|
return async (call, sink) => {
|
|
33
34
|
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
34
35
|
const turnId = randomUUID()
|
|
35
36
|
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
36
37
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error } }, { turnId })
|
|
37
|
-
return { submissionId: call.params.submissionId,
|
|
38
|
+
return { submissionId: (call.params as { submissionId: string }).submissionId,
|
|
38
39
|
accepted: true, disposition: 'started', turnId }
|
|
39
40
|
}
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
test('root runtime exports contain the four independently usable primitives', async () => {
|
|
43
|
-
expect(Object.keys(await import('./index')).sort()).toEqual(['agent', 'parallel', 'pipeline', 'workflow'])
|
|
44
|
+
expect(Object.keys(await import('./index')).sort()).toEqual(['agent', 'isDroppedOutcome', 'journaledCall', 'parallel', 'pipeline', 'prepareOutputSchema', 'workflow'])
|
|
44
45
|
})
|
|
45
46
|
|
|
46
47
|
test('run identity is durable before body, inputs are isolated, and results are persisted', async () => {
|
|
@@ -67,21 +68,59 @@ test('run identity is durable before body, inputs are isolated, and results are
|
|
|
67
68
|
test('resumed runs replay identical agent calls from the journal without new sessions', async () => {
|
|
68
69
|
const options = await setup()
|
|
69
70
|
const { client, adapter } = await fixture()
|
|
70
|
-
const
|
|
71
|
-
agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) })
|
|
72
|
-
const first = await workflow(options, body)
|
|
71
|
+
const first = await workflow(options, async () =>
|
|
72
|
+
agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) }))
|
|
73
73
|
expect(adapter.opened).toHaveLength(1)
|
|
74
74
|
expect(first.result).toEqual({ value: 1 })
|
|
75
|
-
const second = await workflow({ ...options, resumeFrom: first.runId },
|
|
75
|
+
const second = await workflow({ ...options, resumeFrom: first.runId }, async () =>
|
|
76
|
+
agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) }))
|
|
76
77
|
expect(adapter.opened).toHaveLength(1)
|
|
77
78
|
expect(second.result).toEqual({ value: 1 })
|
|
78
79
|
// The resumed run carries its own journal copy; the source can be deleted.
|
|
79
80
|
await rm(join(options.directory, first.runId), { recursive: true })
|
|
80
|
-
const third = await workflow({ ...options, resumeFrom: second.runId },
|
|
81
|
+
const third = await workflow({ ...options, resumeFrom: second.runId }, async () =>
|
|
82
|
+
agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) }))
|
|
81
83
|
expect(adapter.opened).toHaveLength(1)
|
|
82
84
|
expect(third.result).toEqual({ value: 1 })
|
|
83
85
|
})
|
|
84
86
|
|
|
87
|
+
test('workflow reuses results only under the same input hook revision', async () => {
|
|
88
|
+
const options = await setup()
|
|
89
|
+
const identity = { adapterId: 'scripted', runtimeConfigId: 'input-policy' }
|
|
90
|
+
const without = await fixture(undefined, { identity })
|
|
91
|
+
const calls: string[] = []
|
|
92
|
+
const withPolicy = (inputRevision: string) => fixture(undefined, { identity, hooks: {
|
|
93
|
+
inputRevision,
|
|
94
|
+
transformInput: [() => {
|
|
95
|
+
calls.push(inputRevision)
|
|
96
|
+
return [{ type: 'text', text: 'transformed' }]
|
|
97
|
+
}],
|
|
98
|
+
} })
|
|
99
|
+
const v1 = await withPolicy('1')
|
|
100
|
+
const same = await withPolicy('1')
|
|
101
|
+
const v2 = await withPolicy('2')
|
|
102
|
+
const execute = (client: Client) => agent('original', { client, cwd: options.directory })
|
|
103
|
+
const original = await workflow(options, () => execute(without.client))
|
|
104
|
+
const policy = await workflow(options, () => execute(v1.client))
|
|
105
|
+
expect(policy.result).toBe('transformed')
|
|
106
|
+
await expect(workflow({ ...options, resumeFrom: policy.runId }, () => execute(same.client)))
|
|
107
|
+
.resolves.toMatchObject({ result: 'transformed' })
|
|
108
|
+
expect(same.adapter.opened).toHaveLength(0)
|
|
109
|
+
const scenarios = [
|
|
110
|
+
[original.runId, v1.client], [policy.runId, without.client], [policy.runId, v2.client],
|
|
111
|
+
] as const
|
|
112
|
+
for (const [runId, client] of scenarios) {
|
|
113
|
+
await expect(workflow({ ...options, resumeFrom: runId }, async () => {
|
|
114
|
+
try { await execute(client) } catch {}
|
|
115
|
+
try { await agent('later', { client, cwd: options.directory }) } catch {}
|
|
116
|
+
})).rejects.toMatchObject({ code: 'WORKFLOW_INPUT_POLICY_CHANGED', outcomeUnknown: false })
|
|
117
|
+
}
|
|
118
|
+
expect(v1.adapter.opened).toHaveLength(1)
|
|
119
|
+
expect(without.adapter.opened).toHaveLength(1)
|
|
120
|
+
expect(v2.adapter.opened).toHaveLength(0)
|
|
121
|
+
expect(calls).toEqual(['1'])
|
|
122
|
+
})
|
|
123
|
+
|
|
85
124
|
test('chained keys invalidate the downstream prefix when any call changes', async () => {
|
|
86
125
|
const options = await setup()
|
|
87
126
|
const { client, adapter } = await fixture()
|
|
@@ -162,21 +201,22 @@ test('unknown previous outcomes require reconciliation instead of silent re-exec
|
|
|
162
201
|
const { client, adapter } = await fixture({
|
|
163
202
|
execute: failingExecute({ code: 'NATIVE_FAILED', message: 'unknown', retryable: false, outcomeUnknown: true }),
|
|
164
203
|
})
|
|
165
|
-
const failure
|
|
166
|
-
.then(
|
|
167
|
-
|
|
168
|
-
cause => cause,
|
|
169
|
-
)
|
|
204
|
+
const failure = await workflow(options, () => agent('unknown', { client, cwd: options.directory }))
|
|
205
|
+
.then(value => { throw new Error(`expected rejection, completed with ${JSON.stringify(value)}`) })
|
|
206
|
+
.catch(cause => cause as HarnessSdkError & { details: { runId: string } })
|
|
170
207
|
expect(failure).toBeInstanceOf(HarnessSdkError)
|
|
171
|
-
if (!(failure instanceof HarnessSdkError)) throw failure
|
|
172
208
|
expect(failure.outcomeUnknown).toBe(true)
|
|
173
209
|
expect(adapter.opened).toHaveLength(1)
|
|
174
|
-
|
|
175
|
-
if (typeof runId !== 'string') throw new Error('expected the failed run ID')
|
|
176
|
-
await expect(workflow({ ...options, resumeFrom: runId }, () =>
|
|
210
|
+
await expect(workflow({ ...options, resumeFrom: failure.details.runId }, () =>
|
|
177
211
|
agent('unknown', { client, cwd: options.directory })))
|
|
178
212
|
.rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
|
|
213
|
+
const revised = await fixture(undefined, { identity: client.identity,
|
|
214
|
+
hooks: { inputRevision: 'new', beforeInput: [() => undefined] } })
|
|
215
|
+
await expect(workflow({ ...options, resumeFrom: failure.details.runId }, () =>
|
|
216
|
+
agent('unknown', { client: revised.client, cwd: options.directory })))
|
|
217
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
|
|
179
218
|
expect(adapter.opened).toHaveLength(1)
|
|
219
|
+
expect(revised.adapter.opened).toHaveLength(0)
|
|
180
220
|
})
|
|
181
221
|
|
|
182
222
|
test('storage failure is sticky and blocks subsequent agent dispatch', async () => {
|
|
@@ -185,8 +225,10 @@ test('storage failure is sticky and blocks subsequent agent dispatch', async ()
|
|
|
185
225
|
let id = ''
|
|
186
226
|
await expect(workflow(options, async run => {
|
|
187
227
|
id = run.runId
|
|
188
|
-
//
|
|
189
|
-
|
|
228
|
+
// Block atomic replacement of the journal while leaving the open writer lock alone.
|
|
229
|
+
const journal = join(options.directory, id, 'journal.json')
|
|
230
|
+
await rm(journal)
|
|
231
|
+
await mkdir(journal)
|
|
190
232
|
try { await agent('first', { client, cwd: options.directory }) } catch {}
|
|
191
233
|
try { await agent('second', { client, cwd: options.directory }) } catch {}
|
|
192
234
|
return 'caught'
|
|
@@ -198,14 +240,16 @@ test('storage failure is sticky and blocks subsequent agent dispatch', async ()
|
|
|
198
240
|
test('body completion waits for already registered unawaited agent work', async () => {
|
|
199
241
|
const options = await setup()
|
|
200
242
|
const { client } = await fixture()
|
|
201
|
-
|
|
243
|
+
let resolve!: () => void
|
|
244
|
+
const wait = new Promise<void>(done => { resolve = done })
|
|
202
245
|
let ended = false
|
|
203
246
|
const result = workflow(options, () => {
|
|
204
247
|
void agent('slow', { client, cwd: options.directory }).then(() => { ended = true })
|
|
205
|
-
|
|
248
|
+
void wait.then(() => {})
|
|
249
|
+
resolve()
|
|
206
250
|
return 'body'
|
|
207
251
|
})
|
|
208
|
-
await
|
|
252
|
+
await wait
|
|
209
253
|
expect((await result).status).toBe('completed')
|
|
210
254
|
expect(ended).toBe(true)
|
|
211
255
|
})
|
|
@@ -226,22 +270,21 @@ test('agent calls detached from the run context execute as ordinary unjournaled
|
|
|
226
270
|
test('source activity, target competition, and reused explicit ids reject before body', async () => {
|
|
227
271
|
const options = await setup()
|
|
228
272
|
const { client } = await fixture()
|
|
229
|
-
|
|
230
|
-
|
|
273
|
+
let release!: () => void
|
|
274
|
+
let entered!: () => void
|
|
275
|
+
const ready = new Promise<void>(done => { entered = done })
|
|
276
|
+
const waiting = new Promise<void>(done => { release = done })
|
|
231
277
|
const first = workflow({ ...options, runId: 'owned' }, async () => {
|
|
232
|
-
entered
|
|
278
|
+
entered()
|
|
233
279
|
await agent('held', { client, cwd: options.directory })
|
|
234
|
-
await
|
|
280
|
+
await waiting
|
|
235
281
|
return 'done'
|
|
236
282
|
})
|
|
237
|
-
await
|
|
283
|
+
await ready
|
|
238
284
|
try {
|
|
239
285
|
await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
|
|
240
286
|
await expect(workflow({ ...options, resumeFrom: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_SOURCE_ACTIVE' })
|
|
241
|
-
} finally {
|
|
242
|
-
release.resolve()
|
|
243
|
-
await first
|
|
244
|
-
}
|
|
287
|
+
} finally { release(); await first }
|
|
245
288
|
await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
|
|
246
289
|
})
|
|
247
290
|
|
|
@@ -308,7 +351,7 @@ test('strict JSON rejects lossy inputs and canonical hashes ignore object insert
|
|
|
308
351
|
})
|
|
309
352
|
|
|
310
353
|
test('real process death at durable boundaries replays committed agent work only', async () => {
|
|
311
|
-
for (const phase of ['before-started', 'after-execute', 'before-final'
|
|
354
|
+
for (const phase of ['before-started', 'after-execute', 'before-final']) {
|
|
312
355
|
const options = await setup()
|
|
313
356
|
const child = Bun.spawn([process.execPath, fileURLToPath(new URL('./fixtures/workflow-crash.ts', import.meta.url)),
|
|
314
357
|
options.directory, phase], { stdout: 'ignore', stderr: 'pipe' })
|
|
@@ -319,20 +362,10 @@ test('real process death at durable boundaries replays committed agent work only
|
|
|
319
362
|
const adapter = createScriptedAdapter()
|
|
320
363
|
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
|
|
321
364
|
clients.push(client)
|
|
322
|
-
const result = await workflow({ ...options, name: 'crash-test', resumeFrom: 'crashed' },
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
return phase === 'after-later-result'
|
|
326
|
-
? Promise.all([first, agent('later', { client, cwd: options.directory })])
|
|
327
|
-
: first
|
|
328
|
-
})
|
|
329
|
-
expect(result.result).toEqual(phase === 'after-later-result' ? ['work', 'later'] : 'work')
|
|
365
|
+
const result = await workflow({ ...options, name: 'crash-test', resumeFrom: 'crashed' }, () =>
|
|
366
|
+
agent('work', { client, cwd: options.directory }))
|
|
367
|
+
expect(result.result).toBe('work')
|
|
330
368
|
expect(adapter.opened).toHaveLength(phase === 'before-final' ? 0 : 1)
|
|
331
|
-
if (phase === 'after-later-result') {
|
|
332
|
-
const submissions = adapter.calls.filter(call => call.method === 'input/submit')
|
|
333
|
-
expect(submissions).toHaveLength(1)
|
|
334
|
-
expect(submissions[0]?.params).toMatchObject({ input: [{ type: 'text', text: 'work' }] })
|
|
335
|
-
}
|
|
336
369
|
await client.dispose()
|
|
337
370
|
}
|
|
338
371
|
}, 15000)
|
|
@@ -356,7 +389,6 @@ test('an interrupted run reuses the unchanged call prefix in original order', as
|
|
|
356
389
|
expect(result.status).toBe('completed')
|
|
357
390
|
})
|
|
358
391
|
|
|
359
|
-
/** Compile-only consumer checks for context and awaited body-result inference; never invoked. */
|
|
360
392
|
function typeChecks(options: WorkflowOptions<{ files: string[] }>) {
|
|
361
393
|
const run = workflow(options, async context => {
|
|
362
394
|
const file: string = context.input.files[0]!
|
package/src/workflow.ts
CHANGED
|
@@ -1,25 +1,11 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
2
|
import { HarnessSdkError, sdkError } from '@anureo/sdk'
|
|
3
3
|
import type { WorkflowContext, WorkflowOptions, WorkflowResult } from './workflow-types'
|
|
4
|
-
import { RunState,
|
|
4
|
+
import { RunState, storedFailure } from './workflow-state'
|
|
5
|
+
import { runWith } from './run-context'
|
|
5
6
|
import { freezeJson, jsonCopy, type JsonValue } from './persistence/json'
|
|
6
7
|
import { openFileRun, type RunHandle } from './persistence/store'
|
|
7
8
|
|
|
8
|
-
/**
|
|
9
|
-
* Run a body with a durable identity, frozen JSON input and journaled agent calls. The body
|
|
10
|
-
* receives the new run's ID and input after initial publication. On resume the body starts from
|
|
11
|
-
* the beginning and eligible agent calls reuse saved results. Account for repeated side effects
|
|
12
|
-
* from body code and agent calls that execute again.
|
|
13
|
-
* Supply strict JSON for the input and awaited body result. Await your own background work inside
|
|
14
|
-
* the body. Keep borrowed clients alive until the workflow promise settles, then dispose them separately.
|
|
15
|
-
*
|
|
16
|
-
* Resolve with a JSON copy of the body result after registered agent work settles, publication
|
|
17
|
-
* succeeds and the writer lock is released. A drop or an ordinary failure in registered work can
|
|
18
|
-
* yield an incomplete result if the body still returns. Invalid inputs, uncaught body errors,
|
|
19
|
-
* fatal agent failures, and storage failures reject. Run failures report the run ID and storage
|
|
20
|
-
* root in SDK error details, using the supplied directory if initialization fails. A
|
|
21
|
-
* lock-release failure can reject after the result and terminal manifest have been published.
|
|
22
|
-
*/
|
|
23
9
|
export async function workflow<Input, Result>(
|
|
24
10
|
options: WorkflowOptions<Input>,
|
|
25
11
|
body: (run: WorkflowContext<Input>) => Result | Promise<Result>,
|
|
@@ -27,86 +13,42 @@ export async function workflow<Input, Result>(
|
|
|
27
13
|
const runId = options?.runId ?? randomUUID()
|
|
28
14
|
const state = new RunState()
|
|
29
15
|
let handle: RunHandle | undefined
|
|
30
|
-
let
|
|
16
|
+
let value: Awaited<Result> | undefined
|
|
31
17
|
try {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
18
|
+
if (!options || typeof options !== 'object' || typeof body !== 'function') {
|
|
19
|
+
throw new HarnessSdkError('INVALID_PARAMS')
|
|
20
|
+
}
|
|
21
|
+
const input = freezeJson(jsonCopy(options.input))
|
|
22
|
+
const resumeFrom = options.resumeFrom && typeof options.resumeFrom === 'object'
|
|
23
|
+
? { ...options.resumeFrom } : options.resumeFrom
|
|
24
|
+
handle = await openFileRun({ ...options, runId, input: input as JsonValue, resumeFrom })
|
|
25
|
+
const context: WorkflowContext<Input> = { runId, input }
|
|
26
|
+
try {
|
|
27
|
+
value = await runWith({ journal: handle.journal, state }, async () => body(context))
|
|
28
|
+
}
|
|
29
|
+
catch (cause) { state.stop(sdkError(cause, 'WORKFLOW_BODY_FAILED')) }
|
|
30
|
+
await state.closeAndDrain()
|
|
31
|
+
const failure = state.failure
|
|
32
|
+
if (failure) throw failure
|
|
33
|
+
value = jsonCopy(value)
|
|
34
|
+
await handle.finish(state.status, value as JsonValue)
|
|
35
35
|
} catch (cause) {
|
|
36
|
-
|
|
36
|
+
state.stop(sdkError(cause, 'WORKFLOW_FAILED'))
|
|
37
|
+
await state.closeAndDrain()
|
|
38
|
+
if (handle) {
|
|
39
|
+
try { await handle.abort(storedFailure(state.failure!)) }
|
|
40
|
+
catch { state.stop(new HarnessSdkError('WORKFLOW_STORAGE_FAILED')) }
|
|
41
|
+
}
|
|
37
42
|
} finally {
|
|
38
43
|
if (handle) {
|
|
39
44
|
try { await handle.close() }
|
|
40
|
-
catch { state.
|
|
45
|
+
catch { state.stop(new HarnessSdkError('WORKFLOW_STORAGE_FAILED')) }
|
|
41
46
|
}
|
|
42
47
|
}
|
|
43
48
|
const failure = state.failure
|
|
44
49
|
if (failure) {
|
|
45
|
-
throw new HarnessSdkError(failure.code, failure.message, false, failure.outcomeUnknown,
|
|
46
|
-
...failure.details,
|
|
47
|
-
runId,
|
|
48
|
-
directory: handle?.identity.directory ?? options?.directory,
|
|
49
|
-
})
|
|
50
|
-
}
|
|
51
|
-
// A failed publication also stops the run, so only published results reach this return.
|
|
52
|
-
return { runId, status: state.status, result: publishedResult as Awaited<Result> }
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** Snapshot input and an object source reference before workflow awaits storage. The body gets a
|
|
56
|
-
* frozen input and the writer snapshots it separately. Malformed options, a non-function body or
|
|
57
|
-
* non-JSON input throw before storage opens. */
|
|
58
|
-
function prepareRun<Input, Result>(
|
|
59
|
-
options: WorkflowOptions<Input>,
|
|
60
|
-
body: (run: WorkflowContext<Input>) => Result | Promise<Result>,
|
|
61
|
-
runId: string,
|
|
62
|
-
): { storageOptions: WorkflowOptions<JsonValue> & { runId: string }; context: WorkflowContext<Input> } {
|
|
63
|
-
if (!options || typeof options !== 'object' || typeof body !== 'function') {
|
|
64
|
-
throw new HarnessSdkError('INVALID_PARAMS')
|
|
65
|
-
}
|
|
66
|
-
const input = freezeJson(jsonCopy(options.input))
|
|
67
|
-
const resumeFrom = options.resumeFrom && typeof options.resumeFrom === 'object'
|
|
68
|
-
? { ...options.resumeFrom } : options.resumeFrom
|
|
69
|
-
return {
|
|
70
|
-
storageOptions: { ...options, runId, input: input as JsonValue, resumeFrom },
|
|
71
|
-
context: { runId, input },
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** Give the body access to the journal through the async context. Stop dispatch on an uncaught
|
|
76
|
-
* body failure and drain before choosing the terminal outcome, since settling agents can still
|
|
77
|
-
* change it. Return the JSON result after publication. workflow routes rejections through abortRun. */
|
|
78
|
-
async function completeRun<Input, Result>({ handle, state, body, context }: {
|
|
79
|
-
handle: RunHandle
|
|
80
|
-
state: RunState
|
|
81
|
-
body: (run: WorkflowContext<Input>) => Result | Promise<Result>
|
|
82
|
-
context: WorkflowContext<Input>
|
|
83
|
-
}): Promise<Awaited<Result>> {
|
|
84
|
-
let value: Awaited<Result> | undefined
|
|
85
|
-
try {
|
|
86
|
-
value = await runWith({ journal: handle.journal, state }, async () => body(context))
|
|
87
|
-
}
|
|
88
|
-
catch (cause) { state.stop(sdkError(cause, 'WORKFLOW_BODY_FAILED')) }
|
|
89
|
-
await state.closeAndDrain()
|
|
90
|
-
const failure = state.failure
|
|
91
|
-
if (failure) throw failure
|
|
92
|
-
const result = jsonCopy(value)
|
|
93
|
-
await handle.finish(state.status, result as JsonValue)
|
|
94
|
-
return result as Awaited<Result>
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Record workflow's failure and drain before publishing the aggregate to an acquired handle.
|
|
98
|
-
* Initialization failures can arrive before a handle exists. An abort publication error is
|
|
99
|
-
* recorded as a storage failure. workflow still releases the handle and reports the final aggregate. */
|
|
100
|
-
async function abortRun({ cause, state, handle }: {
|
|
101
|
-
cause: unknown
|
|
102
|
-
state: RunState
|
|
103
|
-
handle: RunHandle | undefined
|
|
104
|
-
}): Promise<void> {
|
|
105
|
-
const error = sdkError(cause, 'WORKFLOW_FAILED')
|
|
106
|
-
state.stop(error)
|
|
107
|
-
await state.closeAndDrain()
|
|
108
|
-
if (handle) {
|
|
109
|
-
try { await handle.abort(storedFailure(state.failure ?? error)) }
|
|
110
|
-
catch { state.noteStorageFailure() }
|
|
50
|
+
throw new HarnessSdkError(failure.code, failure.message, false, failure.outcomeUnknown,
|
|
51
|
+
{ ...failure.details, runId, directory: handle?.identity.directory ?? options?.directory })
|
|
111
52
|
}
|
|
53
|
+
return { runId, status: state.status, result: value as Awaited<Result> }
|
|
112
54
|
}
|