@anureo/workflow 0.0.0-stage → 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.
- package/README.md +198 -2
- package/package.json +37 -4
- package/src/agent-adapters.test.ts +121 -0
- package/src/agent-execution.ts +201 -0
- package/src/agent.test.ts +333 -0
- package/src/agent.ts +135 -0
- package/src/fixtures/workflow-crash.ts +53 -0
- package/src/index.ts +9 -0
- package/src/output-schema.test.ts +147 -0
- package/src/output-schema.ts +231 -0
- package/src/parallel.test.ts +96 -0
- package/src/parallel.ts +33 -0
- package/src/persistence/checkpoint-files.ts +82 -0
- package/src/persistence/journal.ts +111 -0
- package/src/persistence/json.ts +83 -0
- package/src/persistence/records.ts +97 -0
- package/src/persistence/replay.ts +91 -0
- package/src/persistence/store.ts +286 -0
- package/src/pipeline.test.ts +201 -0
- package/src/pipeline.ts +99 -0
- package/src/test-helpers.ts +23 -0
- package/src/workflow-state.ts +130 -0
- package/src/workflow-types.ts +38 -0
- package/src/workflow.test.ts +376 -0
- package/src/workflow.ts +112 -0
- package/tsconfig.json +13 -0
package/README.md
CHANGED
|
@@ -1,3 +1,199 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @anureo/workflow
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
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.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import type { Client } from '@anureo/sdk'
|
|
17
|
+
import { agent, parallel, pipeline } from '@anureo/workflow'
|
|
18
|
+
|
|
19
|
+
export async function reviewFiles(client: Client, files: readonly string[], cwd: string) {
|
|
20
|
+
const options = { client, cwd }
|
|
21
|
+
const verified = await pipeline(
|
|
22
|
+
files,
|
|
23
|
+
file => agent(`Review ${file}; include code locations and evidence.`, options),
|
|
24
|
+
(findings, file) => agent(`Independently verify ${file}:\n${findings}`, options),
|
|
25
|
+
)
|
|
26
|
+
if (verified.some(value => value === null)) throw new Error('Some file reviews failed')
|
|
27
|
+
const [summary, tests] = await parallel([
|
|
28
|
+
() => agent(`Summarize: ${JSON.stringify(verified)}`, options),
|
|
29
|
+
() => agent(`Suggest regression tests: ${JSON.stringify(verified)}`, options),
|
|
30
|
+
])
|
|
31
|
+
if (summary === null || tests === null) throw new Error('Review synthesis failed')
|
|
32
|
+
return { verified, summary, tests }
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
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.
|
|
40
|
+
|
|
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.
|
|
43
|
+
|
|
44
|
+
## agent
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import type { Client } from '@anureo/sdk'
|
|
48
|
+
import { z } from 'zod'
|
|
49
|
+
import { agent } from '@anureo/workflow'
|
|
50
|
+
|
|
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>.
|
|
59
|
+
```
|
|
60
|
+
|
|
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`.
|
|
67
|
+
|
|
68
|
+
`schema` accepts a Zod 4 object schema. The library converts it to draft-07 JSON
|
|
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.
|
|
73
|
+
This package depends on Zod 4.6.7. Applications that import Zod to author schemas
|
|
74
|
+
should also declare it as their own dependency. Schema-associated types infer business fields;
|
|
75
|
+
there is no unbound result-type generic or raw JSON Schema overload.
|
|
76
|
+
|
|
77
|
+
Use closed objects and required fields; nullable fields, array properties, enums,
|
|
78
|
+
nested unions and local recursion are supported. Optional properties, open
|
|
79
|
+
objects, records, tuples, value transformations and non-JSON types are rejected.
|
|
80
|
+
Defaults do not fill omitted model answers. Async refinements are supported
|
|
81
|
+
locally; their failures reject without replaying input. See the
|
|
82
|
+
[full schema and failure contract](../../docs/workflow/README.md#schema-mode).
|
|
83
|
+
|
|
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.
|
|
89
|
+
|
|
90
|
+
Cleanup is attempted for successful, failed and discarded executions. A cleanup
|
|
91
|
+
failure rejects with `RESOURCE_RELEASE_FAILED`, or preserves a primary execution
|
|
92
|
+
exception with attached `details.cleanupErrors`. Releasing observation does not
|
|
93
|
+
prove the backend stopped. Use SDK Session/Turn APIs for raw items, usage, event
|
|
94
|
+
observation, multi-turn context, and exact execution controls.
|
|
95
|
+
|
|
96
|
+
Run `bun run example:workflow-schema [all|codex|claude]` for the
|
|
97
|
+
[Zod example](../../examples/workflow-structured.ts) using authenticated local
|
|
98
|
+
CLIs and real model requests.
|
|
99
|
+
|
|
100
|
+
## parallel
|
|
101
|
+
|
|
102
|
+
`parallel([() => taskA(), () => taskB()])` starts every callback and returns
|
|
103
|
+
input-ordered results. Callbacks may return ordinary values or Promises; inline
|
|
104
|
+
heterogeneous tuples preserve each result's type. An empty batch returns `[]`.
|
|
105
|
+
|
|
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.
|
|
112
|
+
|
|
113
|
+
## pipeline
|
|
114
|
+
|
|
115
|
+
`pipeline(items, stage1, stage2, ...)` runs each item through its own sequence of
|
|
116
|
+
stages. A fast item can enter stage two while another item is still in stage one.
|
|
117
|
+
Results retain input order. Empty input returns `[]` before stage validation.
|
|
118
|
+
Zero stages are allowed and return the awaited inputs, with failures as `null`.
|
|
119
|
+
|
|
120
|
+
Every stage receives `(prevResult, originalItem, index)`. The first stage gets
|
|
121
|
+
the awaited input value; later stages get the awaited prior result. The original
|
|
122
|
+
input entry and zero-based index remain available throughout. Stages may change
|
|
123
|
+
types and pass ordinary TS values, including objects and Maps, without a JSON
|
|
124
|
+
serialization boundary.
|
|
125
|
+
|
|
126
|
+
Inline callbacks have contextual type inference for up to six stages. Longer
|
|
127
|
+
chains accept typed stage functions with no runtime stage-count limit. Incompatible
|
|
128
|
+
stage inputs are compile-time errors. A `null` input or stage result skips that
|
|
129
|
+
item's remaining stages. An item failure also skips its remaining stages and
|
|
130
|
+
becomes `null`. The returned Promise waits for all item chains to settle; its
|
|
131
|
+
result type always includes `null`. Stage input types exclude only `null`, so
|
|
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.
|
|
135
|
+
|
|
136
|
+
## Durable workflow
|
|
137
|
+
|
|
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.
|
|
184
|
+
|
|
185
|
+
## Examples
|
|
186
|
+
|
|
187
|
+
Run `bun run example:workflow` from the repository. The ordinary
|
|
188
|
+
[TypeScript example](../../examples/workflow.ts) directly imports all three
|
|
189
|
+
primitives and uses the Codex adapter. It requires a configured, authenticated
|
|
190
|
+
Codex CLI on PATH (`CODEX_BIN` can override its path). It prints every agent
|
|
191
|
+
input and output; each prompt requests arithmetic without tools.
|
|
192
|
+
|
|
193
|
+
For `[2, 3, 4]`, the pipeline asks the model to double then square each value, expecting
|
|
194
|
+
`[16, 36, 64]`. Two parallel agent calls then calculate the sum `116` and maximum `64`.
|
|
195
|
+
The eight agent calls each use an independent Session.
|
|
196
|
+
|
|
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,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anureo/workflow",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.1",
|
|
4
|
+
"description": "Agent execution, composition, and durable workflow steps over the Anureo SDK",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/hi-youichi/anureo-sdk.git",
|
|
9
|
+
"directory": "packages/workflow"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./src/index.ts"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc --noEmit",
|
|
20
|
+
"typecheck": "tsc --noEmit --pretty false",
|
|
21
|
+
"test": "bun test src"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@anureo/sdk": "0.3.1",
|
|
25
|
+
"@anureo/protocol": "0.3.1",
|
|
26
|
+
"ajv": "8.20.0",
|
|
27
|
+
"zod": "4.6.7"
|
|
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
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22"
|
|
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
|
+
])
|