@anureo/workflow 0.3.4 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/agent.test.ts CHANGED
@@ -1,25 +1,53 @@
1
1
  import { afterEach, expect, test } from 'bun:test'
2
2
  import { randomUUID } from 'node:crypto'
3
- import { createClient, HarnessSdkError, type Client, type SessionEventSink } from '@anureo/sdk'
4
- import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
5
- import { z } from 'zod'
6
- import { agent, parallel, pipeline, type AgentOptions } from './index'
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
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'
8
12
 
9
13
  const clients: Client[] = []
10
- afterEach(async () => { await Promise.all(clients.splice(0).map(client => client.dispose())) })
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
+ })
11
20
 
12
- async function fixture(options?: FakeAdapterOptions) {
13
- const adapter = createScriptedAdapter(options)
14
- const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
15
- clients.push(client)
16
- return { client, adapter }
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: {} }
17
25
  }
26
+
27
+ /** Publish final text before the test terminal so Turn.result retains it. */
18
28
  async function complete(sink: SessionEventSink, turnId: string, text: string) {
19
29
  await sink.emit({ type: 'item/completed', payload: { item: { id: randomUUID(), type: 'agentMessage', phase: 'final', text } } }, { turnId })
20
30
  await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
21
31
  }
22
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
+
23
51
  test('returns text from independent sessions and leaves the borrowed client usable', async () => {
24
52
  const { client, adapter } = await fixture()
25
53
  expect(await parallel([
@@ -44,6 +72,32 @@ test('each call chooses its backend explicitly without shared configuration', as
44
72
  expect(b.adapter.opened[0]?.cwd).toBe('/b')
45
73
  })
46
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
+
47
101
  test('native association and acceptance do not replace terminal evidence', async () => {
48
102
  const { promise: terminalEmitterReady, resolve: resolveTerminalEmitter } = Promise.withResolvers<() => Promise<void>>()
49
103
  const { client, adapter } = await fixture({ execute: async (call, sink) => {
@@ -63,16 +117,31 @@ test('native association and acceptance do not replace terminal evidence', async
63
117
  expect(await result).toBe('actual terminal text')
64
118
  })
65
119
 
66
- test('preserves native failure details and releases the session', async () => {
120
+ test.each(['associationMs', 'resultMs'] as const)('%s expires with an unknown outcome and releases the session', async phase => {
67
121
  const { client, adapter } = await fixture({ execute: async (call, sink) => {
68
122
  if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
69
- const turnId = randomUUID()
70
- await sink.emit({ type: 'turn/started', payload: { turnId } })
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 }) => {
71
141
  await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
72
142
  code: 'NATIVE_FAILED', message: 'native failure', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
73
143
  } } })
74
- return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
75
- } })
144
+ }) })
76
145
  await expect(agent('fail', { client, cwd: process.cwd() })).rejects.toMatchObject({
77
146
  code: 'NATIVE_FAILED', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
78
147
  })
@@ -81,13 +150,9 @@ test('preserves native failure details and releases the session', async () => {
81
150
  })
82
151
 
83
152
  test('an interrupted execution cannot return successful text', async () => {
84
- const { client, adapter } = await fixture({ execute: async (call, sink) => {
85
- if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
86
- const turnId = randomUUID()
87
- await sink.emit({ type: 'turn/started', payload: { turnId } })
153
+ const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
88
154
  await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'interrupted' } })
89
- return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
90
- } })
155
+ }) })
91
156
  await expect(agent('interrupted', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
92
157
  expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
93
158
  })
@@ -104,15 +169,35 @@ test('unknown submission outcomes are preserved without retries or implicit inte
104
169
  expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
105
170
  })
106
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
+
107
196
  test('source failure remains uncertain and is not converted into successful cleanup', async () => {
108
- const { client, adapter } = await fixture({ execute: async (call, sink) => {
109
- if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
110
- const turnId = randomUUID()
111
- await sink.emit({ type: 'turn/started', payload: { turnId } })
112
- await sink.bindSubmission(call.params.submissionId, turnId)
197
+ const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId, submissionId }) => {
198
+ await sink.bindSubmission(submissionId, turnId)
113
199
  await sink.fail(new HarnessSdkError('CONNECTION_LOST', 'lost', false, true))
114
- return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
115
- } })
200
+ }) })
116
201
  await expect(agent('source disappears', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'CONNECTION_LOST', outcomeUnknown: true })
117
202
  expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
118
203
  })
@@ -149,19 +234,37 @@ test('cleanup failure cannot hide the primary uncertain execution failure', asyn
149
234
  expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
150
235
  })
151
236
 
152
- async function terminalFixture(
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(
153
255
  status: 'failed' | 'interrupted' | 'completed',
154
- { error, text = 'partial' }: { error?: HarnessError; text?: string } = {},
256
+ { error, text = 'partial', outputSchema = true }: { error?: HarnessError; text?: string; outputSchema?: boolean } = {},
155
257
  ) {
156
- return fixture({ execute: async (call, sink) => {
157
- if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
158
- const turnId = randomUUID()
159
- await sink.emit({ type: 'turn/started', payload: { turnId } })
160
- await sink.emit({ type: 'item/completed', payload: { item: { id: 'output', type: 'agentMessage', phase: 'final', text } } }, { turnId })
161
- // Deliberately terminal before submit's reply: no event subscription can recover this later.
162
- await sink.emit({ type: 'turn/completed', payload: { turnId, status, ...(error ? { error } : {}) } })
163
- return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
164
- } })
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
+ })
165
268
  }
166
269
 
167
270
  test('Zod schema is converted for submission and returns typed data through composition', async () => {
@@ -187,6 +290,53 @@ test('schema preflight rejects before opening, while absent backend support rele
187
290
  expect([...unsupported.adapter.backends.values()][0]?.disposeCount).toBe(1)
188
291
  })
189
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
+
190
340
  test.each(['AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE'])('only terminal %s becomes null', async code => {
191
341
  const error = { code, message: 'native api error', retryable: true, outcomeUnknown: false }
192
342
  const { client, adapter } = await terminalFixture('failed', { error })
@@ -214,6 +364,36 @@ test('uncertainty overrides API and skip classifications, and generic interrupti
214
364
  await expect(agent('interrupted', { client, cwd: '.' })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
215
365
  })
216
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
+
217
397
  test('explicit skip metadata survives terminal-before-reply and startup denial requires its dedicated code', async () => {
218
398
  const skipped = await terminalFixture('interrupted', { error: { code: 'USER_SKIPPED', message: 'skipped', retryable: false, outcomeUnknown: false, details: { workflowDisposition: 'skipped' } } })
219
399
  expect(await agent('skip', { client: skipped.client, cwd: '.' })).toBeNull()
@@ -225,14 +405,24 @@ test('explicit skip metadata survives terminal-before-reply and startup denial r
225
405
  await expect(agent('denied', { client: denied.client, cwd: '.' })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
226
406
  })
227
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
+
228
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
+ })
229
423
  const { client, adapter } = await fixture({ execute: async (call, sink) => {
230
424
  if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
231
- if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
232
- const turnId = randomUUID()
233
- await sink.emit({ type: 'turn/started', payload: { turnId } })
234
- await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: { code: 'RATE_LIMITED', message: 'rate limit', retryable: true, outcomeUnknown: false } } })
235
- return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
425
+ return submit(call, sink)
236
426
  } })
237
427
  await expect(agent('rate limited', { client, cwd: '.' })).rejects.toMatchObject({ code: 'RESOURCE_RELEASE_FAILED', details: { droppedError: { code: 'RATE_LIMITED' } } })
238
428
  expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
@@ -249,18 +439,14 @@ test.each(['', 'bad JSON', '{}', '{"count":"3"}'])('invalid structured terminal
249
439
  test('empty text and multiple final text items retain SDK aggregation', async () => {
250
440
  const empty = await terminalFixture('completed', { text: '' })
251
441
  expect(await agent('empty', { client: empty.client, cwd: '.' })).toBe('')
252
- const { client } = await fixture({ execute: async (call, sink) => {
253
- if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
254
- const turnId = randomUUID()
255
- await sink.emit({ type: 'turn/started', payload: { turnId } })
442
+ const { client } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
256
443
  for (const text of ['first', 'last']) await sink.emit({ type: 'item/completed', payload: { item: { id: text, type: 'agentMessage', phase: 'final', text } } }, { turnId })
257
444
  await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
258
- return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
259
- } })
445
+ }) })
260
446
  expect(await agent('two', { client, cwd: '.' })).toBe('first\nlast')
261
447
  })
262
448
 
263
- // Compiled by package typecheck; never invoke real clients from type assertions.
449
+ /** Exercise root overload inference and rejected assignments during package typecheck. */
264
450
  function agentTypes(client: Client, dynamic: AgentOptions<z.ZodObject<{ count: z.ZodNumber }>>) {
265
451
  const base = { client, cwd: '.' }
266
452
  const schema = z.object({ count: z.number() })
package/src/agent.ts CHANGED
@@ -1,111 +1,80 @@
1
- import { HarnessSdkError, sdkError, type Client } from '@anureo/sdk'
1
+ import { HarnessSdkError } from '@anureo/sdk'
2
2
  import type { z } from 'zod'
3
- import { prepareOutputSchema } from './output-schema'
4
- import { isDroppedOutcome, isStartupBlockException } from './agent-outcome'
5
- import { currentRun } from './run-context'
3
+ import { executeAgent, prepareAgentCall, type AgentOptions, type PreparedAgentCall } from './agent-execution'
4
+ import { currentRun } from './workflow-state'
6
5
  import { journaledCall } from './journal-call'
7
6
  import { canonicalJson, type JsonValue } from './persistence/json'
8
- import type { JsonObject } from '@anureo/protocol'
9
-
10
- // Do not impose the SDK's short observation timeout on model execution.
11
- const LONG_OBSERVATION_TIMEOUT_MS = 0x7fffffff
12
-
13
- export interface AgentOptions<S extends z.ZodObject = z.ZodObject> {
14
- client: Client
15
- cwd: string
16
- model?: string
17
- instructions?: string
18
- /** Optional openSession permission mode; unsupported values fail session open. */
19
- permissionMode?: string
20
- schema?: S
21
- }
22
-
23
- type AgentOutcome =
24
- | { status: 'completed'; value: string | Record<string, unknown> }
25
- | { status: 'dropped'; error: { code: string; outcomeUnknown: boolean } }
26
- | { status: 'failed'; error: HarnessSdkError }
27
7
 
8
+ /**
9
+ * Run a prompt in a fresh session or replay an eligible workflow result. Return the SDK's final
10
+ * text, which can be empty. Fresh execution awaits the associated turn's terminal result.
11
+ * Once a session is acquired, attempt close and then disposal before settlement, even when
12
+ * submission, observation or close fails.
13
+ * Return null for a confirmed authentication, usage-limit, rate-limit or service-unavailability
14
+ * failure reported in a failed terminal, an explicit skip reported on interruption, or a tagged
15
+ * startup denial. Unknown outcomes, other execution failures and cleanup failures reject.
16
+ * Cleanup failures preserve a primary execution error with details.cleanupErrors, or reject with
17
+ * RESOURCE_RELEASE_FAILED. The caller decides whether to retry or request interruption through
18
+ * the SDK. Agent submits at most once per call. Session release ends local observation and can
19
+ * leave native execution running.
20
+ * Inside workflow(), reserve cache keys in invocation order and reuse eligible saved results on
21
+ * resume without opening a session. A journal miss awaits publication of its started record before
22
+ * dispatch and its terminal record before returning a result. Checkpoint failures reject. A saved
23
+ * failure with an unknown outcome at the same key rejects with WORKFLOW_RECONCILIATION_REQUIRED.
24
+ * Keep the borrowed client usable until settlement and dispose it separately when finished.
25
+ */
28
26
  export function agent(prompt: string, options: AgentOptions<never> & { schema?: undefined }): Promise<string | null>
27
+ /**
28
+ * Return typed output from a portable Zod object schema, with the same session ownership,
29
+ * cleanup, drop, and journal behavior as text mode.
30
+ * Unsupported schemas reject before opening. Validation awaits async refinements for fresh and
31
+ * replayed results. The JSON must supply every required field before Zod checks run.
32
+ * Missing, malformed or invalid JSON rejects without resubmitting the prompt.
33
+ */
29
34
  export function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S> & { schema: S }): Promise<z.output<S> | null>
35
+ /** Return text when schema is omitted or undefined, or validated data when it is supplied.
36
+ * Both modes share agent's session ownership, cleanup, drop, and journal behavior. */
30
37
  export function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S>): Promise<string | z.output<S> | null>
31
- /** Execute one fresh session, validate its terminal output, and release its observation resources. */
32
38
  export async function agent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
33
39
  const context = currentRun()
34
40
  if (context) return memoizedAgent(prompt, options)
35
- return executeAgent(prompt, options)
41
+ const outcome = await executeAgent(prompt, prepareAgentCall(options))
42
+ return outcome.status === 'dropped' ? null : outcome.value
36
43
  }
37
44
 
38
- /** Semantic fields participating in the journal cache identity; presentation fields never do. */
39
- function canonicalOptions(options: AgentOptions, schema: JsonObject | undefined): JsonValue {
45
+ /** Project the options the journaled call hashes with the prompt. Preserve the persisted key
46
+ * format by using null for absent model, instructions, permission mode and schema, and omitting
47
+ * absent fallback. Use the client identity so equivalent backend configurations share a key. */
48
+ function canonicalOptions(call: PreparedAgentCall): JsonValue {
40
49
  return {
41
- model: options.model ?? null,
42
- instructions: options.instructions ?? null,
43
- permissionMode: options.permissionMode ?? null,
44
- schema: schema ?? null,
45
- cwd: options.cwd,
46
- client: options.client.identity,
50
+ model: call.model ?? null,
51
+ instructions: call.instructions ?? null,
52
+ permissionMode: call.permissionMode ?? null,
53
+ schema: call.output?.schema ?? null,
54
+ ...(call.outputFallback ? { outputFallback: call.outputFallback } : {}),
55
+ cwd: call.cwd,
56
+ client: call.client.identity,
47
57
  }
48
58
  }
49
59
 
50
- async function memoizedAgent<S extends z.ZodObject>(
51
- prompt: string,
52
- options: AgentOptions<S>,
53
- ): Promise<string | z.output<S> | null> {
54
- const output = options.schema === undefined ? undefined : prepareOutputSchema(options.schema)
55
- const call = {
56
- prompt,
57
- canonical: canonicalOptions(options, output?.schema),
58
- // Older SDK clients have no input-hook revision; the journal key tolerates undefined.
59
- inputHookRevision: (options.client as { inputHookRevision?: string }).inputHookRevision,
60
- }
61
- const execute = () => executeAgent(prompt, options) as Promise<JsonValue | null>
62
- if (output) return journaledCall(call, execute, stored => output.parse(canonicalJson(stored)) as z.output<S>)
63
- return journaledCall(call, execute) as Promise<string | z.output<S> | null>
64
- }
65
-
66
- async function executeAgent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
67
- const { client, cwd, model, instructions, permissionMode, schema } = options
68
- const output = schema === undefined ? undefined : prepareOutputSchema(schema)
69
- const session = await client.sessions.create({ cwd, ...(model !== undefined ? { model } : {}), ...(instructions !== undefined ? { instructions } : {}), ...(permissionMode !== undefined ? { permissionMode } : {}) })
70
- .catch(cause => { if (isStartupBlockException(cause)) return null; throw cause })
71
- if (!session) return null // A failed open never hands session ownership to this call.
72
- let outcome: AgentOutcome
73
- try {
74
- if (output && !session.capabilities.turn?.outputSchema) throw new HarnessSdkError('CAPABILITY_UNSUPPORTED', 'Session does not support structured output')
75
- const turn = await session.submit({ input: prompt, ...(output ? { outputSchema: output.schema } : {}) }, { timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
76
- const result = await turn.result({ timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
77
- if (result.status === 'completed') {
78
- outcome = { status: 'completed', value: output ? await output.parse(result.text) : result.text }
79
- } else if (result.error && isDroppedOutcome(result.error, result.status)) {
80
- outcome = { status: 'dropped', error: { code: result.error.code, outcomeUnknown: result.error.outcomeUnknown } }
81
- } else if (result.error) {
82
- const { code, message, retryable, outcomeUnknown, details } = result.error
83
- throw new HarnessSdkError(code, message, retryable, outcomeUnknown, details)
84
- } else {
85
- throw new HarnessSdkError('AGENT_INTERRUPTED')
86
- }
87
- } catch (cause) {
88
- if (isStartupBlockException(cause)) outcome = { status: 'dropped', error: { code: cause.code, outcomeUnknown: cause.outcomeUnknown } }
89
- else outcome = { status: 'failed', error: sdkError(cause, 'AGENT_FAILED', true) }
90
- }
91
-
92
- // Closing observation does not prove the backend execution stopped. Never retry input.
93
- const cleanupErrors = new Set<HarnessSdkError>()
94
- try { await session.close() } catch (cause) { cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true)) }
95
- try { await session.dispose() } catch (cause) { cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true)) }
96
- if (cleanupErrors.size) {
97
- const errors = [...cleanupErrors].map(error => ({ code: error.code, outcomeUnknown: error.outcomeUnknown }))
98
- if (outcome.status === 'failed') {
99
- const failure = outcome.error
100
- throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown,
101
- { ...failure.details, cleanupErrors: errors })
102
- }
103
- throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false,
104
- errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) })
60
+ /** Reserve the journal key synchronously through journaledCall, then replay the saved result or
61
+ * execute fresh through agent-execution. The prepared call is built inside the tracked region so
62
+ * preflight failures mark the run incomplete. Schema validation awaits async refinements for
63
+ * fresh and replayed results. Drops mark the run incomplete; fatal failures stop later dispatch. */
64
+ async function memoizedAgent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
65
+ let prepared!: PreparedAgentCall
66
+ /** The drop reason is only known after execution; the journal reads it lazily at append time. */
67
+ const dropCode = { value: undefined as string | undefined }
68
+ const build = () => {
69
+ prepared = prepareAgentCall(options)
70
+ return { prompt, canonical: canonicalOptions(prepared), get droppedCode() { return dropCode.value } }
105
71
  }
106
- switch (outcome.status) {
107
- case 'completed': return outcome.value
108
- case 'dropped': return null
109
- case 'failed': throw outcome.error
72
+ const run = () => executeAgent(prompt, prepared).then(outcome => {
73
+ if (outcome.status === 'dropped') dropCode.value = outcome.error.code
74
+ return outcome.status === 'dropped' ? null : outcome.value as JsonValue
75
+ })
76
+ if (options.schema !== undefined) {
77
+ return journaledCall(build, run, stored => prepared.output!.parse(canonicalJson(stored))) as Promise<string | Record<string, unknown> | null>
110
78
  }
79
+ return journaledCall(build, run) as Promise<string | Record<string, unknown> | null>
111
80
  }