@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/agent.ts
CHANGED
|
@@ -1,135 +1,110 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { JsonObject } from '@anureo/protocol'
|
|
3
|
-
import { HarnessSdkError, sdkError } from '@anureo/sdk'
|
|
1
|
+
import { HarnessSdkError, sdkError, type Client } from '@anureo/sdk'
|
|
4
2
|
import type { z } from 'zod'
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { currentRun
|
|
8
|
-
import {
|
|
3
|
+
import { prepareOutputSchema } from './output-schema'
|
|
4
|
+
import { isDroppedOutcome, isStartupBlockException } from './agent-outcome'
|
|
5
|
+
import { currentRun } from './run-context'
|
|
6
|
+
import { journaledCall } from './journal-call'
|
|
7
|
+
import { canonicalJson, type JsonValue } from './persistence/json'
|
|
8
|
+
import type { JsonObject } from '@anureo/protocol'
|
|
9
|
+
|
|
10
|
+
// Do not impose the SDK's short observation timeout on model execution.
|
|
11
|
+
const LONG_OBSERVATION_TIMEOUT_MS = 0x7fffffff
|
|
12
|
+
|
|
13
|
+
export interface AgentOptions<S extends z.ZodObject = z.ZodObject> {
|
|
14
|
+
client: Client
|
|
15
|
+
cwd: string
|
|
16
|
+
model?: string
|
|
17
|
+
instructions?: string
|
|
18
|
+
/** Optional openSession permission mode; unsupported values fail session open. */
|
|
19
|
+
permissionMode?: string
|
|
20
|
+
schema?: S
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type AgentOutcome =
|
|
24
|
+
| { status: 'completed'; value: string | Record<string, unknown> }
|
|
25
|
+
| { status: 'dropped'; error: { code: string; outcomeUnknown: boolean } }
|
|
26
|
+
| { status: 'failed'; error: HarnessSdkError }
|
|
9
27
|
|
|
10
|
-
/**
|
|
11
|
-
* Run a prompt in a fresh session or replay an eligible workflow result. Return the SDK's final
|
|
12
|
-
* text, which can be empty. Fresh execution awaits the associated turn's terminal result.
|
|
13
|
-
* Once a session is acquired, attempt close and then disposal before settlement, even when
|
|
14
|
-
* submission, observation or close fails.
|
|
15
|
-
* Return null for a confirmed authentication, usage-limit, rate-limit or service-unavailability
|
|
16
|
-
* failure reported in a failed terminal, an explicit skip reported on interruption, or a tagged
|
|
17
|
-
* startup denial. Unknown outcomes, other execution failures and cleanup failures reject.
|
|
18
|
-
* Cleanup failures preserve a primary execution error with details.cleanupErrors, or reject with
|
|
19
|
-
* RESOURCE_RELEASE_FAILED. The caller decides whether to retry or request interruption through
|
|
20
|
-
* the SDK. Agent submits at most once per call. Session release ends local observation and can
|
|
21
|
-
* leave native execution running.
|
|
22
|
-
* Inside workflow(), reserve cache keys in invocation order and reuse eligible saved results on
|
|
23
|
-
* resume without opening a session. A journal miss awaits publication of its started record before
|
|
24
|
-
* dispatch and its terminal record before returning a result. Checkpoint failures reject. A saved
|
|
25
|
-
* failure with an unknown outcome at the same key rejects with WORKFLOW_RECONCILIATION_REQUIRED.
|
|
26
|
-
* Keep the borrowed client usable until settlement and dispose it separately when finished.
|
|
27
|
-
*/
|
|
28
28
|
export function agent(prompt: string, options: AgentOptions<never> & { schema?: undefined }): Promise<string | null>
|
|
29
|
-
/**
|
|
30
|
-
* Return typed output from a portable Zod object schema, with the same session ownership,
|
|
31
|
-
* cleanup, drop, and journal behavior as text mode.
|
|
32
|
-
* Unsupported schemas reject before opening. Validation awaits async refinements for fresh and
|
|
33
|
-
* replayed results. The JSON must supply every required field before Zod checks run.
|
|
34
|
-
* Missing, malformed or invalid JSON rejects without resubmitting the prompt.
|
|
35
|
-
*/
|
|
36
29
|
export function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S> & { schema: S }): Promise<z.output<S> | null>
|
|
37
|
-
/** Return text when schema is omitted or undefined, or validated data when it is supplied.
|
|
38
|
-
* Both modes share agent's session ownership, cleanup, drop, and journal behavior. */
|
|
39
30
|
export function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S>): Promise<string | z.output<S> | null>
|
|
31
|
+
/** Execute one fresh session, validate its terminal output, and release its observation resources. */
|
|
40
32
|
export async function agent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
|
|
41
33
|
const context = currentRun()
|
|
42
|
-
if (context) return memoizedAgent(
|
|
34
|
+
if (context) return memoizedAgent(prompt, options)
|
|
43
35
|
return executeAgent(prompt, options)
|
|
44
36
|
}
|
|
45
37
|
|
|
46
|
-
/**
|
|
47
|
-
* Prepare the schema for the key and for replay, then reserve the key synchronously when agent
|
|
48
|
-
* inherits the run context. Preflight failures reject before registration. RunState admits and
|
|
49
|
-
* observes the replay or execution so workflow can drain it even if the body leaves the call
|
|
50
|
-
* unawaited. On a miss, executeAgent prepares the schema from the options again after the started
|
|
51
|
-
* record is published and dispatch is rechecked.
|
|
52
|
-
*/
|
|
53
|
-
async function memoizedAgent<S extends z.ZodObject>(
|
|
54
|
-
context: RunContext,
|
|
55
|
-
prompt: string,
|
|
56
|
-
options: AgentOptions<S>,
|
|
57
|
-
): Promise<string | z.output<S> | null> {
|
|
58
|
-
const { journal, state } = context
|
|
59
|
-
const output = options.schema === undefined ? undefined : prepareOutputSchema(options.schema)
|
|
60
|
-
// The key advances synchronously here: host invocation order fixes the chain.
|
|
61
|
-
const key = journal.nextKey(prompt, canonicalOptions(options, output?.schema))
|
|
62
|
-
return state.track(() => {
|
|
63
|
-
const decision = journal.resolveCall(key)
|
|
64
|
-
if (decision.action === 'replay') return replayAgentResult(decision.result, output)
|
|
65
|
-
if (decision.action === 'reconcile') {
|
|
66
|
-
throw new HarnessSdkError('WORKFLOW_RECONCILIATION_REQUIRED',
|
|
67
|
-
'A previous run left this agent call with an unknown outcome; reconcile it before resuming', false, true)
|
|
68
|
-
}
|
|
69
|
-
return executeJournaledAgent({ context, key, prompt, options })
|
|
70
|
-
})
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** Project the options memoizedAgent hashes with the prompt. Preserve the persisted key format
|
|
74
|
-
* by using null for absent model, instructions, permission mode and schema, and omitting absent
|
|
75
|
-
* fallback. Use the client identity so equivalent backend configurations can share a key. */
|
|
38
|
+
/** Semantic fields participating in the journal cache identity; presentation fields never do. */
|
|
76
39
|
function canonicalOptions(options: AgentOptions, schema: JsonObject | undefined): JsonValue {
|
|
77
40
|
return {
|
|
78
41
|
model: options.model ?? null,
|
|
79
42
|
instructions: options.instructions ?? null,
|
|
80
43
|
permissionMode: options.permissionMode ?? null,
|
|
81
44
|
schema: schema ?? null,
|
|
82
|
-
...(options.outputFallback ? { outputFallback: options.outputFallback } : {}),
|
|
83
45
|
cwd: options.cwd,
|
|
84
46
|
client: options.client.identity,
|
|
85
47
|
}
|
|
86
48
|
}
|
|
87
49
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
output
|
|
93
|
-
|
|
94
|
-
|
|
50
|
+
async function memoizedAgent<S extends z.ZodObject>(
|
|
51
|
+
prompt: string,
|
|
52
|
+
options: AgentOptions<S>,
|
|
53
|
+
): Promise<string | z.output<S> | null> {
|
|
54
|
+
const output = options.schema === undefined ? undefined : prepareOutputSchema(options.schema)
|
|
55
|
+
const call = {
|
|
56
|
+
prompt,
|
|
57
|
+
canonical: canonicalOptions(options, output?.schema),
|
|
58
|
+
inputHookRevision: options.client.inputHookRevision,
|
|
59
|
+
}
|
|
60
|
+
const execute = () => executeAgent(prompt, options) as Promise<JsonValue | null>
|
|
61
|
+
if (output) return journaledCall(call, execute, stored => output.parse(canonicalJson(stored)) as z.output<S>)
|
|
62
|
+
return journaledCall(call, execute) as Promise<string | z.output<S> | null>
|
|
95
63
|
}
|
|
96
64
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
async function executeJournaledAgent<S extends z.ZodObject>({ context, key, prompt, options }: {
|
|
105
|
-
context: RunContext
|
|
106
|
-
key: string
|
|
107
|
-
prompt: string
|
|
108
|
-
options: AgentOptions<S>
|
|
109
|
-
}): Promise<string | z.output<S> | null> {
|
|
110
|
-
const { journal, state } = context
|
|
111
|
-
const agentId = randomUUID()
|
|
112
|
-
await journal.append({ type: 'started', key, agentId })
|
|
113
|
-
state.assertDispatch()
|
|
65
|
+
async function executeAgent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
|
|
66
|
+
const { client, cwd, model, instructions, permissionMode, schema } = options
|
|
67
|
+
const output = schema === undefined ? undefined : prepareOutputSchema(schema)
|
|
68
|
+
const session = await client.sessions.create({ cwd, ...(model !== undefined ? { model } : {}), ...(instructions !== undefined ? { instructions } : {}), ...(permissionMode !== undefined ? { permissionMode } : {}) })
|
|
69
|
+
.catch(cause => { if (isStartupBlockException(cause)) return null; throw cause })
|
|
70
|
+
if (!session) return null // A failed open never hands session ownership to this call.
|
|
71
|
+
let outcome: AgentOutcome
|
|
114
72
|
try {
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
73
|
+
if (output && !session.capabilities.turn?.outputSchema) throw new HarnessSdkError('CAPABILITY_UNSUPPORTED', 'Session does not support structured output')
|
|
74
|
+
const turn = await session.submit({ input: prompt, ...(output ? { outputSchema: output.schema } : {}) }, { timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
|
|
75
|
+
const result = await turn.result({ timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
|
|
76
|
+
if (result.status === 'completed') {
|
|
77
|
+
outcome = { status: 'completed', value: output ? await output.parse(result.text) : result.text }
|
|
78
|
+
} else if (result.error && isDroppedOutcome(result.error, result.status)) {
|
|
79
|
+
outcome = { status: 'dropped', error: { code: result.error.code, outcomeUnknown: result.error.outcomeUnknown } }
|
|
80
|
+
} else if (result.error) {
|
|
81
|
+
const { code, message, retryable, outcomeUnknown, details } = result.error
|
|
82
|
+
throw new HarnessSdkError(code, message, retryable, outcomeUnknown, details)
|
|
83
|
+
} else {
|
|
84
|
+
throw new HarnessSdkError('AGENT_INTERRUPTED')
|
|
121
85
|
}
|
|
122
|
-
const stored = jsonCopy(value) as JsonValue
|
|
123
|
-
await journal.append({ type: 'result', key, agentId, result: stored })
|
|
124
|
-
return jsonCopy(stored) as string | z.output<S>
|
|
125
86
|
} catch (cause) {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
87
|
+
if (isStartupBlockException(cause)) outcome = { status: 'dropped', error: { code: cause.code, outcomeUnknown: cause.outcomeUnknown } }
|
|
88
|
+
else outcome = { status: 'failed', error: sdkError(cause, 'AGENT_FAILED', true) }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Closing observation does not prove the backend execution stopped. Never retry input.
|
|
92
|
+
const cleanupErrors = new Set<HarnessSdkError>()
|
|
93
|
+
try { await session.close() } catch (cause) { cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true)) }
|
|
94
|
+
try { await session.dispose() } catch (cause) { cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true)) }
|
|
95
|
+
if (cleanupErrors.size) {
|
|
96
|
+
const errors = [...cleanupErrors].map(error => ({ code: error.code, outcomeUnknown: error.outcomeUnknown }))
|
|
97
|
+
if (outcome.status === 'failed') {
|
|
98
|
+
const failure = outcome.error
|
|
99
|
+
throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown,
|
|
100
|
+
{ ...failure.details, cleanupErrors: errors })
|
|
132
101
|
}
|
|
133
|
-
throw
|
|
102
|
+
throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false,
|
|
103
|
+
errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) })
|
|
104
|
+
}
|
|
105
|
+
switch (outcome.status) {
|
|
106
|
+
case 'completed': return outcome.value
|
|
107
|
+
case 'dropped': return null
|
|
108
|
+
case 'failed': throw outcome.error
|
|
134
109
|
}
|
|
135
110
|
}
|
|
@@ -1,46 +1,15 @@
|
|
|
1
1
|
import { mock } from 'bun:test'
|
|
2
2
|
import * as fs from 'node:fs/promises'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
3
4
|
import { createClient } from '@anureo/sdk'
|
|
4
5
|
import { createScriptedAdapter } from '@anureo/conformance'
|
|
5
6
|
|
|
6
7
|
const [directory, phase] = process.argv.slice(2) as [string, string]
|
|
7
8
|
const originalRename = fs.rename
|
|
8
9
|
let journalPublishes = 0
|
|
9
|
-
|
|
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 === 'after-later-result' && call.method === 'input/submit' && 'input' in call.params
|
|
17
|
-
&& call.params.input.some(part => part.type === 'text' && part.text === 'work')) {
|
|
18
|
-
// Hold the first call at started while the second reaches durable completion.
|
|
19
|
-
await new Promise<never>(() => {})
|
|
20
|
-
}
|
|
21
|
-
return undefined
|
|
22
|
-
},
|
|
23
|
-
})
|
|
24
|
-
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
|
|
25
|
-
try {
|
|
26
|
-
await workflow({ directory, name: 'crash-test', revision: '1', input: {}, runId: 'crashed' }, async () => {
|
|
27
|
-
const first = agent('work', { client, cwd: directory })
|
|
28
|
-
if (phase !== 'after-later-result') return first
|
|
29
|
-
await agent('later', { client, cwd: directory })
|
|
30
|
-
process.kill(process.pid, 'SIGKILL')
|
|
31
|
-
return first
|
|
32
|
-
})
|
|
33
|
-
} finally {
|
|
34
|
-
await client.dispose()
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** Replace fs.rename for atomicPublish. Kill the process before the selected rename can
|
|
38
|
-
* publish the started marker, agent result or completed manifest. Unselected renames
|
|
39
|
-
* use the original operation and propagate its failures. */
|
|
40
|
-
async function renameAtCrashBoundary(from: string, to: string): Promise<void> {
|
|
10
|
+
mock.module('node:fs/promises', () => ({ ...fs, rename: async (from: string, to: string) => {
|
|
41
11
|
const target = to.replaceAll('\\', '/')
|
|
42
12
|
if (target.endsWith('/journal.json')) {
|
|
43
|
-
// The first publication creates the empty journal before any agent work can start.
|
|
44
13
|
journalPublishes++
|
|
45
14
|
if (phase === 'before-started' && journalPublishes === 2) process.kill(process.pid, 'SIGKILL')
|
|
46
15
|
if (phase === 'after-execute' && journalPublishes === 3) process.kill(process.pid, 'SIGKILL')
|
|
@@ -50,4 +19,14 @@ async function renameAtCrashBoundary(from: string, to: string): Promise<void> {
|
|
|
50
19
|
if (value.status === 'completed') process.kill(process.pid, 'SIGKILL')
|
|
51
20
|
}
|
|
52
21
|
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()
|
|
53
32
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
export { agent } from './agent'
|
|
3
|
-
export type { AgentOptions } from './agent-execution'
|
|
4
|
-
|
|
1
|
+
export { agent, type AgentOptions } from './agent'
|
|
5
2
|
export { parallel } from './parallel'
|
|
6
3
|
export { pipeline } from './pipeline'
|
|
7
|
-
|
|
8
4
|
export { workflow } from './workflow'
|
|
9
|
-
export
|
|
5
|
+
export { journaledCall, type JournaledCall } from './journal-call'
|
|
6
|
+
export { prepareOutputSchema } from './output-schema'
|
|
7
|
+
export { isDroppedOutcome } from './agent-outcome'
|
|
8
|
+
export type { WorkflowOptions, WorkflowContext, WorkflowResult } from './workflow-types'
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { journaledCall } from './journal-call'
|
|
3
|
+
import { workflow } from './workflow'
|
|
4
|
+
import { mkdtemp } from 'node:fs/promises'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { HarnessSdkError } from '@anureo/sdk'
|
|
8
|
+
|
|
9
|
+
describe('journaledCall', () => {
|
|
10
|
+
test('executes unbundled outside workflow() and journals inside it', async () => {
|
|
11
|
+
const unbundled = await journaledCall({ prompt: 'p', canonical: { a: 1 } }, async agentId => {
|
|
12
|
+
expect(typeof agentId).toBe('string')
|
|
13
|
+
return 'outside'
|
|
14
|
+
})
|
|
15
|
+
expect(unbundled).toBe('outside')
|
|
16
|
+
|
|
17
|
+
let calls = 0
|
|
18
|
+
const outcome = await workflow({ name: 'wf', revision: '1', input: { n: 1 } }, async () => {
|
|
19
|
+
calls++
|
|
20
|
+
const first = await journaledCall({ prompt: 'p1', canonical: { a: 1 } }, async () => 'one')
|
|
21
|
+
const second = await journaledCall({ prompt: 'p2', canonical: { a: 2 } }, async () => 'two')
|
|
22
|
+
return [first, second]
|
|
23
|
+
})
|
|
24
|
+
expect(calls).toBe(1)
|
|
25
|
+
expect(outcome.status).toBe('completed')
|
|
26
|
+
expect(outcome.result).toEqual(['one', 'two'])
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
test('memorizes by prompt and canonical options inside one journal chain', async () => {
|
|
30
|
+
const directory = await mkdtemp(join(tmpdir(), 'wf-journal-'))
|
|
31
|
+
const executions: string[] = []
|
|
32
|
+
const body = async () => {
|
|
33
|
+
const a = await journaledCall({ prompt: 'same', canonical: { model: 'm1' } }, async () => { executions.push('m1'); return 'r1' })
|
|
34
|
+
const b = await journaledCall({ prompt: 'same', canonical: { model: 'm2' } }, async () => { executions.push('m2'); return 'r2' })
|
|
35
|
+
return [a, b]
|
|
36
|
+
}
|
|
37
|
+
const first = await workflow({ name: 'wf', revision: '1', directory, input: null }, body)
|
|
38
|
+
expect(first.result).toEqual(['r1', 'r2'])
|
|
39
|
+
expect(executions).toEqual(['m1', 'm2'])
|
|
40
|
+
// A fresh run in a new directory re-executes; the same directory resumed by
|
|
41
|
+
// runId replays both results without executing.
|
|
42
|
+
const second = await workflow({ name: 'wf', revision: '1', directory, input: null, runId: 'again' }, body)
|
|
43
|
+
expect(second.result).toEqual(['r1', 'r2'])
|
|
44
|
+
expect(executions).toEqual(['m1', 'm2', 'm1', 'm2'])
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
test('journals dropped null outcomes and thrown failures with their codes', async () => {
|
|
48
|
+
const directory = await mkdtemp(join(tmpdir(), 'wf-journal-'))
|
|
49
|
+
const outcome = await workflow({ name: 'wf', revision: '1', directory, input: null }, async () => {
|
|
50
|
+
const dropped = await journaledCall({ prompt: 'drop', canonical: {}, droppedCode: 'STEP_DROPPED' }, async () => null)
|
|
51
|
+
const failed = await journaledCall<string>({ prompt: 'fail', canonical: {}, failureCode: 'STEP_FAILED' }, async () => {
|
|
52
|
+
throw new HarnessSdkError('STEP_BOOM')
|
|
53
|
+
}).catch(cause => (cause as HarnessSdkError).code)
|
|
54
|
+
return { dropped, failed }
|
|
55
|
+
})
|
|
56
|
+
expect(outcome.status).toBe('incomplete')
|
|
57
|
+
expect(outcome.result).toEqual({ dropped: null, failed: 'STEP_BOOM' })
|
|
58
|
+
})
|
|
59
|
+
})
|
|
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
|
+
})
|
|
@@ -0,0 +1,93 @@
|
|
|
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'
|
|
5
|
+
import { jsonCopy, type JsonValue } from './persistence/json'
|
|
6
|
+
import { newAgentId, type JournalEvent } from './persistence/journal'
|
|
7
|
+
|
|
8
|
+
export interface JournaledCall {
|
|
9
|
+
/** The step prompt; participates in the journal chain key and cache identity. */
|
|
10
|
+
prompt: string
|
|
11
|
+
/** Canonical semantic options; presentation-only fields must never be included. */
|
|
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
|
|
17
|
+
/** Journal failure code fallback when a cause carries no SDK error; defaults to AGENT_FAILED. */
|
|
18
|
+
failureCode?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type JournalKey = ReturnType<import('./persistence/journal').AgentJournal['nextKey']>
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Execute one journaled workflow step. Inside a workflow() body the call is
|
|
25
|
+
* memoized by prompt plus canonical options and chained onto the run journal;
|
|
26
|
+
* outside a body it executes unbundled. Mirrors agent() journaling exactly.
|
|
27
|
+
*/
|
|
28
|
+
export function journaledCall<T extends JsonValue>(
|
|
29
|
+
call: JournaledCall,
|
|
30
|
+
execute: (agentId: string) => Promise<T | null>,
|
|
31
|
+
): Promise<T | null>
|
|
32
|
+
export function journaledCall<T extends JsonValue, R>(
|
|
33
|
+
call: JournaledCall,
|
|
34
|
+
execute: (agentId: string) => Promise<T | null>,
|
|
35
|
+
revive: (stored: JsonValue) => R,
|
|
36
|
+
): Promise<R | null>
|
|
37
|
+
export async function journaledCall<T extends JsonValue, R = T>(
|
|
38
|
+
call: JournaledCall,
|
|
39
|
+
execute: (agentId: string) => Promise<T | null>,
|
|
40
|
+
revive?: (stored: JsonValue) => R,
|
|
41
|
+
): Promise<(T | R) | null> {
|
|
42
|
+
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)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function memoized<T extends JsonValue, R>(
|
|
50
|
+
run: RunContext,
|
|
51
|
+
key: JournalKey,
|
|
52
|
+
call: JournaledCall,
|
|
53
|
+
execute: (agentId: string) => Promise<T | null>,
|
|
54
|
+
revive?: (stored: JsonValue) => R,
|
|
55
|
+
): Promise<(T | R) | null> {
|
|
56
|
+
const { journal, state } = run
|
|
57
|
+
return state.track(async () => {
|
|
58
|
+
state.assertDispatch()
|
|
59
|
+
const conflict = journal.resumeConflict(key, call.inputHookRevision)
|
|
60
|
+
if (conflict) {
|
|
61
|
+
state.stop(conflict)
|
|
62
|
+
throw conflict
|
|
63
|
+
}
|
|
64
|
+
const hit = journal.resultFor(key)
|
|
65
|
+
if (hit !== undefined) {
|
|
66
|
+
return revive ? revive(hit) : (hit as T)
|
|
67
|
+
}
|
|
68
|
+
journal.beginExecution(key)
|
|
69
|
+
const agentId = newAgentId()
|
|
70
|
+
await journal.append({ type: 'started', key, agentId, ...(call.inputHookRevision === undefined ? {} : { inputHookRevision: call.inputHookRevision }) } satisfies JournalEvent)
|
|
71
|
+
state.assertDispatch()
|
|
72
|
+
try {
|
|
73
|
+
const value = await execute(agentId)
|
|
74
|
+
if (value === null) {
|
|
75
|
+
await journal.append({ type: 'failed', key, agentId, code: call.droppedCode ?? 'AGENT_DROPPED', outcomeUnknown: false } satisfies JournalEvent)
|
|
76
|
+
state.noteIncomplete()
|
|
77
|
+
return null
|
|
78
|
+
}
|
|
79
|
+
const stored = jsonCopy(value) as JsonValue
|
|
80
|
+
await journal.append({ type: 'result', key, agentId, result: stored } satisfies JournalEvent)
|
|
81
|
+
return revive ? revive(stored) : (jsonCopy(stored) as T)
|
|
82
|
+
} catch (cause) {
|
|
83
|
+
const error = sdkError(cause, call.failureCode ?? 'AGENT_FAILED')
|
|
84
|
+
if (isFatal(error)) state.stop(error)
|
|
85
|
+
// The storage layer may have published a terminal record already; never
|
|
86
|
+
// append a contradictory failure after a storage error.
|
|
87
|
+
if (error.code !== 'WORKFLOW_STORAGE_FAILED') {
|
|
88
|
+
await journal.append({ type: 'failed', key, agentId, code: error.code, outcomeUnknown: error.outcomeUnknown === true } satisfies JournalEvent)
|
|
89
|
+
}
|
|
90
|
+
throw error
|
|
91
|
+
}
|
|
92
|
+
}) as Promise<(T | R) | null>
|
|
93
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { mkdtemp, readFile, rm } from 'node:fs/promises'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
import { z } from 'zod'
|
|
7
|
+
import { createClient } from '@anureo/sdk'
|
|
8
|
+
import { createClaudeAdapter } from '@anureo/adapter-claude'
|
|
9
|
+
import { createCodexAdapter } from '@anureo/adapter-codex'
|
|
10
|
+
import { agent, parallel } from './index'
|
|
11
|
+
|
|
12
|
+
test('Zod agent crosses the official Claude SDK and a real JSONL process in fresh native sessions', async () => {
|
|
13
|
+
const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-native-'))
|
|
14
|
+
const log = join(cwd, 'initialize.jsonl')
|
|
15
|
+
const client = await createClient({ adapter: createClaudeAdapter({
|
|
16
|
+
command: fileURLToPath(new URL('../../adapter/claude/tests/fixtures/fake-claude.mjs', import.meta.url)),
|
|
17
|
+
executableRuntime: 'node', stateDir: join(cwd, 'state'), env: { FAKE_SCHEMA_PROBE: '1', FAKE_SCHEMA_LOG: log },
|
|
18
|
+
}), identity: { adapterId: 'claude', runtimeConfigId: 'workflow' } })
|
|
19
|
+
try {
|
|
20
|
+
const schema = z.object({ answer: z.literal(42) })
|
|
21
|
+
expect(await parallel([
|
|
22
|
+
() => agent('first', { client, cwd, schema }),
|
|
23
|
+
() => agent('second', { client, cwd, schema }),
|
|
24
|
+
])).toEqual([{ answer: 42 }, { answer: 42 }])
|
|
25
|
+
const records = (await readFile(log, 'utf8')).trim().split('\n').map(line => JSON.parse(line))
|
|
26
|
+
const structured = records.filter(record => record.schema)
|
|
27
|
+
expect(structured).toHaveLength(2)
|
|
28
|
+
expect(new Set(structured.map(record => record.sessionId)).size).toBe(2)
|
|
29
|
+
expect(structured[0].schema).toMatchObject({ type: 'object', properties: { answer: { const: 42 } } })
|
|
30
|
+
} finally {
|
|
31
|
+
await client.dispose()
|
|
32
|
+
await rm(cwd, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 })
|
|
33
|
+
}
|
|
34
|
+
}, 15_000)
|
|
35
|
+
|
|
36
|
+
test('Claude nominal success without native structured_output never falls back to prose', async () => {
|
|
37
|
+
const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-missing-'))
|
|
38
|
+
const client = await createClient({ adapter: createClaudeAdapter({
|
|
39
|
+
command: fileURLToPath(new URL('../../adapter/claude/tests/fixtures/fake-claude.mjs', import.meta.url)), executableRuntime: 'node', stateDir: cwd,
|
|
40
|
+
}), identity: { adapterId: 'claude', runtimeConfigId: 'missing' } })
|
|
41
|
+
try {
|
|
42
|
+
await expect(agent('missing', { client, cwd, schema: z.object({ answer: z.number() }) })).rejects.toMatchObject({ code: 'CLAUDE_STRUCTURED_OUTPUT_MISSING' })
|
|
43
|
+
} finally {
|
|
44
|
+
await client.dispose()
|
|
45
|
+
await rm(cwd, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 })
|
|
46
|
+
}
|
|
47
|
+
}, 15_000)
|
|
48
|
+
|
|
49
|
+
const codexCases = [
|
|
50
|
+
{ scenario: 'workflow-schema', expected: { answer: 42 }, description: 'returns a successful structured result' },
|
|
51
|
+
{ scenario: 'auth-expired', expected: null, description: 'returns null when authentication expires' },
|
|
52
|
+
] as const
|
|
53
|
+
|
|
54
|
+
for (const { scenario, expected, description } of codexCases) test(`Zod agent crosses Codex native process: ${description}`, async () => {
|
|
55
|
+
const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-codex-'))
|
|
56
|
+
const log = join(cwd, 'requests.jsonl')
|
|
57
|
+
const client = await createClient({ adapter: createCodexAdapter({ command: process.execPath,
|
|
58
|
+
args: [fileURLToPath(new URL('../../adapter/codex/tests/fake-app-server.mjs', import.meta.url))],
|
|
59
|
+
version: '0.164.0', env: { FAKE_SCENARIO: scenario, FAKE_LOG_FILE: log },
|
|
60
|
+
}), identity: { adapterId: 'codex', runtimeConfigId: scenario } })
|
|
61
|
+
try {
|
|
62
|
+
const value = await agent('answer', { client, cwd, schema: z.object({ answer: z.literal(42) }) })
|
|
63
|
+
expect(value).toEqual(expected)
|
|
64
|
+
const starts = (await readFile(log, 'utf8')).trim().split('\n').map(line => JSON.parse(line)).filter(frame => frame.method === 'turn/start')
|
|
65
|
+
expect(starts).toHaveLength(1)
|
|
66
|
+
expect(starts[0].params.outputSchema).toMatchObject({ type: 'object', properties: { answer: { const: 42 } } })
|
|
67
|
+
} finally {
|
|
68
|
+
await client.dispose()
|
|
69
|
+
await rm(cwd, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 })
|
|
70
|
+
}
|
|
71
|
+
}, 15_000)
|
|
@@ -64,13 +64,7 @@ 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
|
-
|
|
68
|
-
code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
|
|
69
|
-
retryable: false,
|
|
70
|
-
outcomeUnknown: false,
|
|
71
|
-
details: { issues: [{ path: '', code: 'required' }] },
|
|
72
|
-
})
|
|
73
|
-
for (const text of ['{"count":4,"extra":1}', '{"count":"4"}', 'null', '[]']) {
|
|
67
|
+
for (const text of ['{}', '{"count":4,"extra":1}', '{"count":"4"}', 'null', '[]']) {
|
|
74
68
|
await expect(output.parse(text)).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', retryable: false, outcomeUnknown: false })
|
|
75
69
|
}
|
|
76
70
|
})
|
|
@@ -96,11 +90,7 @@ test('sync and async refinements and formats validate locally and sanitize custo
|
|
|
96
90
|
} catch (error) {
|
|
97
91
|
failure = error
|
|
98
92
|
}
|
|
99
|
-
expect(failure).toMatchObject({
|
|
100
|
-
code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
|
|
101
|
-
outcomeUnknown: false,
|
|
102
|
-
details: { issues: [{ path: [], code: 'custom' }] },
|
|
103
|
-
})
|
|
93
|
+
expect(failure).toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', outcomeUnknown: false })
|
|
104
94
|
expect(JSON.stringify(failure)).not.toContain('private-')
|
|
105
95
|
}
|
|
106
96
|
await expect(output.parse('{"count":1,"email":"bad"}')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID' })
|
|
@@ -109,21 +99,15 @@ test('sync and async refinements and formats validate locally and sanitize custo
|
|
|
109
99
|
})
|
|
110
100
|
|
|
111
101
|
test('definite generated contradictions and external references are rejected', () => {
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
{
|
|
120
|
-
|
|
121
|
-
rule: 'unsatisfiableRequired',
|
|
122
|
-
},
|
|
123
|
-
]
|
|
124
|
-
for (const { schema, rule } of cases) {
|
|
125
|
-
expect(() => prepareOutputSchema(schema)).toThrow(expect.objectContaining({ code: 'INVALID_PARAMS', details: { rule } }))
|
|
126
|
-
}
|
|
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' }))
|
|
127
111
|
// Numeric bounds do not contradict a string instance.
|
|
128
112
|
expect(prepareOutputSchema(z.object({ a: z.string().meta({ minimum: 5, maximum: 1 }) })).schema.type).toBe('object')
|
|
129
113
|
expect(prepareOutputSchema(z.object({}).meta({ required: ['allowed'], patternProperties: { '^allowed$': { type: 'string' } } })).schema.type).toBe('object')
|
|
@@ -137,11 +121,6 @@ test('user schema callbacks cannot expose their exception or claim execution unc
|
|
|
137
121
|
} catch (cause) {
|
|
138
122
|
failure = cause
|
|
139
123
|
}
|
|
140
|
-
expect(failure).toMatchObject({
|
|
141
|
-
code: 'INVALID_PARAMS',
|
|
142
|
-
retryable: false,
|
|
143
|
-
outcomeUnknown: false,
|
|
144
|
-
details: { rule: 'invalidOrUnrepresentableSchema' },
|
|
145
|
-
})
|
|
124
|
+
expect(failure).toMatchObject({ code: 'INVALID_PARAMS', retryable: false, outcomeUnknown: false })
|
|
146
125
|
expect(String(failure)).not.toContain('private value')
|
|
147
126
|
})
|