@anureo/workflow 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -96
- package/package.json +8 -8
- package/src/agent-mcp.test.ts +19 -0
- package/src/agent-outcome.ts +21 -0
- package/src/agent-pi.test.ts +21 -0
- package/src/agent.test.ts +51 -100
- package/src/agent.ts +81 -106
- package/src/fixtures/workflow-crash.ts +12 -33
- package/src/index.ts +5 -6
- package/src/journal-call.test.ts +68 -0
- package/src/journal-call.ts +93 -0
- package/src/native.test.ts +71 -0
- package/src/output-schema.test.ts +12 -33
- package/src/output-schema.ts +96 -202
- package/src/parallel.test.ts +0 -1
- package/src/parallel.ts +8 -26
- package/src/persistence/atomic.ts +32 -0
- package/src/persistence/journal.ts +88 -79
- package/src/persistence/json.ts +32 -58
- package/src/persistence/records.ts +54 -74
- package/src/persistence/replay.ts +30 -72
- package/src/persistence/store.ts +119 -229
- package/src/pipeline.test.ts +0 -19
- package/src/pipeline.ts +23 -69
- package/src/run-context.ts +19 -0
- package/src/workflow-state.ts +18 -71
- package/src/workflow-types.ts +2 -20
- package/src/workflow.test.ts +87 -55
- package/src/workflow.ts +30 -88
- package/src/agent-adapters.test.ts +0 -121
- package/src/agent-execution.ts +0 -201
- package/src/persistence/checkpoint-files.ts +0 -82
- package/src/test-helpers.ts +0 -23
package/README.md
CHANGED
|
@@ -1,16 +1,28 @@
|
|
|
1
1
|
# @anureo/workflow
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
`agent`
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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).
|
|
8
21
|
|
|
9
22
|
## Usage
|
|
10
23
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
the Client. See the [SDK README](../../README.md) for Client setup.
|
|
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:
|
|
14
26
|
|
|
15
27
|
```ts
|
|
16
28
|
import type { Client } from '@anureo/sdk'
|
|
@@ -33,43 +45,39 @@ export async function reviewFiles(client: Client, files: readonly string[], cwd:
|
|
|
33
45
|
}
|
|
34
46
|
```
|
|
35
47
|
|
|
36
|
-
`pipeline` and `parallel`
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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.
|
|
40
52
|
|
|
41
|
-
|
|
42
|
-
|
|
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.
|
|
43
57
|
|
|
44
58
|
## agent
|
|
45
59
|
|
|
46
60
|
```ts
|
|
47
|
-
import type { Client } from '@anureo/sdk'
|
|
48
61
|
import { z } from 'zod'
|
|
49
62
|
import { agent } from '@anureo/workflow'
|
|
50
63
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
}
|
|
58
|
-
|
|
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)
|
|
59
72
|
```
|
|
60
73
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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`.
|
|
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.
|
|
67
77
|
|
|
68
78
|
`schema` accepts a Zod 4 object schema. The library converts it to draft-07 JSON
|
|
69
|
-
Schema,
|
|
70
|
-
and returns `z.output<S>`.
|
|
71
|
-
`turn.outputSchema` support. Set `outputFallback: 'json-text'` to include the schema
|
|
72
|
-
in the prompt when the session lacks that capability.
|
|
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>`.
|
|
73
81
|
This package depends on Zod 4.6.7. Applications that import Zod to author schemas
|
|
74
82
|
should also declare it as their own dependency. Schema-associated types infer business fields;
|
|
75
83
|
there is no unbound result-type generic or raw JSON Schema overload.
|
|
@@ -81,11 +89,11 @@ Defaults do not fill omitted model answers. Async refinements are supported
|
|
|
81
89
|
locally; their failures reject without replaying input. See the
|
|
82
90
|
[full schema and failure contract](../../docs/workflow/README.md#schema-mode).
|
|
83
91
|
|
|
84
|
-
Confirmed native failed terminals for authentication, usage
|
|
85
|
-
service unavailability
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
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.
|
|
89
97
|
|
|
90
98
|
Cleanup is attempted for successful, failed and discarded executions. A cleanup
|
|
91
99
|
failure rejects with `RESOURCE_RELEASE_FAILED`, or preserves a primary execution
|
|
@@ -103,12 +111,12 @@ CLIs and real model requests.
|
|
|
103
111
|
input-ordered results. Callbacks may return ordinary values or Promises; inline
|
|
104
112
|
heterogeneous tuples preserve each result's type. An empty batch returns `[]`.
|
|
105
113
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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.
|
|
112
120
|
|
|
113
121
|
## pipeline
|
|
114
122
|
|
|
@@ -129,58 +137,47 @@ stage inputs are compile-time errors. A `null` input or stage result skips that
|
|
|
129
137
|
item's remaining stages. An item failure also skips its remaining stages and
|
|
130
138
|
becomes `null`. The returned Promise waits for all item chains to settle; its
|
|
131
139
|
result type always includes `null`. Stage input types exclude only `null`, so
|
|
132
|
-
`undefined` and other falsy values continue normally.
|
|
133
|
-
|
|
134
|
-
concurrency limits, cancellation, and resources used by input work or stages.
|
|
140
|
+
`undefined` and other falsy values continue normally. Invalid composition
|
|
141
|
+
arguments still reject the call.
|
|
135
142
|
|
|
136
143
|
## Durable workflow
|
|
137
144
|
|
|
138
|
-
`workflow(options, body)`
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
##
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
-
|
|
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.
|
|
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. Omitting `directory`
|
|
151
|
+
starts a memory-only run: it journals for its own lifetime (memoization and
|
|
152
|
+
chain keys) but writes no files and cannot be resumed after exit; resuming a
|
|
153
|
+
memory run fails with `WORKFLOW_RESUME_NOT_FOUND`.
|
|
154
|
+
|
|
155
|
+
Live calls use the client's [input and native hooks](../core/README.md#input-hooks).
|
|
156
|
+
The journal records the client's `inputHookRevision` with each started call.
|
|
157
|
+
Resume can reuse a matching result under the same policy revision without
|
|
158
|
+
running callbacks. A different revision, including adding or removing the
|
|
159
|
+
policy, stops resume for that call with `WORKFLOW_INPUT_POLICY_CHANGED`.
|
|
160
|
+
Start a new run after confirming the previous execution's outcome. For a
|
|
161
|
+
matching call whose previous outcome is already known to be uncertain,
|
|
162
|
+
`WORKFLOW_RECONCILIATION_REQUIRED` takes precedence.
|
|
163
|
+
|
|
164
|
+
The [persistence reference](../../docs/workflow/persistence.md) defines the
|
|
165
|
+
journal contract, cache keys, error handling and file guarantees.
|
|
166
|
+
Try `bun run example:workflow-persistence` and then repeat with its printed run
|
|
167
|
+
ID: the resumed run opens zero new sessions. This example uses a scripted
|
|
168
|
+
backend and makes no model requests.
|
|
169
|
+
|
|
170
|
+
## Adapter-facing helpers
|
|
171
|
+
|
|
172
|
+
Root exports also include three functions for adapter authors composing their
|
|
173
|
+
own journaled step primitives (for example `beer()` in
|
|
174
|
+
[`@anureo/adapter-swarm`](../adapter/swarm/README.md#workflow-execution)).
|
|
175
|
+
`journaledCall({ prompt, canonical, inputHookRevision?, droppedCode?,
|
|
176
|
+
failureCode? }, execute, revive?)` runs one memoized step with exactly the
|
|
177
|
+
`agent()` journal semantics: it executes unbundled outside a `workflow()` body.
|
|
178
|
+
`prepareOutputSchema(schema)` turns a zod object into the canonical JSON schema
|
|
179
|
+
plus `parse` used by structured-output steps, and `isDroppedOutcome(error,
|
|
180
|
+
status)` detects drop-class turn failures that map to a journaled null result.
|
|
184
181
|
|
|
185
182
|
## Examples
|
|
186
183
|
|
|
@@ -194,6 +191,7 @@ For `[2, 3, 4]`, the pipeline asks the model to double then square each value, e
|
|
|
194
191
|
`[16, 36, 64]`. Two parallel agent calls then calculate the sum `116` and maximum `64`.
|
|
195
192
|
The eight agent calls each use an independent Session.
|
|
196
193
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
194
|
+
The [migration plan](../../draft/docs/workflow-primitives-plan.md) records the removed
|
|
195
|
+
framework and the [development record](../../draft/docs/development.md#workflow-agent-zod)
|
|
196
|
+
contains current verification evidence. The package has only its root entry;
|
|
197
|
+
there is no `/mcp` subentry.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anureo/workflow",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
4
|
"description": "Agent execution, composition, and durable workflow steps over the Anureo SDK",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -21,17 +21,17 @@
|
|
|
21
21
|
"test": "bun test src"
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@anureo/sdk": "0.3.
|
|
25
|
-
"@anureo/protocol": "0.3.
|
|
24
|
+
"@anureo/sdk": "0.3.3",
|
|
25
|
+
"@anureo/protocol": "0.3.2",
|
|
26
26
|
"ajv": "8.20.0",
|
|
27
27
|
"zod": "4.6.7"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@anureo/conformance": "0.3.
|
|
31
|
-
"@anureo/adapter-claude": "0.3.
|
|
32
|
-
"@anureo/adapter-codex": "0.3.
|
|
33
|
-
"@anureo/adapter-acp": "0.3.
|
|
34
|
-
"@anureo/adapter-pi": "0.3.
|
|
30
|
+
"@anureo/conformance": "0.3.2",
|
|
31
|
+
"@anureo/adapter-claude": "0.3.4",
|
|
32
|
+
"@anureo/adapter-codex": "0.3.4",
|
|
33
|
+
"@anureo/adapter-acp": "0.3.2",
|
|
34
|
+
"@anureo/adapter-pi": "0.3.2"
|
|
35
35
|
},
|
|
36
36
|
"engines": {
|
|
37
37
|
"node": ">=22"
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { createClient } from '@anureo/sdk'
|
|
4
|
+
import { createAcpAdapter } from '@anureo/adapter-acp'
|
|
5
|
+
import { z } from 'zod'
|
|
6
|
+
import { rejectionOf } from '../../adapter/acp/tests/test-helpers'
|
|
7
|
+
import { agent } from './agent'
|
|
8
|
+
|
|
9
|
+
test('workflow Zod output uses the same MCP path and retains local refinement failures', async () => {
|
|
10
|
+
const adapter = createAcpAdapter({ command: process.execPath, args: [fileURLToPath(new URL('../../adapter/acp/tests/fixtures/fake-acp.mjs', import.meta.url)), '--scenario', 'mcp-output'] })
|
|
11
|
+
const client = await createClient({ adapter, identity: { adapterId: 'acp', runtimeConfigId: 'workflow-mcp' } })
|
|
12
|
+
try {
|
|
13
|
+
const schema = z.object({ sum: z.number().int() })
|
|
14
|
+
const value = await agent('17 + 25', { client, cwd: process.cwd(), schema })
|
|
15
|
+
expect(value).toEqual({ sum: 42 })
|
|
16
|
+
const failure = await rejectionOf(agent('17 + 25', { client, cwd: process.cwd(), schema: schema.refine(value => value.sum < 0) }))
|
|
17
|
+
expect(failure).toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', outcomeUnknown: false })
|
|
18
|
+
} finally { await client.dispose() }
|
|
19
|
+
})
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { HarnessError } from '@anureo/protocol'
|
|
2
|
+
import { HarnessSdkError } from '@anureo/sdk'
|
|
3
|
+
|
|
4
|
+
// Only apply to native failed terminal results, never open/submit/observation failures.
|
|
5
|
+
const terminalApiErrors = new Set([
|
|
6
|
+
'AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE',
|
|
7
|
+
])
|
|
8
|
+
|
|
9
|
+
export function isDroppedOutcome(error: HarnessError, status: 'failed' | 'interrupted'): boolean {
|
|
10
|
+
if (error.outcomeUnknown) return false
|
|
11
|
+
if (status === 'interrupted') return error.details?.workflowDisposition === 'skipped'
|
|
12
|
+
return isStartupBlocked(error) || terminalApiErrors.has(error.code)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isStartupBlocked(error: Pick<HarnessSdkError, 'code' | 'outcomeUnknown' | 'details'>): boolean {
|
|
16
|
+
return !error.outcomeUnknown && error.code === 'AGENT_STARTUP_BLOCKED' && error.details?.workflowDisposition === 'startup_blocked'
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function isStartupBlockException(cause: unknown): cause is HarnessSdkError {
|
|
20
|
+
return cause instanceof HarnessSdkError && isStartupBlocked(cause)
|
|
21
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { createClient, type StructuredOutputToolDefinition } from '@anureo/sdk'
|
|
3
|
+
import { createPiAdapter } from '@anureo/adapter-pi'
|
|
4
|
+
import { fakeFactory } from '../../adapter/pi/tests/fake-host'
|
|
5
|
+
import { z } from 'zod'
|
|
6
|
+
import { agent } from './agent'
|
|
7
|
+
|
|
8
|
+
test('workflow schema uses direct Pi tools and retains Zod refinement validation', async () => {
|
|
9
|
+
const fake = fakeFactory(host => {
|
|
10
|
+
let output: StructuredOutputToolDefinition | undefined
|
|
11
|
+
Object.assign(host, { async setOutputTool(tool?: StructuredOutputToolDefinition) { output = tool } })
|
|
12
|
+
host.script = async host => { await output!.execute({ sum: 42 }); await host.assistant('submitted') }
|
|
13
|
+
})
|
|
14
|
+
const client = await createClient({ adapter: createPiAdapter({ version: '1.5.2', createHost: fake.factory }), identity: { adapterId: 'pi', runtimeConfigId: 'workflow-direct-tool' } })
|
|
15
|
+
try {
|
|
16
|
+
const schema = z.object({ sum: z.number().int() })
|
|
17
|
+
expect(await agent('17 + 25', { client, cwd: process.cwd(), schema })).toEqual({ sum: 42 })
|
|
18
|
+
await expect(agent('17 + 25', { client, cwd: process.cwd(), schema: schema.refine(value => value.sum < 0) })).rejects.toMatchObject({ code: 'AGENT_STRUCTURED_OUTPUT_INVALID', outcomeUnknown: false })
|
|
19
|
+
expect(fake.opens.every(open => !Object.hasOwn(open, 'mcpServers'))).toBe(true)
|
|
20
|
+
} finally { await client.dispose() }
|
|
21
|
+
})
|
package/src/agent.test.ts
CHANGED
|
@@ -1,40 +1,25 @@
|
|
|
1
1
|
import { afterEach, expect, test } from 'bun:test'
|
|
2
2
|
import { randomUUID } from 'node:crypto'
|
|
3
|
-
import type
|
|
4
|
-
import type
|
|
5
|
-
import { HarnessSdkError, type Client, type SessionEventSink } from '@anureo/sdk'
|
|
3
|
+
import { createClient, HarnessSdkError, type Client, type SessionEventSink } from '@anureo/sdk'
|
|
4
|
+
import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
|
|
6
5
|
import { z } from 'zod'
|
|
7
6
|
import { agent, parallel, pipeline, type AgentOptions } from './index'
|
|
8
|
-
import {
|
|
7
|
+
import type { HarnessError } from '@anureo/protocol'
|
|
9
8
|
|
|
10
9
|
const clients: Client[] = []
|
|
11
|
-
const fixture = createFixture(clients)
|
|
12
10
|
afterEach(async () => { await Promise.all(clients.splice(0).map(client => client.dispose())) })
|
|
13
11
|
|
|
14
|
-
|
|
12
|
+
async function fixture(options?: FakeAdapterOptions) {
|
|
13
|
+
const adapter = createScriptedAdapter(options)
|
|
14
|
+
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
|
|
15
|
+
clients.push(client)
|
|
16
|
+
return { client, adapter }
|
|
17
|
+
}
|
|
15
18
|
async function complete(sink: SessionEventSink, turnId: string, text: string) {
|
|
16
19
|
await sink.emit({ type: 'item/completed', payload: { item: { id: randomUUID(), type: 'agentMessage', phase: 'final', text } } }, { turnId })
|
|
17
20
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
|
|
18
21
|
}
|
|
19
22
|
|
|
20
|
-
/**
|
|
21
|
-
* Supply the execute hook awaited by the scripted backend. For a submit, publish the start and
|
|
22
|
-
* await the test's event callback before replying with the same turn ID. A callback rejection
|
|
23
|
-
* fails the dispatch. Other calls fall through to the default adapter.
|
|
24
|
-
*/
|
|
25
|
-
function scriptSubmission(
|
|
26
|
-
publish: (submission: { sink: SessionEventSink; turnId: string; submissionId: string }) => Promise<void>,
|
|
27
|
-
): NonNullable<FakeAdapterOptions['execute']> {
|
|
28
|
-
return async (call, sink) => {
|
|
29
|
-
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
30
|
-
const { submissionId } = call.params
|
|
31
|
-
const turnId = randomUUID()
|
|
32
|
-
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
33
|
-
await publish({ sink, turnId, submissionId })
|
|
34
|
-
return { submissionId, accepted: true, disposition: 'started', turnId }
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
23
|
test('returns text from independent sessions and leaves the borrowed client usable', async () => {
|
|
39
24
|
const { client, adapter } = await fixture()
|
|
40
25
|
expect(await parallel([
|
|
@@ -79,11 +64,15 @@ test('native association and acceptance do not replace terminal evidence', async
|
|
|
79
64
|
})
|
|
80
65
|
|
|
81
66
|
test('preserves native failure details and releases the session', async () => {
|
|
82
|
-
const { client, adapter } = await fixture({ execute:
|
|
67
|
+
const { client, adapter } = await fixture({ execute: async (call, sink) => {
|
|
68
|
+
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
69
|
+
const turnId = randomUUID()
|
|
70
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
83
71
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
|
|
84
72
|
code: 'NATIVE_FAILED', message: 'native failure', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
|
|
85
73
|
} } })
|
|
86
|
-
|
|
74
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
75
|
+
} })
|
|
87
76
|
await expect(agent('fail', { client, cwd: process.cwd() })).rejects.toMatchObject({
|
|
88
77
|
code: 'NATIVE_FAILED', retryable: true, outcomeUnknown: false, details: { reason: 'test' },
|
|
89
78
|
})
|
|
@@ -92,9 +81,13 @@ test('preserves native failure details and releases the session', async () => {
|
|
|
92
81
|
})
|
|
93
82
|
|
|
94
83
|
test('an interrupted execution cannot return successful text', async () => {
|
|
95
|
-
const { client, adapter } = await fixture({ execute:
|
|
84
|
+
const { client, adapter } = await fixture({ execute: async (call, sink) => {
|
|
85
|
+
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
86
|
+
const turnId = randomUUID()
|
|
87
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
96
88
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'interrupted' } })
|
|
97
|
-
|
|
89
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
90
|
+
} })
|
|
98
91
|
await expect(agent('interrupted', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'AGENT_INTERRUPTED' })
|
|
99
92
|
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
100
93
|
})
|
|
@@ -112,10 +105,14 @@ test('unknown submission outcomes are preserved without retries or implicit inte
|
|
|
112
105
|
})
|
|
113
106
|
|
|
114
107
|
test('source failure remains uncertain and is not converted into successful cleanup', async () => {
|
|
115
|
-
const { client, adapter } = await fixture({ execute:
|
|
116
|
-
|
|
108
|
+
const { client, adapter } = await fixture({ execute: async (call, sink) => {
|
|
109
|
+
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
110
|
+
const turnId = randomUUID()
|
|
111
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
112
|
+
await sink.bindSubmission(call.params.submissionId, turnId)
|
|
117
113
|
await sink.fail(new HarnessSdkError('CONNECTION_LOST', 'lost', false, true))
|
|
118
|
-
|
|
114
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
115
|
+
} })
|
|
119
116
|
await expect(agent('source disappears', { client, cwd: process.cwd() })).rejects.toMatchObject({ code: 'CONNECTION_LOST', outcomeUnknown: true })
|
|
120
117
|
expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
|
|
121
118
|
})
|
|
@@ -152,22 +149,19 @@ test('cleanup failure cannot hide the primary uncertain execution failure', asyn
|
|
|
152
149
|
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
153
150
|
})
|
|
154
151
|
|
|
155
|
-
|
|
156
|
-
* Disable the advertised output-schema route to exercise fallback against the same terminal. */
|
|
157
|
-
function terminalFixture(
|
|
152
|
+
async function terminalFixture(
|
|
158
153
|
status: 'failed' | 'interrupted' | 'completed',
|
|
159
|
-
{ error, text = 'partial'
|
|
154
|
+
{ error, text = 'partial' }: { error?: HarnessError; text?: string } = {},
|
|
160
155
|
) {
|
|
161
|
-
return fixture({
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
})
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
})
|
|
156
|
+
return fixture({ execute: async (call, sink) => {
|
|
157
|
+
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
158
|
+
const turnId = randomUUID()
|
|
159
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
160
|
+
await sink.emit({ type: 'item/completed', payload: { item: { id: 'output', type: 'agentMessage', phase: 'final', text } } }, { turnId })
|
|
161
|
+
// Deliberately terminal before submit's reply: no event subscription can recover this later.
|
|
162
|
+
await sink.emit({ type: 'turn/completed', payload: { turnId, status, ...(error ? { error } : {}) } })
|
|
163
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
164
|
+
} })
|
|
171
165
|
}
|
|
172
166
|
|
|
173
167
|
test('Zod schema is converted for submission and returns typed data through composition', async () => {
|
|
@@ -193,43 +187,6 @@ test('schema preflight rejects before opening, while absent backend support rele
|
|
|
193
187
|
expect([...unsupported.adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
194
188
|
})
|
|
195
189
|
|
|
196
|
-
test.each([
|
|
197
|
-
{ text: '{"count":3}', error: null },
|
|
198
|
-
{ text: '{"count":3,"extra":true}', error: 'AGENT_STRUCTURED_OUTPUT_INVALID' },
|
|
199
|
-
{ text: 'plain text', error: 'AGENT_STRUCTURED_OUTPUT_NOT_JSON' },
|
|
200
|
-
])('JSON text fallback submits once and validates the terminal text ($error)', async ({ text, error }) => {
|
|
201
|
-
const { client, adapter } = await terminalFixture('completed', { text, outputSchema: false })
|
|
202
|
-
const result = agent('Plan the work', { client, cwd: '.', schema: z.strictObject({ count: z.number() }), outputFallback: 'json-text' })
|
|
203
|
-
if (error) await expect(result).rejects.toMatchObject({ code: error })
|
|
204
|
-
else await expect(result).resolves.toEqual({ count: 3 })
|
|
205
|
-
const calls = adapter.calls.filter(call => call.method === 'input/submit')
|
|
206
|
-
expect(calls).toHaveLength(1)
|
|
207
|
-
expect(calls[0]?.params).not.toHaveProperty('outputSchema')
|
|
208
|
-
expect(calls[0]?.params).toMatchObject({ input: [{ text: expect.stringContaining('JSON Schema') }] })
|
|
209
|
-
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
210
|
-
})
|
|
211
|
-
|
|
212
|
-
test('session cleanup waits for asynchronous local output validation', async () => {
|
|
213
|
-
const entered = Promise.withResolvers<void>()
|
|
214
|
-
const validation = Promise.withResolvers<boolean>()
|
|
215
|
-
const schema = z.object({ count: z.number() }).refine(async () => {
|
|
216
|
-
entered.resolve()
|
|
217
|
-
return validation.promise
|
|
218
|
-
})
|
|
219
|
-
const { client, adapter } = await terminalFixture('completed', { text: '{"count":3}' })
|
|
220
|
-
const result = agent('validate before cleanup', { client, cwd: '.', schema })
|
|
221
|
-
try {
|
|
222
|
-
await entered.promise
|
|
223
|
-
expect(adapter.calls.some(call => call.method === 'session/close')).toBe(false)
|
|
224
|
-
expect([...adapter.backends.values()][0]?.disposeCount).toBe(0)
|
|
225
|
-
} finally {
|
|
226
|
-
validation.resolve(true)
|
|
227
|
-
}
|
|
228
|
-
expect(await result).toEqual({ count: 3 })
|
|
229
|
-
expect(adapter.calls.some(call => call.method === 'session/close')).toBe(true)
|
|
230
|
-
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
231
|
-
})
|
|
232
|
-
|
|
233
190
|
test.each(['AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE'])('only terminal %s becomes null', async code => {
|
|
234
191
|
const error = { code, message: 'native api error', retryable: true, outcomeUnknown: false }
|
|
235
192
|
const { client, adapter } = await terminalFixture('failed', { error })
|
|
@@ -268,24 +225,14 @@ test('explicit skip metadata survives terminal-before-reply and startup denial r
|
|
|
268
225
|
await expect(agent('denied', { client: denied.client, cwd: '.' })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
|
|
269
226
|
})
|
|
270
227
|
|
|
271
|
-
test.each(['failed', 'interrupted'] as const)('tagged startup denial in a %s terminal returns null after cleanup', async status => {
|
|
272
|
-
const { client, adapter } = await terminalFixture(status, { error: {
|
|
273
|
-
code: 'AGENT_STARTUP_BLOCKED', message: 'blocked', retryable: false, outcomeUnknown: false,
|
|
274
|
-
details: { workflowDisposition: 'startup_blocked' },
|
|
275
|
-
} })
|
|
276
|
-
expect(await agent('blocked', { client, cwd: '.' })).toBeNull()
|
|
277
|
-
expect(adapter.calls.filter(call => call.method === 'input/submit')).toHaveLength(1)
|
|
278
|
-
expect(adapter.calls.some(call => call.method === 'session/close')).toBe(true)
|
|
279
|
-
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
280
|
-
})
|
|
281
|
-
|
|
282
228
|
test('a null candidate cannot hide cleanup failure', async () => {
|
|
283
|
-
const submit = scriptSubmission(async ({ sink, turnId }) => {
|
|
284
|
-
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: { code: 'RATE_LIMITED', message: 'rate limit', retryable: true, outcomeUnknown: false } } })
|
|
285
|
-
})
|
|
286
229
|
const { client, adapter } = await fixture({ execute: async (call, sink) => {
|
|
287
230
|
if (call.method === 'session/close') throw new HarnessSdkError('CLOSE_FAILED')
|
|
288
|
-
|
|
231
|
+
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
232
|
+
const turnId = randomUUID()
|
|
233
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
234
|
+
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: { code: 'RATE_LIMITED', message: 'rate limit', retryable: true, outcomeUnknown: false } } })
|
|
235
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
289
236
|
} })
|
|
290
237
|
await expect(agent('rate limited', { client, cwd: '.' })).rejects.toMatchObject({ code: 'RESOURCE_RELEASE_FAILED', details: { droppedError: { code: 'RATE_LIMITED' } } })
|
|
291
238
|
expect([...adapter.backends.values()][0]?.disposeCount).toBe(1)
|
|
@@ -302,14 +249,18 @@ test.each(['', 'bad JSON', '{}', '{"count":"3"}'])('invalid structured terminal
|
|
|
302
249
|
test('empty text and multiple final text items retain SDK aggregation', async () => {
|
|
303
250
|
const empty = await terminalFixture('completed', { text: '' })
|
|
304
251
|
expect(await agent('empty', { client: empty.client, cwd: '.' })).toBe('')
|
|
305
|
-
const { client } = await fixture({ execute:
|
|
252
|
+
const { client } = await fixture({ execute: async (call, sink) => {
|
|
253
|
+
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
254
|
+
const turnId = randomUUID()
|
|
255
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
306
256
|
for (const text of ['first', 'last']) await sink.emit({ type: 'item/completed', payload: { item: { id: text, type: 'agentMessage', phase: 'final', text } } }, { turnId })
|
|
307
257
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
|
|
308
|
-
|
|
258
|
+
return { submissionId: call.params.submissionId, accepted: true, disposition: 'started', turnId }
|
|
259
|
+
} })
|
|
309
260
|
expect(await agent('two', { client, cwd: '.' })).toBe('first\nlast')
|
|
310
261
|
})
|
|
311
262
|
|
|
312
|
-
|
|
263
|
+
// Compiled by package typecheck; never invoke real clients from type assertions.
|
|
313
264
|
function agentTypes(client: Client, dynamic: AgentOptions<z.ZodObject<{ count: z.ZodNumber }>>) {
|
|
314
265
|
const base = { client, cwd: '.' }
|
|
315
266
|
const schema = z.object({ count: z.number() })
|