@anureo/workflow 0.3.2 → 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 +4 -5
- 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 -237
- package/src/agent.ts +89 -115
- package/src/fixtures/workflow-crash.ts +17 -54
- 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 -45
- package/src/output-schema.ts +96 -208
- 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 +92 -104
- package/src/persistence/json.ts +32 -58
- package/src/persistence/records.ts +56 -82
- package/src/persistence/replay.ts +30 -74
- package/src/persistence/store.ts +120 -259
- 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 -72
- package/src/workflow-types.ts +2 -20
- package/src/workflow.test.ts +104 -199
- package/src/workflow.ts +30 -88
- package/src/agent-adapters.test.ts +0 -121
- package/src/agent-execution.ts +0 -220
- package/src/persistence/checkpoint-files.ts +0 -83
- package/src/test-helpers.ts +0 -23
package/src/persistence/store.ts
CHANGED
|
@@ -1,315 +1,176 @@
|
|
|
1
|
+
import type { WorkflowOptions } from '../workflow-types'
|
|
1
2
|
import { randomUUID } from 'node:crypto'
|
|
2
3
|
import { hostname } from 'node:os'
|
|
3
4
|
import { lstat, mkdir, open, readdir, realpath, unlink, type FileHandle } from 'node:fs/promises'
|
|
4
5
|
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
5
6
|
import { HarnessSdkError } from '@anureo/sdk'
|
|
6
|
-
import
|
|
7
|
-
import { atomicPublish, storageError, syncDirectory } from './checkpoint-files'
|
|
7
|
+
import { atomicPublish, syncDirectory } from './atomic'
|
|
8
8
|
import { canonicalJson, digest, jsonCopy, type JsonValue } from './json'
|
|
9
|
-
import { AgentJournal } from './journal'
|
|
10
|
-
import {
|
|
9
|
+
import { AgentJournal, type JournalEvent } from './journal'
|
|
10
|
+
import { invalidCheckpoint, record, runIdSchema, type Manifest } from './records'
|
|
11
11
|
import { loadSourceJournal } from './replay'
|
|
12
12
|
|
|
13
|
-
/** Internal identity saved before workflow enters its body. */
|
|
14
13
|
export interface RunIdentity {
|
|
15
|
-
/** Validated basename of the run within directory. */
|
|
16
14
|
runId: string
|
|
17
|
-
/** Canonical parent containing the run's subdirectory. */
|
|
18
15
|
directory: string
|
|
19
|
-
/** Workflow name used to match a compatible source run. */
|
|
20
16
|
name: string
|
|
21
|
-
/** Application revision used to match a compatible source run. */
|
|
22
17
|
revision: string
|
|
23
|
-
/** Isolated persistence snapshot. The body receives its own frozen copy from prepareRun. */
|
|
24
18
|
input: JsonValue
|
|
25
19
|
}
|
|
26
20
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
21
|
+
export interface StoredFailure {
|
|
22
|
+
code: string
|
|
23
|
+
retryable: boolean
|
|
24
|
+
outcomeUnknown: boolean
|
|
25
|
+
cleanupFailed: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
30
28
|
export interface RunHandle {
|
|
31
|
-
/** Provides the canonical storage directory for workflow's error details. */
|
|
32
29
|
readonly identity: RunIdentity
|
|
33
|
-
/** Installed by completeRun as the journal for agent calls in the body. */
|
|
34
30
|
readonly journal: AgentJournal
|
|
35
|
-
/** Publish result.json before the terminal manifest and resolve after both publications.
|
|
36
|
-
* A rejection may leave a result or manifest already replaced. A queued call that starts
|
|
37
|
-
* after closure rejects with WORKFLOW_CLOSED. */
|
|
38
31
|
finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void>
|
|
39
|
-
/** Publish a failed manifest and keep any earlier result file and the writer lock.
|
|
40
|
-
* Publication failures reject, as does a queued call that starts after closure. */
|
|
41
32
|
abort(failure: StoredFailure): Promise<void>
|
|
42
|
-
/** Wait for queued manifests, then release the owned writer lock and close its descriptor.
|
|
43
|
-
* Lock-release failures reject. Sequential repeats are no-ops, including after rejection.
|
|
44
|
-
* Callers must finish scheduling work before closure. */
|
|
45
33
|
close(): Promise<void>
|
|
46
34
|
}
|
|
47
35
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
* SDK errors propagate unless lock rollback fails. Rollback failures and otherwise unclassified
|
|
52
|
-
* I/O failures reject as WORKFLOW_STORAGE_FAILED. If publication left run files behind,
|
|
53
|
-
* a later attempt on the same target rejects with WORKFLOW_RUN_EXISTS. */
|
|
54
|
-
export async function openFileRun(options: FileRunOptions): Promise<RunHandle> {
|
|
55
|
-
validateRunOptions(options)
|
|
56
|
-
try {
|
|
57
|
-
const prepared = await prepareRunStorage(options)
|
|
58
|
-
return await initializeLockedRun({ options, prepared })
|
|
59
|
-
} catch (cause) { throw storageError(cause) }
|
|
36
|
+
function storageError(cause: unknown): HarnessSdkError {
|
|
37
|
+
if (cause instanceof HarnessSdkError) return cause
|
|
38
|
+
return new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
|
|
60
39
|
}
|
|
61
40
|
|
|
62
|
-
|
|
63
|
-
|
|
41
|
+
function overlaps(a: string, b: string): boolean {
|
|
42
|
+
const inside = (parent: string, child: string) => {
|
|
43
|
+
const path = relative(parent, child)
|
|
44
|
+
return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path))
|
|
45
|
+
}
|
|
46
|
+
return inside(a, b) || inside(b, a)
|
|
47
|
+
}
|
|
64
48
|
|
|
65
|
-
/**
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
49
|
+
/** Ownership is tied to the inode held by this instance, including partial initialization. */
|
|
50
|
+
async function releaseLock(path: string, handle: FileHandle) {
|
|
51
|
+
try {
|
|
52
|
+
const held = await handle.stat()
|
|
53
|
+
const actual = await lstat(path)
|
|
54
|
+
if (actual.dev !== held.dev || actual.ino !== held.ino || !actual.isFile()) {
|
|
55
|
+
throw new HarnessSdkError('WORKFLOW_LOCK_OWNERSHIP_LOST')
|
|
56
|
+
}
|
|
57
|
+
await unlink(path)
|
|
58
|
+
await syncDirectory(dirname(path))
|
|
59
|
+
} finally { await handle.close() }
|
|
71
60
|
}
|
|
72
61
|
|
|
73
|
-
/** Own the open lock descriptor and serialize manifest transitions until workflow releases it. */
|
|
74
62
|
class FileRunHandle implements RunHandle {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
lock: FileHandle
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
this.
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
63
|
+
private closed = false
|
|
64
|
+
private manifestQueue: Promise<void> = Promise.resolve()
|
|
65
|
+
|
|
66
|
+
constructor(readonly identity: RunIdentity, private readonly path: string,
|
|
67
|
+
private readonly lock: FileHandle, private manifest: Manifest,
|
|
68
|
+
readonly journal: AgentJournal) {}
|
|
69
|
+
|
|
70
|
+
private async io<T>(operation: () => Promise<T>): Promise<T> {
|
|
71
|
+
if (this.closed) throw new HarnessSdkError('WORKFLOW_CLOSED')
|
|
72
|
+
try { return await operation() } catch (cause) { throw storageError(cause) }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private updateManifest(update: () => Promise<void>): Promise<void> {
|
|
76
|
+
const next = this.manifestQueue.catch(() => {}).then(() => this.io(update))
|
|
77
|
+
this.manifestQueue = next
|
|
78
|
+
return next
|
|
88
79
|
}
|
|
89
80
|
|
|
90
|
-
/** completeRun awaits both publications before returning the body result to workflow.
|
|
91
|
-
* The manifest comes last so it refers to an already published result. */
|
|
92
81
|
async finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void> {
|
|
93
82
|
await this.updateManifest(async () => {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
83
|
+
await atomicPublish(join(this.path, 'result.json'), result)
|
|
84
|
+
const { recordDigest: _, ...payload } = this.manifest
|
|
85
|
+
this.manifest = record({ ...payload, status, resultDigest: digest(result), failure: null })
|
|
86
|
+
await atomicPublish(join(this.path, 'run.json'), this.manifest)
|
|
97
87
|
})
|
|
98
88
|
}
|
|
99
89
|
|
|
100
|
-
/** abortRun awaits this after draining. Replay treats the failed manifest as authoritative
|
|
101
|
-
* even if finish left an earlier result file. */
|
|
102
90
|
async abort(failure: StoredFailure): Promise<void> {
|
|
103
91
|
await this.updateManifest(async () => {
|
|
104
|
-
const {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
...(unpublishedUnknownFailures.length ? { unpublishedUnknownFailures } : {}),
|
|
108
|
-
} })
|
|
92
|
+
const { recordDigest: _, ...payload } = this.manifest
|
|
93
|
+
this.manifest = record({ ...payload, status: 'failed', resultDigest: null, failure })
|
|
94
|
+
await atomicPublish(join(this.path, 'run.json'), this.manifest)
|
|
109
95
|
})
|
|
110
96
|
}
|
|
111
97
|
|
|
112
|
-
/** workflow awaits this in finally and records any rejection as a storage failure.
|
|
113
|
-
* A failed publication already reached finish or abort, so proceed with lock release. */
|
|
114
98
|
async close(): Promise<void> {
|
|
115
99
|
if (this.closed) return
|
|
116
|
-
try {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
} catch (cause) {
|
|
120
|
-
throw storageError(cause)
|
|
121
|
-
} finally {
|
|
122
|
-
this.closed = true
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
readonly identity: RunIdentity
|
|
127
|
-
readonly journal: AgentJournal
|
|
128
|
-
|
|
129
|
-
private closed = false
|
|
130
|
-
private manifestQueue: Promise<void> = Promise.resolve()
|
|
131
|
-
private readonly path: string
|
|
132
|
-
private readonly lock: FileHandle
|
|
133
|
-
private manifest: Manifest
|
|
134
|
-
|
|
135
|
-
/** Run finish/abort's publication callback in order, checking closure when it actually starts.
|
|
136
|
-
* A rejected predecessor still permits abort publication. Non-SDK failures are normalized. */
|
|
137
|
-
private updateManifest(update: () => Promise<void>): Promise<void> {
|
|
138
|
-
const next = this.manifestQueue.catch(() => {}).then(async () => {
|
|
139
|
-
if (this.closed) throw new HarnessSdkError('WORKFLOW_CLOSED')
|
|
140
|
-
try { await update() } catch (cause) { throw storageError(cause) }
|
|
141
|
-
})
|
|
142
|
-
this.manifestQueue = next
|
|
143
|
-
return next
|
|
100
|
+
try { await this.manifestQueue.catch(() => {}); await releaseLock(join(this.path, 'writer.lock'), this.lock) }
|
|
101
|
+
catch (cause) { throw storageError(cause) }
|
|
102
|
+
finally { this.closed = true }
|
|
144
103
|
}
|
|
145
|
-
|
|
146
|
-
/** Recompute the digest from payload only for every terminal transition, then publish it.
|
|
147
|
-
* Keep the in-memory transition even if publication rejects, as abort may follow a failed finish. */
|
|
148
|
-
private async publishManifest(update: Pick<Manifest, 'status' | 'journalDigest' | 'resultDigest' | 'failure'>): Promise<void> {
|
|
149
|
-
const { recordDigest: _, ...payload } = this.manifest
|
|
150
|
-
this.manifest = record({ ...payload, ...update })
|
|
151
|
-
await atomicPublish(join(this.path, checkpointFormat.manifest), this.manifest)
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** Throw INVALID_PARAMS for malformed target identity before copying input or touching storage. */
|
|
156
|
-
function validateRunOptions(options: FileRunOptions): void {
|
|
157
|
-
const issues: string[] = []
|
|
158
|
-
if (!runIdSchema.safeParse(options.runId).success) {
|
|
159
|
-
issues.push('runId must be a valid directory basename (at most 255 UTF-8 bytes)')
|
|
160
|
-
}
|
|
161
|
-
if (typeof options.name !== 'string' || !options.name) issues.push('name must be a nonempty string')
|
|
162
|
-
if (typeof options.revision !== 'string' || !options.revision) issues.push('revision must be a nonempty string')
|
|
163
|
-
if (typeof options.directory !== 'string' || !options.directory) issues.push('directory must be a nonempty string')
|
|
164
|
-
if (issues.length) throw new HarnessSdkError('INVALID_PARAMS', `Invalid workflow options: ${issues.join(', ')}`)
|
|
165
104
|
}
|
|
166
105
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
async
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
if (options.resumeFrom !== undefined && typeof options.resumeFrom !== 'string') {
|
|
173
|
-
const directory = await prospectiveDirectory(root)
|
|
174
|
-
await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path: join(directory, options.runId) })
|
|
175
|
-
}
|
|
176
|
-
await mkdir(root, { recursive: true, mode: 0o700 })
|
|
177
|
-
const directory = await realpath(root)
|
|
178
|
-
const path = join(directory, options.runId)
|
|
179
|
-
const source = await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path })
|
|
180
|
-
try {
|
|
181
|
-
await mkdir(path, { mode: 0o700 })
|
|
182
|
-
await syncDirectory(directory)
|
|
183
|
-
} catch (cause) {
|
|
184
|
-
if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause
|
|
185
|
-
}
|
|
186
|
-
if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
|
|
187
|
-
if (source && overlaps(await realpath(path), join(source.directory, source.runId))) {
|
|
188
|
-
throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
|
|
189
|
-
}
|
|
190
|
-
return { directory, path, input, source }
|
|
106
|
+
class MemoryRunHandle implements RunHandle {
|
|
107
|
+
constructor(readonly identity: RunIdentity, readonly journal: AgentJournal) {}
|
|
108
|
+
async finish(): Promise<void> { /* No checkpoint: the run lives only for this process. */ }
|
|
109
|
+
async abort(): Promise<void> { /* No checkpoint: the run lives only for this process. */ }
|
|
110
|
+
async close(): Promise<void> { /* No lock was acquired. */ }
|
|
191
111
|
}
|
|
192
112
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
const parent = dirname(path)
|
|
199
|
-
if ((cause as NodeJS.ErrnoException).code !== 'ENOENT' || parent === path) throw cause
|
|
200
|
-
return join(await prospectiveDirectory(parent), relative(parent, path))
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/** Resolve optional replay coordinates before target creation so overlapping source/target trees
|
|
205
|
-
* reject before a writer claim. Omission selects fresh execution. A string uses the target's
|
|
206
|
-
* canonical parent, while an object supplies its own parent to resolve. */
|
|
207
|
-
async function resolveSourceRun({ resumeFrom, directory, path }: {
|
|
208
|
-
resumeFrom: FileRunOptions['resumeFrom']
|
|
209
|
-
directory: string
|
|
210
|
-
path: string
|
|
211
|
-
}): Promise<SourceRun | null> {
|
|
212
|
-
if (resumeFrom === undefined) return null
|
|
213
|
-
const reference = typeof resumeFrom === 'string' ? { directory, runId: resumeFrom } : resumeFrom
|
|
214
|
-
if (!reference || !runIdSchema.safeParse(reference.runId).success || typeof reference.directory !== 'string') {
|
|
113
|
+
export async function openFileRun(
|
|
114
|
+
options: WorkflowOptions<JsonValue> & { runId: string },
|
|
115
|
+
): Promise<RunHandle> {
|
|
116
|
+
if (!runIdSchema.safeParse(options.runId).success || typeof options.name !== 'string' || !options.name
|
|
117
|
+
|| typeof options.revision !== 'string' || !options.revision) {
|
|
215
118
|
throw new HarnessSdkError('INVALID_PARAMS')
|
|
216
119
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
async function initializeLockedRun({ options, prepared }: {
|
|
226
|
-
options: FileRunOptions
|
|
227
|
-
prepared: PreparedRun
|
|
228
|
-
}): Promise<RunHandle> {
|
|
229
|
-
const lockPath = join(prepared.path, checkpointFormat.lock)
|
|
230
|
-
const lock = await open(lockPath, 'wx', 0o600).catch(cause => {
|
|
231
|
-
if ((cause as NodeJS.ErrnoException).code === 'EEXIST') throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
|
|
232
|
-
throw cause
|
|
233
|
-
})
|
|
120
|
+
if (options.directory === undefined) {
|
|
121
|
+
if (options.resumeFrom !== undefined) throw new HarnessSdkError('WORKFLOW_RESUME_NOT_FOUND')
|
|
122
|
+
const identity = { runId: options.runId, directory: '', name: options.name, revision: options.revision, input: jsonCopy(options.input) }
|
|
123
|
+
return new MemoryRunHandle(identity, new AgentJournal(`memory:${options.runId}`, [], false))
|
|
124
|
+
}
|
|
125
|
+
if (typeof options.directory !== 'string' || !options.directory) throw new HarnessSdkError('INVALID_PARAMS')
|
|
126
|
+
let lock: FileHandle | undefined
|
|
127
|
+
let lockPath: string | undefined
|
|
234
128
|
try {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
129
|
+
const input = jsonCopy(options.input)
|
|
130
|
+
await mkdir(resolve(options.directory), { recursive: true, mode: 0o700 })
|
|
131
|
+
const directory = await realpath(resolve(options.directory))
|
|
132
|
+
const path = join(directory, options.runId)
|
|
133
|
+
let source: { directory: string; runId: string } | null = null
|
|
134
|
+
if (options.resumeFrom !== undefined) {
|
|
135
|
+
const reference = typeof options.resumeFrom === 'string'
|
|
136
|
+
? { directory, runId: options.resumeFrom } : options.resumeFrom
|
|
137
|
+
if (!reference || !runIdSchema.safeParse(reference.runId).success || typeof reference.directory !== 'string') {
|
|
138
|
+
throw new HarnessSdkError('INVALID_PARAMS')
|
|
139
|
+
}
|
|
140
|
+
source = { directory: await realpath(resolve(reference.directory)), runId: reference.runId }
|
|
141
|
+
if (overlaps(path, join(source.directory, source.runId))) throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
|
|
142
|
+
}
|
|
143
|
+
try { await mkdir(path, { mode: 0o700 }); await syncDirectory(directory) }
|
|
144
|
+
catch (cause) { if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause }
|
|
145
|
+
if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
|
|
146
|
+
lockPath = join(path, 'writer.lock')
|
|
147
|
+
try { lock = await open(lockPath, 'wx', 0o600) }
|
|
148
|
+
catch (cause) {
|
|
149
|
+
if ((cause as NodeJS.ErrnoException).code === 'EEXIST') throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
|
|
150
|
+
throw cause
|
|
238
151
|
}
|
|
239
|
-
|
|
152
|
+
await lock.writeFile(`${canonicalJson(record({ checkpointFormatVersion: 2, token: randomUUID(),
|
|
153
|
+
hostname: hostname(), pid: process.pid, createdAt: new Date().toISOString() }))}\n`)
|
|
154
|
+
await lock.sync()
|
|
155
|
+
if ((await readdir(path)).some(name => name !== 'writer.lock')) throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
|
|
156
|
+
const inherited: JournalEvent[] = source
|
|
157
|
+
? await loadSourceJournal(join(source.directory, source.runId), {
|
|
158
|
+
name: options.name, revision: options.revision, runId: source.runId,
|
|
159
|
+
})
|
|
160
|
+
: []
|
|
161
|
+
const journal = new AgentJournal(join(path, 'journal.json'), inherited)
|
|
162
|
+
await atomicPublish(join(path, 'journal.json'), [...inherited])
|
|
163
|
+
const identity = { runId: options.runId, directory, name: options.name, revision: options.revision, input }
|
|
164
|
+
const manifest: Manifest = record({ checkpointFormatVersion: 2,
|
|
165
|
+
identity, createdAt: new Date().toISOString(), resumedFrom: source,
|
|
166
|
+
status: 'running', resultDigest: null, failure: null })
|
|
167
|
+
await atomicPublish(join(path, 'run.json'), manifest)
|
|
168
|
+
return new FileRunHandle(identity, path, lock, manifest, journal)
|
|
240
169
|
} catch (cause) {
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/** Write and flush the claim on the exclusively opened descriptor. Replay validates this
|
|
248
|
-
* record before probing its writer, and initializeLockedRun owns rollback on rejection. */
|
|
249
|
-
async function writeWriterClaim(lock: FileHandle): Promise<void> {
|
|
250
|
-
const claim = record({
|
|
251
|
-
checkpointFormatVersion: checkpointFormat.version,
|
|
252
|
-
token: randomUUID(),
|
|
253
|
-
hostname: hostname(),
|
|
254
|
-
pid: process.pid,
|
|
255
|
-
createdAt: new Date().toISOString(),
|
|
256
|
-
})
|
|
257
|
-
await lock.writeFile(`${canonicalJson(claim)}\n`)
|
|
258
|
-
await lock.sync()
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
/** Validate replay under the target lock, publish a self-contained journal before its manifest,
|
|
262
|
-
* then hand the descriptor to FileRunHandle. Failures leave lock cleanup to initializeLockedRun. */
|
|
263
|
-
async function publishInitialRun({ options, prepared, lock }: {
|
|
264
|
-
options: FileRunOptions
|
|
265
|
-
prepared: PreparedRun
|
|
266
|
-
lock: FileHandle
|
|
267
|
-
}): Promise<RunHandle> {
|
|
268
|
-
const { directory, path, input, source } = prepared
|
|
269
|
-
const inherited = source
|
|
270
|
-
? await loadSourceJournal(join(source.directory, source.runId), {
|
|
271
|
-
name: options.name, revision: options.revision, runId: source.runId,
|
|
272
|
-
})
|
|
273
|
-
: []
|
|
274
|
-
const journalPath = join(path, checkpointFormat.journal)
|
|
275
|
-
const journal = new AgentJournal(journalPath, inherited)
|
|
276
|
-
await atomicPublish(journalPath, [...inherited])
|
|
277
|
-
const identity = { runId: options.runId, directory, name: options.name, revision: options.revision, input }
|
|
278
|
-
const manifest: Manifest = record({
|
|
279
|
-
checkpointFormatVersion: checkpointFormat.version,
|
|
280
|
-
identity,
|
|
281
|
-
createdAt: new Date().toISOString(),
|
|
282
|
-
resumedFrom: source,
|
|
283
|
-
status: 'running',
|
|
284
|
-
journalDigest: null,
|
|
285
|
-
resultDigest: null,
|
|
286
|
-
failure: null,
|
|
287
|
-
})
|
|
288
|
-
await atomicPublish(join(path, checkpointFormat.manifest), manifest)
|
|
289
|
-
return new FileRunHandle({ identity, path, lock, manifest, journal })
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/** Detect equal or nested run trees in either direction. resolveSourceRun uses canonical
|
|
293
|
-
* parent directories so writes cannot overlap the selected source tree. */
|
|
294
|
-
function overlaps(a: string, b: string): boolean {
|
|
295
|
-
const inside = (parent: string, child: string) => {
|
|
296
|
-
const path = relative(parent, child)
|
|
297
|
-
return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path))
|
|
298
|
-
}
|
|
299
|
-
return inside(a, b) || inside(b, a)
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
/** Compare the on-disk entry with the held descriptor before unlinking, so rollback also works
|
|
303
|
-
* for a partially written lock. Flush the parent after unlinking and always close the descriptor.
|
|
304
|
-
* An observed inode or file kind mismatch rejects as WORKFLOW_LOCK_OWNERSHIP_LOST. */
|
|
305
|
-
async function releaseLock(path: string, handle: FileHandle): Promise<void> {
|
|
306
|
-
try {
|
|
307
|
-
const held = await handle.stat()
|
|
308
|
-
const actual = await lstat(path)
|
|
309
|
-
if (actual.dev !== held.dev || actual.ino !== held.ino || !actual.isFile()) {
|
|
310
|
-
throw new HarnessSdkError('WORKFLOW_LOCK_OWNERSHIP_LOST')
|
|
170
|
+
if (lock && lockPath) {
|
|
171
|
+
try { await releaseLock(lockPath, lock) }
|
|
172
|
+
catch { throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED') }
|
|
311
173
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
} finally { await handle.close() }
|
|
174
|
+
throw storageError(cause)
|
|
175
|
+
}
|
|
315
176
|
}
|
package/src/pipeline.test.ts
CHANGED
|
@@ -85,24 +85,6 @@ test('passes the previous result, original item and index to every stage', async
|
|
|
85
85
|
expect(result).toEqual([{ length: 5, item: 'first', index: 0 }, { length: 6, item: 'second', index: 1 }])
|
|
86
86
|
})
|
|
87
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
88
|
test('null input or stage results skip later stages while other falsy values continue', async () => {
|
|
107
89
|
const entered: unknown[] = []
|
|
108
90
|
const next: unknown[] = []
|
|
@@ -143,7 +125,6 @@ test('validates arrays and all stages before processing nonempty input', async (
|
|
|
143
125
|
expect(await pipeline([], undefined)).toEqual([])
|
|
144
126
|
})
|
|
145
127
|
|
|
146
|
-
/** Compile-only assertions for stage compatibility, context and nullable results; never invoked at runtime. */
|
|
147
128
|
function checkTypes() {
|
|
148
129
|
const firstStage = (value: string) => value.length
|
|
149
130
|
const secondStage = (value: number) => value > 0
|
package/src/pipeline.ts
CHANGED
|
@@ -1,23 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
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
|
-
*/
|
|
1
|
+
// Prepending Input aligns each stage's index with the previous stage's output.
|
|
2
|
+
type PreviousStageOutput<Input, Outputs extends readonly unknown[], K> =
|
|
3
|
+
K extends '0' ? Input : [Input, ...Outputs][K & keyof [Input, ...Outputs]]
|
|
4
|
+
|
|
5
|
+
type Stages<Input, Outputs extends readonly unknown[]> = {
|
|
6
|
+
[K in keyof Outputs]: Stage<PreviousStageOutput<Input, Outputs, K>, Input, Outputs[K]>
|
|
7
|
+
}
|
|
8
|
+
type Last<Outputs extends readonly unknown[]> = Outputs extends readonly [...unknown[], infer Output] ? Awaited<Output> : never
|
|
9
|
+
type Stage<Previous, Input, Output> = (value: Exclude<Awaited<Previous>, null>, originalItem: Input, index: number) => Output
|
|
10
|
+
|
|
11
|
+
/** Items advance independently; null or failure stops an item and retains its position. */
|
|
21
12
|
export function pipeline<Input>(items: readonly Input[]): Promise<(Awaited<Input> | null)[]>
|
|
22
13
|
export function pipeline<A, B>(items: readonly A[], first: Stage<A, A, B>): Promise<(Awaited<B> | null)[]>
|
|
23
14
|
export function pipeline<A, B, C>(
|
|
@@ -40,60 +31,23 @@ export function pipeline<A, B, C, D, E, F, G>(
|
|
|
40
31
|
third: Stage<C, A, D>, fourth: Stage<D, A, E>,
|
|
41
32
|
fifth: Stage<E, A, F>, sixth: Stage<F, A, G>,
|
|
42
33
|
): 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
|
-
*/
|
|
34
|
+
// Homomorphic tuple inference also supports arbitrary-length chains of typed functions.
|
|
47
35
|
export function pipeline<Input, Outputs extends readonly unknown[]>(
|
|
48
36
|
items: readonly Input[],
|
|
49
37
|
...stages: Stages<Input, Outputs> & { 0: Stage<Input, Input, unknown> }
|
|
50
|
-
): Promise<(
|
|
51
|
-
export async function pipeline(
|
|
52
|
-
items: readonly unknown[],
|
|
53
|
-
...stages: Stage<never, never, unknown>[]
|
|
54
|
-
): Promise<unknown[]> {
|
|
38
|
+
): Promise<(Last<Outputs> | null)[]>
|
|
39
|
+
export async function pipeline(items: readonly unknown[], ...stages: Array<(value: never, originalItem: never, index: number) => unknown>): Promise<unknown[]> {
|
|
55
40
|
if (!Array.isArray(items)) throw new TypeError('pipeline expects an array as the first argument')
|
|
56
41
|
const inputs = [...items]
|
|
57
42
|
if (!inputs.length) return []
|
|
58
43
|
if (stages.some(stage => typeof stage !== 'function')) throw new TypeError('pipeline stages must be functions')
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
|
44
|
+
const results = await Promise.allSettled(inputs.map(async (originalItem, index) => {
|
|
45
|
+
let value = await originalItem
|
|
46
|
+
for (const stage of stages) {
|
|
47
|
+
if (value === null) break
|
|
48
|
+
value = await (stage as (value: unknown, originalItem: unknown, index: number) => unknown)(value, originalItem, index)
|
|
49
|
+
}
|
|
50
|
+
return value
|
|
51
|
+
}))
|
|
52
|
+
return results.map(result => result.status === 'fulfilled' ? result.value : null)
|
|
83
53
|
}
|
|
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,19 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import type { AgentJournal } from './persistence/journal'
|
|
3
|
+
import type { RunState } from './workflow-state'
|
|
4
|
+
|
|
5
|
+
/** Ambient context linking agent() calls inside a workflow body to its journal. */
|
|
6
|
+
export interface RunContext {
|
|
7
|
+
readonly journal: AgentJournal
|
|
8
|
+
readonly state: RunState
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const storage = new AsyncLocalStorage<RunContext>()
|
|
12
|
+
|
|
13
|
+
export function runWith<T>(context: RunContext, body: () => Promise<T>): Promise<T> {
|
|
14
|
+
return storage.run(context, body)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function currentRun(): RunContext | undefined {
|
|
18
|
+
return storage.getStore()
|
|
19
|
+
}
|