@anureo/workflow 0.0.0-stage → 0.3.1

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.
@@ -0,0 +1,333 @@
1
+ import { afterEach, expect, test } from 'bun:test'
2
+ import { randomUUID } from 'node:crypto'
3
+ import type { FakeAdapterOptions } from '@anureo/conformance'
4
+ import type { HarnessError } from '@anureo/protocol'
5
+ import { HarnessSdkError, type Client, type SessionEventSink } from '@anureo/sdk'
6
+ import { z } from 'zod'
7
+ import { agent, parallel, pipeline, type AgentOptions } from './index'
8
+ import { createFixture } from './test-helpers'
9
+
10
+ const clients: Client[] = []
11
+ const fixture = createFixture(clients)
12
+ afterEach(async () => { await Promise.all(clients.splice(0).map(client => client.dispose())) })
13
+
14
+ /** Publish final text before the test terminal so Turn.result retains it. */
15
+ async function complete(sink: SessionEventSink, turnId: string, text: string) {
16
+ await sink.emit({ type: 'item/completed', payload: { item: { id: randomUUID(), type: 'agentMessage', phase: 'final', text } } }, { turnId })
17
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
18
+ }
19
+
20
+ /**
21
+ * Supply the execute hook awaited by the scripted backend. For a submit, publish the start and
22
+ * await the test's event callback before replying with the same turn ID. A callback rejection
23
+ * fails the dispatch. Other calls fall through to the default adapter.
24
+ */
25
+ function scriptSubmission(
26
+ publish: (submission: { sink: SessionEventSink; turnId: string; submissionId: string }) => Promise<void>,
27
+ ): NonNullable<FakeAdapterOptions['execute']> {
28
+ return async (call, sink) => {
29
+ if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
30
+ const { submissionId } = call.params
31
+ const turnId = randomUUID()
32
+ await sink.emit({ type: 'turn/started', payload: { turnId } })
33
+ await publish({ sink, turnId, submissionId })
34
+ return { submissionId, accepted: true, disposition: 'started', turnId }
35
+ }
36
+ }
37
+
38
+ test('returns text from independent sessions and leaves the borrowed client usable', async () => {
39
+ const { client, adapter } = await fixture()
40
+ expect(await parallel([
41
+ () => agent('first', { client, cwd: process.cwd(), model: 'test-model', instructions: 'review carefully' }),
42
+ () => agent('second', { client, cwd: process.cwd() }),
43
+ ])).toEqual(['first', 'second'])
44
+ expect(adapter.opened).toHaveLength(2)
45
+ expect(new Set(adapter.opened.map(session => session.binding.sessionId)).size).toBe(2)
46
+ expect(adapter.opened[0]).toMatchObject({ cwd: process.cwd(), model: 'test-model', instructions: 'review carefully' })
47
+ expect([...adapter.backends.values()].every(backend => backend.disposeCount === 1)).toBe(true)
48
+ expect(adapter.disposeCount).toBe(0)
49
+ expect(await agent('third', { client, cwd: process.cwd() })).toBe('third')
50
+ })
51
+
52
+ test('each call chooses its backend explicitly without shared configuration', async () => {
53
+ const a = await fixture(), b = await fixture()
54
+ expect(await parallel([
55
+ () => agent('backend a', { client: a.client, cwd: '/a' }),
56
+ () => agent('backend b', { client: b.client, cwd: '/b' }),
57
+ ])).toEqual(['backend a', 'backend b'])
58
+ expect(a.adapter.opened[0]?.cwd).toBe('/a')
59
+ expect(b.adapter.opened[0]?.cwd).toBe('/b')
60
+ })
61
+
62
+ test('native association and acceptance do not replace terminal evidence', async () => {
63
+ const { promise: terminalEmitterReady, resolve: resolveTerminalEmitter } = Promise.withResolvers<() => Promise<void>>()
64
+ const { client, adapter } = await fixture({ execute: async (call, sink) => {
65
+ if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
66
+ const turnId = randomUUID()
67
+ await sink.emit({ type: 'turn/started', payload: { turnId } })
68
+ await sink.bindSubmission(call.params.submissionId, turnId)
69
+ resolveTerminalEmitter(() => complete(sink, turnId, 'actual terminal text'))
70
+ return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
71
+ } })
72
+ let settled = false
73
+ const result = agent('wait for native work', { client, cwd: process.cwd() }).then(text => { settled = true; return text })
74
+ const emitTerminal = await terminalEmitterReady
75
+ expect(settled).toBe(false)
76
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(false)
77
+ await emitTerminal()
78
+ expect(await result).toBe('actual terminal text')
79
+ })
80
+
81
+ test('preserves native failure details and releases the session', async () => {
82
+ const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
83
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
84
+ code: 'NATIVE_FAILED', message: 'native failure', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
85
+ } } })
86
+ }) })
87
+ await expect(agent('fail', { client, cwd: process.cwd() })).rejects.toMatchObject({
88
+ code: 'NATIVE_FAILED', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
89
+ })
90
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(true)
91
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
92
+ })
93
+
94
+ test('an interrupted execution cannot return successful text', async () => {
95
+ const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
96
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'interrupted' } })
97
+ }) })
98
+ await expect(agent('interrupted', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
99
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
100
+ })
101
+
102
+ test('unknown submission outcomes are preserved without retries or implicit interrupts', async () => {
103
+ const failure = new HarnessSdkError('RECEIPT_LOST', 'receipt lost', false, true)
104
+ const { client, adapter } = await fixture({ execute: async call => {
105
+ if (call.method === 'input/submit') throw failure
106
+ return undefined
107
+ } })
108
+ await expect(agent('send once', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'RECEIPT_LOST', outcomeUnknown: true })
109
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
110
+ expect(adapter.calls.some(call => call.method === 'turn/interrupt' || call.method === 'session/interrupt')).toBe(false)
111
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
112
+ })
113
+
114
+ test('source failure remains uncertain and is not converted into successful cleanup', async () => {
115
+ const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId, submissionId }) => {
116
+ await sink.bindSubmission(submissionId, turnId)
117
+ await sink.fail(new HarnessSdkError('CONNECTION_LOST', 'lost', false, true))
118
+ }) })
119
+ await expect(agent('source disappears', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'CONNECTION_LOST', outcomeUnknown: true })
120
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
121
+ })
122
+
123
+ test('opening failure does not submit input or dispose the borrowed client', async () => {
124
+ const { client, adapter } = await fixture({ onOpen: async () => { throw new HarnessSdkError('OPEN_FAILED') } })
125
+ await expect(agent('not sent', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'OPEN_FAILED' })
126
+ expect(adapter.calls).toHaveLength(0)
127
+ expect(adapter.disposeCount).toBe(0)
128
+ })
129
+
130
+ test('cleanup failure is surfaced and backend disposal is still attempted', async () => {
131
+ const { client, adapter } = await fixture({ execute: async call => {
132
+ if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
133
+ return undefined
134
+ } })
135
+ await expect(agent('completed but cleanup failed', { client, cwd: process.cwd() })).rejects.toMatchObject({
136
+ code: 'RESOURCE_RELEASE_FAILED', details: { errors: [{ code: 'CLOSE_FAILED', outcomeUnknown: false }] },
137
+ })
138
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
139
+ })
140
+
141
+ test('cleanup failure cannot hide the primary uncertain execution failure', async () => {
142
+ const { client, adapter } = await fixture({ execute: async call => {
143
+ if (call.method === 'input/submit') throw new HarnessSdkError('RECEIPT_LOST', 'receipt lost', false, true)
144
+ if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
145
+ return undefined
146
+ } })
147
+ await expect(agent('once', { client, cwd: process.cwd() })).rejects.toMatchObject({
148
+ code: 'RECEIPT_LOST', outcomeUnknown: true,
149
+ details: { cleanupErrors: [{ code: 'CLOSE_FAILED', outcomeUnknown: false }] },
150
+ })
151
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
152
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
153
+ })
154
+
155
+ /** Register a scripted client that publishes final text and a terminal before the submit receipt.
156
+ * Disable the advertised output-schema route to exercise fallback against the same terminal. */
157
+ function terminalFixture(
158
+ status: 'failed' | 'interrupted' | 'completed',
159
+ { error, text = 'partial', outputSchema = true }: { error?: HarnessError; text?: string; outputSchema?: boolean } = {},
160
+ ) {
161
+ return fixture({
162
+ ...(outputSchema ? {} : {
163
+ capabilities: { input: { delivery: ['native'] }, turn: { inputModalities: ['text'], outputSchema: false } },
164
+ }),
165
+ execute: scriptSubmission(async ({ sink, turnId }) => {
166
+ await sink.emit({ type: 'item/completed', payload: { item: { id: 'output', type: 'agentMessage', phase: 'final', text } } }, { turnId })
167
+ // A live subscription opened after submit cannot recover a retained terminal.
168
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status, ...(error ? { error } : {}) } })
169
+ }),
170
+ })
171
+ }
172
+
173
+ test('Zod schema is converted for submission and returns typed data through composition', async () => {
174
+ const schema = z.object({ count: z.number() })
175
+ const { client, adapter } = await terminalFixture('completed', { text: '{"count":3}' })
176
+ const options = { client, cwd: process.cwd(), schema }
177
+ const results = await pipeline(['a', 'b'], prompt => agent(prompt, options), value => value.count * 2)
178
+ expect(results).toEqual([6, 6])
179
+ const starts = adapter.calls.filter(call => call.method === 'input/submit')
180
+ expect(starts).toHaveLength(2)
181
+ expect(starts[0]!.params).toMatchObject({ outputSchema: { type: 'object', required: ['count'], properties: { count: { type: 'number' } }, additionalProperties: false } })
182
+ expect('outputSchema' in starts[0]!.params && starts[0]!.params.outputSchema).not.toBe(schema)
183
+ expect([...adapter.backends.values()].every(backend => backend.disposeCount === 1)).toBe(true)
184
+ })
185
+
186
+ test('schema preflight rejects before opening, while absent backend support releases without submitting', async () => {
187
+ const { client, adapter } = await fixture()
188
+ await expect(agent('invalid', { client, cwd: '.', schema: z.object({ a: z.coerce.number() }) })).rejects.toMatchObject({ code: 'INVALID_PARAMS', outcomeUnknown: false })
189
+ expect(adapter.opened).toHaveLength(0)
190
+ const unsupported = await fixture({ capabilities: { turn: { outputSchema: false } } })
191
+ await expect(agent('unsupported', { client: unsupported.client, cwd: '.', schema: z.object({ a: z.string() }) })).rejects.toMatchObject({ code: 'CAPABILITY_UNSUPPORTED' })
192
+ expect(unsupported.adapter.calls.some(call => call.method === 'input/submit')).toBe(false)
193
+ expect([...unsupported.adapter.backends.values()][0]?.disposeCount).toBe(1)
194
+ })
195
+
196
+ test.each([
197
+ { text: '{"count":3}', error: null },
198
+ { text: '{"count":3,"extra":true}', error: 'AGENT_STRUCTURED_OUTPUT_INVALID' },
199
+ { text: 'plain text', error: 'AGENT_STRUCTURED_OUTPUT_NOT_JSON' },
200
+ ])('JSON text fallback submits once and validates the terminal text ($error)', async ({ text, error }) => {
201
+ const { client, adapter } = await terminalFixture('completed', { text, outputSchema: false })
202
+ const result = agent('Plan the work', { client, cwd: '.', schema: z.strictObject({ count: z.number() }), outputFallback: 'json-text' })
203
+ if (error) await expect(result).rejects.toMatchObject({ code: error })
204
+ else await expect(result).resolves.toEqual({ count: 3 })
205
+ const calls = adapter.calls.filter(call => call.method === 'input/submit')
206
+ expect(calls).toHaveLength(1)
207
+ expect(calls[0]?.params).not.toHaveProperty('outputSchema')
208
+ expect(calls[0]?.params).toMatchObject({ input: [{ text: expect.stringContaining('JSON Schema') }] })
209
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
210
+ })
211
+
212
+ test('session cleanup waits for asynchronous local output validation', async () => {
213
+ const entered = Promise.withResolvers<void>()
214
+ const validation = Promise.withResolvers<boolean>()
215
+ const schema = z.object({ count: z.number() }).refine(async () => {
216
+ entered.resolve()
217
+ return validation.promise
218
+ })
219
+ const { client, adapter } = await terminalFixture('completed', { text: '{"count":3}' })
220
+ const result = agent('validate before cleanup', { client, cwd: '.', schema })
221
+ try {
222
+ await entered.promise
223
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(false)
224
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(0)
225
+ } finally {
226
+ validation.resolve(true)
227
+ }
228
+ expect(await result).toEqual({ count: 3 })
229
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(true)
230
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
231
+ })
232
+
233
+ test.each(['AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE'])('only terminal %s becomes null', async code => {
234
+ const error = { code, message: 'native api error', retryable: true, outcomeUnknown: false }
235
+ const { client, adapter } = await terminalFixture('failed', { error })
236
+ expect(await agent('failed terminal', { client, cwd: '.' })).toBeNull()
237
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
238
+ for (const stage of ['open', 'submit']) {
239
+ const denied = await fixture(stage === 'open'
240
+ ? { onOpen: async () => { throw new HarnessSdkError(code) } }
241
+ : { execute: async call => { if (call.method === 'input/submit') throw new HarnessSdkError(code); return undefined } })
242
+ await expect(agent('not a terminal', { client: denied.client, cwd: '.' })).rejects.toMatchObject({ code })
243
+ }
244
+ })
245
+
246
+ test.each(['NATIVE_TURN_FAILED', 'CLAUDE_TURN_FAILED', 'NATIVE_REQUEST_INVALID', 'CLAUDE_STRUCTURED_OUTPUT_RETRIES_EXCEEDED', 'CLAUDE_MAX_TURNS_EXCEEDED'])('terminal %s still rejects', async code => {
247
+ const { client } = await terminalFixture('failed', { error: { code, message: 'failure', retryable: false, outcomeUnknown: false } })
248
+ await expect(agent('fail', { client, cwd: '.' })).rejects.toMatchObject({ code })
249
+ })
250
+
251
+ test('uncertainty overrides API and skip classifications, and generic interruptions never become null', async () => {
252
+ for (const status of ['failed', 'interrupted'] as const) {
253
+ const { client } = await terminalFixture(status, { error: { code: 'RATE_LIMITED', message: 'unknown', retryable: false, outcomeUnknown: true, details: { workflowDisposition: 'skipped' } } })
254
+ await expect(agent('unknown', { client, cwd: '.' })).rejects.toMatchObject({ code: 'RATE_LIMITED', outcomeUnknown: true })
255
+ }
256
+ const { client } = await terminalFixture('interrupted')
257
+ await expect(agent('interrupted', { client, cwd: '.' })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
258
+ })
259
+
260
+ test('explicit skip metadata survives terminal-before-reply and startup denial requires its dedicated code', async () => {
261
+ const skipped = await terminalFixture('interrupted', { error: { code: 'USER_SKIPPED', message: 'skipped', retryable: false, outcomeUnknown: false, details: { workflowDisposition: 'skipped' } } })
262
+ expect(await agent('skip', { client: skipped.client, cwd: '.' })).toBeNull()
263
+ expect([...skipped.adapter.backends.values()][0]?.disposeCount).toBe(1)
264
+ const blocked = await fixture({ onOpen: async () => { throw new HarnessSdkError('AGENT_STARTUP_BLOCKED', 'blocked', false, false, { workflowDisposition: 'startup_blocked' }) } })
265
+ expect(await agent('blocked', { client: blocked.client, cwd: '.' })).toBeNull()
266
+ expect(blocked.adapter.calls).toHaveLength(0)
267
+ const denied = await terminalFixture('failed', { error: { code: 'PERMISSION_DENIED', message: 'denied', retryable: false, outcomeUnknown: false, details: { workflowDisposition: 'startup_blocked' } } })
268
+ await expect(agent('denied', { client: denied.client, cwd: '.' })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
269
+ })
270
+
271
+ test.each(['failed', 'interrupted'] as const)('tagged startup denial in a %s terminal returns null after cleanup', async status => {
272
+ const { client, adapter } = await terminalFixture(status, { error: {
273
+ code: 'AGENT_STARTUP_BLOCKED', message: 'blocked', retryable: false, outcomeUnknown: false,
274
+ details: { workflowDisposition: 'startup_blocked' },
275
+ } })
276
+ expect(await agent('blocked', { client, cwd: '.' })).toBeNull()
277
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
278
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(true)
279
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
280
+ })
281
+
282
+ test('a null candidate cannot hide cleanup failure', async () => {
283
+ const submit = scriptSubmission(async ({ sink, turnId }) => {
284
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: { code: 'RATE_LIMITED', message: 'rate limit', retryable: true, outcomeUnknown: false } } })
285
+ })
286
+ const { client, adapter } = await fixture({ execute: async (call, sink) => {
287
+ if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
288
+ return submit(call, sink)
289
+ } })
290
+ await expect(agent('rate limited', { client, cwd: '.' })).rejects.toMatchObject({ code: 'RESOURCE_RELEASE_FAILED', details: { droppedError: { code: 'RATE_LIMITED' } } })
291
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
292
+ })
293
+
294
+ test.each(['', 'bad JSON', '{}', '{"count":"3"}'])('invalid structured terminal %j rejects, cleans up and never replays', async text => {
295
+ const { client, adapter } = await terminalFixture('completed', { text })
296
+ await expect(agent('structured', { client, cwd: '.', schema: z.object({ count: z.number() }) })).rejects.toMatchObject({ outcomeUnknown: false, retryable: false })
297
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
298
+ expect(adapter.calls.some(call => call.method === 'session/interrupt' || call.method === 'turn/interrupt')).toBe(false)
299
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
300
+ })
301
+
302
+ test('empty text and multiple final text items retain SDK aggregation', async () => {
303
+ const empty = await terminalFixture('completed', { text: '' })
304
+ expect(await agent('empty', { client: empty.client, cwd: '.' })).toBe('')
305
+ const { client } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
306
+ for (const text of ['first', 'last']) await sink.emit({ type: 'item/completed', payload: { item: { id: text, type: 'agentMessage', phase: 'final', text } } }, { turnId })
307
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
308
+ }) })
309
+ expect(await agent('two', { client, cwd: '.' })).toBe('first\nlast')
310
+ })
311
+
312
+ /** Exercise root overload inference and rejected assignments during package typecheck. */
313
+ function agentTypes(client: Client, dynamic: AgentOptions<z.ZodObject<{ count: z.ZodNumber }>>) {
314
+ const base = { client, cwd: '.' }
315
+ const schema = z.object({ count: z.number() })
316
+ const text: Promise<string | null> = agent('text', base)
317
+ const explicitUndefined: Promise<string | null> = agent('text', { ...base, schema: undefined })
318
+ const value: Promise<{ count: number } | null> = agent('value', { ...base, schema })
319
+ const inline: Promise<{ issues: string[] } | null> = agent('inline', { ...base, schema: z.object({ issues: z.array(z.string()) }) })
320
+ const maybe: Promise<string | { count: number } | null> = agent('dynamic', dynamic)
321
+ // @ts-expect-error Null must be handled.
322
+ const unsafeText: Promise<string> = agent('text', base)
323
+ // @ts-expect-error Schema output is numeric, not a string.
324
+ const wrong: Promise<{ count: string } | null> = agent('value', { ...base, schema })
325
+ // @ts-expect-error Raw JSON Schema is not a workflow schema.
326
+ agent('raw', { ...base, schema: { type: 'object' } })
327
+ // @ts-expect-error A business type cannot replace the schema type parameter.
328
+ agent<{ count: number }>('unbound', { ...base, schema })
329
+ // @ts-expect-error Object roots are required.
330
+ agent('string', { ...base, schema: z.string() })
331
+ void [text, explicitUndefined, value, inline, maybe, unsafeText, wrong]
332
+ }
333
+ void agentTypes
package/src/agent.ts ADDED
@@ -0,0 +1,135 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { JsonObject } from '@anureo/protocol'
3
+ import { HarnessSdkError, sdkError } from '@anureo/sdk'
4
+ import type { z } from 'zod'
5
+ import { executeAgent, type AgentOptions } from './agent-execution'
6
+ import { prepareOutputSchema, type AgentOutputSchema } from './output-schema'
7
+ import { currentRun, isFatal, type RunContext } from './workflow-state'
8
+ import { canonicalJson, jsonCopy, type JsonValue } from './persistence/json'
9
+
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
+ 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
+ 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
+ export function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S>): Promise<string | z.output<S> | null>
40
+ export async function agent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
41
+ const context = currentRun()
42
+ if (context) return memoizedAgent(context, prompt, options)
43
+ return executeAgent(prompt, options)
44
+ }
45
+
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. */
76
+ function canonicalOptions(options: AgentOptions, schema: JsonObject | undefined): JsonValue {
77
+ return {
78
+ model: options.model ?? null,
79
+ instructions: options.instructions ?? null,
80
+ permissionMode: options.permissionMode ?? null,
81
+ schema: schema ?? null,
82
+ ...(options.outputFallback ? { outputFallback: options.outputFallback } : {}),
83
+ cwd: options.cwd,
84
+ client: options.client.identity,
85
+ }
86
+ }
87
+
88
+ /** Return saved text or await current schema validation for memoizedAgent's typed hit.
89
+ * A rejected validation propagates to the agent caller without rerunning the prompt. */
90
+ async function replayAgentResult<S extends z.ZodObject>(
91
+ hit: JsonValue,
92
+ output: AgentOutputSchema<S> | undefined,
93
+ ): Promise<string | z.output<S>> {
94
+ return output ? output.parse(canonicalJson(hit)) : hit as string
95
+ }
96
+
97
+ /**
98
+ * Execute memoizedAgent's cache miss after saving its started marker and rechecking dispatch.
99
+ * Await fresh execution and session release before publishing the terminal event. Drops mark
100
+ * the run incomplete. Fatal failures stop later dispatch, and WORKFLOW_STORAGE_FAILED rejects
101
+ * without attempting a second terminal write. The dispatch check is outside the execution catch
102
+ * so a call stopped during publication retains its started marker.
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()
114
+ try {
115
+ // Cache identity was computed at invocation. Fresh execution reads options after publication.
116
+ const value = await executeAgent(prompt, options)
117
+ if (value === null) {
118
+ await journal.append({ type: 'failed', key, agentId, code: 'AGENT_DROPPED', outcomeUnknown: false })
119
+ state.noteIncomplete()
120
+ return null
121
+ }
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
+ } catch (cause) {
126
+ const error = sdkError(cause, 'AGENT_FAILED')
127
+ if (isFatal(error)) state.stop(error)
128
+ // The storage layer may have published a terminal record already.
129
+ if (error.code !== 'WORKFLOW_STORAGE_FAILED') {
130
+ await journal.append({ type: 'failed', key, agentId,
131
+ code: error.code, outcomeUnknown: error.outcomeUnknown === true })
132
+ }
133
+ throw error
134
+ }
135
+ }
@@ -0,0 +1,53 @@
1
+ import { mock } from 'bun:test'
2
+ import * as fs from 'node:fs/promises'
3
+ import { createClient } from '@anureo/sdk'
4
+ import { createScriptedAdapter } from '@anureo/conformance'
5
+
6
+ const [directory, phase] = process.argv.slice(2) as [string, string]
7
+ const originalRename = fs.rename
8
+ let journalPublishes = 0
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 === '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> {
41
+ const target = to.replaceAll('\\', '/')
42
+ if (target.endsWith('/journal.json')) {
43
+ // The first publication creates the empty journal before any agent work can start.
44
+ journalPublishes++
45
+ if (phase === 'before-started' && journalPublishes === 2) process.kill(process.pid, 'SIGKILL')
46
+ if (phase === 'after-execute' && journalPublishes === 3) process.kill(process.pid, 'SIGKILL')
47
+ }
48
+ if (phase === 'before-final' && target.endsWith('/run.json')) {
49
+ const value = JSON.parse(await fs.readFile(from, 'utf8'))
50
+ if (value.status === 'completed') process.kill(process.pid, 'SIGKILL')
51
+ }
52
+ await originalRename(from, to)
53
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
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
+
5
+ export { parallel } from './parallel'
6
+ export { pipeline } from './pipeline'
7
+
8
+ export { workflow } from './workflow'
9
+ export type { WorkflowContext, WorkflowOptions, WorkflowResult } from './workflow-types'