@anureo/workflow 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -96
- package/package.json +4 -5
- package/src/agent-mcp.test.ts +19 -0
- package/src/agent-outcome.ts +21 -0
- package/src/agent-pi.test.ts +21 -0
- package/src/agent.test.ts +51 -237
- package/src/agent.ts +89 -115
- package/src/fixtures/workflow-crash.ts +17 -54
- package/src/index.ts +5 -6
- package/src/journal-call.test.ts +68 -0
- package/src/journal-call.ts +93 -0
- package/src/native.test.ts +71 -0
- package/src/output-schema.test.ts +12 -45
- package/src/output-schema.ts +96 -208
- package/src/parallel.test.ts +0 -1
- package/src/parallel.ts +8 -26
- package/src/persistence/atomic.ts +32 -0
- package/src/persistence/journal.ts +92 -104
- package/src/persistence/json.ts +32 -58
- package/src/persistence/records.ts +56 -82
- package/src/persistence/replay.ts +30 -74
- package/src/persistence/store.ts +120 -259
- package/src/pipeline.test.ts +0 -19
- package/src/pipeline.ts +23 -69
- package/src/run-context.ts +19 -0
- package/src/workflow-state.ts +18 -72
- package/src/workflow-types.ts +2 -20
- package/src/workflow.test.ts +104 -199
- package/src/workflow.ts +30 -88
- package/src/agent-adapters.test.ts +0 -121
- package/src/agent-execution.ts +0 -220
- package/src/persistence/checkpoint-files.ts +0 -83
- package/src/test-helpers.ts +0 -23
package/src/agent.test.ts
CHANGED
|
@@ -1,53 +1,25 @@
|
|
|
1
1
|
import { afterEach, expect, test } from 'bun:test'
|
|
2
2
|
import { randomUUID } from 'node:crypto'
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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'
|
|
3
|
+
import { createClient, HarnessSdkError, type Client, type SessionEventSink } from '@anureo/sdk'
|
|
4
|
+
import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
|
|
9
5
|
import { z } from 'zod'
|
|
10
|
-
import { agent, parallel, pipeline,
|
|
11
|
-
import {
|
|
6
|
+
import { agent, parallel, pipeline, type AgentOptions } from './index'
|
|
7
|
+
import type { HarnessError } from '@anureo/protocol'
|
|
12
8
|
|
|
13
9
|
const clients: Client[] = []
|
|
14
|
-
|
|
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
|
-
})
|
|
10
|
+
afterEach(async () => { await Promise.all(clients.splice(0).map(client => client.dispose())) })
|
|
20
11
|
|
|
21
|
-
async function
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
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 }
|
|
25
17
|
}
|
|
26
|
-
|
|
27
|
-
/** Publish final text before the test terminal so Turn.result retains it. */
|
|
28
18
|
async function complete(sink: SessionEventSink, turnId: string, text: string) {
|
|
29
19
|
await sink.emit({ type: 'item/completed', payload: { item: { id: randomUUID(), type: 'agentMessage', phase: 'final', text } } }, { turnId })
|
|
30
20
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
|
|
31
21
|
}
|
|
32
22
|
|
|
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
23
|
test('returns text from independent sessions and leaves the borrowed client usable', async () => {
|
|
52
24
|
const { client, adapter } = await fixture()
|
|
53
25
|
expect(await parallel([
|
|
@@ -72,32 +44,6 @@ test('each call chooses its backend explicitly without shared configuration', as
|
|
|
72
44
|
expect(b.adapter.opened[0]?.cwd).toBe('/b')
|
|
73
45
|
})
|
|
74
46
|
|
|
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
47
|
test('native association and acceptance do not replace terminal evidence', async () => {
|
|
102
48
|
const { promise: terminalEmitterReady, resolve: resolveTerminalEmitter } = Promise.withResolvers<() => Promise<void>>()
|
|
103
49
|
const { client, adapter } = await fixture({ execute: async (call, sink) => {
|
|
@@ -117,31 +63,16 @@ test('native association and acceptance do not replace terminal evidence', async
|
|
|
117
63
|
expect(await result).toBe('actual terminal text')
|
|
118
64
|
})
|
|
119
65
|
|
|
120
|
-
test
|
|
66
|
+
test('preserves native failure details and releases the session', async () => {
|
|
121
67
|
const { client, adapter } = await fixture({ execute: async (call, sink) => {
|
|
122
68
|
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
123
|
-
const
|
|
124
|
-
|
|
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 }) => {
|
|
69
|
+
const turnId = randomUUID()
|
|
70
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
141
71
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
|
|
142
72
|
code: 'NATIVE_FAILED', message: 'native failure', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
|
|
143
73
|
} } })
|
|
144
|
-
|
|
74
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
75
|
+
} })
|
|
145
76
|
await expect(agent('fail', { client, cwd: process.cwd() })).rejects.toMatchObject({
|
|
146
77
|
code: 'NATIVE_FAILED', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
|
|
147
78
|
})
|
|
@@ -150,9 +81,13 @@ test('preserves native failure details and releases the session', async () => {
|
|
|
150
81
|
})
|
|
151
82
|
|
|
152
83
|
test('an interrupted execution cannot return successful text', async () => {
|
|
153
|
-
const { client, adapter } = await fixture({ execute:
|
|
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 } })
|
|
154
88
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'interrupted' } })
|
|
155
|
-
|
|
89
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
90
|
+
} })
|
|
156
91
|
await expect(agent('interrupted', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
|
|
157
92
|
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
158
93
|
})
|
|
@@ -169,35 +104,15 @@ test('unknown submission outcomes are preserved without retries or implicit inte
|
|
|
169
104
|
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
170
105
|
})
|
|
171
106
|
|
|
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
107
|
test('source failure remains uncertain and is not converted into successful cleanup', async () => {
|
|
197
|
-
const { client, adapter } = await fixture({ execute:
|
|
198
|
-
|
|
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)
|
|
199
113
|
await sink.fail(new HarnessSdkError('CONNECTION_LOST', 'lost', false, true))
|
|
200
|
-
|
|
114
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
115
|
+
} })
|
|
201
116
|
await expect(agent('source disappears', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'CONNECTION_LOST', outcomeUnknown: true })
|
|
202
117
|
expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
|
|
203
118
|
})
|
|
@@ -234,37 +149,19 @@ test('cleanup failure cannot hide the primary uncertain execution failure', asyn
|
|
|
234
149
|
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
235
150
|
})
|
|
236
151
|
|
|
237
|
-
|
|
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(
|
|
152
|
+
async function terminalFixture(
|
|
255
153
|
status: 'failed' | 'interrupted' | 'completed',
|
|
256
|
-
{ error, text = 'partial'
|
|
154
|
+
{ error, text = 'partial' }: { error?: HarnessError; text?: string } = {},
|
|
257
155
|
) {
|
|
258
|
-
return fixture({
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
})
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
})
|
|
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
|
+
} })
|
|
268
165
|
}
|
|
269
166
|
|
|
270
167
|
test('Zod schema is converted for submission and returns typed data through composition', async () => {
|
|
@@ -290,53 +187,6 @@ test('schema preflight rejects before opening, while absent backend support rele
|
|
|
290
187
|
expect([...unsupported.adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
291
188
|
})
|
|
292
189
|
|
|
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
190
|
test.each(['AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE'])('only terminal %s becomes null', async code => {
|
|
341
191
|
const error = { code, message: 'native api error', retryable: true, outcomeUnknown: false }
|
|
342
192
|
const { client, adapter } = await terminalFixture('failed', { error })
|
|
@@ -364,36 +214,6 @@ test('uncertainty overrides API and skip classifications, and generic interrupti
|
|
|
364
214
|
await expect(agent('interrupted', { client, cwd: '.' })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
|
|
365
215
|
})
|
|
366
216
|
|
|
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
217
|
test('explicit skip metadata survives terminal-before-reply and startup denial requires its dedicated code', async () => {
|
|
398
218
|
const skipped = await terminalFixture('interrupted', { error: { code: 'USER_SKIPPED', message: 'skipped', retryable: false, outcomeUnknown: false, details: { workflowDisposition: 'skipped' } } })
|
|
399
219
|
expect(await agent('skip', { client: skipped.client, cwd: '.' })).toBeNull()
|
|
@@ -405,24 +225,14 @@ test('explicit skip metadata survives terminal-before-reply and startup denial r
|
|
|
405
225
|
await expect(agent('denied', { client: denied.client, cwd: '.' })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
|
|
406
226
|
})
|
|
407
227
|
|
|
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
228
|
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
229
|
const { client, adapter } = await fixture({ execute: async (call, sink) => {
|
|
424
230
|
if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
|
|
425
|
-
|
|
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 }
|
|
426
236
|
} })
|
|
427
237
|
await expect(agent('rate limited', { client, cwd: '.' })).rejects.toMatchObject({ code: 'RESOURCE_RELEASE_FAILED', details: { droppedError: { code: 'RATE_LIMITED' } } })
|
|
428
238
|
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
@@ -439,14 +249,18 @@ test.each(['', 'bad JSON', '{}', '{"count":"3"}'])('invalid structured terminal
|
|
|
439
249
|
test('empty text and multiple final text items retain SDK aggregation', async () => {
|
|
440
250
|
const empty = await terminalFixture('completed', { text: '' })
|
|
441
251
|
expect(await agent('empty', { client: empty.client, cwd: '.' })).toBe('')
|
|
442
|
-
const { client } = await fixture({ execute:
|
|
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 } })
|
|
443
256
|
for (const text of ['first', 'last']) await sink.emit({ type: 'item/completed', payload: { item: { id: text, type: 'agentMessage', phase: 'final', text } } }, { turnId })
|
|
444
257
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
|
|
445
|
-
|
|
258
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
259
|
+
} })
|
|
446
260
|
expect(await agent('two', { client, cwd: '.' })).toBe('first\nlast')
|
|
447
261
|
})
|
|
448
262
|
|
|
449
|
-
|
|
263
|
+
// Compiled by package typecheck; never invoke real clients from type assertions.
|
|
450
264
|
function agentTypes(client: Client, dynamic: AgentOptions<z.ZodObject<{ count: z.ZodNumber }>>) {
|
|
451
265
|
const base = { client, cwd: '.' }
|
|
452
266
|
const schema = z.object({ count: z.number() })
|
package/src/agent.ts
CHANGED
|
@@ -1,136 +1,110 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { HarnessSdkError, sdkError } from '@anureo/sdk'
|
|
1
|
+
import { HarnessSdkError, sdkError, type Client } from '@anureo/sdk'
|
|
3
2
|
import type { z } from 'zod'
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import { currentRun
|
|
7
|
-
import {
|
|
3
|
+
import { prepareOutputSchema } from './output-schema'
|
|
4
|
+
import { isDroppedOutcome, isStartupBlockException } from './agent-outcome'
|
|
5
|
+
import { currentRun } from './run-context'
|
|
6
|
+
import { journaledCall } from './journal-call'
|
|
7
|
+
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 }
|
|
8
27
|
|
|
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
28
|
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
29
|
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
30
|
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. */
|
|
39
32
|
export async function agent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
|
|
40
33
|
const context = currentRun()
|
|
41
|
-
if (context) return memoizedAgent(
|
|
42
|
-
|
|
43
|
-
return outcome.status === 'dropped' ? null : outcome.value
|
|
34
|
+
if (context) return memoizedAgent(prompt, options)
|
|
35
|
+
return executeAgent(prompt, options)
|
|
44
36
|
}
|
|
45
37
|
|
|
46
|
-
/**
|
|
47
|
-
|
|
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 {
|
|
38
|
+
/** Semantic fields participating in the journal cache identity; presentation fields never do. */
|
|
39
|
+
function canonicalOptions(options: AgentOptions, schema: JsonObject | undefined): JsonValue {
|
|
73
40
|
return {
|
|
74
|
-
model:
|
|
75
|
-
instructions:
|
|
76
|
-
permissionMode:
|
|
77
|
-
schema:
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
client: call.client.identity,
|
|
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,
|
|
81
47
|
}
|
|
82
48
|
}
|
|
83
49
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
output
|
|
89
|
-
|
|
90
|
-
|
|
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
|
+
inputHookRevision: options.client.inputHookRevision,
|
|
59
|
+
}
|
|
60
|
+
const execute = () => executeAgent(prompt, options) as Promise<JsonValue | null>
|
|
61
|
+
if (output) return journaledCall(call, execute, stored => output.parse(canonicalJson(stored)) as z.output<S>)
|
|
62
|
+
return journaledCall(call, execute) as Promise<string | z.output<S> | null>
|
|
91
63
|
}
|
|
92
64
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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()
|
|
65
|
+
async function executeAgent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
|
|
66
|
+
const { client, cwd, model, instructions, permissionMode, schema } = options
|
|
67
|
+
const output = schema === undefined ? undefined : prepareOutputSchema(schema)
|
|
68
|
+
const session = await client.sessions.create({ cwd, ...(model !== undefined ? { model } : {}), ...(instructions !== undefined ? { instructions } : {}), ...(permissionMode !== undefined ? { permissionMode } : {}) })
|
|
69
|
+
.catch(cause => { if (isStartupBlockException(cause)) return null; throw cause })
|
|
70
|
+
if (!session) return null // A failed open never hands session ownership to this call.
|
|
71
|
+
let outcome: AgentOutcome
|
|
110
72
|
try {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
73
|
+
if (output && !session.capabilities.turn?.outputSchema) throw new HarnessSdkError('CAPABILITY_UNSUPPORTED', 'Session does not support structured output')
|
|
74
|
+
const turn = await session.submit({ input: prompt, ...(output ? { outputSchema: output.schema } : {}) }, { timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
|
|
75
|
+
const result = await turn.result({ timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
|
|
76
|
+
if (result.status === 'completed') {
|
|
77
|
+
outcome = { status: 'completed', value: output ? await output.parse(result.text) : result.text }
|
|
78
|
+
} else if (result.error && isDroppedOutcome(result.error, result.status)) {
|
|
79
|
+
outcome = { status: 'dropped', error: { code: result.error.code, outcomeUnknown: result.error.outcomeUnknown } }
|
|
80
|
+
} else if (result.error) {
|
|
81
|
+
const { code, message, retryable, outcomeUnknown, details } = result.error
|
|
82
|
+
throw new HarnessSdkError(code, message, retryable, outcomeUnknown, details)
|
|
83
|
+
} else {
|
|
84
|
+
throw new HarnessSdkError('AGENT_INTERRUPTED')
|
|
116
85
|
}
|
|
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
86
|
} catch (cause) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
87
|
+
if (isStartupBlockException(cause)) outcome = { status: 'dropped', error: { code: cause.code, outcomeUnknown: cause.outcomeUnknown } }
|
|
88
|
+
else outcome = { status: 'failed', error: sdkError(cause, 'AGENT_FAILED', true) }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Closing observation does not prove the backend execution stopped. Never retry input.
|
|
92
|
+
const cleanupErrors = new Set<HarnessSdkError>()
|
|
93
|
+
try { await session.close() } catch (cause) { cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true)) }
|
|
94
|
+
try { await session.dispose() } catch (cause) { cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true)) }
|
|
95
|
+
if (cleanupErrors.size) {
|
|
96
|
+
const errors = [...cleanupErrors].map(error => ({ code: error.code, outcomeUnknown: error.outcomeUnknown }))
|
|
97
|
+
if (outcome.status === 'failed') {
|
|
98
|
+
const failure = outcome.error
|
|
99
|
+
throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown,
|
|
100
|
+
{ ...failure.details, cleanupErrors: errors })
|
|
133
101
|
}
|
|
134
|
-
throw
|
|
102
|
+
throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false,
|
|
103
|
+
errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) })
|
|
104
|
+
}
|
|
105
|
+
switch (outcome.status) {
|
|
106
|
+
case 'completed': return outcome.value
|
|
107
|
+
case 'dropped': return null
|
|
108
|
+
case 'failed': throw outcome.error
|
|
135
109
|
}
|
|
136
110
|
}
|