@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 CHANGED
@@ -1,16 +1,28 @@
1
1
  # @anureo/workflow
2
2
 
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.
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
- 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.
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` 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.
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
- 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.
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
- 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>.
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
- 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`.
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, 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.
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 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.
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
- `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.
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. 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.
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)` 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.
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
- 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.
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.1",
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.1",
25
- "@anureo/protocol": "0.3.1",
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.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"
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 { FakeAdapterOptions } from '@anureo/conformance'
4
- import type { HarnessError } from '@anureo/protocol'
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 { createFixture } from './test-helpers'
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
- /** Publish final text before the test terminal so Turn.result retains it. */
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: scriptSubmission(async ({ sink, turnId }) => {
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: scriptSubmission(async ({ sink, turnId }) => {
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: scriptSubmission(async ({ sink, turnId, submissionId }) => {
116
- await sink.bindSubmission(submissionId, turnId)
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
- /** Register a scripted client that publishes final text and a terminal before the submit receipt.
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', outputSchema = true }: { error?: HarnessError; text?: string; outputSchema?: boolean } = {},
154
+ { error, text = 'partial' }: { error?: HarnessError; text?: string } = {},
160
155
  ) {
161
- return fixture({
162
- ...(outputSchema ? {} : {
163
- capabilities: { input: { delivery: ['native'] }, turn: { inputModalities: ['text'], outputSchema: false } },
164
- }),
165
- execute: scriptSubmission(async ({ sink, turnId }) => {
166
- await sink.emit({ type: 'item/completed', payload: { item: { id: 'output', type: 'agentMessage', phase: 'final', text } } }, { turnId })
167
- // A live subscription opened after submit cannot recover a retained terminal.
168
- await sink.emit({ type: 'turn/completed', payload: { turnId, status, ...(error ? { error } : {}) } })
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
- return submit(call, sink)
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: scriptSubmission(async ({ sink, turnId }) => {
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
- /** Exercise root overload inference and rejected assignments during package typecheck. */
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() })