@anureo/workflow 0.3.2 → 0.3.4

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.
@@ -1,92 +1,56 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks'
2
1
  import { HarnessSdkError, sdkError } from '@anureo/sdk'
3
- import type { AgentJournal } from './persistence/journal'
4
- import type { StoredFailure } from './persistence/records'
2
+ import type { StoredFailure } from './persistence/store'
5
3
 
6
- /** Internal run context installed for the workflow body and inherited by agent calls. */
7
- export interface RunContext {
8
- /** Source replay and target journal used by memoizedAgent. */
9
- readonly journal: AgentJournal
10
- /** Admission, pending work and failure state shared with workflow. */
11
- readonly state: RunState
12
- }
13
-
14
- /** Invoke completeRun's callback with context inherited by asynchronous descendants. The caller
15
- * receives the callback promise or a synchronous throw and owns closing admission and draining work. */
16
- export function runWith<T>(context: RunContext, body: () => Promise<T>): Promise<T> {
17
- return storage.run(context, body)
18
- }
19
-
20
- /** Read the current async context so agent can choose journaled or ordinary execution.
21
- * Async descendants can retain a closed context. RunState.track then rejects admission. */
22
- export function currentRun(): RunContext | undefined {
23
- return storage.getStore()
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
- code: error.code,
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
- /** Preserve a failure for workflow's rejection and prevent later dispatch. Active work keeps settling. */
49
- stop(error: HarnessSdkError): void { this.stops.add(error) }
22
+ private accepting = true
23
+ private pending = new Set<Promise<void>>()
24
+ private stops = new Set<HarnessSdkError>()
25
+ private rejected = 0
50
26
 
51
- /** Record a normalized storage failure when abortRun cannot publish or workflow cannot release the handle. */
52
- noteStorageFailure(): void { this.stop(new HarnessSdkError('WORKFLOW_STORAGE_FAILED')) }
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]
59
32
  if (!first) return undefined
60
33
  return new HarnessSdkError(first.code, first.message, false,
61
34
  failures.some(error => error.outcomeUnknown), {
62
- ...first.details,
63
35
  failureCodes: [...new Set(failures.map(error => error.code))],
64
36
  cleanupFailed: failures.some(cleanupFailed),
65
37
  })
66
38
  }
67
39
 
68
- /** Publication status for workflow when no sticky failure remains to reject the run. */
69
40
  get status(): 'completed' | 'incomplete' {
70
- return this.incomplete ? 'incomplete' : 'completed'
41
+ return this.rejected ? 'incomplete' : 'completed'
71
42
  }
72
43
 
73
- /** Mark a drop from executeJournaledAgent or a rejection observed by track incomplete.
74
- * Fatality is checked separately. */
75
- noteIncomplete(): void { this.incomplete = true }
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++ }
76
47
 
77
- /** Throw the sticky aggregate. track checks this before starting registered work, and
78
- * executeJournaledAgent checks again after publishing started because another call may have
79
- * stopped dispatch during that await. */
80
48
  assertDispatch(): void {
81
49
  const failure = this.failure
82
50
  if (failure) throw failure
83
51
  }
84
52
 
85
- /** Invoke memoizedAgent's operation immediately and register it for workflow's drain.
86
- * Closed admission returns a WORKFLOW_CLOSED rejection without invoking the operation.
87
- * Sticky failures and synchronous operation throws become rejected promises. Return the work
88
- * promise and register a separate observer so catching its rejection cannot hide incomplete
89
- * work or fatal failures from workflow. */
53
+ /** Registers in-flight work so body completion waits for it; late calls reject. */
90
54
  track<T>(operation: () => Promise<T>): Promise<T> {
91
55
  if (!this.accepting) return Promise.reject(new HarnessSdkError('WORKFLOW_CLOSED'))
92
56
  let work: Promise<T>
@@ -97,7 +61,7 @@ export class RunState {
97
61
  work = Promise.reject(cause)
98
62
  }
99
63
  const observed = work.then(() => {}, cause => {
100
- this.noteIncomplete()
64
+ this.rejected++
101
65
  const error = sdkError(cause, 'WORKFLOW_STEP_FAILED')
102
66
  if (isFatal(error)) this.stop(error)
103
67
  })
@@ -106,26 +70,8 @@ export class RunState {
106
70
  return work
107
71
  }
108
72
 
109
- /** Stop admitting agent work synchronously, then await all work already registered by track.
110
- * completeRun calls this before publication, and abortRun uses it on failure. Work continues
111
- * settling without cancellation. The observers record operation rejections in run state. */
112
73
  async closeAndDrain(): Promise<void> {
113
74
  this.accepting = false
114
75
  await Promise.all([...this.pending])
115
76
  }
116
-
117
- private accepting = true
118
- private pending = new Set<Promise<void>>()
119
- private stops = new Set<HarnessSdkError>()
120
- private incomplete = false
121
- }
122
-
123
- const storage = new AsyncLocalStorage<RunContext>()
124
-
125
- /** Recognize SDK resource-release errors and explicit cleanup evidence on another failure.
126
- * isFatal, storedFailure and RunState.failure share this rule for dispatch and reporting. */
127
- function cleanupFailed(error: HarnessSdkError): boolean {
128
- return error.code === 'RESOURCE_RELEASE_FAILED'
129
- || error.details?.cleanupFailed === true
130
- || (Array.isArray(error.details?.cleanupErrors) && error.details.cleanupErrors.length > 0)
131
77
  }
@@ -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
- /** Nonempty storage root. Relative paths are resolved against the process working directory. */
8
- directory: string
9
- /** New target directory name, defaulting to a random UUID. Use a nonblank single path
10
- * component of at most 255 UTF-8 bytes. Control characters, separators, `.` and `..` are
11
- * invalid. A locked or nonempty target directory rejects. */
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
  }