@anureo/workflow 0.3.3 → 0.3.7

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,32 +1,69 @@
1
1
  import { mock } from 'bun:test'
2
2
  import * as fs from 'node:fs/promises'
3
- import { randomUUID } from 'node:crypto'
4
- import { createClient } from '@anureo/sdk'
3
+ import { createClient, HarnessSdkError } from '@anureo/sdk'
5
4
  import { createScriptedAdapter } from '@anureo/conformance'
5
+ import type { JournalEvent } from '../persistence/records'
6
6
 
7
7
  const [directory, phase] = process.argv.slice(2) as [string, string]
8
8
  const originalRename = fs.rename
9
- let journalPublishes = 0
10
- mock.module('node:fs/promises', () => ({ ...fs, rename: async (from: string, to: string) => {
9
+ // workflow.test.ts spawns a fresh process per crash point. Install the mock before
10
+ // importing workflow so atomic publication uses the injected rename in this process.
11
+ mock.module('node:fs/promises', () => ({ ...fs, rename: renameAtCrashBoundary }))
12
+ const { workflow, agent } = await import('../index')
13
+
14
+ const adapter = createScriptedAdapter({
15
+ async execute(call) {
16
+ if (phase === 'unpublished-unknown' && call.method === 'input/submit' && 'submissionId' in call.params) {
17
+ throw new HarnessSdkError('NATIVE_FAILED', 'unknown', false, true)
18
+ }
19
+ if (phase === 'after-later-result' && call.method === 'input/submit' && 'input' in call.params
20
+ && call.params.input.some(part => part.type === 'text' && part.text === 'work')) {
21
+ // Hold the first call at started while the second reaches durable completion.
22
+ await new Promise<never>(() => {})
23
+ }
24
+ return undefined
25
+ },
26
+ })
27
+ const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
28
+ try {
29
+ await workflow({ directory, name: 'crash-test', revision: '1', input: {}, runId: 'crashed',
30
+ resumeFrom: phase === 'after-retry' ? 'source' : undefined }, async () => {
31
+ if (phase === 'after-retry') {
32
+ await agent('prefix', { client, cwd: directory })
33
+ await agent('work', { client, cwd: directory })
34
+ process.kill(process.pid, 'SIGKILL')
35
+ }
36
+ const first = agent('work', { client, cwd: directory })
37
+ if (phase !== 'after-later-result') return first
38
+ await agent('later', { client, cwd: directory })
39
+ process.kill(process.pid, 'SIGKILL')
40
+ return first
41
+ })
42
+ } catch (error) {
43
+ const codes = error instanceof HarnessSdkError ? error.details?.failureCodes : undefined
44
+ if (phase !== 'unpublished-unknown' || !(error instanceof HarnessSdkError)
45
+ || !error.outcomeUnknown || !Array.isArray(codes) || !codes.includes('WORKFLOW_STORAGE_FAILED')) throw error
46
+ } finally {
47
+ await client.dispose()
48
+ }
49
+
50
+ /** Replace fs.rename for atomicPublish. Kill the process before the selected rename can
51
+ * publish the started marker, agent result or completed manifest. Unselected renames
52
+ * use the original operation and propagate its failures. */
53
+ async function renameAtCrashBoundary(from: string, to: string): Promise<void> {
11
54
  const target = to.replaceAll('\\', '/')
12
55
  if (target.endsWith('/journal.json')) {
13
- journalPublishes++
14
- if (phase === 'before-started' && journalPublishes === 2) process.kill(process.pid, 'SIGKILL')
15
- if (phase === 'after-execute' && journalPublishes === 3) process.kill(process.pid, 'SIGKILL')
56
+ const pending = JSON.parse(await fs.readFile(from, 'utf8')) as JournalEvent[]
57
+ const event = pending.at(-1)
58
+ if ((phase === 'before-started' && event?.type === 'started')
59
+ || (phase === 'after-execute' && event?.type === 'result')) process.kill(process.pid, 'SIGKILL')
60
+ if (phase === 'unpublished-unknown' && event?.type === 'failed' && event.outcomeUnknown) {
61
+ throw new Error('Injected journal replacement failure')
62
+ }
16
63
  }
17
64
  if (phase === 'before-final' && target.endsWith('/run.json')) {
18
65
  const value = JSON.parse(await fs.readFile(from, 'utf8'))
19
66
  if (value.status === 'completed') process.kill(process.pid, 'SIGKILL')
20
67
  }
21
68
  await originalRename(from, to)
22
- } }))
23
- const { workflow, agent } = await import('../index')
24
-
25
- const adapter = createScriptedAdapter()
26
- const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
27
- try {
28
- await workflow({ directory, name: 'crash-test', revision: '1', input: {}, runId: 'crashed' }, async () =>
29
- agent('work', { client, cwd: directory }))
30
- } finally {
31
- await client.dispose()
32
69
  }
package/src/index.ts CHANGED
@@ -1,8 +1,12 @@
1
- export { agent, type AgentOptions } from './agent'
1
+ /** Application entry point for agent execution, concurrent composition, and durable runs. */
2
+ export { agent } from './agent'
3
+ export type { AgentOptions } from './agent-execution'
4
+
2
5
  export { parallel } from './parallel'
3
6
  export { pipeline } from './pipeline'
7
+
4
8
  export { workflow } from './workflow'
5
9
  export { journaledCall, type JournaledCall } from './journal-call'
6
10
  export { prepareOutputSchema } from './output-schema'
7
- export { isDroppedOutcome } from './agent-outcome'
11
+ export { isDroppedOutcome } from './agent-execution'
8
12
  export type { WorkflowOptions, WorkflowContext, WorkflowResult } from './workflow-types'
@@ -15,7 +15,8 @@ describe('journaledCall', () => {
15
15
  expect(unbundled).toBe('outside')
16
16
 
17
17
  let calls = 0
18
- const outcome = await workflow({ name: 'wf', revision: '1', input: { n: 1 } }, async () => {
18
+ const directory = await mkdtemp(join(tmpdir(), 'wf-journal-'))
19
+ const outcome = await workflow({ name: 'wf', revision: '1', directory, input: { n: 1 } }, async () => {
19
20
  calls++
20
21
  const first = await journaledCall({ prompt: 'p1', canonical: { a: 1 } }, async () => 'one')
21
22
  const second = await journaledCall({ prompt: 'p2', canonical: { a: 2 } }, async () => 'two')
@@ -57,12 +58,3 @@ describe('journaledCall', () => {
57
58
  expect(outcome.result).toEqual({ dropped: null, failed: 'STEP_BOOM' })
58
59
  })
59
60
  })
60
-
61
- describe('memory-only workflow runs', () => {
62
- test('complete without a directory and cannot be resumed', async () => {
63
- const outcome = await workflow({ name: 'wf', revision: '1', input: { a: 1 } }, async run => run.input)
64
- expect(outcome).toMatchObject({ status: 'completed', result: { a: 1 } })
65
- const resume = workflow({ name: 'wf', revision: '1', input: null, resumeFrom: { directory: '', runId: outcome.runId } }, () => 'x')
66
- await expect(resume).rejects.toThrow('WORKFLOW_RESUME_NOT_FOUND')
67
- })
68
- })
@@ -1,78 +1,84 @@
1
1
  // Shared journaling for call-shaped workflow steps; agent() and adapter-owned primitives reuse it.
2
- import { sdkError } from '@anureo/sdk'
3
- import { currentRun, type RunContext } from './run-context'
4
- import { isFatal } from './workflow-state'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { HarnessSdkError, sdkError } from '@anureo/sdk'
4
+ import { currentRun, isFatal, type RunContext } from './workflow-state'
5
5
  import { jsonCopy, type JsonValue } from './persistence/json'
6
- import { newAgentId, type JournalEvent } from './persistence/journal'
6
+ import type { JournalEvent } from './persistence/records'
7
7
 
8
8
  export interface JournaledCall {
9
9
  /** The step prompt; participates in the journal chain key and cache identity. */
10
10
  prompt: string
11
11
  /** Canonical semantic options; presentation-only fields must never be included. */
12
12
  canonical: JsonValue
13
- /** Client input-hook revision recorded on started records. */
14
- inputHookRevision?: string
15
- /** Journal failure code for a null (dropped) outcome; defaults to AGENT_DROPPED. */
16
- droppedCode?: string
13
+ /** Journal failure code for a null (dropped) outcome; a function is read lazily at append
14
+ * time so the real terminal code can be captured after execution; defaults to AGENT_DROPPED. */
15
+ droppedCode?: string | (() => string | undefined)
17
16
  /** Journal failure code fallback when a cause carries no SDK error; defaults to AGENT_FAILED. */
18
17
  failureCode?: string
19
18
  }
20
19
 
21
- type JournalKey = ReturnType<import('./persistence/journal').AgentJournal['nextKey']>
22
-
23
20
  /**
24
21
  * Execute one journaled workflow step. Inside a workflow() body the call is
25
22
  * memoized by prompt plus canonical options and chained onto the run journal;
26
- * outside a body it executes unbundled. Mirrors agent() journaling exactly.
23
+ * outside a body it executes unbundled. Journal semantics follow AgentJournal:
24
+ * keys reserve in invocation order, replay serves isolated saved results, and a
25
+ * source failure with an unknown outcome rejects with
26
+ * WORKFLOW_RECONCILIATION_REQUIRED before dispatch.
27
+ * Pass the call directly, or as a thunk evaluated inside the tracked region when
28
+ * building it can throw preflight failures that must mark the run incomplete.
27
29
  */
28
30
  export function journaledCall<T extends JsonValue>(
29
- call: JournaledCall,
31
+ call: JournaledCall | (() => JournaledCall),
30
32
  execute: (agentId: string) => Promise<T | null>,
31
33
  ): Promise<T | null>
32
34
  export function journaledCall<T extends JsonValue, R>(
33
- call: JournaledCall,
35
+ call: JournaledCall | (() => JournaledCall),
34
36
  execute: (agentId: string) => Promise<T | null>,
35
37
  revive: (stored: JsonValue) => R,
36
38
  ): Promise<R | null>
37
39
  export async function journaledCall<T extends JsonValue, R = T>(
38
- call: JournaledCall,
40
+ call: JournaledCall | (() => JournaledCall),
39
41
  execute: (agentId: string) => Promise<T | null>,
40
42
  revive?: (stored: JsonValue) => R,
41
43
  ): Promise<(T | R) | null> {
42
44
  const run = currentRun()
43
- if (!run) return execute(newAgentId())
44
- // The key advances synchronously here: host invocation order fixes the chain.
45
- const key = run.journal.nextKey(call.prompt, call.canonical)
46
- return memoized(run, key, call, execute, revive)
45
+ if (!run) {
46
+ if (typeof call === 'function') call()
47
+ return execute(randomUUID())
48
+ }
49
+ return memoized(run, call, execute, revive)
47
50
  }
48
51
 
49
52
  async function memoized<T extends JsonValue, R>(
50
53
  run: RunContext,
51
- key: JournalKey,
52
- call: JournaledCall,
54
+ input: JournaledCall | (() => JournaledCall),
53
55
  execute: (agentId: string) => Promise<T | null>,
54
56
  revive?: (stored: JsonValue) => R,
55
57
  ): Promise<(T | R) | null> {
56
58
  const { journal, state } = run
57
59
  return state.track(async () => {
58
60
  state.assertDispatch()
59
- const conflict = journal.resumeConflict(key, call.inputHookRevision)
60
- if (conflict) {
61
- state.stop(conflict)
62
- throw conflict
61
+ // Resolve the call and reserve its key synchronously inside the tracked
62
+ // region, so preflight failures land on the run state and the chain keeps
63
+ // host invocation order.
64
+ const call = typeof input === 'function' ? input() : input
65
+ const key = journal.nextKey(call.prompt, call.canonical)
66
+ const decision = journal.resolveCall(key)
67
+ if (decision.action === 'reconcile') {
68
+ throw new HarnessSdkError('WORKFLOW_RECONCILIATION_REQUIRED',
69
+ 'A previous run left this agent call with an unknown outcome; reconcile it before resuming', false, true)
63
70
  }
64
- const hit = journal.resultFor(key)
65
- if (hit !== undefined) {
66
- return revive ? revive(hit) : (hit as T)
71
+ if (decision.action === 'replay') {
72
+ return revive ? revive(decision.result) : (decision.result as T)
67
73
  }
68
- journal.beginExecution(key)
69
- const agentId = newAgentId()
70
- await journal.append({ type: 'started', key, agentId, ...(call.inputHookRevision === undefined ? {} : { inputHookRevision: call.inputHookRevision }) } satisfies JournalEvent)
74
+ const agentId = randomUUID()
75
+ await journal.append({ type: 'started', key, agentId } satisfies JournalEvent)
71
76
  state.assertDispatch()
72
77
  try {
73
78
  const value = await execute(agentId)
74
79
  if (value === null) {
75
- await journal.append({ type: 'failed', key, agentId, code: call.droppedCode ?? 'AGENT_DROPPED', outcomeUnknown: false } satisfies JournalEvent)
80
+ const dropped = typeof call.droppedCode === 'function' ? call.droppedCode() : call.droppedCode
81
+ await journal.append({ type: 'failed', key, agentId, code: dropped ?? 'AGENT_DROPPED', outcomeUnknown: false } satisfies JournalEvent)
76
82
  state.noteIncomplete()
77
83
  return null
78
84
  }
@@ -85,7 +91,13 @@ async function memoized<T extends JsonValue, R>(
85
91
  // The storage layer may have published a terminal record already; never
86
92
  // append a contradictory failure after a storage error.
87
93
  if (error.code !== 'WORKFLOW_STORAGE_FAILED') {
88
- await journal.append({ type: 'failed', key, agentId, code: error.code, outcomeUnknown: error.outcomeUnknown === true } satisfies JournalEvent)
94
+ try {
95
+ await journal.append({ type: 'failed', key, agentId, code: error.code, outcomeUnknown: error.outcomeUnknown === true } satisfies JournalEvent)
96
+ } catch {
97
+ state.noteStorageFailure()
98
+ throw new HarnessSdkError(error.code, error.message, error.retryable, error.outcomeUnknown,
99
+ { ...error.details, journalErrorCode: 'WORKFLOW_STORAGE_FAILED' })
100
+ }
89
101
  }
90
102
  throw error
91
103
  }
@@ -64,11 +64,29 @@ test('schema-like keys in business enum and default data are not treated as sche
64
64
  test('raw JSON is validated before Zod can strip extra fields or supply defaults', async () => {
65
65
  const output = prepareOutputSchema(z.object({ count: z.number().default(3) }))
66
66
  expect(await output.parse('{"count":4}')).toEqual({ count: 4 })
67
- for (const text of ['{}', '{"count":4,"extra":1}', '{"count":"4"}', 'null', '[]']) {
67
+ await expect(output.parse('{}')).rejects.toMatchObject({
68
+ code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
69
+ retryable: false,
70
+ outcomeUnknown: false,
71
+ details: { issues: [{ path: '/count', code: 'required' }] },
72
+ })
73
+ for (const text of ['{"count":4,"extra":1}', '{"count":"4"}', 'null', '[]']) {
68
74
  await expect(output.parse(text)).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', retryable: false, outcomeUnknown: false })
69
75
  }
70
76
  })
71
77
 
78
+ test('raw JSON issues identify missing and extra fields with escaped pointer segments', async () => {
79
+ const output = prepareOutputSchema(z.object({ nested: z.object({ 'a/b': z.number(), 'a~b': z.number() }) }))
80
+ await expect(output.parse('{"nested":{"extra~/":"private value"}}')).rejects.toMatchObject({
81
+ code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
82
+ details: { issues: [
83
+ { path: '/nested/a~1b', code: 'required' },
84
+ { path: '/nested/a~0b', code: 'required' },
85
+ { path: '/nested/extra~0~1', code: 'additionalProperties' },
86
+ ] },
87
+ })
88
+ })
89
+
72
90
  test('missing and malformed output remain distinct failures without recovering prose', async () => {
73
91
  const output = prepareOutputSchema(z.object({ count: z.number() }))
74
92
  await expect(output.parse(' ')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_MISSING' })
@@ -90,7 +108,11 @@ test('sync and async refinements and formats validate locally and sanitize custo
90
108
  } catch (error) {
91
109
  failure = error
92
110
  }
93
- expect(failure).toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', outcomeUnknown: false })
111
+ expect(failure).toMatchObject({
112
+ code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
113
+ outcomeUnknown: false,
114
+ details: { issues: [{ path: [], code: 'custom' }] },
115
+ })
94
116
  expect(JSON.stringify(failure)).not.toContain('private-')
95
117
  }
96
118
  await expect(output.parse('{"count":1,"email":"bad"}')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID' })
@@ -99,15 +121,21 @@ test('sync and async refinements and formats validate locally and sanitize custo
99
121
  })
100
122
 
101
123
  test('definite generated contradictions and external references are rejected', () => {
102
- for (const schema of [
103
- z.object({ a: z.string().meta({ minLength: 5, maxLength: 1 }) }),
104
- z.object({ a: z.number().meta({ minimum: 5, maximum: 1 }) }),
105
- z.object({ a: z.number().meta({ minimum: 1, exclusiveMaximum: 1 }) }),
106
- z.object({ a: z.array(z.string()).meta({ minItems: 3, maxItems: 1 }) }),
107
- z.object({ a: z.string().meta({ $ref: 'https://private.example/schema' }) }),
108
- z.object({ a: z.string() }).meta({ required: ['missing'] }),
109
- z.object({}).meta({ required: ['missing'], patternProperties: { '^allowed$': { type: 'string' } } }),
110
- ]) expect(() => prepareOutputSchema(schema)).toThrow(expect.objectContaining({ code: 'INVALID_PARAMS' }))
124
+ const cases: Array<{ schema: z.ZodObject; rule: string }> = [
125
+ { schema: z.object({ a: z.string().meta({ minLength: 5, maxLength: 1 }) }), rule: 'unsatisfiableBounds' },
126
+ { schema: z.object({ a: z.number().meta({ minimum: 5, maximum: 1 }) }), rule: 'unsatisfiableBounds' },
127
+ { schema: z.object({ a: z.number().meta({ minimum: 1, exclusiveMaximum: 1 }) }), rule: 'unsatisfiableBounds' },
128
+ { schema: z.object({ a: z.array(z.string()).meta({ minItems: 3, maxItems: 1 }) }), rule: 'unsatisfiableBounds' },
129
+ { schema: z.object({ a: z.string().meta({ $ref: 'https://private.example/schema' }) }), rule: 'externalOrAsyncSchema' },
130
+ { schema: z.object({ a: z.string() }).meta({ required: ['missing'] }), rule: 'optionalProperty' },
131
+ {
132
+ schema: z.object({}).meta({ required: ['missing'], patternProperties: { '^allowed$': { type: 'string' } } }),
133
+ rule: 'unsatisfiableRequired',
134
+ },
135
+ ]
136
+ for (const { schema, rule } of cases) {
137
+ expect(() => prepareOutputSchema(schema)).toThrow(expect.objectContaining({ code: 'INVALID_PARAMS', details: { rule } }))
138
+ }
111
139
  // Numeric bounds do not contradict a string instance.
112
140
  expect(prepareOutputSchema(z.object({ a: z.string().meta({ minimum: 5, maximum: 1 }) })).schema.type).toBe('object')
113
141
  expect(prepareOutputSchema(z.object({}).meta({ required: ['allowed'], patternProperties: { '^allowed$': { type: 'string' } } })).schema.type).toBe('object')
@@ -121,6 +149,11 @@ test('user schema callbacks cannot expose their exception or claim execution unc
121
149
  } catch (cause) {
122
150
  failure = cause
123
151
  }
124
- expect(failure).toMatchObject({ code: 'INVALID_PARAMS', retryable: false, outcomeUnknown: false })
152
+ expect(failure).toMatchObject({
153
+ code: 'INVALID_PARAMS',
154
+ retryable: false,
155
+ outcomeUnknown: false,
156
+ details: { rule: 'invalidOrUnrepresentableSchema' },
157
+ })
125
158
  expect(String(failure)).not.toContain('private value')
126
159
  })