@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,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,220 +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
- * Positive observation timeouts in milliseconds, up to 2,147,483,647 (the default).
28
- * The association wait begins at submission and the result wait begins after association.
29
- * Expiry rejects with an unknown outcome and does not interrupt native execution.
30
- * These limits do not affect journal replay identity.
31
- */
32
- wait?: { associationMs?: number; resultMs?: number }
33
- }
34
-
35
- const LONG_OBSERVATION_TIMEOUT_MS = 0x7fffffff
36
-
37
- /** Capture session settings and prepare structured output before any asynchronous work. */
38
- export function prepareAgentCall(options: AgentOptions) {
39
- const { client, cwd, model, instructions, permissionMode, schema, outputFallback, wait } = options
40
- const timeouts = wait && { associationMs: wait.associationMs, resultMs: wait.resultMs }
41
- for (const timeout of [timeouts?.associationMs, timeouts?.resultMs]) {
42
- if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0 || timeout > LONG_OBSERVATION_TIMEOUT_MS)) {
43
- throw new HarnessSdkError('INVALID_PARAMS', 'Agent observation timeouts must be positive and at most 2,147,483,647 ms')
44
- }
45
- }
46
- return {
47
- client, cwd, model, instructions, permissionMode, outputFallback,
48
- wait: timeouts,
49
- output: schema === undefined ? undefined : prepareOutputSchema(schema),
50
- }
51
- }
52
-
53
- export type PreparedAgentCall = ReturnType<typeof prepareAgentCall>
54
-
55
- /**
56
- * Run a fresh call for agent outside a workflow or for executeJournaledAgent after it publishes
57
- * its started marker and rechecks dispatch. Release the acquired session before returning the
58
- * completed or dropped outcome or throwing an execution or release failure.
59
- */
60
- export async function executeAgent(prompt: string, call: PreparedAgentCall): Promise<SettledAgentOutcome> {
61
- const { output, outputFallback, wait } = call
62
- const opening = openAgentSession(call)
63
- let session: Session
64
- try {
65
- session = await opening
66
- } catch (cause) {
67
- if (isStartupBlockException(cause)) return { status: 'dropped', error: summarizeAgentError(cause) }
68
- throw cause
69
- }
70
- const outcome = await observeAgentTurn({ session, prompt, output, outputFallback, wait })
71
- const cleanupErrors = await releaseAgentSession(session)
72
- return settleAgentOutcome(outcome, cleanupErrors)
73
- }
74
-
75
- /** Completed or dropped execution after successful session release. */
76
- type SettledAgentOutcome =
77
- | { status: 'completed'; value: string | Record<string, unknown> }
78
- | { status: 'dropped'; error: AgentErrorSummary }
79
-
80
- type AgentOutcome =
81
- | SettledAgentOutcome
82
- | { status: 'failed'; error: HarnessSdkError }
83
-
84
- /** Safe diagnostics retained from cleanup and dropped terminals without native messages. */
85
- interface AgentErrorSummary {
86
- code: string
87
- outcomeUnknown: boolean
88
- }
89
-
90
- interface AgentTurnRequest {
91
- session: Session
92
- prompt: string
93
- output: AgentOutputSchema | undefined
94
- outputFallback: AgentOptions['outputFallback']
95
- wait: AgentOptions['wait']
96
- }
97
-
98
- /** Request a fresh session and give executeAgent ownership when it attaches. */
99
- function openAgentSession({ client, cwd, model, instructions, permissionMode }: Pick<
100
- AgentOptions, 'client' | 'cwd' | 'model' | 'instructions' | 'permissionMode'
101
- >): Promise<Session> {
102
- return client.sessions.create({
103
- cwd,
104
- ...(model !== undefined ? { model } : {}),
105
- ...(instructions !== undefined ? { instructions } : {}),
106
- ...(permissionMode !== undefined ? { permissionMode } : {}),
107
- })
108
- }
109
-
110
- /**
111
- * Submit once, then await the associated turn's retained terminal result and any local validation.
112
- * Return execution evidence to executeAgent, which owns session release and final settlement.
113
- */
114
- async function observeAgentTurn(request: AgentTurnRequest): Promise<AgentOutcome> {
115
- const { session, output, wait } = request
116
- try {
117
- const submission = agentSubmission(request)
118
- const turn = await session.submit(submission, { timeoutMs: wait?.associationMs ?? LONG_OBSERVATION_TIMEOUT_MS })
119
- const result = await turn.result({ timeoutMs: wait?.resultMs ?? LONG_OBSERVATION_TIMEOUT_MS })
120
- if (result.status === 'completed') {
121
- return { status: 'completed', value: output ? await output.parse(result.text) : result.text }
122
- }
123
- return classifyTerminalFailure(result.status, result.error)
124
- } catch (cause) {
125
- if (isStartupBlockException(cause)) return { status: 'dropped', error: summarizeAgentError(cause) }
126
- return { status: 'failed', error: sdkError(cause, 'AGENT_FAILED', true) }
127
- }
128
- }
129
-
130
- /**
131
- * Build observeAgentTurn's single submission using the attached session's capabilities.
132
- * With structured output requested, use its schema route or the opted-in JSON text prompt.
133
- * Throw CAPABILITY_UNSUPPORTED before submission if neither route is available.
134
- */
135
- function agentSubmission({ session, prompt, output, outputFallback }: AgentTurnRequest): SubmitOptions {
136
- if (!output) return { input: prompt }
137
- if (session.capabilities.turn?.outputSchema) return { input: prompt, outputSchema: output.schema }
138
- if (outputFallback !== 'json-text') {
139
- throw new HarnessSdkError('CAPABILITY_UNSUPPORTED', 'Session does not support structured output')
140
- }
141
- const instruction = 'Return the final answer as a single JSON object that matches this JSON Schema. Do not include Markdown fences or surrounding prose.'
142
- return { input: `${prompt}\n\n${instruction}\n${JSON.stringify(output.schema)}` }
143
- }
144
-
145
- /**
146
- * Classify a retained failed or interrupted terminal for observeAgentTurn to return to executeAgent.
147
- * Only confirmed outcomes qualify for a drop. Tagged startup denial qualifies in either status,
148
- * explicit skip applies to interruption, and the terminal API allowlist applies to failure.
149
- * Retain other errors for rejection after cleanup and supply AGENT_INTERRUPTED when details are absent.
150
- */
151
- function classifyTerminalFailure(status: 'failed' | 'interrupted', error: HarnessError | undefined): AgentOutcome {
152
- if (!error) return { status: 'failed', error: new HarnessSdkError('AGENT_INTERRUPTED') }
153
- if (!error.outcomeUnknown) {
154
- const explicitSkip = status === 'interrupted' && error.details?.workflowDisposition === 'skipped'
155
- if (explicitSkip || isStartupBlocked(error) || (status === 'failed' && terminalApiErrors.has(error.code))) {
156
- return { status: 'dropped', error: summarizeAgentError(error) }
157
- }
158
- }
159
- return {
160
- status: 'failed',
161
- error: new HarnessSdkError(error.code, error.message, error.retryable, error.outcomeUnknown, error.details),
162
- }
163
- }
164
-
165
- /** Project errors to the code and uncertainty exposed in agent's cleanup diagnostics. */
166
- function summarizeAgentError(error: AgentErrorSummary): AgentErrorSummary {
167
- return { code: error.code, outcomeUnknown: error.outcomeUnknown }
168
- }
169
-
170
- /**
171
- * Release executeAgent's session in close/dispose order. Attempt disposal after close failure
172
- * and return distinct normalized SDK error instances as safe diagnostics in encounter order.
173
- */
174
- async function releaseAgentSession(session: Session): Promise<AgentErrorSummary[]> {
175
- const cleanupErrors = new Set<HarnessSdkError>()
176
- for (const method of ['close', 'dispose'] as const) {
177
- try {
178
- await session[method]()
179
- } catch (cause) {
180
- cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true))
181
- }
182
- }
183
- return [...cleanupErrors].map(summarizeAgentError)
184
- }
185
-
186
- /**
187
- * Settle executeAgent after both release attempts. Return completed or dropped outcomes on successful cleanup.
188
- * Throw the primary failure with any cleanup diagnostics, or RESOURCE_RELEASE_FAILED if cleanup
189
- * was the only failure.
190
- */
191
- function settleAgentOutcome(outcome: AgentOutcome, errors: AgentErrorSummary[]): SettledAgentOutcome {
192
- if (errors.length) {
193
- if (outcome.status === 'failed') {
194
- const failure = outcome.error
195
- const prior = failure.details?.cleanupErrors
196
- throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown,
197
- { ...failure.details, cleanupErrors: [...(Array.isArray(prior) ? prior : []), ...errors] })
198
- }
199
- throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false,
200
- errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) })
201
- }
202
- if (outcome.status === 'failed') throw outcome.error
203
- return outcome
204
- }
205
-
206
- /** Share the startup-denial rule between classifyTerminalFailure and isStartupBlockException.
207
- * The adapter must supply the dedicated code, a confirmed outcome and the startup disposition. */
208
- function isStartupBlocked(error: Pick<HarnessSdkError, 'code' | 'outcomeUnknown' | 'details'>): boolean {
209
- return !error.outcomeUnknown && error.code === 'AGENT_STARTUP_BLOCKED' && error.details?.workflowDisposition === 'startup_blocked'
210
- }
211
-
212
- /** Recognize a thrown SDK startup denial during session creation or turn observation. */
213
- function isStartupBlockException(cause: unknown): cause is HarnessSdkError {
214
- return cause instanceof HarnessSdkError && isStartupBlocked(cause)
215
- }
216
-
217
- // Only apply to native failed terminal results, never open/submit/observation failures.
218
- const terminalApiErrors = new Set([
219
- 'AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE',
220
- ])
@@ -1,83 +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
- * The optional callback observes replacement before the directory flush, which can still fail.
22
- * If temporary-file cleanup fails, the rejection includes both failures. */
23
- export async function atomicPublish(path: string, value: unknown, onReplace?: () => void): 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
- onReplace?.()
45
- await syncDirectory(dirname(path))
46
- }
47
-
48
- /** Read strict JSON from a regular file and always close its descriptor. Check the final
49
- * component with lstat and verify the opened inode to catch replacement during open.
50
- * Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
51
- * filesystem failures and validates the returned value against the checkpoint schema. */
52
- export async function readJson(path: string): Promise<JsonValue> {
53
- const before = await lstat(path)
54
- if (!before.isFile()) return invalidCheckpoint()
55
- const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
56
- try {
57
- const current = await file.stat()
58
- if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino) return invalidCheckpoint()
59
- return parseCheckpointJson(await file.readFile('utf8'))
60
- } finally {
61
- await file.close()
62
- }
63
- }
64
-
65
- /** Normalize failures caught by openFileRun, FileRunHandle and AgentJournal.append.
66
- * Preserve SDK errors by identity; report other failures as WORKFLOW_STORAGE_FAILED
67
- * without passing filesystem diagnostics to workflow consumers. */
68
- export function storageError(cause: unknown): HarnessSdkError {
69
- if (cause instanceof HarnessSdkError) return cause
70
- return new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
71
- }
72
-
73
- /** Map malformed or nonrepresentable JSON to checkpoint corruption before schema validation.
74
- * JSON.parse alone accepts number literals that overflow to Infinity. */
75
- function parseCheckpointJson(text: string): JsonValue {
76
- try {
77
- const value = JSON.parse(text) as JsonValue
78
- canonicalJson(value)
79
- return value
80
- } catch {
81
- return invalidCheckpoint()
82
- }
83
- }
@@ -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
- }