@anureo/workflow 0.3.0 → 0.3.2

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.
Files changed (63) hide show
  1. package/README.md +96 -70
  2. package/package.json +18 -16
  3. package/src/agent-adapters.test.ts +121 -0
  4. package/src/agent-execution.ts +220 -0
  5. package/src/agent.test.ts +470 -0
  6. package/src/agent.ts +136 -0
  7. package/src/fixtures/workflow-crash.ts +69 -0
  8. package/src/index.ts +9 -0
  9. package/src/output-schema.test.ts +159 -0
  10. package/src/output-schema.ts +237 -0
  11. package/src/parallel.test.ts +96 -0
  12. package/src/parallel.ts +33 -0
  13. package/src/persistence/checkpoint-files.ts +83 -0
  14. package/src/persistence/journal.ts +132 -0
  15. package/src/persistence/json.ts +83 -0
  16. package/src/persistence/records.ts +103 -0
  17. package/src/persistence/replay.ts +93 -0
  18. package/src/persistence/store.ts +315 -0
  19. package/src/pipeline.test.ts +201 -0
  20. package/src/pipeline.ts +99 -0
  21. package/src/test-helpers.ts +23 -0
  22. package/src/workflow-state.ts +131 -0
  23. package/src/workflow-types.ts +38 -0
  24. package/src/workflow.test.ts +503 -0
  25. package/src/workflow.ts +112 -0
  26. package/tsconfig.json +13 -0
  27. package/LICENSE +0 -201
  28. package/src/agent-outcome.d.ts +0 -15
  29. package/src/agent-outcome.js +0 -28
  30. package/src/agent.d.ts +0 -49
  31. package/src/agent.js +0 -206
  32. package/src/index.d.ts +0 -6
  33. package/src/index.js +0 -5
  34. package/src/output-schema.d.ts +0 -27
  35. package/src/output-schema.js +0 -192
  36. package/src/parallel.d.ts +0 -18
  37. package/src/parallel.js +0 -25
  38. package/src/persistence/atomic.d.ts +0 -9
  39. package/src/persistence/atomic.js +0 -48
  40. package/src/persistence/journal.d.ts +0 -54
  41. package/src/persistence/journal.js +0 -106
  42. package/src/persistence/json.d.ts +0 -17
  43. package/src/persistence/json.js +0 -75
  44. package/src/persistence/read-json.d.ts +0 -11
  45. package/src/persistence/read-json.js +0 -46
  46. package/src/persistence/records.d.ts +0 -92
  47. package/src/persistence/records.js +0 -70
  48. package/src/persistence/replay.d.ts +0 -11
  49. package/src/persistence/replay.js +0 -79
  50. package/src/persistence/store.d.ts +0 -45
  51. package/src/persistence/store.js +0 -238
  52. package/src/pipeline.d.ts +0 -41
  53. package/src/pipeline.js +0 -24
  54. package/src/run-context.d.ts +0 -16
  55. package/src/run-context.js +0 -13
  56. package/src/test-helpers.d.ts +0 -11
  57. package/src/test-helpers.js +0 -21
  58. package/src/workflow-state.d.ts +0 -44
  59. package/src/workflow-state.js +0 -96
  60. package/src/workflow-types.d.ts +0 -39
  61. package/src/workflow-types.js +0 -0
  62. package/src/workflow.d.ts +0 -17
  63. package/src/workflow.js +0 -104
@@ -0,0 +1,470 @@
1
+ import { afterEach, expect, test } from 'bun:test'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import type { FakeAdapterOptions } from '@anureo/conformance'
7
+ import type { HarnessError } from '@anureo/protocol'
8
+ import { HarnessSdkError, type Client, type SessionEventSink } from '@anureo/sdk'
9
+ import { z } from 'zod'
10
+ import { agent, parallel, pipeline, workflow, type AgentOptions } from './index'
11
+ import { createFixture } from './test-helpers'
12
+
13
+ const clients: Client[] = []
14
+ const fixture = createFixture(clients)
15
+ const workflowDirectories: string[] = []
16
+ afterEach(async () => {
17
+ await Promise.all(clients.splice(0).map(client => client.dispose()))
18
+ await Promise.all(workflowDirectories.splice(0).map(directory => rm(directory, { recursive: true, force: true })))
19
+ })
20
+
21
+ async function workflowOptions() {
22
+ const directory = await mkdtemp(join(tmpdir(), 'anureo-agent-'))
23
+ workflowDirectories.push(directory)
24
+ return { directory, name: 'agent', revision: '1', input: {} }
25
+ }
26
+
27
+ /** Publish final text before the test terminal so Turn.result retains it. */
28
+ async function complete(sink: SessionEventSink, turnId: string, text: string) {
29
+ await sink.emit({ type: 'item/completed', payload: { item: { id: randomUUID(), type: 'agentMessage', phase: 'final', text } } }, { turnId })
30
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
31
+ }
32
+
33
+ /**
34
+ * Supply the execute hook awaited by the scripted backend. For a submit, publish the start and
35
+ * await the test's event callback before replying with the same turn ID. A callback rejection
36
+ * fails the dispatch. Other calls fall through to the default adapter.
37
+ */
38
+ function scriptSubmission(
39
+ publish: (submission: { sink: SessionEventSink; turnId: string; submissionId: string }) => Promise<void>,
40
+ ): NonNullable<FakeAdapterOptions['execute']> {
41
+ return async (call, sink) => {
42
+ if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
43
+ const { submissionId } = call.params
44
+ const turnId = randomUUID()
45
+ await sink.emit({ type: 'turn/started', payload: { turnId } })
46
+ await publish({ sink, turnId, submissionId })
47
+ return { submissionId, accepted: true, disposition: 'started', turnId }
48
+ }
49
+ }
50
+
51
+ test('returns text from independent sessions and leaves the borrowed client usable', async () => {
52
+ const { client, adapter } = await fixture()
53
+ expect(await parallel([
54
+ () => agent('first', { client, cwd: process.cwd(), model: 'test-model', instructions: 'review carefully' }),
55
+ () => agent('second', { client, cwd: process.cwd() }),
56
+ ])).toEqual(['first', 'second'])
57
+ expect(adapter.opened).toHaveLength(2)
58
+ expect(new Set(adapter.opened.map(session => session.binding.sessionId)).size).toBe(2)
59
+ expect(adapter.opened[0]).toMatchObject({ cwd: process.cwd(), model: 'test-model', instructions: 'review carefully' })
60
+ expect([...adapter.backends.values()].every(backend => backend.disposeCount === 1)).toBe(true)
61
+ expect(adapter.disposeCount).toBe(0)
62
+ expect(await agent('third', { client, cwd: process.cwd() })).toBe('third')
63
+ })
64
+
65
+ test('each call chooses its backend explicitly without shared configuration', async () => {
66
+ const a = await fixture(), b = await fixture()
67
+ expect(await parallel([
68
+ () => agent('backend a', { client: a.client, cwd: '/a' }),
69
+ () => agent('backend b', { client: b.client, cwd: '/b' }),
70
+ ])).toEqual(['backend a', 'backend b'])
71
+ expect(a.adapter.opened[0]?.cwd).toBe('/a')
72
+ expect(b.adapter.opened[0]?.cwd).toBe('/b')
73
+ })
74
+
75
+ test('journaled execution and replay use the options captured at invocation', async () => {
76
+ const run = await workflowOptions()
77
+ const { client, adapter } = await fixture()
78
+ const other = await fixture()
79
+ const initial = {
80
+ client, cwd: run.directory, model: 'original', permissionMode: 'original',
81
+ schema: z.object({ count: z.number() }),
82
+ }
83
+ const first = await workflow(run, () => {
84
+ const options: AgentOptions = { ...initial }
85
+ const result = agent('{"count":3}', options)
86
+ Object.assign(options, {
87
+ client: other.client, cwd: tmpdir(), model: 'changed', permissionMode: 'changed',
88
+ schema: z.object({ other: z.string() }),
89
+ })
90
+ return result
91
+ })
92
+ expect(first.result).toEqual({ count: 3 })
93
+ expect(adapter.opened[0]).toMatchObject({ cwd: run.directory, model: 'original', permissionMode: 'original' })
94
+ const resumed = await workflow({ ...run, resumeFrom: first.runId }, () =>
95
+ agent('{"count":3}', { ...initial, wait: { associationMs: 1, resultMs: 1 } }))
96
+ expect(resumed.result).toEqual({ count: 3 })
97
+ expect(adapter.opened).toHaveLength(1)
98
+ expect(other.adapter.opened).toHaveLength(0)
99
+ })
100
+
101
+ test('native association and acceptance do not replace terminal evidence', async () => {
102
+ const { promise: terminalEmitterReady, resolve: resolveTerminalEmitter } = Promise.withResolvers<() => Promise<void>>()
103
+ const { client, adapter } = await fixture({ execute: async (call, sink) => {
104
+ if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
105
+ const turnId = randomUUID()
106
+ await sink.emit({ type: 'turn/started', payload: { turnId } })
107
+ await sink.bindSubmission(call.params.submissionId, turnId)
108
+ resolveTerminalEmitter(() => complete(sink, turnId, 'actual terminal text'))
109
+ return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
110
+ } })
111
+ let settled = false
112
+ const result = agent('wait for native work', { client, cwd: process.cwd() }).then(text => { settled = true; return text })
113
+ const emitTerminal = await terminalEmitterReady
114
+ expect(settled).toBe(false)
115
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(false)
116
+ await emitTerminal()
117
+ expect(await result).toBe('actual terminal text')
118
+ })
119
+
120
+ test.each(['associationMs', 'resultMs'] as const)('%s expires with an unknown outcome and releases the session', async phase => {
121
+ const { client, adapter } = await fixture({ execute: async (call, sink) => {
122
+ if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
123
+ const { submissionId } = call.params
124
+ if (phase === 'resultMs') {
125
+ const turnId = randomUUID()
126
+ await sink.emit({ type: 'turn/started', payload: { turnId } })
127
+ return { submissionId, accepted: true, disposition: 'started', turnId }
128
+ }
129
+ return { submissionId, accepted: true, disposition: 'queued', receipt: { nativeId: submissionId } }
130
+ } })
131
+ await expect(agent('send once', { client, cwd: '.', wait: { [phase]: 20 } })).rejects.toMatchObject({
132
+ code: 'REQUEST_TIMEOUT', outcomeUnknown: true,
133
+ })
134
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
135
+ expect(adapter.calls.some(call => call.method === 'turn/interrupt' || call.method === 'session/interrupt')).toBe(false)
136
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
137
+ })
138
+
139
+ test('preserves native failure details and releases the session', async () => {
140
+ const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
141
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
142
+ code: 'NATIVE_FAILED', message: 'native failure', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
143
+ } } })
144
+ }) })
145
+ await expect(agent('fail', { client, cwd: process.cwd() })).rejects.toMatchObject({
146
+ code: 'NATIVE_FAILED', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
147
+ })
148
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(true)
149
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
150
+ })
151
+
152
+ test('an interrupted execution cannot return successful text', async () => {
153
+ const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
154
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'interrupted' } })
155
+ }) })
156
+ await expect(agent('interrupted', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
157
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
158
+ })
159
+
160
+ test('unknown submission outcomes are preserved without retries or implicit interrupts', async () => {
161
+ const failure = new HarnessSdkError('RECEIPT_LOST', 'receipt lost', false, true)
162
+ const { client, adapter } = await fixture({ execute: async call => {
163
+ if (call.method === 'input/submit') throw failure
164
+ return undefined
165
+ } })
166
+ await expect(agent('send once', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'RECEIPT_LOST', outcomeUnknown: true })
167
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
168
+ expect(adapter.calls.some(call => call.method === 'turn/interrupt' || call.method === 'session/interrupt')).toBe(false)
169
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
170
+ })
171
+
172
+ test('a failed terminal journal write preserves the uncertain error for the agent caller', async () => {
173
+ const run = { ...await workflowOptions(), runId: 'uncertain' }
174
+ const { client } = await fixture({ execute: async call => {
175
+ if (call.method !== 'input/submit') return undefined
176
+ const journal = join(run.directory, run.runId, 'journal.json')
177
+ await rm(journal)
178
+ await mkdir(journal)
179
+ throw new HarnessSdkError('RECEIPT_LOST', 'receipt lost', false, true)
180
+ } })
181
+ let caught: unknown
182
+ await expect(workflow(run, async () => {
183
+ try { await agent('send once', { client, cwd: run.directory }) }
184
+ catch (cause) { caught = cause }
185
+ return 'caught'
186
+ })).rejects.toMatchObject({
187
+ code: 'RECEIPT_LOST', outcomeUnknown: true,
188
+ details: { failureCodes: expect.arrayContaining(['WORKFLOW_STORAGE_FAILED']) },
189
+ })
190
+ expect(caught).toMatchObject({
191
+ code: 'RECEIPT_LOST', outcomeUnknown: true,
192
+ details: { journalErrorCode: 'WORKFLOW_STORAGE_FAILED' },
193
+ })
194
+ })
195
+
196
+ test('source failure remains uncertain and is not converted into successful cleanup', async () => {
197
+ const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId, submissionId }) => {
198
+ await sink.bindSubmission(submissionId, turnId)
199
+ await sink.fail(new HarnessSdkError('CONNECTION_LOST', 'lost', false, true))
200
+ }) })
201
+ await expect(agent('source disappears', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'CONNECTION_LOST', outcomeUnknown: true })
202
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
203
+ })
204
+
205
+ test('opening failure does not submit input or dispose the borrowed client', async () => {
206
+ const { client, adapter } = await fixture({ onOpen: async () => { throw new HarnessSdkError('OPEN_FAILED') } })
207
+ await expect(agent('not sent', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'OPEN_FAILED' })
208
+ expect(adapter.calls).toHaveLength(0)
209
+ expect(adapter.disposeCount).toBe(0)
210
+ })
211
+
212
+ test('cleanup failure is surfaced and backend disposal is still attempted', async () => {
213
+ const { client, adapter } = await fixture({ execute: async call => {
214
+ if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
215
+ return undefined
216
+ } })
217
+ await expect(agent('completed but cleanup failed', { client, cwd: process.cwd() })).rejects.toMatchObject({
218
+ code: 'RESOURCE_RELEASE_FAILED', details: { errors: [{ code: 'CLOSE_FAILED', outcomeUnknown: false }] },
219
+ })
220
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
221
+ })
222
+
223
+ test('cleanup failure cannot hide the primary uncertain execution failure', async () => {
224
+ const { client, adapter } = await fixture({ execute: async call => {
225
+ if (call.method === 'input/submit') throw new HarnessSdkError('RECEIPT_LOST', 'receipt lost', false, true)
226
+ if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
227
+ return undefined
228
+ } })
229
+ await expect(agent('once', { client, cwd: process.cwd() })).rejects.toMatchObject({
230
+ code: 'RECEIPT_LOST', outcomeUnknown: true,
231
+ details: { cleanupErrors: [{ code: 'CLOSE_FAILED', outcomeUnknown: false }] },
232
+ })
233
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
234
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
235
+ })
236
+
237
+ test('session release appends to cleanup diagnostics from submission', async () => {
238
+ const prior = { code: 'OUTPUT_TOOL_RELEASE_FAILED', outcomeUnknown: true }
239
+ const { client } = await fixture({ execute: async call => {
240
+ if (call.method === 'input/submit') {
241
+ throw new HarnessSdkError('SUBMIT_FAILED', 'submit failed', true, false, { cleanupErrors: [prior] })
242
+ }
243
+ if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
244
+ return undefined
245
+ } })
246
+ await expect(agent('send', { client, cwd: '.' })).rejects.toMatchObject({
247
+ code: 'SUBMIT_FAILED', retryable: true, outcomeUnknown: false,
248
+ details: { cleanupErrors: [prior, { code: 'CLOSE_FAILED', outcomeUnknown: false }] },
249
+ })
250
+ })
251
+
252
+ /** Register a scripted client that publishes final text and a terminal before the submit receipt.
253
+ * Disable the advertised output-schema route to exercise fallback against the same terminal. */
254
+ function terminalFixture(
255
+ status: 'failed' | 'interrupted' | 'completed',
256
+ { error, text = 'partial', outputSchema = true }: { error?: HarnessError; text?: string; outputSchema?: boolean } = {},
257
+ ) {
258
+ return fixture({
259
+ ...(outputSchema ? {} : {
260
+ capabilities: { input: { delivery: ['native'] }, turn: { inputModalities: ['text'], outputSchema: false } },
261
+ }),
262
+ execute: scriptSubmission(async ({ sink, turnId }) => {
263
+ await sink.emit({ type: 'item/completed', payload: { item: { id: 'output', type: 'agentMessage', phase: 'final', text } } }, { turnId })
264
+ // A live subscription opened after submit cannot recover a retained terminal.
265
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status, ...(error ? { error } : {}) } })
266
+ }),
267
+ })
268
+ }
269
+
270
+ test('Zod schema is converted for submission and returns typed data through composition', async () => {
271
+ const schema = z.object({ count: z.number() })
272
+ const { client, adapter } = await terminalFixture('completed', { text: '{"count":3}' })
273
+ const options = { client, cwd: process.cwd(), schema }
274
+ const results = await pipeline(['a', 'b'], prompt => agent(prompt, options), value => value.count * 2)
275
+ expect(results).toEqual([6, 6])
276
+ const starts = adapter.calls.filter(call => call.method === 'input/submit')
277
+ expect(starts).toHaveLength(2)
278
+ expect(starts[0]!.params).toMatchObject({ outputSchema: { type: 'object', required: ['count'], properties: { count: { type: 'number' } }, additionalProperties: false } })
279
+ expect('outputSchema' in starts[0]!.params && starts[0]!.params.outputSchema).not.toBe(schema)
280
+ expect([...adapter.backends.values()].every(backend => backend.disposeCount === 1)).toBe(true)
281
+ })
282
+
283
+ test('schema preflight rejects before opening, while absent backend support releases without submitting', async () => {
284
+ const { client, adapter } = await fixture()
285
+ await expect(agent('invalid', { client, cwd: '.', schema: z.object({ a: z.coerce.number() }) })).rejects.toMatchObject({ code: 'INVALID_PARAMS', outcomeUnknown: false })
286
+ expect(adapter.opened).toHaveLength(0)
287
+ const unsupported = await fixture({ capabilities: { turn: { outputSchema: false } } })
288
+ await expect(agent('unsupported', { client: unsupported.client, cwd: '.', schema: z.object({ a: z.string() }) })).rejects.toMatchObject({ code: 'CAPABILITY_UNSUPPORTED' })
289
+ expect(unsupported.adapter.calls.some(call => call.method === 'input/submit')).toBe(false)
290
+ expect([...unsupported.adapter.backends.values()][0]?.disposeCount).toBe(1)
291
+ })
292
+
293
+ test('a caught schema preflight failure leaves the workflow incomplete', async () => {
294
+ const run = await workflowOptions()
295
+ const { client, adapter } = await fixture()
296
+ const outcome = await workflow(run, () => parallel([
297
+ () => agent('invalid', { client, cwd: run.directory, schema: z.object({ count: z.coerce.number() }) }),
298
+ ]))
299
+ expect(outcome).toMatchObject({ status: 'incomplete', result: [null] })
300
+ expect(adapter.opened).toHaveLength(0)
301
+ })
302
+
303
+ test.each([
304
+ { text: '{"count":3}', error: null },
305
+ { text: '{"count":3,"extra":true}', error: 'AGENT_STRUCTURED_OUTPUT_INVALID' },
306
+ { text: 'plain text', error: 'AGENT_STRUCTURED_OUTPUT_NOT_JSON' },
307
+ ])('JSON text fallback submits once and validates the terminal text ($error)', async ({ text, error }) => {
308
+ const { client, adapter } = await terminalFixture('completed', { text, outputSchema: false })
309
+ const result = agent('Plan the work', { client, cwd: '.', schema: z.strictObject({ count: z.number() }), outputFallback: 'json-text' })
310
+ if (error) await expect(result).rejects.toMatchObject({ code: error })
311
+ else await expect(result).resolves.toEqual({ count: 3 })
312
+ const calls = adapter.calls.filter(call => call.method === 'input/submit')
313
+ expect(calls).toHaveLength(1)
314
+ expect(calls[0]?.params).not.toHaveProperty('outputSchema')
315
+ expect(calls[0]?.params).toMatchObject({ input: [{ text: expect.stringContaining('JSON Schema') }] })
316
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
317
+ })
318
+
319
+ test('session cleanup waits for asynchronous local output validation', async () => {
320
+ const entered = Promise.withResolvers<void>()
321
+ const validation = Promise.withResolvers<boolean>()
322
+ const schema = z.object({ count: z.number() }).refine(async () => {
323
+ entered.resolve()
324
+ return validation.promise
325
+ })
326
+ const { client, adapter } = await terminalFixture('completed', { text: '{"count":3}' })
327
+ const result = agent('validate before cleanup', { client, cwd: '.', schema })
328
+ try {
329
+ await entered.promise
330
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(false)
331
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(0)
332
+ } finally {
333
+ validation.resolve(true)
334
+ }
335
+ expect(await result).toEqual({ count: 3 })
336
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(true)
337
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
338
+ })
339
+
340
+ test.each(['AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE'])('only terminal %s becomes null', async code => {
341
+ const error = { code, message: 'native api error', retryable: true, outcomeUnknown: false }
342
+ const { client, adapter } = await terminalFixture('failed', { error })
343
+ expect(await agent('failed terminal', { client, cwd: '.' })).toBeNull()
344
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
345
+ for (const stage of ['open', 'submit']) {
346
+ const denied = await fixture(stage === 'open'
347
+ ? { onOpen: async () => { throw new HarnessSdkError(code) } }
348
+ : { execute: async call => { if (call.method === 'input/submit') throw new HarnessSdkError(code); return undefined } })
349
+ await expect(agent('not a terminal', { client: denied.client, cwd: '.' })).rejects.toMatchObject({ code })
350
+ }
351
+ })
352
+
353
+ 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 => {
354
+ const { client } = await terminalFixture('failed', { error: { code, message: 'failure', retryable: false, outcomeUnknown: false } })
355
+ await expect(agent('fail', { client, cwd: '.' })).rejects.toMatchObject({ code })
356
+ })
357
+
358
+ test('uncertainty overrides API and skip classifications, and generic interruptions never become null', async () => {
359
+ for (const status of ['failed', 'interrupted'] as const) {
360
+ const { client } = await terminalFixture(status, { error: { code: 'RATE_LIMITED', message: 'unknown', retryable: false, outcomeUnknown: true, details: { workflowDisposition: 'skipped' } } })
361
+ await expect(agent('unknown', { client, cwd: '.' })).rejects.toMatchObject({ code: 'RATE_LIMITED', outcomeUnknown: true })
362
+ }
363
+ const { client } = await terminalFixture('interrupted')
364
+ await expect(agent('interrupted', { client, cwd: '.' })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
365
+ })
366
+
367
+ test.each([
368
+ { status: 'interrupted', code: 'RATE_LIMITED', details: undefined },
369
+ { status: 'failed', code: 'USER_SKIPPED', details: { workflowDisposition: 'skipped' } },
370
+ ] as const)('$code in a confirmed $status terminal still rejects', async ({ status, code, details }) => {
371
+ const { client } = await terminalFixture(status, { error: {
372
+ code, message: 'failure', retryable: false, outcomeUnknown: false, details,
373
+ } })
374
+ await expect(agent('fail', { client, cwd: '.' })).rejects.toMatchObject({ code, outcomeUnknown: false })
375
+ })
376
+
377
+ test('journaled drops retain their reason codes and still return null', async () => {
378
+ const run = await workflowOptions()
379
+ const limited = await terminalFixture('failed', { error: {
380
+ code: 'RATE_LIMITED', message: 'rate limited', retryable: true, outcomeUnknown: false,
381
+ } })
382
+ const blocked = await fixture({ onOpen: async () => {
383
+ throw new HarnessSdkError('AGENT_STARTUP_BLOCKED', 'blocked', false, false, { workflowDisposition: 'startup_blocked' })
384
+ } })
385
+ const result = await workflow(run, () => parallel([
386
+ () => agent('limited', { client: limited.client, cwd: run.directory }),
387
+ () => agent('blocked', { client: blocked.client, cwd: run.directory }),
388
+ ]))
389
+ expect(result).toMatchObject({ status: 'incomplete', result: [null, null] })
390
+ const events = JSON.parse(await readFile(join(run.directory, result.runId, 'journal.json'), 'utf8'))
391
+ expect(events.filter((event: { type: string }) => event.type === 'failed')).toEqual(expect.arrayContaining([
392
+ expect.objectContaining({ code: 'RATE_LIMITED', outcomeUnknown: false }),
393
+ expect.objectContaining({ code: 'AGENT_STARTUP_BLOCKED', outcomeUnknown: false }),
394
+ ]))
395
+ })
396
+
397
+ test('explicit skip metadata survives terminal-before-reply and startup denial requires its dedicated code', async () => {
398
+ const skipped = await terminalFixture('interrupted', { error: { code: 'USER_SKIPPED', message: 'skipped', retryable: false, outcomeUnknown: false, details: { workflowDisposition: 'skipped' } } })
399
+ expect(await agent('skip', { client: skipped.client, cwd: '.' })).toBeNull()
400
+ expect([...skipped.adapter.backends.values()][0]?.disposeCount).toBe(1)
401
+ const blocked = await fixture({ onOpen: async () => { throw new HarnessSdkError('AGENT_STARTUP_BLOCKED', 'blocked', false, false, { workflowDisposition: 'startup_blocked' }) } })
402
+ expect(await agent('blocked', { client: blocked.client, cwd: '.' })).toBeNull()
403
+ expect(blocked.adapter.calls).toHaveLength(0)
404
+ const denied = await terminalFixture('failed', { error: { code: 'PERMISSION_DENIED', message: 'denied', retryable: false, outcomeUnknown: false, details: { workflowDisposition: 'startup_blocked' } } })
405
+ await expect(agent('denied', { client: denied.client, cwd: '.' })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
406
+ })
407
+
408
+ test.each(['failed', 'interrupted'] as const)('tagged startup denial in a %s terminal returns null after cleanup', async status => {
409
+ const { client, adapter } = await terminalFixture(status, { error: {
410
+ code: 'AGENT_STARTUP_BLOCKED', message: 'blocked', retryable: false, outcomeUnknown: false,
411
+ details: { workflowDisposition: 'startup_blocked' },
412
+ } })
413
+ expect(await agent('blocked', { client, cwd: '.' })).toBeNull()
414
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
415
+ expect(adapter.calls.some(call => call.method === 'session/close')).toBe(true)
416
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
417
+ })
418
+
419
+ test('a null candidate cannot hide cleanup failure', async () => {
420
+ const submit = scriptSubmission(async ({ sink, turnId }) => {
421
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: { code: 'RATE_LIMITED', message: 'rate limit', retryable: true, outcomeUnknown: false } } })
422
+ })
423
+ const { client, adapter } = await fixture({ execute: async (call, sink) => {
424
+ if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
425
+ return submit(call, sink)
426
+ } })
427
+ await expect(agent('rate limited', { client, cwd: '.' })).rejects.toMatchObject({ code: 'RESOURCE_RELEASE_FAILED', details: { droppedError: { code: 'RATE_LIMITED' } } })
428
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
429
+ })
430
+
431
+ test.each(['', 'bad JSON', '{}', '{"count":"3"}'])('invalid structured terminal %j rejects, cleans up and never replays', async text => {
432
+ const { client, adapter } = await terminalFixture('completed', { text })
433
+ await expect(agent('structured', { client, cwd: '.', schema: z.object({ count: z.number() }) })).rejects.toMatchObject({ outcomeUnknown: false, retryable: false })
434
+ expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
435
+ expect(adapter.calls.some(call => call.method === 'session/interrupt' || call.method === 'turn/interrupt')).toBe(false)
436
+ expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
437
+ })
438
+
439
+ test('empty text and multiple final text items retain SDK aggregation', async () => {
440
+ const empty = await terminalFixture('completed', { text: '' })
441
+ expect(await agent('empty', { client: empty.client, cwd: '.' })).toBe('')
442
+ const { client } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
443
+ for (const text of ['first', 'last']) await sink.emit({ type: 'item/completed', payload: { item: { id: text, type: 'agentMessage', phase: 'final', text } } }, { turnId })
444
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
445
+ }) })
446
+ expect(await agent('two', { client, cwd: '.' })).toBe('first\nlast')
447
+ })
448
+
449
+ /** Exercise root overload inference and rejected assignments during package typecheck. */
450
+ function agentTypes(client: Client, dynamic: AgentOptions<z.ZodObject<{ count: z.ZodNumber }>>) {
451
+ const base = { client, cwd: '.' }
452
+ const schema = z.object({ count: z.number() })
453
+ const text: Promise<string | null> = agent('text', base)
454
+ const explicitUndefined: Promise<string | null> = agent('text', { ...base, schema: undefined })
455
+ const value: Promise<{ count: number } | null> = agent('value', { ...base, schema })
456
+ const inline: Promise<{ issues: string[] } | null> = agent('inline', { ...base, schema: z.object({ issues: z.array(z.string()) }) })
457
+ const maybe: Promise<string | { count: number } | null> = agent('dynamic', dynamic)
458
+ // @ts-expect-error Null must be handled.
459
+ const unsafeText: Promise<string> = agent('text', base)
460
+ // @ts-expect-error Schema output is numeric, not a string.
461
+ const wrong: Promise<{ count: string } | null> = agent('value', { ...base, schema })
462
+ // @ts-expect-error Raw JSON Schema is not a workflow schema.
463
+ agent('raw', { ...base, schema: { type: 'object' } })
464
+ // @ts-expect-error A business type cannot replace the schema type parameter.
465
+ agent<{ count: number }>('unbound', { ...base, schema })
466
+ // @ts-expect-error Object roots are required.
467
+ agent('string', { ...base, schema: z.string() })
468
+ void [text, explicitUndefined, value, inline, maybe, unsafeText, wrong]
469
+ }
470
+ void agentTypes
package/src/agent.ts ADDED
@@ -0,0 +1,136 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { HarnessSdkError, sdkError } from '@anureo/sdk'
3
+ import type { z } from 'zod'
4
+ import { executeAgent, prepareAgentCall, type AgentOptions, type PreparedAgentCall } from './agent-execution'
5
+ import type { AgentOutputSchema } from './output-schema'
6
+ import { currentRun, isFatal, type RunContext } from './workflow-state'
7
+ import { canonicalJson, jsonCopy, type JsonValue } from './persistence/json'
8
+
9
+ /**
10
+ * Run a prompt in a fresh session or replay an eligible workflow result. Return the SDK's final
11
+ * text, which can be empty. Fresh execution awaits the associated turn's terminal result.
12
+ * Once a session is acquired, attempt close and then disposal before settlement, even when
13
+ * submission, observation or close fails.
14
+ * Return null for a confirmed authentication, usage-limit, rate-limit or service-unavailability
15
+ * failure reported in a failed terminal, an explicit skip reported on interruption, or a tagged
16
+ * startup denial. Unknown outcomes, other execution failures and cleanup failures reject.
17
+ * Cleanup failures preserve a primary execution error with details.cleanupErrors, or reject with
18
+ * RESOURCE_RELEASE_FAILED. The caller decides whether to retry or request interruption through
19
+ * the SDK. Agent submits at most once per call. Session release ends local observation and can
20
+ * leave native execution running.
21
+ * Inside workflow(), reserve cache keys in invocation order and reuse eligible saved results on
22
+ * resume without opening a session. A journal miss awaits publication of its started record before
23
+ * dispatch and its terminal record before returning a result. Checkpoint failures reject. A saved
24
+ * failure with an unknown outcome at the same key rejects with WORKFLOW_RECONCILIATION_REQUIRED.
25
+ * Keep the borrowed client usable until settlement and dispose it separately when finished.
26
+ */
27
+ export function agent(prompt: string, options: AgentOptions<never> & { schema?: undefined }): Promise<string | null>
28
+ /**
29
+ * Return typed output from a portable Zod object schema, with the same session ownership,
30
+ * cleanup, drop, and journal behavior as text mode.
31
+ * Unsupported schemas reject before opening. Validation awaits async refinements for fresh and
32
+ * replayed results. The JSON must supply every required field before Zod checks run.
33
+ * Missing, malformed or invalid JSON rejects without resubmitting the prompt.
34
+ */
35
+ export function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S> & { schema: S }): Promise<z.output<S> | null>
36
+ /** Return text when schema is omitted or undefined, or validated data when it is supplied.
37
+ * Both modes share agent's session ownership, cleanup, drop, and journal behavior. */
38
+ export function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S>): Promise<string | z.output<S> | null>
39
+ export async function agent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
40
+ const context = currentRun()
41
+ if (context) return memoizedAgent(context, prompt, options)
42
+ const outcome = await executeAgent(prompt, prepareAgentCall(options))
43
+ return outcome.status === 'dropped' ? null : outcome.value
44
+ }
45
+
46
+ /**
47
+ * Track preflight, replay and execution so workflow observes failures and can drain unawaited calls.
48
+ * Prepare the call and reserve its key synchronously in invocation order.
49
+ */
50
+ async function memoizedAgent(
51
+ context: RunContext,
52
+ prompt: string,
53
+ options: AgentOptions,
54
+ ): Promise<string | Record<string, unknown> | null> {
55
+ const { journal, state } = context
56
+ return state.track(() => {
57
+ const call = prepareAgentCall(options)
58
+ const key = journal.nextKey(prompt, canonicalOptions(call))
59
+ const decision = journal.resolveCall(key)
60
+ if (decision.action === 'replay') return replayAgentResult(decision.result, call.output)
61
+ if (decision.action === 'reconcile') {
62
+ throw new HarnessSdkError('WORKFLOW_RECONCILIATION_REQUIRED',
63
+ 'A previous run left this agent call with an unknown outcome; reconcile it before resuming', false, true)
64
+ }
65
+ return executeJournaledAgent({ context, key, prompt, call })
66
+ })
67
+ }
68
+
69
+ /** Project the options memoizedAgent hashes with the prompt. Preserve the persisted key format
70
+ * by using null for absent model, instructions, permission mode and schema, and omitting absent
71
+ * fallback. Use the client identity so equivalent backend configurations can share a key. */
72
+ function canonicalOptions(call: PreparedAgentCall): JsonValue {
73
+ return {
74
+ model: call.model ?? null,
75
+ instructions: call.instructions ?? null,
76
+ permissionMode: call.permissionMode ?? null,
77
+ schema: call.output?.schema ?? null,
78
+ ...(call.outputFallback ? { outputFallback: call.outputFallback } : {}),
79
+ cwd: call.cwd,
80
+ client: call.client.identity,
81
+ }
82
+ }
83
+
84
+ /** Return saved text or await current schema validation for memoizedAgent's typed hit.
85
+ * A rejected validation propagates to the agent caller without rerunning the prompt. */
86
+ async function replayAgentResult(
87
+ hit: JsonValue,
88
+ output: AgentOutputSchema | undefined,
89
+ ): Promise<string | Record<string, unknown>> {
90
+ return output ? output.parse(canonicalJson(hit)) : hit as string
91
+ }
92
+
93
+ /**
94
+ * Execute memoizedAgent's cache miss after saving its started marker and rechecking dispatch.
95
+ * Await fresh execution and session release before publishing the terminal event. Drops mark
96
+ * the run incomplete. Fatal failures stop later dispatch, and WORKFLOW_STORAGE_FAILED rejects
97
+ * without attempting a second terminal write. The dispatch check is outside the execution catch
98
+ * so a call stopped during publication retains its started marker.
99
+ */
100
+ async function executeJournaledAgent({ context, key, prompt, call }: {
101
+ context: RunContext
102
+ key: string
103
+ prompt: string
104
+ call: PreparedAgentCall
105
+ }): Promise<string | Record<string, unknown> | null> {
106
+ const { journal, state } = context
107
+ const agentId = randomUUID()
108
+ await journal.append({ type: 'started', key, agentId })
109
+ state.assertDispatch()
110
+ try {
111
+ const outcome = await executeAgent(prompt, call)
112
+ if (outcome.status === 'dropped') {
113
+ await journal.append({ type: 'failed', key, agentId, code: outcome.error.code, outcomeUnknown: false })
114
+ state.noteIncomplete()
115
+ return null
116
+ }
117
+ const stored = jsonCopy(outcome.value) as JsonValue
118
+ await journal.append({ type: 'result', key, agentId, result: stored })
119
+ return jsonCopy(stored) as string | Record<string, unknown>
120
+ } catch (cause) {
121
+ const error = sdkError(cause, 'AGENT_FAILED')
122
+ if (isFatal(error)) state.stop(error)
123
+ // The storage layer may have published a terminal record already.
124
+ if (error.code !== 'WORKFLOW_STORAGE_FAILED') {
125
+ try {
126
+ await journal.append({ type: 'failed', key, agentId,
127
+ code: error.code, outcomeUnknown: error.outcomeUnknown === true })
128
+ } catch {
129
+ state.noteStorageFailure()
130
+ throw new HarnessSdkError(error.code, error.message, error.retryable, error.outcomeUnknown,
131
+ { ...error.details, journalErrorCode: 'WORKFLOW_STORAGE_FAILED' })
132
+ }
133
+ }
134
+ throw error
135
+ }
136
+ }