@anureo/workflow 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +96 -70
  2. package/package.json +17 -16
  3. package/src/agent-adapters.test.ts +121 -0
  4. package/src/agent-execution.ts +201 -0
  5. package/src/agent.test.ts +333 -0
  6. package/src/agent.ts +135 -0
  7. package/src/fixtures/workflow-crash.ts +53 -0
  8. package/src/index.ts +9 -0
  9. package/src/output-schema.test.ts +147 -0
  10. package/src/output-schema.ts +231 -0
  11. package/src/parallel.test.ts +96 -0
  12. package/src/parallel.ts +33 -0
  13. package/src/persistence/checkpoint-files.ts +82 -0
  14. package/src/persistence/journal.ts +111 -0
  15. package/src/persistence/json.ts +83 -0
  16. package/src/persistence/records.ts +97 -0
  17. package/src/persistence/replay.ts +91 -0
  18. package/src/persistence/store.ts +286 -0
  19. package/src/pipeline.test.ts +201 -0
  20. package/src/pipeline.ts +99 -0
  21. package/src/test-helpers.ts +23 -0
  22. package/src/workflow-state.ts +130 -0
  23. package/src/workflow-types.ts +38 -0
  24. package/src/workflow.test.ts +376 -0
  25. package/src/workflow.ts +112 -0
  26. package/tsconfig.json +13 -0
  27. package/LICENSE +0 -201
  28. package/src/agent-outcome.d.ts +0 -15
  29. package/src/agent-outcome.js +0 -28
  30. package/src/agent.d.ts +0 -49
  31. package/src/agent.js +0 -206
  32. package/src/index.d.ts +0 -6
  33. package/src/index.js +0 -5
  34. package/src/output-schema.d.ts +0 -27
  35. package/src/output-schema.js +0 -192
  36. package/src/parallel.d.ts +0 -18
  37. package/src/parallel.js +0 -25
  38. package/src/persistence/atomic.d.ts +0 -9
  39. package/src/persistence/atomic.js +0 -48
  40. package/src/persistence/journal.d.ts +0 -54
  41. package/src/persistence/journal.js +0 -106
  42. package/src/persistence/json.d.ts +0 -17
  43. package/src/persistence/json.js +0 -75
  44. package/src/persistence/read-json.d.ts +0 -11
  45. package/src/persistence/read-json.js +0 -46
  46. package/src/persistence/records.d.ts +0 -92
  47. package/src/persistence/records.js +0 -70
  48. package/src/persistence/replay.d.ts +0 -11
  49. package/src/persistence/replay.js +0 -79
  50. package/src/persistence/store.d.ts +0 -45
  51. package/src/persistence/store.js +0 -238
  52. package/src/pipeline.d.ts +0 -41
  53. package/src/pipeline.js +0 -24
  54. package/src/run-context.d.ts +0 -16
  55. package/src/run-context.js +0 -13
  56. package/src/test-helpers.d.ts +0 -11
  57. package/src/test-helpers.js +0 -21
  58. package/src/workflow-state.d.ts +0 -44
  59. package/src/workflow-state.js +0 -96
  60. package/src/workflow-types.d.ts +0 -39
  61. package/src/workflow-types.js +0 -0
  62. package/src/workflow.d.ts +0 -17
  63. package/src/workflow.js +0 -104
package/README.md CHANGED
@@ -1,28 +1,16 @@
1
1
  # @anureo/workflow
2
2
 
3
- Directly imported primitives for ordinary TypeScript workflows:
4
- `agent`, `parallel`, `pipeline`, and optional `workflow`. The host creates SDK Clients, imports its
5
- workflow functions, awaits their results, and handles errors with normal TS.
6
-
7
- See the [workflow authoring reference](../../docs/workflow/SKILL.md) for current
8
- APIs, composition patterns, failure handling, and application-owned recovery.
9
-
10
- The [Workflow primitives reference](../../docs/workflow/README.md) defines
11
- parameters and result semantics for `agent`, `parallel`, and `pipeline`,
12
- and records current support.
13
-
14
- See the [composition comparison](../../draft/docs/workflow-composition-differences.md)
15
- and [alignment plan](../../draft/docs/workflow-composition-plan.md) for Claude Code
16
- semantics, the implemented changes, and retained host differences (Chinese).
17
-
18
- This workspace package uses the revised native lifecycle API and is pending
19
- publication with that revision. Requires Node.js 22+; TypeScript loading and
20
- compilation are provided by your project (for example, Bun, tsx, or tsc).
3
+ `@anureo/workflow` runs Anureo SDK agents from ordinary TypeScript functions. Use
4
+ `agent` for one prompt, `parallel` for independent callbacks, `pipeline` for
5
+ per-item stages, and `workflow` when you need a disk-backed run and agent replay.
6
+ The package exposes one entry point, `@anureo/workflow`. Its Node.js engine
7
+ requirement is 22 or newer, and applications supply their TypeScript tooling.
21
8
 
22
9
  ## Usage
23
10
 
24
- Create an initialized Client using `createClient` and your chosen adapter as
25
- described in the [SDK README](../../README.md). A workflow is just a function:
11
+ This function accepts an initialized SDK Client and reviews files in two stages
12
+ before running two synthesis tasks concurrently. The application creates and owns
13
+ the Client. See the [SDK README](../../README.md) for Client setup.
26
14
 
27
15
  ```ts
28
16
  import type { Client } from '@anureo/sdk'
@@ -45,39 +33,43 @@ export async function reviewFiles(client: Client, files: readonly string[], cwd:
45
33
  }
46
34
  ```
47
35
 
48
- In this example, `pipeline` and `parallel` convert internal `agent` rejections to
49
- `null`; `pipeline` also skips the affected item's remaining stages. The two
50
- explicit checks then throw summary errors for `null` results, so those errors do
51
- not preserve the original agent failure classification.
36
+ `pipeline` and `parallel` turn rejected agent calls into `null` at the affected
37
+ positions. The two guards report those positions as batch-level errors. Keep the
38
+ Client usable until `reviewFiles` settles, then release it when the application
39
+ has finished using it.
52
40
 
53
- Import `reviewFiles` from another TS file and call it with a Client. Calls do not
54
- require workflow registration, source-string execution, ambient context, or runtime setup.
55
- Use [durable workflow steps](../../docs/workflow/persistence.md) when a function
56
- needs a persisted run ID and recoverable results.
41
+ See the [workflow authoring guide](../../docs/workflow/SKILL.md) for composition and
42
+ recovery patterns and the [primitives reference](../../docs/workflow/README.md) for API contracts.
57
43
 
58
44
  ## agent
59
45
 
60
46
  ```ts
47
+ import type { Client } from '@anureo/sdk'
61
48
  import { z } from 'zod'
62
49
  import { agent } from '@anureo/workflow'
63
50
 
64
- const options = { client, cwd: process.cwd() }
65
- const text: string | null = await agent('Inspect the authentication module.', options)
66
- const findings = await agent('List authentication issues.', {
67
- ...options,
68
- schema: z.strictObject({ issues: z.array(z.string()) }),
69
- })
70
- // findings: { issues: string[] } | null
71
- if (findings !== null) console.log(findings.issues)
51
+ export function listIssues(client: Client, cwd: string) {
52
+ return agent('List the authentication module’s issues.', {
53
+ client,
54
+ cwd,
55
+ schema: z.strictObject({ issues: z.array(z.string()) }),
56
+ })
57
+ }
58
+ // listIssues returns Promise<{ issues: string[] } | null>.
72
59
  ```
73
60
 
74
- Each call owns a fresh Session, submits once, waits for its native terminal
75
- result, and releases its resources. `client` and `cwd` are required; `model` and
76
- `instructions` are optional. The caller owns the borrowed Client.
61
+ For fresh execution, `agent` opens a Session, submits one prompt, awaits the native
62
+ terminal result, and attempts to close and dispose the Session before settling.
63
+ The root exports `AgentOptions` for callers building options. Supply an initialized
64
+ `client` and a `cwd`. You can also supply `model`, `instructions`, and `permissionMode`
65
+ for session creation. The caller owns the Client.
66
+ Omit `schema` to receive the final text, which can be empty, or `null`.
77
67
 
78
68
  `schema` accepts a Zod 4 object schema. The library converts it to draft-07 JSON
79
- Schema, requires effective session `turn.outputSchema` support, validates the raw JSON
80
- result, then validates it with the original Zod schema and returns `z.output<S>`.
69
+ Schema, validates the raw JSON result, then validates it with the original Zod schema
70
+ and returns `z.output<S>`. By default, schema mode requires effective session
71
+ `turn.outputSchema` support. Set `outputFallback: 'json-text'` to include the schema
72
+ in the prompt when the session lacks that capability.
81
73
  This package depends on Zod 4.6.7. Applications that import Zod to author schemas
82
74
  should also declare it as their own dependency. Schema-associated types infer business fields;
83
75
  there is no unbound result-type generic or raw JSON Schema overload.
@@ -89,11 +81,11 @@ Defaults do not fill omitted model answers. Async refinements are supported
89
81
  locally; their failures reject without replaying input. See the
90
82
  [full schema and failure contract](../../docs/workflow/README.md#schema-mode).
91
83
 
92
- Confirmed native failed terminals for authentication, usage/rate limits, and
93
- service unavailability return `null`. Other failures and ordinary interruptions
94
- reject. Trusted adapters may explicitly report user skip or classifier startup
95
- denial; bundled adapters do not infer these reasons. Unknown execution outcomes
96
- retain `outcomeUnknown: true` and always reject. No input is automatically retried.
84
+ Confirmed native failed terminals for authentication, usage or rate limits, and
85
+ service unavailability can return `null`. Explicit user skip on interruption and
86
+ tagged startup denial can also return `null`. Other failures and ordinary
87
+ interruptions reject. Unknown execution outcomes reject with `outcomeUnknown: true`.
88
+ The caller decides whether and when to retry.
97
89
 
98
90
  Cleanup is attempted for successful, failed and discarded executions. A cleanup
99
91
  failure rejects with `RESOURCE_RELEASE_FAILED`, or preserves a primary execution
@@ -111,12 +103,12 @@ CLIs and real model requests.
111
103
  input-ordered results. Callbacks may return ordinary values or Promises; inline
112
104
  heterogeneous tuples preserve each result's type. An empty batch returns `[]`.
113
105
 
114
- The array and every entry are validated before any callback starts. The call
115
- waits for all callbacks to settle and uses `null` at each failed position,
116
- including synchronous throws. Result types include `null` at every position.
117
- Invalid arguments still reject the call. Use `value !== null` to filter failures
118
- without dropping valid `0`, `false`, or empty-string results.
119
- There is no implicit interruption, shared scheduler, or concurrency limit.
106
+ `parallel` snapshots the array and validates every entry before any callback
107
+ starts. Invalid arguments reject with `TypeError`. The promise waits for all
108
+ callbacks to settle. A synchronous throw, a rejected promise, or a `null` return
109
+ all produce `null` at that position. Use `value !== null` to retain other falsy
110
+ values, and handle errors inside callbacks if you need their original causes.
111
+ The caller manages concurrency limits, cancellation, and callback resources.
120
112
 
121
113
  ## pipeline
122
114
 
@@ -137,23 +129,58 @@ stage inputs are compile-time errors. A `null` input or stage result skips that
137
129
  item's remaining stages. An item failure also skips its remaining stages and
138
130
  becomes `null`. The returned Promise waits for all item chains to settle; its
139
131
  result type always includes `null`. Stage input types exclude only `null`, so
140
- `undefined` and other falsy values continue normally. Invalid composition
141
- arguments still reject the call.
132
+ `undefined` and other falsy values continue normally. A non-array input or a
133
+ non-function stage on nonempty input rejects with `TypeError`. The caller manages
134
+ concurrency limits, cancellation, and resources used by input work or stages.
142
135
 
143
136
  ## Durable workflow
144
137
 
145
- `workflow(options, body)` saves an initial manifest before passing explicit
146
- `runId` and `input` to the body. Every `agent()` call made inside the body is
147
- journaled automatically: identical calls on a `resumeFrom` run return their
148
- saved results without opening new sessions, and any changed call invalidates
149
- the calls after it. Existing three-primitive functions keep their independent
150
- behavior, and `agent()` outside `workflow()` is unchanged.
151
-
152
- The [persistence reference](../../docs/workflow/persistence.md) defines the
153
- journal contract, cache keys, error handling and file guarantees.
154
- Try `bun run example:workflow-persistence` and then repeat with its printed run
155
- ID: the resumed run opens zero new sessions. This example uses a scripted
156
- backend and makes no model requests.
138
+ `workflow(options, body)` creates a new file-backed run and saves its initial
139
+ manifest before calling `body({ runId, input })`. Supply strict JSON for the input
140
+ and the awaited body result. Set `directory` to the storage root and `name` and
141
+ `revision` to identify compatible runs. `runId` defaults to a new UUID. The body
142
+ receives a deeply frozen input copy. The root exports `WorkflowOptions`,
143
+ `WorkflowContext`, and `WorkflowResult` for typing the options, callback context,
144
+ and published result.
145
+
146
+ To resume, set `resumeFrom` to an inactive source run with the same name and
147
+ revision. The body runs again from the beginning in a new run. After schema
148
+ validation, journaled calls reserve keys in invocation order using their prompt,
149
+ options, and predecessor. Eligible saved results are reused without opening a
150
+ Session. A changed key ends replay for later calls. A matching call left at a
151
+ started record can rerun while later calls remain eligible. A prior terminal
152
+ failure with an unknown outcome requires reconciliation before that call can run.
153
+ The body owns any side effects that may repeat during resume.
154
+
155
+ The promise drains registered agent calls, publishes a JSON copy of the body result, and
156
+ releases the writer lock before resolving with `{ runId, status, result }`.
157
+ A registered agent rejection or drop can produce `status: 'incomplete'` if the
158
+ body still returns a publishable result. Body errors, fatal agent failures, and
159
+ storage failures reject. Keep Clients usable until settlement and await any
160
+ other background work inside the body. See the [persistence reference](../../docs/workflow/persistence.md)
161
+ for cache keys, failure recovery, and file guarantees.
162
+
163
+ ## Code structure
164
+
165
+ - [Package entry](src/index.ts) exposes the four application primitives and links their public
166
+ types directly to the modules that define them. [TypeScript configuration](tsconfig.json)
167
+ checks `src`, including tests, with Bun and Node types. The [package manifest](package.json)
168
+ declares the root entry and the no-emit build and typecheck scripts.
169
+ - [Agent calls](src/agent.ts) choose between fresh execution and journal replay, and record
170
+ the outcome of journaled calls. [Fresh execution](src/agent-execution.ts) owns the SDK
171
+ session from creation through release. [Output schemas](src/output-schema.ts) prepare the
172
+ request schema and validate fresh and replayed results.
173
+ - [Parallel](src/parallel.ts) starts independent callbacks. [Pipeline](src/pipeline.ts)
174
+ advances each input through its own typed stage chain.
175
+ - [Workflow](src/workflow.ts) opens the run, invokes the body, drains registered agent work,
176
+ and publishes the result or failure before releasing the run. [Workflow types](src/workflow-types.ts)
177
+ define the application contract. [Run state](src/workflow-state.ts) gives nested agent calls
178
+ access to the active run and tracks admission, pending work and sticky failures.
179
+ - [Persistence](src/persistence/) holds the [target writer](src/persistence/store.ts), the
180
+ [source reader](src/persistence/replay.ts), and the [journal](src/persistence/journal.ts).
181
+ [Checkpoint records](src/persistence/records.ts) define the shared file layout and schemas.
182
+ [Checkpoint file I/O](src/persistence/checkpoint-files.ts) owns atomic publication and
183
+ checked reads. [Canonical JSON](src/persistence/json.ts) supplies copying and hashing rules.
157
184
 
158
185
  ## Examples
159
186
 
@@ -167,7 +194,6 @@ For `[2, 3, 4]`, the pipeline asks the model to double then square each value, e
167
194
  `[16, 36, 64]`. Two parallel agent calls then calculate the sum `116` and maximum `64`.
168
195
  The eight agent calls each use an independent Session.
169
196
 
170
- The [migration plan](../../draft/docs/workflow-primitives-plan.md) records the removed
171
- framework and the [development record](../../draft/docs/development.md#workflow-agent-zod)
172
- contains current verification evidence. The package has only its root entry;
173
- there is no `/mcp` subentry.
197
+ Run `bun run example:workflow-persistence` and repeat with the printed run ID to
198
+ replay the saved agent results. The example uses a scripted backend, and the
199
+ resumed run opens zero new sessions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anureo/workflow",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Agent execution, composition, and durable workflow steps over the Anureo SDK",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -13,26 +13,27 @@
13
13
  },
14
14
  "type": "module",
15
15
  "exports": {
16
- ".": {
17
- "types": "./src/index.d.ts",
18
- "import": "./src/index.js",
19
- "default": "./src/index.js"
20
- }
16
+ ".": "./src/index.ts"
17
+ },
18
+ "scripts": {
19
+ "build": "tsc --noEmit",
20
+ "typecheck": "tsc --noEmit --pretty false",
21
+ "test": "bun test src"
21
22
  },
22
23
  "dependencies": {
23
- "@anureo/sdk": "0.3.0",
24
- "@anureo/protocol": "0.3.0",
24
+ "@anureo/sdk": "0.3.1",
25
+ "@anureo/protocol": "0.3.1",
25
26
  "ajv": "8.20.0",
26
27
  "zod": "4.6.7"
27
28
  },
29
+ "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"
35
+ },
28
36
  "engines": {
29
37
  "node": ">=22"
30
- },
31
- "files": [
32
- "src",
33
- "bin",
34
- "schema",
35
- "protocol",
36
- "examples"
37
- ]
38
+ }
38
39
  }
@@ -0,0 +1,121 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { mkdtemp, readFile, rm } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { z } from 'zod'
7
+ import { createClient, type Client, type StructuredOutputToolDefinition } from '@anureo/sdk'
8
+ import { createAcpAdapter } from '@anureo/adapter-acp'
9
+ import { createClaudeAdapter } from '@anureo/adapter-claude'
10
+ import { createCodexAdapter } from '@anureo/adapter-codex'
11
+ import { createPiAdapter } from '@anureo/adapter-pi'
12
+ import { fakeFactory } from '../../adapter/pi/tests/fake-host'
13
+ import { agent, parallel } from './index'
14
+
15
+ const fakeClaude = fileURLToPath(new URL('../../adapter/claude/tests/fixtures/fake-claude.mjs', import.meta.url))
16
+
17
+ test('Zod agent crosses the official Claude SDK and a real JSONL process in fresh native sessions', async () => {
18
+ const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-native-'))
19
+ const log = join(cwd, 'initialize.jsonl')
20
+ const client = await createClient({ adapter: createClaudeAdapter({
21
+ command: fakeClaude,
22
+ executableRuntime: 'node', stateDir: join(cwd, 'state'), env: { FAKE_SCHEMA_PROBE: '1', FAKE_SCHEMA_LOG: log },
23
+ }), identity: { adapterId: 'claude', runtimeConfigId: 'workflow' } })
24
+ try {
25
+ const schema = z.object({ answer: z.literal(42) })
26
+ expect(await parallel([
27
+ () => agent('first', { client, cwd, schema }),
28
+ () => agent('second', { client, cwd, schema }),
29
+ ])).toEqual([{ answer: 42 }, { answer: 42 }])
30
+ const records = await readNativeLog(log)
31
+ const structured = records.filter(record => record.schema)
32
+ expect(structured).toHaveLength(2)
33
+ expect(new Set(structured.map(record => record.sessionId)).size).toBe(2)
34
+ expect(structured[0].schema).toMatchObject({ type: 'object', properties: { answer: { const: 42 } } })
35
+ } finally {
36
+ await releaseNativeFixture(client, cwd)
37
+ }
38
+ }, 15_000)
39
+
40
+ test('Claude nominal success without native structured_output never falls back to prose', async () => {
41
+ const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-missing-'))
42
+ const client = await createClient({ adapter: createClaudeAdapter({
43
+ command: fakeClaude, executableRuntime: 'node', stateDir: cwd,
44
+ }), identity: { adapterId: 'claude', runtimeConfigId: 'missing' } })
45
+ try {
46
+ await expect(agent('missing', { client, cwd, schema: z.object({ answer: z.number() }) })).rejects.toMatchObject({ code: 'CLAUDE_STRUCTURED_OUTPUT_MISSING' })
47
+ } finally {
48
+ await releaseNativeFixture(client, cwd)
49
+ }
50
+ }, 15_000)
51
+
52
+ const codexCases = [
53
+ { scenario: 'workflow-schema', expected: { answer: 42 }, description: 'returns a successful structured result' },
54
+ { scenario: 'auth-expired', expected: null, description: 'returns null when authentication expires' },
55
+ ] as const
56
+
57
+ for (const { scenario, expected, description } of codexCases) test(`Zod agent crosses Codex native process: ${description}`, async () => {
58
+ const cwd = await mkdtemp(join(tmpdir(), 'anureo-workflow-codex-'))
59
+ const log = join(cwd, 'requests.jsonl')
60
+ const client = await createClient({ adapter: createCodexAdapter({ command: process.execPath,
61
+ args: [fileURLToPath(new URL('../../adapter/codex/tests/fake-app-server.mjs', import.meta.url))],
62
+ version: '0.164.0', env: { FAKE_SCENARIO: scenario, FAKE_LOG_FILE: log },
63
+ }), identity: { adapterId: 'codex', runtimeConfigId: scenario } })
64
+ try {
65
+ const value = await agent('answer', { client, cwd, schema: z.object({ answer: z.literal(42) }) })
66
+ expect(value).toEqual(expected)
67
+ const starts = (await readNativeLog(log)).filter(frame => frame.method === 'turn/start')
68
+ expect(starts).toHaveLength(1)
69
+ expect(starts[0].params.outputSchema).toMatchObject({ type: 'object', properties: { answer: { const: 42 } } })
70
+ } finally {
71
+ await releaseNativeFixture(client, cwd)
72
+ }
73
+ }, 15_000)
74
+
75
+ test('workflow Zod output uses MCP and retains local refinement failures', async () => {
76
+ const adapter = createAcpAdapter({ command: process.execPath, args: [fileURLToPath(new URL('../../adapter/acp/tests/fixtures/fake-acp.mjs', import.meta.url)), '--scenario', 'mcp-output'] })
77
+ const client = await createClient({ adapter, identity: { adapterId: 'acp', runtimeConfigId: 'workflow-mcp' } })
78
+ try {
79
+ const options = { client, cwd: process.cwd() }
80
+ const schema = z.object({ sum: z.number().int() })
81
+ const value = await agent('17 + 25', { ...options, schema })
82
+ expect(value).toEqual({ sum: 42 })
83
+ await expect(agent('17 + 25', { ...options, schema: schema.refine(value => value.sum < 0) }))
84
+ .rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', outcomeUnknown: false })
85
+ } finally { await client.dispose() }
86
+ })
87
+
88
+ test('workflow schema uses direct Pi tools and retains Zod refinement validation', async () => {
89
+ const fake = fakeFactory(host => {
90
+ let output: StructuredOutputToolDefinition | undefined
91
+ Object.assign(host, {
92
+ /** Store the SDK's tool for the host script. The Pi adapter forwards an omitted tool to clear it. */
93
+ async setOutputTool(tool?: StructuredOutputToolDefinition) { output = tool },
94
+ })
95
+ host.script = async host => {
96
+ if (!output) throw new Error('Output tool must be registered before scripted execution')
97
+ await output.execute({ sum: 42 })
98
+ await host.assistant('submitted')
99
+ }
100
+ })
101
+ const client = await createClient({ adapter: createPiAdapter({ version: '1.5.2', createHost: fake.factory }), identity: { adapterId: 'pi', runtimeConfigId: 'workflow-direct-tool' } })
102
+ try {
103
+ const options = { client, cwd: process.cwd() }
104
+ const schema = z.object({ sum: z.number().int() })
105
+ expect(await agent('17 + 25', { ...options, schema })).toEqual({ sum: 42 })
106
+ await expect(agent('17 + 25', { ...options, schema: schema.refine(value => value.sum < 0) }))
107
+ .rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', outcomeUnknown: false })
108
+ expect(fake.opens.every(open => !Object.hasOwn(open, 'mcpServers'))).toBe(true)
109
+ } finally { await client.dispose() }
110
+ })
111
+
112
+ /** Read the fixture's JSONL records in write order. Missing logs or malformed records fail the test. */
113
+ async function readNativeLog(path: string) {
114
+ return (await readFile(path, 'utf8')).trim().split('\n').map(line => JSON.parse(line))
115
+ }
116
+
117
+ /** Remove fixture files after client disposal succeeds. Either failure rejects the test. */
118
+ async function releaseNativeFixture(client: Client, cwd: string): Promise<void> {
119
+ await client.dispose()
120
+ await rm(cwd, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 })
121
+ }
@@ -0,0 +1,201 @@
1
+ import type { HarnessError } from '@anureo/protocol'
2
+ import { HarnessSdkError, sdkError, type Client, type Session, type SubmitOptions } from '@anureo/sdk'
3
+ import type { z } from 'zod'
4
+ import { prepareOutputSchema, type AgentOutputSchema } from './output-schema'
5
+
6
+ /** Configure an agent call. Keep the client usable until settlement and dispose it separately. */
7
+ export interface AgentOptions<S extends z.ZodObject = z.ZodObject> {
8
+ /** Initialized client selecting the backend. The caller owns client disposal. */
9
+ client: Client
10
+ /** Working directory forwarded to the fresh session. */
11
+ cwd: string
12
+ /** Backend model selection. Omit to use the backend's selection. */
13
+ model?: string
14
+ /** Session instructions, separate from the input prompt. */
15
+ instructions?: string
16
+ /** Permission mode forwarded to the fresh session. Accepted values and defaults depend on the backend. */
17
+ permissionMode?: string
18
+ /** Portable Zod object schema with closed objects and required JSON fields. Omit to return text. */
19
+ schema?: S
20
+ /**
21
+ * With a schema, opt in to prompting for JSON when the session lacks structured output.
22
+ * With a schema and no fallback, an unsupported session causes agent to reject before submission.
23
+ * In a workflow this option contributes to replay identity even in text mode.
24
+ */
25
+ outputFallback?: 'json-text'
26
+ }
27
+
28
+ /**
29
+ * 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.
34
+ */
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 })
41
+ const cleanupErrors = await releaseAgentSession(session)
42
+ return settleAgentOutcome(outcome, cleanupErrors)
43
+ }
44
+
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 =
50
+ | { status: 'completed'; value: string | Record<string, unknown> }
51
+ | { status: 'dropped'; error: AgentErrorSummary }
52
+ | { status: 'failed'; error: HarnessSdkError }
53
+
54
+ /** Safe diagnostics retained from cleanup and dropped terminals without native messages. */
55
+ interface AgentErrorSummary {
56
+ code: string
57
+ outcomeUnknown: boolean
58
+ }
59
+
60
+ interface AgentTurnRequest {
61
+ session: Session
62
+ prompt: string
63
+ output: AgentOutputSchema | undefined
64
+ outputFallback: AgentOptions['outputFallback']
65
+ }
66
+
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
+ */
71
+ function openAgentSession({ client, cwd, model, instructions, permissionMode }: Pick<
72
+ AgentOptions, 'client' | 'cwd' | 'model' | 'instructions' | 'permissionMode'
73
+ >): Promise<Session | null> {
74
+ return client.sessions.create({
75
+ cwd,
76
+ ...(model !== undefined ? { model } : {}),
77
+ ...(instructions !== undefined ? { instructions } : {}),
78
+ ...(permissionMode !== undefined ? { permissionMode } : {}),
79
+ })
80
+ .catch(cause => {
81
+ if (isStartupBlockException(cause)) return null
82
+ throw cause
83
+ })
84
+ }
85
+
86
+ /**
87
+ * Submit once, then await the associated turn's retained terminal result and any local validation.
88
+ * Return execution evidence to executeAgent, which owns session release and final settlement.
89
+ */
90
+ async function observeAgentTurn(request: AgentTurnRequest): Promise<AgentOutcome> {
91
+ const { session, output } = request
92
+ try {
93
+ 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 })
96
+ if (result.status === 'completed') {
97
+ return { status: 'completed', value: output ? await output.parse(result.text) : result.text }
98
+ }
99
+ return classifyTerminalFailure(result.status, result.error)
100
+ } catch (cause) {
101
+ if (isStartupBlockException(cause)) return { status: 'dropped', error: summarizeAgentError(cause) }
102
+ return { status: 'failed', error: sdkError(cause, 'AGENT_FAILED', true) }
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Build observeAgentTurn's single submission using the attached session's capabilities.
108
+ * With structured output requested, use its schema route or the opted-in JSON text prompt.
109
+ * Throw CAPABILITY_UNSUPPORTED before submission if neither route is available.
110
+ */
111
+ function agentSubmission({ session, prompt, output, outputFallback }: AgentTurnRequest): SubmitOptions {
112
+ if (!output) return { input: prompt }
113
+ if (session.capabilities.turn?.outputSchema) return { input: prompt, outputSchema: output.schema }
114
+ if (outputFallback !== 'json-text') {
115
+ throw new HarnessSdkError('CAPABILITY_UNSUPPORTED', 'Session does not support structured output')
116
+ }
117
+ const instruction = 'Return the final answer as a single JSON object that matches this JSON Schema. Do not include Markdown fences or surrounding prose.'
118
+ return { input: `${prompt}\n\n${instruction}\n${JSON.stringify(output.schema)}` }
119
+ }
120
+
121
+ /**
122
+ * Classify a retained failed or interrupted terminal for observeAgentTurn to return to executeAgent.
123
+ * Only confirmed outcomes qualify for a drop. Tagged startup denial qualifies in either status,
124
+ * explicit skip applies to interruption, and the terminal API allowlist applies to failure.
125
+ * Retain other errors for rejection after cleanup and supply AGENT_INTERRUPTED when details are absent.
126
+ */
127
+ function classifyTerminalFailure(status: 'failed' | 'interrupted', error: HarnessError | undefined): AgentOutcome {
128
+ if (!error) return { status: 'failed', error: new HarnessSdkError('AGENT_INTERRUPTED') }
129
+ if (!error.outcomeUnknown) {
130
+ const explicitSkip = status === 'interrupted' && error.details?.workflowDisposition === 'skipped'
131
+ if (explicitSkip || isStartupBlocked(error) || (status === 'failed' && terminalApiErrors.has(error.code))) {
132
+ return { status: 'dropped', error: summarizeAgentError(error) }
133
+ }
134
+ }
135
+ return {
136
+ status: 'failed',
137
+ error: new HarnessSdkError(error.code, error.message, error.retryable, error.outcomeUnknown, error.details),
138
+ }
139
+ }
140
+
141
+ /** Project errors to the code and uncertainty exposed in agent's cleanup diagnostics. */
142
+ function summarizeAgentError(error: AgentErrorSummary): AgentErrorSummary {
143
+ return { code: error.code, outcomeUnknown: error.outcomeUnknown }
144
+ }
145
+
146
+ /**
147
+ * Release executeAgent's session in close/dispose order. Attempt disposal after close failure
148
+ * and return distinct normalized SDK error instances as safe diagnostics in encounter order.
149
+ */
150
+ async function releaseAgentSession(session: Session): Promise<AgentErrorSummary[]> {
151
+ const cleanupErrors = new Set<HarnessSdkError>()
152
+ for (const method of ['close', 'dispose'] as const) {
153
+ try {
154
+ await session[method]()
155
+ } catch (cause) {
156
+ cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true))
157
+ }
158
+ }
159
+ return [...cleanupErrors].map(summarizeAgentError)
160
+ }
161
+
162
+ /**
163
+ * Settle executeAgent after both release attempts. Return text/data or null on successful cleanup.
164
+ * Throw the primary failure with any cleanup diagnostics, or RESOURCE_RELEASE_FAILED if cleanup
165
+ * was the only failure.
166
+ */
167
+ function settleAgentOutcome(outcome: AgentOutcome, errors: AgentErrorSummary[]): string | Record<string, unknown> | null {
168
+ if (errors.length) {
169
+ if (outcome.status === 'failed') {
170
+ const failure = outcome.error
171
+ throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown,
172
+ { ...failure.details, cleanupErrors: errors })
173
+ }
174
+ throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false,
175
+ errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) })
176
+ }
177
+ switch (outcome.status) {
178
+ case 'completed': return outcome.value
179
+ case 'dropped': return null
180
+ case 'failed': throw outcome.error
181
+ }
182
+ }
183
+
184
+ /** Share the startup-denial rule between classifyTerminalFailure and isStartupBlockException.
185
+ * The adapter must supply the dedicated code, a confirmed outcome and the startup disposition. */
186
+ function isStartupBlocked(error: Pick<HarnessSdkError, 'code' | 'outcomeUnknown' | 'details'>): boolean {
187
+ return !error.outcomeUnknown && error.code === 'AGENT_STARTUP_BLOCKED' && error.details?.workflowDisposition === 'startup_blocked'
188
+ }
189
+
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
+ */
194
+ function isStartupBlockException(cause: unknown): cause is HarnessSdkError {
195
+ return cause instanceof HarnessSdkError && isStartupBlocked(cause)
196
+ }
197
+
198
+ // Only apply to native failed terminal results, never open/submit/observation failures.
199
+ const terminalApiErrors = new Set([
200
+ 'AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE',
201
+ ])