@anureo/workflow 0.3.1 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anureo/workflow",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Agent execution, composition, and durable workflow steps over the Anureo SDK",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -8,6 +8,7 @@
8
8
  "url": "git+https://github.com/hi-youichi/anureo-sdk.git",
9
9
  "directory": "packages/workflow"
10
10
  },
11
+ "homepage": "https://github.com/hi-youichi/anureo-sdk/tree/main/packages/workflow#readme",
11
12
  "publishConfig": {
12
13
  "access": "public"
13
14
  },
@@ -21,17 +22,17 @@
21
22
  "test": "bun test src"
22
23
  },
23
24
  "dependencies": {
24
- "@anureo/sdk": "0.3.1",
25
- "@anureo/protocol": "0.3.1",
25
+ "@anureo/sdk": "0.3.2",
26
+ "@anureo/protocol": "0.3.2",
26
27
  "ajv": "8.20.0",
27
28
  "zod": "4.6.7"
28
29
  },
29
30
  "devDependencies": {
30
- "@anureo/conformance": "0.3.1",
31
- "@anureo/adapter-claude": "0.3.1",
32
- "@anureo/adapter-codex": "0.3.1",
33
- "@anureo/adapter-acp": "0.3.1",
34
- "@anureo/adapter-pi": "0.3.1"
31
+ "@anureo/conformance": "0.3.2",
32
+ "@anureo/adapter-claude": "0.3.2",
33
+ "@anureo/adapter-codex": "0.3.2",
34
+ "@anureo/adapter-acp": "0.3.2",
35
+ "@anureo/adapter-pi": "0.3.2"
35
36
  },
36
37
  "engines": {
37
38
  "node": ">=22"
@@ -23,32 +23,62 @@ export interface AgentOptions<S extends z.ZodObject = z.ZodObject> {
23
23
  * In a workflow this option contributes to replay identity even in text mode.
24
24
  */
25
25
  outputFallback?: 'json-text'
26
+ /**
27
+ * Positive observation timeouts in milliseconds, up to 2,147,483,647 (the default).
28
+ * The association wait begins at submission and the result wait begins after association.
29
+ * Expiry rejects with an unknown outcome and does not interrupt native execution.
30
+ * These limits do not affect journal replay identity.
31
+ */
32
+ wait?: { associationMs?: number; resultMs?: number }
26
33
  }
27
34
 
35
+ const LONG_OBSERVATION_TIMEOUT_MS = 0x7fffffff
36
+
37
+ /** Capture session settings and prepare structured output before any asynchronous work. */
38
+ export function prepareAgentCall(options: AgentOptions) {
39
+ const { client, cwd, model, instructions, permissionMode, schema, outputFallback, wait } = options
40
+ const timeouts = wait && { associationMs: wait.associationMs, resultMs: wait.resultMs }
41
+ for (const timeout of [timeouts?.associationMs, timeouts?.resultMs]) {
42
+ if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0 || timeout > LONG_OBSERVATION_TIMEOUT_MS)) {
43
+ throw new HarnessSdkError('INVALID_PARAMS', 'Agent observation timeouts must be positive and at most 2,147,483,647 ms')
44
+ }
45
+ }
46
+ return {
47
+ client, cwd, model, instructions, permissionMode, outputFallback,
48
+ wait: timeouts,
49
+ output: schema === undefined ? undefined : prepareOutputSchema(schema),
50
+ }
51
+ }
52
+
53
+ export type PreparedAgentCall = ReturnType<typeof prepareAgentCall>
54
+
28
55
  /**
29
56
  * Run a fresh call for agent outside a workflow or for executeJournaledAgent after it publishes
30
- * its started marker and rechecks dispatch. Prepare the supplied schema before opening, then
31
- * release the acquired session before resolving with text, data or null, or rejecting with an
32
- * execution or release failure. The caller retains the Client. executeJournaledAgent uses the
33
- * settled outcome to publish a terminal journal event.
57
+ * its started marker and rechecks dispatch. Release the acquired session before returning the
58
+ * completed or dropped outcome or throwing an execution or release failure.
34
59
  */
35
- export async function executeAgent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
36
- const { client, cwd, model, instructions, permissionMode, schema } = options
37
- const output = schema === undefined ? undefined : prepareOutputSchema(schema)
38
- const session = await openAgentSession({ client, cwd, model, instructions, permissionMode })
39
- if (!session) return null // A failed open never hands session ownership to this call.
40
- const outcome = await observeAgentTurn({ session, prompt, output, outputFallback: options.outputFallback })
60
+ export async function executeAgent(prompt: string, call: PreparedAgentCall): Promise<SettledAgentOutcome> {
61
+ const { output, outputFallback, wait } = call
62
+ const opening = openAgentSession(call)
63
+ let session: Session
64
+ try {
65
+ session = await opening
66
+ } catch (cause) {
67
+ if (isStartupBlockException(cause)) return { status: 'dropped', error: summarizeAgentError(cause) }
68
+ throw cause
69
+ }
70
+ const outcome = await observeAgentTurn({ session, prompt, output, outputFallback, wait })
41
71
  const cleanupErrors = await releaseAgentSession(session)
42
72
  return settleAgentOutcome(outcome, cleanupErrors)
43
73
  }
44
74
 
45
- // Give association and terminal observation the longest supported timer delay for model execution.
46
- const LONG_OBSERVATION_TIMEOUT_MS = 0x7fffffff
47
-
48
- /** Execution evidence retained until cleanup has settled, before returning or rejecting the call. */
49
- type AgentOutcome =
75
+ /** Completed or dropped execution after successful session release. */
76
+ type SettledAgentOutcome =
50
77
  | { status: 'completed'; value: string | Record<string, unknown> }
51
78
  | { status: 'dropped'; error: AgentErrorSummary }
79
+
80
+ type AgentOutcome =
81
+ | SettledAgentOutcome
52
82
  | { status: 'failed'; error: HarnessSdkError }
53
83
 
54
84
  /** Safe diagnostics retained from cleanup and dropped terminals without native messages. */
@@ -62,25 +92,19 @@ interface AgentTurnRequest {
62
92
  prompt: string
63
93
  output: AgentOutputSchema | undefined
64
94
  outputFallback: AgentOptions['outputFallback']
95
+ wait: AgentOptions['wait']
65
96
  }
66
97
 
67
- /**
68
- * Give executeAgent ownership of the attached session. A confirmed startup denial from the open
69
- * promise resolves to null. Other rejections and synchronous request setup errors propagate.
70
- */
98
+ /** Request a fresh session and give executeAgent ownership when it attaches. */
71
99
  function openAgentSession({ client, cwd, model, instructions, permissionMode }: Pick<
72
100
  AgentOptions, 'client' | 'cwd' | 'model' | 'instructions' | 'permissionMode'
73
- >): Promise<Session | null> {
101
+ >): Promise<Session> {
74
102
  return client.sessions.create({
75
103
  cwd,
76
104
  ...(model !== undefined ? { model } : {}),
77
105
  ...(instructions !== undefined ? { instructions } : {}),
78
106
  ...(permissionMode !== undefined ? { permissionMode } : {}),
79
107
  })
80
- .catch(cause => {
81
- if (isStartupBlockException(cause)) return null
82
- throw cause
83
- })
84
108
  }
85
109
 
86
110
  /**
@@ -88,11 +112,11 @@ function openAgentSession({ client, cwd, model, instructions, permissionMode }:
88
112
  * Return execution evidence to executeAgent, which owns session release and final settlement.
89
113
  */
90
114
  async function observeAgentTurn(request: AgentTurnRequest): Promise<AgentOutcome> {
91
- const { session, output } = request
115
+ const { session, output, wait } = request
92
116
  try {
93
117
  const submission = agentSubmission(request)
94
- const turn = await session.submit(submission, { timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
95
- const result = await turn.result({ timeoutMs: LONG_OBSERVATION_TIMEOUT_MS })
118
+ const turn = await session.submit(submission, { timeoutMs: wait?.associationMs ?? LONG_OBSERVATION_TIMEOUT_MS })
119
+ const result = await turn.result({ timeoutMs: wait?.resultMs ?? LONG_OBSERVATION_TIMEOUT_MS })
96
120
  if (result.status === 'completed') {
97
121
  return { status: 'completed', value: output ? await output.parse(result.text) : result.text }
98
122
  }
@@ -160,25 +184,23 @@ async function releaseAgentSession(session: Session): Promise<AgentErrorSummary[
160
184
  }
161
185
 
162
186
  /**
163
- * Settle executeAgent after both release attempts. Return text/data or null on successful cleanup.
187
+ * Settle executeAgent after both release attempts. Return completed or dropped outcomes on successful cleanup.
164
188
  * Throw the primary failure with any cleanup diagnostics, or RESOURCE_RELEASE_FAILED if cleanup
165
189
  * was the only failure.
166
190
  */
167
- function settleAgentOutcome(outcome: AgentOutcome, errors: AgentErrorSummary[]): string | Record<string, unknown> | null {
191
+ function settleAgentOutcome(outcome: AgentOutcome, errors: AgentErrorSummary[]): SettledAgentOutcome {
168
192
  if (errors.length) {
169
193
  if (outcome.status === 'failed') {
170
194
  const failure = outcome.error
195
+ const prior = failure.details?.cleanupErrors
171
196
  throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown,
172
- { ...failure.details, cleanupErrors: errors })
197
+ { ...failure.details, cleanupErrors: [...(Array.isArray(prior) ? prior : []), ...errors] })
173
198
  }
174
199
  throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false,
175
200
  errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) })
176
201
  }
177
- switch (outcome.status) {
178
- case 'completed': return outcome.value
179
- case 'dropped': return null
180
- case 'failed': throw outcome.error
181
- }
202
+ if (outcome.status === 'failed') throw outcome.error
203
+ return outcome
182
204
  }
183
205
 
184
206
  /** Share the startup-denial rule between classifyTerminalFailure and isStartupBlockException.
@@ -187,10 +209,7 @@ function isStartupBlocked(error: Pick<HarnessSdkError, 'code' | 'outcomeUnknown'
187
209
  return !error.outcomeUnknown && error.code === 'AGENT_STARTUP_BLOCKED' && error.details?.workflowDisposition === 'startup_blocked'
188
210
  }
189
211
 
190
- /**
191
- * Recognize a thrown SDK startup denial. openAgentSession returns null for a matching rejection
192
- * from session creation. observeAgentTurn records a drop candidate and leaves settlement to cleanup.
193
- */
212
+ /** Recognize a thrown SDK startup denial during session creation or turn observation. */
194
213
  function isStartupBlockException(cause: unknown): cause is HarnessSdkError {
195
214
  return cause instanceof HarnessSdkError && isStartupBlocked(cause)
196
215
  }
package/src/agent.test.ts CHANGED
@@ -1,15 +1,28 @@
1
1
  import { afterEach, expect, test } from 'bun:test'
2
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'
3
6
  import type { FakeAdapterOptions } from '@anureo/conformance'
4
7
  import type { HarnessError } from '@anureo/protocol'
5
8
  import { HarnessSdkError, type Client, type SessionEventSink } from '@anureo/sdk'
6
9
  import { z } from 'zod'
7
- import { agent, parallel, pipeline, type AgentOptions } from './index'
10
+ import { agent, parallel, pipeline, workflow, type AgentOptions } from './index'
8
11
  import { createFixture } from './test-helpers'
9
12
 
10
13
  const clients: Client[] = []
11
14
  const fixture = createFixture(clients)
12
- afterEach(async () => { await Promise.all(clients.splice(0).map(client => client.dispose())) })
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
+ }
13
26
 
14
27
  /** Publish final text before the test terminal so Turn.result retains it. */
15
28
  async function complete(sink: SessionEventSink, turnId: string, text: string) {
@@ -59,6 +72,32 @@ test('each call chooses its backend explicitly without shared configuration', as
59
72
  expect(b.adapter.opened[0]?.cwd).toBe('/b')
60
73
  })
61
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
+
62
101
  test('native association and acceptance do not replace terminal evidence', async () => {
63
102
  const { promise: terminalEmitterReady, resolve: resolveTerminalEmitter } = Promise.withResolvers<() => Promise<void>>()
64
103
  const { client, adapter } = await fixture({ execute: async (call, sink) => {
@@ -78,6 +117,25 @@ test('native association and acceptance do not replace terminal evidence', async
78
117
  expect(await result).toBe('actual terminal text')
79
118
  })
80
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
+
81
139
  test('preserves native failure details and releases the session', async () => {
82
140
  const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId }) => {
83
141
  await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
@@ -111,6 +169,30 @@ test('unknown submission outcomes are preserved without retries or implicit inte
111
169
  expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
112
170
  })
113
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
+
114
196
  test('source failure remains uncertain and is not converted into successful cleanup', async () => {
115
197
  const { client, adapter } = await fixture({ execute: scriptSubmission(async ({ sink, turnId, submissionId }) => {
116
198
  await sink.bindSubmission(submissionId, turnId)
@@ -152,6 +234,21 @@ test('cleanup failure cannot hide the primary uncertain execution failure', asyn
152
234
  expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
153
235
  })
154
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
+
155
252
  /** Register a scripted client that publishes final text and a terminal before the submit receipt.
156
253
  * Disable the advertised output-schema route to exercise fallback against the same terminal. */
157
254
  function terminalFixture(
@@ -193,6 +290,16 @@ test('schema preflight rejects before opening, while absent backend support rele
193
290
  expect([...unsupported.adapter.backends.values()][0]?.disposeCount).toBe(1)
194
291
  })
195
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
+
196
303
  test.each([
197
304
  { text: '{"count":3}', error: null },
198
305
  { text: '{"count":3,"extra":true}', error: 'AGENT_STRUCTURED_OUTPUT_INVALID' },
@@ -257,6 +364,36 @@ test('uncertainty overrides API and skip classifications, and generic interrupti
257
364
  await expect(agent('interrupted', { client, cwd: '.' })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
258
365
  })
259
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
+
260
397
  test('explicit skip metadata survives terminal-before-reply and startup denial requires its dedicated code', async () => {
261
398
  const skipped = await terminalFixture('interrupted', { error: { code: 'USER_SKIPPED', message: 'skipped', retryable: false, outcomeUnknown: false, details: { workflowDisposition: 'skipped' } } })
262
399
  expect(await agent('skip', { client: skipped.client, cwd: '.' })).toBeNull()
package/src/agent.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import type { JsonObject } from '@anureo/protocol'
3
2
  import { HarnessSdkError, sdkError } from '@anureo/sdk'
4
3
  import type { z } from 'zod'
5
- import { executeAgent, type AgentOptions } from './agent-execution'
6
- import { prepareOutputSchema, type AgentOutputSchema } from './output-schema'
4
+ import { executeAgent, prepareAgentCall, type AgentOptions, type PreparedAgentCall } from './agent-execution'
5
+ import type { AgentOutputSchema } from './output-schema'
7
6
  import { currentRun, isFatal, type RunContext } from './workflow-state'
8
7
  import { canonicalJson, jsonCopy, type JsonValue } from './persistence/json'
9
8
 
@@ -40,57 +39,54 @@ export function agent<S extends z.ZodObject>(prompt: string, options: AgentOptio
40
39
  export async function agent(prompt: string, options: AgentOptions): Promise<string | Record<string, unknown> | null> {
41
40
  const context = currentRun()
42
41
  if (context) return memoizedAgent(context, prompt, options)
43
- return executeAgent(prompt, options)
42
+ const outcome = await executeAgent(prompt, prepareAgentCall(options))
43
+ return outcome.status === 'dropped' ? null : outcome.value
44
44
  }
45
45
 
46
46
  /**
47
- * Prepare the schema for the key and for replay, then reserve the key synchronously when agent
48
- * inherits the run context. Preflight failures reject before registration. RunState admits and
49
- * observes the replay or execution so workflow can drain it even if the body leaves the call
50
- * unawaited. On a miss, executeAgent prepares the schema from the options again after the started
51
- * record is published and dispatch is rechecked.
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.
52
49
  */
53
- async function memoizedAgent<S extends z.ZodObject>(
50
+ async function memoizedAgent(
54
51
  context: RunContext,
55
52
  prompt: string,
56
- options: AgentOptions<S>,
57
- ): Promise<string | z.output<S> | null> {
53
+ options: AgentOptions,
54
+ ): Promise<string | Record<string, unknown> | null> {
58
55
  const { journal, state } = context
59
- const output = options.schema === undefined ? undefined : prepareOutputSchema(options.schema)
60
- // The key advances synchronously here: host invocation order fixes the chain.
61
- const key = journal.nextKey(prompt, canonicalOptions(options, output?.schema))
62
56
  return state.track(() => {
57
+ const call = prepareAgentCall(options)
58
+ const key = journal.nextKey(prompt, canonicalOptions(call))
63
59
  const decision = journal.resolveCall(key)
64
- if (decision.action === 'replay') return replayAgentResult(decision.result, output)
60
+ if (decision.action === 'replay') return replayAgentResult(decision.result, call.output)
65
61
  if (decision.action === 'reconcile') {
66
62
  throw new HarnessSdkError('WORKFLOW_RECONCILIATION_REQUIRED',
67
63
  'A previous run left this agent call with an unknown outcome; reconcile it before resuming', false, true)
68
64
  }
69
- return executeJournaledAgent({ context, key, prompt, options })
65
+ return executeJournaledAgent({ context, key, prompt, call })
70
66
  })
71
67
  }
72
68
 
73
69
  /** Project the options memoizedAgent hashes with the prompt. Preserve the persisted key format
74
70
  * by using null for absent model, instructions, permission mode and schema, and omitting absent
75
71
  * fallback. Use the client identity so equivalent backend configurations can share a key. */
76
- function canonicalOptions(options: AgentOptions, schema: JsonObject | undefined): JsonValue {
72
+ function canonicalOptions(call: PreparedAgentCall): JsonValue {
77
73
  return {
78
- model: options.model ?? null,
79
- instructions: options.instructions ?? null,
80
- permissionMode: options.permissionMode ?? null,
81
- schema: schema ?? null,
82
- ...(options.outputFallback ? { outputFallback: options.outputFallback } : {}),
83
- cwd: options.cwd,
84
- client: options.client.identity,
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,
85
81
  }
86
82
  }
87
83
 
88
84
  /** Return saved text or await current schema validation for memoizedAgent's typed hit.
89
85
  * A rejected validation propagates to the agent caller without rerunning the prompt. */
90
- async function replayAgentResult<S extends z.ZodObject>(
86
+ async function replayAgentResult(
91
87
  hit: JsonValue,
92
- output: AgentOutputSchema<S> | undefined,
93
- ): Promise<string | z.output<S>> {
88
+ output: AgentOutputSchema | undefined,
89
+ ): Promise<string | Record<string, unknown>> {
94
90
  return output ? output.parse(canonicalJson(hit)) : hit as string
95
91
  }
96
92
 
@@ -101,34 +97,39 @@ async function replayAgentResult<S extends z.ZodObject>(
101
97
  * without attempting a second terminal write. The dispatch check is outside the execution catch
102
98
  * so a call stopped during publication retains its started marker.
103
99
  */
104
- async function executeJournaledAgent<S extends z.ZodObject>({ context, key, prompt, options }: {
100
+ async function executeJournaledAgent({ context, key, prompt, call }: {
105
101
  context: RunContext
106
102
  key: string
107
103
  prompt: string
108
- options: AgentOptions<S>
109
- }): Promise<string | z.output<S> | null> {
104
+ call: PreparedAgentCall
105
+ }): Promise<string | Record<string, unknown> | null> {
110
106
  const { journal, state } = context
111
107
  const agentId = randomUUID()
112
108
  await journal.append({ type: 'started', key, agentId })
113
109
  state.assertDispatch()
114
110
  try {
115
- // Cache identity was computed at invocation. Fresh execution reads options after publication.
116
- const value = await executeAgent(prompt, options)
117
- if (value === null) {
118
- await journal.append({ type: 'failed', key, agentId, code: 'AGENT_DROPPED', outcomeUnknown: false })
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 })
119
114
  state.noteIncomplete()
120
115
  return null
121
116
  }
122
- const stored = jsonCopy(value) as JsonValue
117
+ const stored = jsonCopy(outcome.value) as JsonValue
123
118
  await journal.append({ type: 'result', key, agentId, result: stored })
124
- return jsonCopy(stored) as string | z.output<S>
119
+ return jsonCopy(stored) as string | Record<string, unknown>
125
120
  } catch (cause) {
126
121
  const error = sdkError(cause, 'AGENT_FAILED')
127
122
  if (isFatal(error)) state.stop(error)
128
123
  // The storage layer may have published a terminal record already.
129
124
  if (error.code !== 'WORKFLOW_STORAGE_FAILED') {
130
- await journal.append({ type: 'failed', key, agentId,
131
- code: error.code, outcomeUnknown: error.outcomeUnknown === true })
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
+ }
132
133
  }
133
134
  throw error
134
135
  }
@@ -1,11 +1,11 @@
1
1
  import { mock } from 'bun:test'
2
2
  import * as fs from 'node:fs/promises'
3
- import { createClient } from '@anureo/sdk'
3
+ import { createClient, HarnessSdkError } from '@anureo/sdk'
4
4
  import { createScriptedAdapter } from '@anureo/conformance'
5
+ import type { JournalEvent } from '../persistence/records'
5
6
 
6
7
  const [directory, phase] = process.argv.slice(2) as [string, string]
7
8
  const originalRename = fs.rename
8
- let journalPublishes = 0
9
9
  // workflow.test.ts spawns a fresh process per crash point. Install the mock before
10
10
  // importing workflow so atomic publication uses the injected rename in this process.
11
11
  mock.module('node:fs/promises', () => ({ ...fs, rename: renameAtCrashBoundary }))
@@ -13,6 +13,9 @@ const { workflow, agent } = await import('../index')
13
13
 
14
14
  const adapter = createScriptedAdapter({
15
15
  async execute(call) {
16
+ if (phase === 'unpublished-unknown' && call.method === 'input/submit' && 'submissionId' in call.params) {
17
+ throw new HarnessSdkError('NATIVE_FAILED', 'unknown', false, true)
18
+ }
16
19
  if (phase === 'after-later-result' && call.method === 'input/submit' && 'input' in call.params
17
20
  && call.params.input.some(part => part.type === 'text' && part.text === 'work')) {
18
21
  // Hold the first call at started while the second reaches durable completion.
@@ -23,13 +26,23 @@ const adapter = createScriptedAdapter({
23
26
  })
24
27
  const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
25
28
  try {
26
- await workflow({ directory, name: 'crash-test', revision: '1', input: {}, runId: 'crashed' }, async () => {
29
+ await workflow({ directory, name: 'crash-test', revision: '1', input: {}, runId: 'crashed',
30
+ resumeFrom: phase === 'after-retry' ? 'source' : undefined }, async () => {
31
+ if (phase === 'after-retry') {
32
+ await agent('prefix', { client, cwd: directory })
33
+ await agent('work', { client, cwd: directory })
34
+ process.kill(process.pid, 'SIGKILL')
35
+ }
27
36
  const first = agent('work', { client, cwd: directory })
28
37
  if (phase !== 'after-later-result') return first
29
38
  await agent('later', { client, cwd: directory })
30
39
  process.kill(process.pid, 'SIGKILL')
31
40
  return first
32
41
  })
42
+ } catch (error) {
43
+ const codes = error instanceof HarnessSdkError ? error.details?.failureCodes : undefined
44
+ if (phase !== 'unpublished-unknown' || !(error instanceof HarnessSdkError)
45
+ || !error.outcomeUnknown || !Array.isArray(codes) || !codes.includes('WORKFLOW_STORAGE_FAILED')) throw error
33
46
  } finally {
34
47
  await client.dispose()
35
48
  }
@@ -40,10 +53,13 @@ try {
40
53
  async function renameAtCrashBoundary(from: string, to: string): Promise<void> {
41
54
  const target = to.replaceAll('\\', '/')
42
55
  if (target.endsWith('/journal.json')) {
43
- // The first publication creates the empty journal before any agent work can start.
44
- journalPublishes++
45
- if (phase === 'before-started' && journalPublishes === 2) process.kill(process.pid, 'SIGKILL')
46
- if (phase === 'after-execute' && journalPublishes === 3) process.kill(process.pid, 'SIGKILL')
56
+ const pending = JSON.parse(await fs.readFile(from, 'utf8')) as JournalEvent[]
57
+ const event = pending.at(-1)
58
+ if ((phase === 'before-started' && event?.type === 'started')
59
+ || (phase === 'after-execute' && event?.type === 'result')) process.kill(process.pid, 'SIGKILL')
60
+ if (phase === 'unpublished-unknown' && event?.type === 'failed' && event.outcomeUnknown) {
61
+ throw new Error('Injected journal replacement failure')
62
+ }
47
63
  }
48
64
  if (phase === 'before-final' && target.endsWith('/run.json')) {
49
65
  const value = JSON.parse(await fs.readFile(from, 'utf8'))
@@ -68,13 +68,25 @@ test('raw JSON is validated before Zod can strip extra fields or supply defaults
68
68
  code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
69
69
  retryable: false,
70
70
  outcomeUnknown: false,
71
- details: { issues: [{ path: '', code: 'required' }] },
71
+ details: { issues: [{ path: '/count', code: 'required' }] },
72
72
  })
73
73
  for (const text of ['{"count":4,"extra":1}', '{"count":"4"}', 'null', '[]']) {
74
74
  await expect(output.parse(text)).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', retryable: false, outcomeUnknown: false })
75
75
  }
76
76
  })
77
77
 
78
+ test('raw JSON issues identify missing and extra fields with escaped pointer segments', async () => {
79
+ const output = prepareOutputSchema(z.object({ nested: z.object({ 'a/b': z.number(), 'a~b': z.number() }) }))
80
+ await expect(output.parse('{"nested":{"extra~/":"private value"}}')).rejects.toMatchObject({
81
+ code: 'AGENT_STRUCTURED_OUTPUT_INVALID',
82
+ details: { issues: [
83
+ { path: '/nested/a~1b', code: 'required' },
84
+ { path: '/nested/a~0b', code: 'required' },
85
+ { path: '/nested/extra~0~1', code: 'additionalProperties' },
86
+ ] },
87
+ })
88
+ })
89
+
78
90
  test('missing and malformed output remain distinct failures without recovering prose', async () => {
79
91
  const output = prepareOutputSchema(z.object({ count: z.number() }))
80
92
  await expect(output.parse(' ')).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_MISSING' })