@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.
@@ -1,121 +0,0 @@
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, type Client, type StructuredOutputToolDefinition } from '@anureo/sdk'
8
- import { createAcpAdapter } from '@anureo/adapter-acp'
9
- import { createClaudeAdapter } from '@anureo/adapter-claude'
10
- import { createCodexAdapter } from '@anureo/adapter-codex'
11
- import { createPiAdapter } from '@anureo/adapter-pi'
12
- import { fakeFactory } from '../../adapter/pi/tests/fake-host'
13
- import { agent, parallel } from './index'
14
-
15
- const fakeClaude = fileURLToPath(new URL('../../adapter/claude/tests/fixtures/fake-claude.mjs', import.meta.url))
16
-
17
- test('Zod agent crosses the official Claude SDK and a real JSONL process in fresh native sessions', async () => {
18
- const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-native-'))
19
- const log = join(cwd, 'initialize.jsonl')
20
- const client = await createClient({ adapter: createClaudeAdapter({
21
- command: fakeClaude,
22
- executableRuntime: 'node', stateDir: join(cwd, 'state'), env: { FAKE_SCHEMA_PROBE: '1', FAKE_SCHEMA_LOG: log },
23
- }), identity: { adapterId: 'claude', runtimeConfigId: 'workflow' } })
24
- try {
25
- const schema = z.object({ answer: z.literal(42) })
26
- expect(await parallel([
27
- () => agent('first', { client, cwd, schema }),
28
- () => agent('second', { client, cwd, schema }),
29
- ])).toEqual([{ answer: 42 }, { answer: 42 }])
30
- const records = await readNativeLog(log)
31
- const structured = records.filter(record => record.schema)
32
- expect(structured).toHaveLength(2)
33
- expect(new Set(structured.map(record => record.sessionId)).size).toBe(2)
34
- expect(structured[0].schema).toMatchObject({ type: 'object', properties: { answer: { const: 42 } } })
35
- } finally {
36
- await releaseNativeFixture(client, cwd)
37
- }
38
- }, 15_000)
39
-
40
- test('Claude nominal success without native structured_output never falls back to prose', async () => {
41
- const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-missing-'))
42
- const client = await createClient({ adapter: createClaudeAdapter({
43
- command: fakeClaude, executableRuntime: 'node', stateDir: cwd,
44
- }), identity: { adapterId: 'claude', runtimeConfigId: 'missing' } })
45
- try {
46
- await expect(agent('missing', { client, cwd, schema: z.object({ answer: z.number() }) })).rejects.toMatchObject({ code: 'CLAUDE_STRUCTURED_OUTPUT_MISSING' })
47
- } finally {
48
- await releaseNativeFixture(client, cwd)
49
- }
50
- }, 15_000)
51
-
52
- const codexCases = [
53
- { scenario: 'workflow-schema', expected: { answer: 42 }, description: 'returns a successful structured result' },
54
- { scenario: 'auth-expired', expected: null, description: 'returns null when authentication expires' },
55
- ] as const
56
-
57
- for (const { scenario, expected, description } of codexCases) test(`Zod agent crosses Codex native process: ${description}`, async () => {
58
- const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-codex-'))
59
- const log = join(cwd, 'requests.jsonl')
60
- const client = await createClient({ adapter: createCodexAdapter({ command: process.execPath,
61
- args: [fileURLToPath(new URL('../../adapter/codex/tests/fake-app-server.mjs', import.meta.url))],
62
- version: '0.164.0', env: { FAKE_SCENARIO: scenario, FAKE_LOG_FILE: log },
63
- }), identity: { adapterId: 'codex', runtimeConfigId: scenario } })
64
- try {
65
- const value = await agent('answer', { client, cwd, schema: z.object({ answer: z.literal(42) }) })
66
- expect(value).toEqual(expected)
67
- const starts = (await readNativeLog(log)).filter(frame => frame.method === 'turn/start')
68
- expect(starts).toHaveLength(1)
69
- expect(starts[0].params.outputSchema).toMatchObject({ type: 'object', properties: { answer: { const: 42 } } })
70
- } finally {
71
- await releaseNativeFixture(client, cwd)
72
- }
73
- }, 15_000)
74
-
75
- test('workflow Zod output uses MCP and retains local refinement failures', async () => {
76
- const adapter = createAcpAdapter({ command: process.execPath, args: [fileURLToPath(new URL('../../adapter/acp/tests/fixtures/fake-acp.mjs', import.meta.url)), '--scenario', 'mcp-output'] })
77
- const client = await createClient({ adapter, identity: { adapterId: 'acp', runtimeConfigId: 'workflow-mcp' } })
78
- try {
79
- const options = { client, cwd: process.cwd() }
80
- const schema = z.object({ sum: z.number().int() })
81
- const value = await agent('17 + 25', { ...options, schema })
82
- expect(value).toEqual({ sum: 42 })
83
- await expect(agent('17 + 25', { ...options, schema: schema.refine(value => value.sum < 0) }))
84
- .rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', outcomeUnknown: false })
85
- } finally { await client.dispose() }
86
- })
87
-
88
- test('workflow schema uses direct Pi tools and retains Zod refinement validation', async () => {
89
- const fake = fakeFactory(host => {
90
- let output: StructuredOutputToolDefinition | undefined
91
- Object.assign(host, {
92
- /** Store the SDK's tool for the host script. The Pi adapter forwards an omitted tool to clear it. */
93
- async setOutputTool(tool?: StructuredOutputToolDefinition) { output = tool },
94
- })
95
- host.script = async host => {
96
- if (!output) throw new Error('Output tool must be registered before scripted execution')
97
- await output.execute({ sum: 42 })
98
- await host.assistant('submitted')
99
- }
100
- })
101
- const client = await createClient({ adapter: createPiAdapter({ version: '1.5.2', createHost: fake.factory }), identity: { adapterId: 'pi', runtimeConfigId: 'workflow-direct-tool' } })
102
- try {
103
- const options = { client, cwd: process.cwd() }
104
- const schema = z.object({ sum: z.number().int() })
105
- expect(await agent('17 + 25', { ...options, schema })).toEqual({ sum: 42 })
106
- await expect(agent('17 + 25', { ...options, schema: schema.refine(value => value.sum < 0) }))
107
- .rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', outcomeUnknown: false })
108
- expect(fake.opens.every(open => !Object.hasOwn(open, 'mcpServers'))).toBe(true)
109
- } finally { await client.dispose() }
110
- })
111
-
112
- /** Read the fixture's JSONL records in write order. Missing logs or malformed records fail the test. */
113
- async function readNativeLog(path: string) {
114
- return (await readFile(path, 'utf8')).trim().split('\n').map(line => JSON.parse(line))
115
- }
116
-
117
- /** Remove fixture files after client disposal succeeds. Either failure rejects the test. */
118
- async function releaseNativeFixture(client: Client, cwd: string): Promise<void> {
119
- await client.dispose()
120
- await rm(cwd, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 })
121
- }
@@ -1,201 +0,0 @@
1
- import type { HarnessError } from '@anureo/protocol'
2
- import { HarnessSdkError, sdkError, type Client, type Session, type SubmitOptions } from '@anureo/sdk'
3
- import type { z } from 'zod'
4
- import { prepareOutputSchema, type AgentOutputSchema } from './output-schema'
5
-
6
- /** Configure an agent call. Keep the client usable until settlement and dispose it separately. */
7
- export interface AgentOptions<S extends z.ZodObject = z.ZodObject> {
8
- /** Initialized client selecting the backend. The caller owns client disposal. */
9
- client: Client
10
- /** Working directory forwarded to the fresh session. */
11
- cwd: string
12
- /** Backend model selection. Omit to use the backend's selection. */
13
- model?: string
14
- /** Session instructions, separate from the input prompt. */
15
- instructions?: string
16
- /** Permission mode forwarded to the fresh session. Accepted values and defaults depend on the backend. */
17
- permissionMode?: string
18
- /** Portable Zod object schema with closed objects and required JSON fields. Omit to return text. */
19
- schema?: S
20
- /**
21
- * With a schema, opt in to prompting for JSON when the session lacks structured output.
22
- * With a schema and no fallback, an unsupported session causes agent to reject before submission.
23
- * In a workflow this option contributes to replay identity even in text mode.
24
- */
25
- outputFallback?: 'json-text'
26
- }
27
-
28
- /**
29
- * Run a fresh call for agent outside a workflow or for executeJournaledAgent after it publishes
30
- * its started marker and rechecks dispatch. Prepare the supplied schema before opening, then
31
- * release the acquired session before resolving with text, data or null, or rejecting with an
32
- * execution or release failure. The caller retains the Client. executeJournaledAgent uses the
33
- * settled outcome to publish a terminal journal event.
34
- */
35
- export async function executeAgent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
36
- const { client, cwd, model, instructions, permissionMode, schema } = options
37
- const output = schema === undefined ? undefined : prepareOutputSchema(schema)
38
- const session = await openAgentSession({ client, cwd, model, instructions, permissionMode })
39
- if (!session) return null // A failed open never hands session ownership to this call.
40
- const outcome = await observeAgentTurn({ session, prompt, output, outputFallback: options.outputFallback })
41
- const cleanupErrors = await releaseAgentSession(session)
42
- return settleAgentOutcome(outcome, cleanupErrors)
43
- }
44
-
45
- // Give association and terminal observation the longest supported timer delay for model execution.
46
- const LONG_OBSERVATION_TIMEOUT_MS = 0x7fffffff
47
-
48
- /** Execution evidence retained until cleanup has settled, before returning or rejecting the call. */
49
- type AgentOutcome =
50
- | { status: 'completed'; value: string | Record<string, unknown> }
51
- | { status: 'dropped'; error: AgentErrorSummary }
52
- | { status: 'failed'; error: HarnessSdkError }
53
-
54
- /** Safe diagnostics retained from cleanup and dropped terminals without native messages. */
55
- interface AgentErrorSummary {
56
- code: string
57
- outcomeUnknown: boolean
58
- }
59
-
60
- interface AgentTurnRequest {
61
- session: Session
62
- prompt: string
63
- output: AgentOutputSchema | undefined
64
- outputFallback: AgentOptions['outputFallback']
65
- }
66
-
67
- /**
68
- * Give executeAgent ownership of the attached session. A confirmed startup denial from the open
69
- * promise resolves to null. Other rejections and synchronous request setup errors propagate.
70
- */
71
- function openAgentSession({ client, cwd, model, instructions, permissionMode }: Pick<
72
- AgentOptions, 'client' | 'cwd' | 'model' | 'instructions' | 'permissionMode'
73
- >): Promise<Session | null> {
74
- return client.sessions.create({
75
- cwd,
76
- ...(model !== undefined ? { model } : {}),
77
- ...(instructions !== undefined ? { instructions } : {}),
78
- ...(permissionMode !== undefined ? { permissionMode } : {}),
79
- })
80
- .catch(cause => {
81
- if (isStartupBlockException(cause)) return null
82
- throw cause
83
- })
84
- }
85
-
86
- /**
87
- * Submit once, then await the associated turn's retained terminal result and any local validation.
88
- * Return execution evidence to executeAgent, which owns session release and final settlement.
89
- */
90
- async function observeAgentTurn(request: AgentTurnRequest): Promise<AgentOutcome> {
91
- const { session, output } = request
92
- try {
93
- const submission = agentSubmission(request)
94
- const turn = await session.submit(submission, { timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
95
- const result = await turn.result({ timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
96
- if (result.status === 'completed') {
97
- return { status: 'completed', value: output ? await output.parse(result.text) : result.text }
98
- }
99
- return classifyTerminalFailure(result.status, result.error)
100
- } catch (cause) {
101
- if (isStartupBlockException(cause)) return { status: 'dropped', error: summarizeAgentError(cause) }
102
- return { status: 'failed', error: sdkError(cause, 'AGENT_FAILED', true) }
103
- }
104
- }
105
-
106
- /**
107
- * Build observeAgentTurn's single submission using the attached session's capabilities.
108
- * With structured output requested, use its schema route or the opted-in JSON text prompt.
109
- * Throw CAPABILITY_UNSUPPORTED before submission if neither route is available.
110
- */
111
- function agentSubmission({ session, prompt, output, outputFallback }: AgentTurnRequest): SubmitOptions {
112
- if (!output) return { input: prompt }
113
- if (session.capabilities.turn?.outputSchema) return { input: prompt, outputSchema: output.schema }
114
- if (outputFallback !== 'json-text') {
115
- throw new HarnessSdkError('CAPABILITY_UNSUPPORTED', 'Session does not support structured output')
116
- }
117
- const instruction = 'Return the final answer as a single JSON object that matches this JSON Schema. Do not include Markdown fences or surrounding prose.'
118
- return { input: `${prompt}\n\n${instruction}\n${JSON.stringify(output.schema)}` }
119
- }
120
-
121
- /**
122
- * Classify a retained failed or interrupted terminal for observeAgentTurn to return to executeAgent.
123
- * Only confirmed outcomes qualify for a drop. Tagged startup denial qualifies in either status,
124
- * explicit skip applies to interruption, and the terminal API allowlist applies to failure.
125
- * Retain other errors for rejection after cleanup and supply AGENT_INTERRUPTED when details are absent.
126
- */
127
- function classifyTerminalFailure(status: 'failed' | 'interrupted', error: HarnessError | undefined): AgentOutcome {
128
- if (!error) return { status: 'failed', error: new HarnessSdkError('AGENT_INTERRUPTED') }
129
- if (!error.outcomeUnknown) {
130
- const explicitSkip = status === 'interrupted' && error.details?.workflowDisposition === 'skipped'
131
- if (explicitSkip || isStartupBlocked(error) || (status === 'failed' && terminalApiErrors.has(error.code))) {
132
- return { status: 'dropped', error: summarizeAgentError(error) }
133
- }
134
- }
135
- return {
136
- status: 'failed',
137
- error: new HarnessSdkError(error.code, error.message, error.retryable, error.outcomeUnknown, error.details),
138
- }
139
- }
140
-
141
- /** Project errors to the code and uncertainty exposed in agent's cleanup diagnostics. */
142
- function summarizeAgentError(error: AgentErrorSummary): AgentErrorSummary {
143
- return { code: error.code, outcomeUnknown: error.outcomeUnknown }
144
- }
145
-
146
- /**
147
- * Release executeAgent's session in close/dispose order. Attempt disposal after close failure
148
- * and return distinct normalized SDK error instances as safe diagnostics in encounter order.
149
- */
150
- async function releaseAgentSession(session: Session): Promise<AgentErrorSummary[]> {
151
- const cleanupErrors = new Set<HarnessSdkError>()
152
- for (const method of ['close', 'dispose'] as const) {
153
- try {
154
- await session[method]()
155
- } catch (cause) {
156
- cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true))
157
- }
158
- }
159
- return [...cleanupErrors].map(summarizeAgentError)
160
- }
161
-
162
- /**
163
- * Settle executeAgent after both release attempts. Return text/data or null on successful cleanup.
164
- * Throw the primary failure with any cleanup diagnostics, or RESOURCE_RELEASE_FAILED if cleanup
165
- * was the only failure.
166
- */
167
- function settleAgentOutcome(outcome: AgentOutcome, errors: AgentErrorSummary[]): string | Record<string, unknown> | null {
168
- if (errors.length) {
169
- if (outcome.status === 'failed') {
170
- const failure = outcome.error
171
- throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown,
172
- { ...failure.details, cleanupErrors: errors })
173
- }
174
- throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false,
175
- errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) })
176
- }
177
- switch (outcome.status) {
178
- case 'completed': return outcome.value
179
- case 'dropped': return null
180
- case 'failed': throw outcome.error
181
- }
182
- }
183
-
184
- /** Share the startup-denial rule between classifyTerminalFailure and isStartupBlockException.
185
- * The adapter must supply the dedicated code, a confirmed outcome and the startup disposition. */
186
- function isStartupBlocked(error: Pick<HarnessSdkError, 'code' | 'outcomeUnknown' | 'details'>): boolean {
187
- return !error.outcomeUnknown && error.code === 'AGENT_STARTUP_BLOCKED' && error.details?.workflowDisposition === 'startup_blocked'
188
- }
189
-
190
- /**
191
- * Recognize a thrown SDK startup denial. openAgentSession returns null for a matching rejection
192
- * from session creation. observeAgentTurn records a drop candidate and leaves settlement to cleanup.
193
- */
194
- function isStartupBlockException(cause: unknown): cause is HarnessSdkError {
195
- return cause instanceof HarnessSdkError && isStartupBlocked(cause)
196
- }
197
-
198
- // Only apply to native failed terminal results, never open/submit/observation failures.
199
- const terminalApiErrors = new Set([
200
- 'AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE',
201
- ])
@@ -1,82 +0,0 @@
1
- import { randomUUID } from 'node:crypto'
2
- import { constants } from 'node:fs'
3
- import { lstat, open, rename, unlink } from 'node:fs/promises'
4
- import { dirname } from 'node:path'
5
- import { HarnessSdkError } from '@anureo/sdk'
6
- import { canonicalJson, type JsonValue } from './json'
7
- import { invalidCheckpoint } from './records'
8
-
9
- /** Flush directory-entry changes and close the directory handle. I/O failures reject.
10
- * On Windows this resolves without a flush because Node does not provide directory fsync. */
11
- export async function syncDirectory(path: string): Promise<void> {
12
- if (process.platform === 'win32') return
13
- const directory = await open(path, 'r')
14
- try { await directory.sync() } finally { await directory.close() }
15
- }
16
-
17
- /** Publish one complete checkpoint by renaming a flushed sibling temporary file, then flush
18
- * its parent directory where supported. FileRunHandle and AgentJournal serialize their own
19
- * writes because a rename alone cannot prevent an older snapshot from overwriting a newer one.
20
- * The caller creates the parent. Invalid JSON rejects before any file I/O.
21
- * A directory flush can fail after replacement.
22
- * If temporary-file cleanup fails, the rejection includes both failures. */
23
- export async function atomicPublish(path: string, value: unknown): Promise<void> {
24
- const text = `${canonicalJson(value)}\n`
25
- const temporary = `${path}.${randomUUID()}.tmp`
26
- // An exclusive open establishes ownership. Cleanup must leave an existing file alone.
27
- const file = await open(temporary, 'wx', 0o600)
28
- try {
29
- try {
30
- await file.writeFile(text, 'utf8')
31
- await file.sync()
32
- } finally {
33
- await file.close()
34
- }
35
- await rename(temporary, path)
36
- } catch (cause) {
37
- try {
38
- await unlink(temporary)
39
- } catch (cleanup) {
40
- throw new AggregateError([cause, cleanup], 'Atomic publish failed')
41
- }
42
- throw cause
43
- }
44
- await syncDirectory(dirname(path))
45
- }
46
-
47
- /** Read strict JSON from a regular file and always close its descriptor. Check the final
48
- * component with lstat and verify the opened inode to catch replacement during open.
49
- * Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
50
- * filesystem failures and validates the returned value against the checkpoint schema. */
51
- export async function readJson(path: string): Promise<JsonValue> {
52
- const before = await lstat(path)
53
- if (!before.isFile()) return invalidCheckpoint()
54
- const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
55
- try {
56
- const current = await file.stat()
57
- if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino) return invalidCheckpoint()
58
- return parseCheckpointJson(await file.readFile('utf8'))
59
- } finally {
60
- await file.close()
61
- }
62
- }
63
-
64
- /** Normalize failures caught by openFileRun, FileRunHandle and AgentJournal.append.
65
- * Preserve SDK errors by identity; report other failures as WORKFLOW_STORAGE_FAILED
66
- * without passing filesystem diagnostics to workflow consumers. */
67
- export function storageError(cause: unknown): HarnessSdkError {
68
- if (cause instanceof HarnessSdkError) return cause
69
- return new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
70
- }
71
-
72
- /** Map malformed or nonrepresentable JSON to checkpoint corruption before schema validation.
73
- * JSON.parse alone accepts number literals that overflow to Infinity. */
74
- function parseCheckpointJson(text: string): JsonValue {
75
- try {
76
- const value = JSON.parse(text) as JsonValue
77
- canonicalJson(value)
78
- return value
79
- } catch {
80
- return invalidCheckpoint()
81
- }
82
- }
@@ -1,23 +0,0 @@
1
- // Scripted client setup shared by workflow tests; each suite retains its own disposal registry.
2
- import { randomUUID } from 'node:crypto'
3
- import { createClient, type Client } from '@anureo/sdk'
4
- import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
5
-
6
- /**
7
- * Give the agent and workflow suites a factory for initialized scripted clients. Register each
8
- * initialized client in the caller's registry. Both suites dispose those clients in afterEach.
9
- * Initialization failures reject before registration.
10
- */
11
- export function createFixture(clients: Client[]) {
12
- /**
13
- * Forward optional hook and capability overrides to the scripted adapter. Return the initialized
14
- * client and adapter for dispatch assertions. Give each fixture a distinct runtime identity so
15
- * journal replay can distinguish clients.
16
- */
17
- return async function fixture(options?: FakeAdapterOptions) {
18
- const adapter = createScriptedAdapter(options)
19
- const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
20
- clients.push(client)
21
- return { client, adapter }
22
- }
23
- }