@anureo/workflow 0.3.0 → 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.
Files changed (63) hide show
  1. package/README.md +96 -70
  2. package/package.json +17 -16
  3. package/src/agent-adapters.test.ts +121 -0
  4. package/src/agent-execution.ts +201 -0
  5. package/src/agent.test.ts +333 -0
  6. package/src/agent.ts +135 -0
  7. package/src/fixtures/workflow-crash.ts +53 -0
  8. package/src/index.ts +9 -0
  9. package/src/output-schema.test.ts +147 -0
  10. package/src/output-schema.ts +231 -0
  11. package/src/parallel.test.ts +96 -0
  12. package/src/parallel.ts +33 -0
  13. package/src/persistence/checkpoint-files.ts +82 -0
  14. package/src/persistence/journal.ts +111 -0
  15. package/src/persistence/json.ts +83 -0
  16. package/src/persistence/records.ts +97 -0
  17. package/src/persistence/replay.ts +91 -0
  18. package/src/persistence/store.ts +286 -0
  19. package/src/pipeline.test.ts +201 -0
  20. package/src/pipeline.ts +99 -0
  21. package/src/test-helpers.ts +23 -0
  22. package/src/workflow-state.ts +130 -0
  23. package/src/workflow-types.ts +38 -0
  24. package/src/workflow.test.ts +376 -0
  25. package/src/workflow.ts +112 -0
  26. package/tsconfig.json +13 -0
  27. package/LICENSE +0 -201
  28. package/src/agent-outcome.d.ts +0 -15
  29. package/src/agent-outcome.js +0 -28
  30. package/src/agent.d.ts +0 -49
  31. package/src/agent.js +0 -206
  32. package/src/index.d.ts +0 -6
  33. package/src/index.js +0 -5
  34. package/src/output-schema.d.ts +0 -27
  35. package/src/output-schema.js +0 -192
  36. package/src/parallel.d.ts +0 -18
  37. package/src/parallel.js +0 -25
  38. package/src/persistence/atomic.d.ts +0 -9
  39. package/src/persistence/atomic.js +0 -48
  40. package/src/persistence/journal.d.ts +0 -54
  41. package/src/persistence/journal.js +0 -106
  42. package/src/persistence/json.d.ts +0 -17
  43. package/src/persistence/json.js +0 -75
  44. package/src/persistence/read-json.d.ts +0 -11
  45. package/src/persistence/read-json.js +0 -46
  46. package/src/persistence/records.d.ts +0 -92
  47. package/src/persistence/records.js +0 -70
  48. package/src/persistence/replay.d.ts +0 -11
  49. package/src/persistence/replay.js +0 -79
  50. package/src/persistence/store.d.ts +0 -45
  51. package/src/persistence/store.js +0 -238
  52. package/src/pipeline.d.ts +0 -41
  53. package/src/pipeline.js +0 -24
  54. package/src/run-context.d.ts +0 -16
  55. package/src/run-context.js +0 -13
  56. package/src/test-helpers.d.ts +0 -11
  57. package/src/test-helpers.js +0 -21
  58. package/src/workflow-state.d.ts +0 -44
  59. package/src/workflow-state.js +0 -96
  60. package/src/workflow-types.d.ts +0 -39
  61. package/src/workflow-types.js +0 -0
  62. package/src/workflow.d.ts +0 -17
  63. package/src/workflow.js +0 -104
@@ -0,0 +1,376 @@
1
+ import { createFixture } from './test-helpers'
2
+ import { afterEach, expect, test } from 'bun:test'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises'
5
+ import { tmpdir } from 'node:os'
6
+ import { join } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { createClient, HarnessSdkError, type Client } from '@anureo/sdk'
9
+ import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
10
+ import type { HarnessError } from '@anureo/protocol'
11
+ import { z } from 'zod'
12
+ import { workflow, parallel, agent, type WorkflowOptions } from './index'
13
+ import { canonicalJson, digest } from './persistence/json'
14
+
15
+ const clients: Client[] = []
16
+ const fixture = createFixture(clients)
17
+ const roots: string[] = []
18
+ afterEach(async () => {
19
+ await Promise.all(clients.splice(0).map(client => client.dispose()))
20
+ await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true })))
21
+ })
22
+ /** Create isolated run storage; afterEach removes it after disposing the test's clients. */
23
+ async function setup() {
24
+ const directory = await mkdtemp(join(tmpdir(), 'anureo-workflow-'))
25
+ roots.push(directory)
26
+ return { directory, name: 'test', revision: '1', input: {} }
27
+ }
28
+
29
+ /** Supply a scripted input/submit handler that emits terminal failure before returning acceptance.
30
+ * Returning undefined for other calls lets the scripted adapter apply its default behavior. */
31
+ function failingExecute(error: HarnessError): NonNullable<FakeAdapterOptions['execute']> {
32
+ return async (call, sink) => {
33
+ if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
34
+ const turnId = randomUUID()
35
+ await sink.emit({ type: 'turn/started', payload: { turnId } })
36
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error } }, { turnId })
37
+ return { submissionId: call.params.submissionId,
38
+ accepted: true, disposition: 'started', turnId }
39
+ }
40
+ }
41
+
42
+ 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
+ })
45
+
46
+ test('run identity is durable before body, inputs are isolated, and results are persisted', async () => {
47
+ const options = { ...await setup(), input: { values: [1] } }
48
+ const { client } = await fixture()
49
+ const result = await workflow(options, async run => {
50
+ const manifest = JSON.parse(await readFile(join(options.directory, run.runId, 'run.json'), 'utf8'))
51
+ expect(manifest.identity.runId).toBe(run.runId)
52
+ expect(manifest.status).toBe('running')
53
+ expect(manifest.checkpointFormatVersion).toBe(2)
54
+ expect(Object.isFrozen(run.input.values)).toBe(true)
55
+ expect(Object.isFrozen(options.input.values)).toBe(false)
56
+ return agent('hello', { client, cwd: options.directory })
57
+ })
58
+ expect(result.result).toBe('hello')
59
+ expect(result.status).toBe('completed')
60
+ const stored = await readdir(join(options.directory, result.runId))
61
+ expect(stored.sort()).toEqual(['journal.json', 'result.json', 'run.json'])
62
+ const journal = JSON.parse(await readFile(join(options.directory, result.runId, 'journal.json'), 'utf8'))
63
+ expect(journal).toHaveLength(2)
64
+ expect(journal[1]).toMatchObject({ type: 'result', result: 'hello' })
65
+ })
66
+
67
+ test('resumed runs replay identical agent calls from the journal without new sessions', async () => {
68
+ const options = await setup()
69
+ const { client, adapter } = await fixture()
70
+ const body = async () =>
71
+ agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) })
72
+ const first = await workflow(options, body)
73
+ expect(adapter.opened).toHaveLength(1)
74
+ expect(first.result).toEqual({ value: 1 })
75
+ const second = await workflow({ ...options, resumeFrom: first.runId }, body)
76
+ expect(adapter.opened).toHaveLength(1)
77
+ expect(second.result).toEqual({ value: 1 })
78
+ // The resumed run carries its own journal copy; the source can be deleted.
79
+ await rm(join(options.directory, first.runId), { recursive: true })
80
+ const third = await workflow({ ...options, resumeFrom: second.runId }, body)
81
+ expect(adapter.opened).toHaveLength(1)
82
+ expect(third.result).toEqual({ value: 1 })
83
+ })
84
+
85
+ test('chained keys invalidate the downstream prefix when any call changes', async () => {
86
+ const options = await setup()
87
+ const { client, adapter } = await fixture()
88
+ const first = await workflow(options, async () => {
89
+ const a = await agent('a', { client, cwd: options.directory })
90
+ const b = await agent('b', { client, cwd: options.directory })
91
+ return `${a}${b}`
92
+ })
93
+ expect(first.result).toBe('ab')
94
+ expect(adapter.opened).toHaveLength(2)
95
+ const second = await workflow({ ...options, resumeFrom: first.runId }, async () => {
96
+ const a = await agent('a', { client, cwd: options.directory })
97
+ const changed = await agent('CHANGED', { client, cwd: options.directory })
98
+ const b = await agent('b', { client, cwd: options.directory })
99
+ return `${a}${changed}${b}`
100
+ })
101
+ expect(adapter.opened).toHaveLength(4)
102
+ expect(second.result).toBe('aCHANGEDb')
103
+ })
104
+
105
+ test('prompt, options, and client identity changes miss the cache', async () => {
106
+ const options = await setup()
107
+ const { client, adapter } = await fixture()
108
+ const other = await fixture()
109
+ const first = await workflow(options, () => agent('same', { client, cwd: options.directory, model: 'm1' }))
110
+ expect(adapter.opened).toHaveLength(1)
111
+ await workflow({ ...options, resumeFrom: first.runId }, () => agent('same', { client, cwd: options.directory, model: 'm2' }))
112
+ expect(adapter.opened).toHaveLength(2)
113
+ await workflow({ ...options, resumeFrom: first.runId }, () => agent('other', { client, cwd: options.directory, model: 'm1' }))
114
+ expect(adapter.opened).toHaveLength(3)
115
+ await workflow({ ...options, resumeFrom: first.runId }, () => agent('same', { client: other.client, cwd: options.directory, model: 'm1' }))
116
+ expect(adapter.opened).toHaveLength(3)
117
+ expect(other.adapter.opened).toHaveLength(1)
118
+ })
119
+
120
+ test('name or revision changes reject resume before the body runs', async () => {
121
+ const options = await setup()
122
+ const { client } = await fixture()
123
+ const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
124
+ for (const update of [{ revision: '2' }, { name: 'other' }]) {
125
+ let entered = false
126
+ await expect(workflow({ ...options, ...update, resumeFrom: first.runId }, () => {
127
+ entered = true; return 'bad'
128
+ })).rejects.toMatchObject({ code: 'WORKFLOW_INCOMPATIBLE_RUN' })
129
+ expect(entered).toBe(false)
130
+ }
131
+ })
132
+
133
+ test('dropped agents never cache and resume repeats them', async () => {
134
+ const options = await setup()
135
+ const { client, adapter } = await fixture({
136
+ execute: failingExecute({ code: 'RATE_LIMITED', message: 'limited', retryable: true, outcomeUnknown: false }),
137
+ })
138
+ const first = await workflow(options, async () =>
139
+ await agent('dropped', { client, cwd: options.directory }))
140
+ expect(first.result).toBeNull()
141
+ expect(first.status).toBe('incomplete')
142
+ await workflow({ ...options, resumeFrom: first.runId }, () => agent('dropped', { client, cwd: options.directory }))
143
+ expect(adapter.opened).toHaveLength(2)
144
+ })
145
+
146
+ test('failed agent outcomes stay incomplete through composition and re-execute on resume', async () => {
147
+ const options = await setup()
148
+ const { client, adapter } = await fixture({
149
+ execute: failingExecute({ code: 'NATIVE_FAILED', message: 'failed', retryable: true, outcomeUnknown: false }),
150
+ })
151
+ const result = await workflow(options, async () =>
152
+ await parallel([() => agent('failing', { client, cwd: options.directory })]))
153
+ expect(result.status).toBe('incomplete')
154
+ expect(result.result).toEqual([null])
155
+ await workflow({ ...options, resumeFrom: result.runId }, () =>
156
+ parallel([() => agent('failing', { client, cwd: options.directory })]))
157
+ expect(adapter.opened).toHaveLength(2)
158
+ })
159
+
160
+ test('unknown previous outcomes require reconciliation instead of silent re-execution', async () => {
161
+ const options = await setup()
162
+ const { client, adapter } = await fixture({
163
+ execute: failingExecute({ code: 'NATIVE_FAILED', message: 'unknown', retryable: false, outcomeUnknown: true }),
164
+ })
165
+ const failure: unknown = await workflow(options, () => agent('unknown', { client, cwd: options.directory }))
166
+ .then(
167
+ value => { throw new Error(`expected rejection, completed with ${JSON.stringify(value)}`) },
168
+ cause => cause,
169
+ )
170
+ expect(failure).toBeInstanceOf(HarnessSdkError)
171
+ if (!(failure instanceof HarnessSdkError)) throw failure
172
+ expect(failure.outcomeUnknown).toBe(true)
173
+ expect(adapter.opened).toHaveLength(1)
174
+ const runId = failure.details?.runId
175
+ if (typeof runId !== 'string') throw new Error('expected the failed run ID')
176
+ await expect(workflow({ ...options, resumeFrom: runId }, () =>
177
+ agent('unknown', { client, cwd: options.directory })))
178
+ .rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
179
+ expect(adapter.opened).toHaveLength(1)
180
+ })
181
+
182
+ test('storage failure is sticky and blocks subsequent agent dispatch', async () => {
183
+ const options = await setup()
184
+ const { client, adapter } = await fixture()
185
+ let id = ''
186
+ await expect(workflow(options, async run => {
187
+ id = run.runId
188
+ // Moving the run directory breaks every subsequent journal publication.
189
+ await rename(join(options.directory, id), join(options.directory, `${id}-moved`))
190
+ try { await agent('first', { client, cwd: options.directory }) } catch {}
191
+ try { await agent('second', { client, cwd: options.directory }) } catch {}
192
+ return 'caught'
193
+ })).rejects.toMatchObject({ code: 'WORKFLOW_STORAGE_FAILED' })
194
+ // The started marker could not be published, so no session was ever opened.
195
+ expect(adapter.opened).toHaveLength(0)
196
+ })
197
+
198
+ test('body completion waits for already registered unawaited agent work', async () => {
199
+ const options = await setup()
200
+ const { client } = await fixture()
201
+ const entered = Promise.withResolvers<void>()
202
+ let ended = false
203
+ const result = workflow(options, () => {
204
+ void agent('slow', { client, cwd: options.directory }).then(() => { ended = true })
205
+ entered.resolve()
206
+ return 'body'
207
+ })
208
+ await entered.promise
209
+ expect((await result).status).toBe('completed')
210
+ expect(ended).toBe(true)
211
+ })
212
+
213
+ test('agent calls detached from the run context execute as ordinary unjournaled agents', async () => {
214
+ const options = await setup()
215
+ const { client, adapter } = await fixture()
216
+ let saved!: () => Promise<unknown>
217
+ await workflow(options, () => {
218
+ saved = () => agent('late', { client, cwd: options.directory })
219
+ return 'body'
220
+ })
221
+ // The closure escapes the run's async context, so no journal applies.
222
+ expect(await saved()).toBe('late')
223
+ expect(adapter.opened).toHaveLength(1)
224
+ })
225
+
226
+ test('source activity, target competition, and reused explicit ids reject before body', async () => {
227
+ const options = await setup()
228
+ const { client } = await fixture()
229
+ const entered = Promise.withResolvers<void>()
230
+ const release = Promise.withResolvers<void>()
231
+ const first = workflow({ ...options, runId: 'owned' }, async () => {
232
+ entered.resolve()
233
+ await agent('held', { client, cwd: options.directory })
234
+ await release.promise
235
+ return 'done'
236
+ })
237
+ await entered.promise
238
+ try {
239
+ await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
240
+ await expect(workflow({ ...options, resumeFrom: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_SOURCE_ACTIVE' })
241
+ } finally {
242
+ release.resolve()
243
+ await first
244
+ }
245
+ await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
246
+ })
247
+
248
+ test('initialization rejects invalid identities and releases a failed target claim before entering body', async () => {
249
+ const options = await setup()
250
+ let entered = false
251
+ await expect(workflow({ ...options, runId: '../escape' }, () => { entered = true; return {} }))
252
+ .rejects.toMatchObject({ code: 'INVALID_PARAMS' })
253
+ const { client } = await fixture()
254
+ const original = await workflow({ ...options, runId: 'source' }, () => agent('a', { client, cwd: options.directory }))
255
+ await expect(workflow({ ...options, name: 'incompatible', runId: 'target', resumeFrom: original.runId }, () => {
256
+ entered = true; return {}
257
+ })).rejects.toMatchObject({ code: 'WORKFLOW_INCOMPATIBLE_RUN' })
258
+ expect(entered).toBe(false)
259
+ expect(await readdir(join(options.directory, 'target'))).not.toContain('writer.lock')
260
+ })
261
+
262
+ test('preallocated Unicode and spaced output names resume without changing directory meaning', async () => {
263
+ const options = await setup()
264
+ const { client, adapter } = await fixture()
265
+ const first = await workflow({ ...options, runId: '审查 output' }, () => agent('同', { client, cwd: options.directory }))
266
+ const result = await workflow({ ...options, resumeFrom: first.runId }, () => agent('同', { client, cwd: options.directory }))
267
+ expect(first.runId).toBe('审查 output')
268
+ expect(result.result).toBe('同')
269
+ expect(adapter.opened).toHaveLength(1)
270
+ })
271
+
272
+ test('corrupt or missing recovery materials fail rather than execute', async () => {
273
+ for (const variant of ['bad-json', 'missing', 'symlink'] as const) {
274
+ const options = await setup()
275
+ const { client, adapter } = await fixture()
276
+ const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
277
+ const path = join(options.directory, first.runId, 'journal.json')
278
+ if (variant === 'bad-json') await writeFile(path, '{broken')
279
+ else {
280
+ await rm(path)
281
+ if (variant === 'symlink') await symlink(join(options.directory, first.runId, 'run.json'), path)
282
+ }
283
+ await expect(workflow({ ...options, resumeFrom: first.runId }, () => agent('a', { client, cwd: options.directory })))
284
+ .rejects.toMatchObject({ code: 'WORKFLOW_CHECKPOINT_INVALID' })
285
+ expect(adapter.opened).toHaveLength(1)
286
+ }
287
+ })
288
+
289
+ test('format-v1 run directories are rejected on resume', async () => {
290
+ const options = await setup()
291
+ const { client } = await fixture()
292
+ const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
293
+ const manifestPath = join(options.directory, first.runId, 'run.json')
294
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
295
+ await writeFile(manifestPath, JSON.stringify({ ...manifest, checkpointFormatVersion: 1 }))
296
+ await expect(workflow({ ...options, resumeFrom: first.runId }, () => 'bad'))
297
+ .rejects.toMatchObject({ code: 'WORKFLOW_CHECKPOINT_INVALID' })
298
+ })
299
+
300
+ test('strict JSON rejects lossy inputs and canonical hashes ignore object insertion order', () => {
301
+ for (const value of [undefined, NaN, Infinity, new Date(), [undefined], Array(1), { a: undefined },
302
+ Object.defineProperty({}, 'hidden', { value: 1 }), { get a() { return 1 } }]) {
303
+ expect(() => canonicalJson(value)).toThrow()
304
+ }
305
+ const cyclic: Record<string, unknown> = {}; cyclic.self = cyclic
306
+ expect(() => canonicalJson(cyclic)).toThrow()
307
+ expect(digest({ a: 1, b: 2 })).toBe(digest({ b: 2, a: 1 }))
308
+ })
309
+
310
+ test('real process death at durable boundaries replays committed agent work only', async () => {
311
+ for (const phase of ['before-started', 'after-execute', 'before-final', 'after-later-result']) {
312
+ const options = await setup()
313
+ const child = Bun.spawn([process.execPath, fileURLToPath(new URL('./fixtures/workflow-crash.ts', import.meta.url)),
314
+ options.directory, phase], { stdout: 'ignore', stderr: 'pipe' })
315
+ const code = await child.exited
316
+ expect(code).not.toBe(0)
317
+ const error = await new Response(child.stderr).text()
318
+ expect(error).toBe('')
319
+ const adapter = createScriptedAdapter()
320
+ const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
321
+ clients.push(client)
322
+ const result = await workflow({ ...options, name: 'crash-test', resumeFrom: 'crashed' }, async () => {
323
+ const first = agent('work', { client, cwd: options.directory })
324
+ // An unfinished first key permits a rerun without invalidating the second key's saved result.
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')
330
+ 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
+ await client.dispose()
337
+ }
338
+ }, 15000)
339
+
340
+ test('an interrupted run reuses the unchanged call prefix in original order', async () => {
341
+ const options = await setup()
342
+ const { client, adapter } = await fixture()
343
+ await expect(workflow({ ...options, runId: 'partial' }, async () => {
344
+ for (let n = 0; n < 3; n++) await agent(`item-${n}`, { client, cwd: options.directory })
345
+ throw new HarnessSdkError('HOST_STOPPED')
346
+ })).rejects.toMatchObject({ code: 'HOST_STOPPED' })
347
+ expect(adapter.opened).toHaveLength(3)
348
+ const executed: number[] = []
349
+ const result = await workflow({ ...options, resumeFrom: 'partial' }, async () => {
350
+ for (let n = 0; n < 3; n++) await agent(`item-${n}`, { client, cwd: options.directory })
351
+ for (let n = 3; n < 5; n++) { await agent(`item-${n}`, { client, cwd: options.directory }); executed.push(n) }
352
+ return 'done'
353
+ })
354
+ expect(executed).toEqual([3, 4])
355
+ expect(adapter.opened).toHaveLength(5)
356
+ expect(result.status).toBe('completed')
357
+ })
358
+
359
+ /** Compile-only consumer checks for context and awaited body-result inference; never invoked. */
360
+ function typeChecks(options: WorkflowOptions<{ files: string[] }>) {
361
+ const run = workflow(options, async context => {
362
+ const file: string = context.input.files[0]!
363
+ const result = await agent('review', {
364
+ client: {} as never, cwd: file, schema: z.strictObject({ value: z.number() }),
365
+ })
366
+ // @ts-expect-error result is inferred from the schema.
367
+ const invalid: string = result.value
368
+ return result === null ? null : result.value
369
+ })
370
+ const positive: Promise<{ runId: string; status: 'completed' | 'incomplete'; result: number | null }> = run
371
+ // @ts-expect-error body result inference is retained.
372
+ const negative: Promise<{ result: string }> = run
373
+ void negative
374
+ return positive
375
+ }
376
+ void typeChecks
@@ -0,0 +1,112 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { HarnessSdkError, sdkError } from '@anureo/sdk'
3
+ import type { WorkflowContext, WorkflowOptions, WorkflowResult } from './workflow-types'
4
+ import { RunState, runWith, storedFailure } from './workflow-state'
5
+ import { freezeJson, jsonCopy, type JsonValue } from './persistence/json'
6
+ import { openFileRun, type RunHandle } from './persistence/store'
7
+
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
+ export async function workflow<Input, Result>(
24
+ options: WorkflowOptions<Input>,
25
+ body: (run: WorkflowContext<Input>) => Result | Promise<Result>,
26
+ ): Promise<WorkflowResult<Awaited<Result>>> {
27
+ const runId = options?.runId ?? randomUUID()
28
+ const state = new RunState()
29
+ let handle: RunHandle | undefined
30
+ let publishedResult: Awaited<Result> | undefined
31
+ try {
32
+ const { storageOptions, context } = prepareRun(options, body, runId)
33
+ handle = await openFileRun(storageOptions)
34
+ publishedResult = await completeRun({ handle, state, body, context })
35
+ } catch (cause) {
36
+ await abortRun({ cause, state, handle })
37
+ } finally {
38
+ if (handle) {
39
+ try { await handle.close() }
40
+ catch { state.noteStorageFailure() }
41
+ }
42
+ }
43
+ const failure = state.failure
44
+ 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() }
111
+ }
112
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "Preserve",
5
+ "moduleResolution": "Bundler",
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "allowImportingTsExtensions": true,
10
+ "types": ["bun", "node"]
11
+ },
12
+ "include": ["src"]
13
+ }