@anureo/workflow 0.3.3 → 0.3.7

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,28 +1,16 @@
1
1
  # @anureo/workflow
2
2
 
3
- Directly imported primitives for ordinary TypeScript workflows:
4
- `agent`, `parallel`, `pipeline`, and optional `workflow`. The host creates SDK Clients, imports its
5
- workflow functions, awaits their results, and handles errors with normal TS.
6
-
7
- See the [workflow authoring reference](../../docs/workflow/SKILL.md) for current
8
- APIs, composition patterns, failure handling, and application-owned recovery.
9
-
10
- The [Workflow primitives reference](../../docs/workflow/README.md) defines
11
- parameters and result semantics for `agent`, `parallel`, and `pipeline`,
12
- and records current support.
13
-
14
- See the [composition comparison](../../draft/docs/workflow-composition-differences.md)
15
- and [alignment plan](../../draft/docs/workflow-composition-plan.md) for Claude Code
16
- semantics, the implemented changes, and retained host differences (Chinese).
17
-
18
- This workspace package uses the revised native lifecycle API and is pending
19
- publication with that revision. Requires Node.js 22+; TypeScript loading and
20
- compilation are provided by your project (for example, Bun, tsx, or tsc).
3
+ `@anureo/workflow` runs Anureo SDK agents from ordinary TypeScript functions. Use
4
+ `agent` for one prompt, `parallel` for independent callbacks, `pipeline` for
5
+ per-item stages, and `workflow` when you need a disk-backed run and agent replay.
6
+ The package exposes one entry point, `@anureo/workflow`. Its Node.js engine
7
+ requirement is 22 or newer, and applications supply their TypeScript tooling.
21
8
 
22
9
  ## Usage
23
10
 
24
- Create an initialized Client using `createClient` and your chosen adapter as
25
- described in the [SDK README](../../README.md). A workflow is just a function:
11
+ This function accepts an initialized SDK Client and reviews files in two stages
12
+ before running two synthesis tasks concurrently. The application creates and owns
13
+ the Client. See the [SDK README](../../README.md) for Client setup.
26
14
 
27
15
  ```ts
28
16
  import type { Client } from '@anureo/sdk'
@@ -45,39 +33,43 @@ export async function reviewFiles(client: Client, files: readonly string[], cwd:
45
33
  }
46
34
  ```
47
35
 
48
- In this example, `pipeline` and `parallel` convert internal `agent` rejections to
49
- `null`; `pipeline` also skips the affected item's remaining stages. The two
50
- explicit checks then throw summary errors for `null` results, so those errors do
51
- not preserve the original agent failure classification.
36
+ `pipeline` and `parallel` turn rejected agent calls into `null` at the affected
37
+ positions. The two guards report those positions as batch-level errors. Keep the
38
+ Client usable until `reviewFiles` settles, then release it when the application
39
+ has finished using it.
52
40
 
53
- Import `reviewFiles` from another TS file and call it with a Client. Calls do not
54
- require workflow registration, source-string execution, ambient context, or runtime setup.
55
- Use [durable workflow steps](../../docs/workflow/persistence.md) when a function
56
- needs a persisted run ID and recoverable results.
41
+ See the [workflow authoring guide](../../docs/workflow/SKILL.md) for composition and
42
+ recovery patterns and the [primitives reference](../../docs/workflow/README.md) for API contracts.
57
43
 
58
44
  ## agent
59
45
 
60
46
  ```ts
47
+ import type { Client } from '@anureo/sdk'
61
48
  import { z } from 'zod'
62
49
  import { agent } from '@anureo/workflow'
63
50
 
64
- const options = { client, cwd: process.cwd() }
65
- const text: string | null = await agent('Inspect the authentication module.', options)
66
- const findings = await agent('List authentication issues.', {
67
- ...options,
68
- schema: z.strictObject({ issues: z.array(z.string()) }),
69
- })
70
- // findings: { issues: string[] } | null
71
- if (findings !== null) console.log(findings.issues)
51
+ export function listIssues(client: Client, cwd: string) {
52
+ return agent('List the authentication module’s issues.', {
53
+ client,
54
+ cwd,
55
+ schema: z.strictObject({ issues: z.array(z.string()) }),
56
+ })
57
+ }
58
+ // listIssues returns Promise<{ issues: string[] } | null>.
72
59
  ```
73
60
 
74
- Each call owns a fresh Session, submits once, waits for its native terminal
75
- result, and releases its resources. `client` and `cwd` are required; `model` and
76
- `instructions` are optional. The caller owns the borrowed Client.
61
+ For fresh execution, `agent` opens a Session, submits one prompt, awaits the native
62
+ terminal result, and attempts to close and dispose the Session before settling.
63
+ The root exports `AgentOptions` for callers building options. Supply an initialized
64
+ `client` and a `cwd`. You can also supply `model`, `instructions`, and `permissionMode`
65
+ for session creation. The caller owns the Client.
66
+ Omit `schema` to receive the final text, which can be empty, or `null`.
77
67
 
78
68
  `schema` accepts a Zod 4 object schema. The library converts it to draft-07 JSON
79
- Schema, requires effective session `turn.outputSchema` support, validates the raw JSON
80
- result, then validates it with the original Zod schema and returns `z.output<S>`.
69
+ Schema, validates the raw JSON result, then validates it with the original Zod schema
70
+ and returns `z.output<S>`. By default, schema mode requires effective session
71
+ `turn.outputSchema` support. Set `outputFallback: 'json-text'` to include the schema
72
+ in the prompt when the session lacks that capability.
81
73
  This package depends on Zod 4.6.7. Applications that import Zod to author schemas
82
74
  should also declare it as their own dependency. Schema-associated types infer business fields;
83
75
  there is no unbound result-type generic or raw JSON Schema overload.
@@ -89,11 +81,11 @@ Defaults do not fill omitted model answers. Async refinements are supported
89
81
  locally; their failures reject without replaying input. See the
90
82
  [full schema and failure contract](../../docs/workflow/README.md#schema-mode).
91
83
 
92
- Confirmed native failed terminals for authentication, usage/rate limits, and
93
- service unavailability return `null`. Other failures and ordinary interruptions
94
- reject. Trusted adapters may explicitly report user skip or classifier startup
95
- denial; bundled adapters do not infer these reasons. Unknown execution outcomes
96
- retain `outcomeUnknown: true` and always reject. No input is automatically retried.
84
+ Confirmed native failed terminals for authentication, usage or rate limits, and
85
+ service unavailability can return `null`. Explicit user skip on interruption and
86
+ tagged startup denial can also return `null`. Other failures and ordinary
87
+ interruptions reject. Unknown execution outcomes reject with `outcomeUnknown: true`.
88
+ The caller decides whether and when to retry.
97
89
 
98
90
  Cleanup is attempted for successful, failed and discarded executions. A cleanup
99
91
  failure rejects with `RESOURCE_RELEASE_FAILED`, or preserves a primary execution
@@ -111,12 +103,12 @@ CLIs and real model requests.
111
103
  input-ordered results. Callbacks may return ordinary values or Promises; inline
112
104
  heterogeneous tuples preserve each result's type. An empty batch returns `[]`.
113
105
 
114
- The array and every entry are validated before any callback starts. The call
115
- waits for all callbacks to settle and uses `null` at each failed position,
116
- including synchronous throws. Result types include `null` at every position.
117
- Invalid arguments still reject the call. Use `value !== null` to filter failures
118
- without dropping valid `0`, `false`, or empty-string results.
119
- There is no implicit interruption, shared scheduler, or concurrency limit.
106
+ `parallel` snapshots the array and validates every entry before any callback
107
+ starts. Invalid arguments reject with `TypeError`. The promise waits for all
108
+ callbacks to settle. A synchronous throw, a rejected promise, or a `null` return
109
+ all produce `null` at that position. Use `value !== null` to retain other falsy
110
+ values, and handle errors inside callbacks if you need their original causes.
111
+ The caller manages concurrency limits, cancellation, and callback resources.
120
112
 
121
113
  ## pipeline
122
114
 
@@ -137,35 +129,64 @@ stage inputs are compile-time errors. A `null` input or stage result skips that
137
129
  item's remaining stages. An item failure also skips its remaining stages and
138
130
  becomes `null`. The returned Promise waits for all item chains to settle; its
139
131
  result type always includes `null`. Stage input types exclude only `null`, so
140
- `undefined` and other falsy values continue normally. Invalid composition
141
- arguments still reject the call.
132
+ `undefined` and other falsy values continue normally. A non-array input or a
133
+ non-function stage on nonempty input rejects with `TypeError`. The caller manages
134
+ concurrency limits, cancellation, and resources used by input work or stages.
142
135
 
143
136
  ## Durable workflow
144
137
 
145
- `workflow(options, body)` saves an initial manifest before passing explicit
146
- `runId` and `input` to the body. Every `agent()` call made inside the body is
147
- journaled automatically: identical calls on a `resumeFrom` run return their
148
- saved results without opening new sessions, and any changed call invalidates
149
- the calls after it. Existing three-primitive functions keep their independent
150
- behavior, and `agent()` outside `workflow()` is unchanged. 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.
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
+ Every `agent()` call made inside the body is journaled automatically: identical
147
+ calls on a `resumeFrom` run return their saved results without opening new
148
+ sessions, and any changed call invalidates the calls after it. A saved call whose
149
+ previous outcome is unknown rejects resume with `WORKFLOW_RECONCILIATION_REQUIRED`
150
+ until the previous execution's outcome is confirmed.
151
+
152
+ To resume, set `resumeFrom` to an inactive source run with the same name and
153
+ revision. The body runs again from the beginning in a new run. After schema
154
+ validation, journaled calls reserve keys in invocation order using their prompt,
155
+ options, and predecessor. Eligible saved results are reused without opening a
156
+ Session. A changed key ends replay for later calls. A matching call left at a
157
+ started record can rerun while later calls remain eligible. A prior terminal
158
+ failure with an unknown outcome requires reconciliation before that call can run.
159
+ The body owns any side effects that may repeat during resume.
160
+
161
+ The promise drains registered agent calls, publishes a JSON copy of the body result, and
162
+ releases the writer lock before resolving with `{ runId, status, result }`.
163
+ A registered agent rejection or drop can produce `status: 'incomplete'` if the
164
+ body still returns a publishable result. Body errors, fatal agent failures, and
165
+ storage failures reject. Keep Clients usable until settlement and await any
166
+ other background work inside the body. See the [persistence reference](../../docs/workflow/persistence.md)
167
+ for cache keys, failure recovery, and file guarantees.
168
+
169
+ ## Code structure
170
+
171
+ - [Package entry](src/index.ts) exposes the four application primitives and links their public
172
+ types directly to the modules that define them. [TypeScript configuration](tsconfig.json)
173
+ checks `src`, including tests, with Bun and Node types. The [package manifest](package.json)
174
+ declares the root entry and the no-emit build and typecheck scripts.
175
+ - [Agent calls](src/agent.ts) choose between fresh execution and journal replay, and record
176
+ the outcome of journaled calls. [Fresh execution](src/agent-execution.ts) owns the SDK
177
+ session from creation through release. [Output schemas](src/output-schema.ts) prepare the
178
+ request schema and validate fresh and replayed results.
179
+ - [Parallel](src/parallel.ts) starts independent callbacks. [Pipeline](src/pipeline.ts)
180
+ advances each input through its own typed stage chain.
181
+ - [Workflow](src/workflow.ts) opens the run, invokes the body, drains registered agent work,
182
+ and publishes the result or failure before releasing the run. [Workflow types](src/workflow-types.ts)
183
+ define the application contract. [Run state](src/workflow-state.ts) gives nested agent calls
184
+ access to the active run and tracks admission, pending work and sticky failures.
185
+ - [Persistence](src/persistence/) holds the [target writer](src/persistence/store.ts), the
186
+ [source reader](src/persistence/replay.ts), and the [journal](src/persistence/journal.ts).
187
+ [Checkpoint records](src/persistence/records.ts) define the shared file layout and schemas.
188
+ [Checkpoint file I/O](src/persistence/checkpoint-files.ts) owns atomic publication and
189
+ checked reads. [Canonical JSON](src/persistence/json.ts) supplies copying and hashing rules.
169
190
 
170
191
  ## Adapter-facing helpers
171
192
 
@@ -191,7 +212,6 @@ For `[2, 3, 4]`, the pipeline asks the model to double then square each value, e
191
212
  `[16, 36, 64]`. Two parallel agent calls then calculate the sum `116` and maximum `64`.
192
213
  The eight agent calls each use an independent Session.
193
214
 
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.
215
+ Run `bun run example:workflow-persistence` and repeat with the printed run ID to
216
+ replay the saved agent results. The example uses a scripted backend, and the
217
+ resumed run opens zero new sessions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anureo/workflow",
3
- "version": "0.3.3",
3
+ "version": "0.3.7",
4
4
  "description": "Agent execution, composition, and durable workflow steps over the Anureo SDK",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -8,6 +8,7 @@
8
8
  "url": "git+https://github.com/hi-youichi/anureo-sdk.git",
9
9
  "directory": "packages/workflow"
10
10
  },
11
+ "homepage": "https://github.com/hi-youichi/anureo-sdk/tree/main/packages/workflow#readme",
11
12
  "publishConfig": {
12
13
  "access": "public"
13
14
  },
@@ -21,17 +22,17 @@
21
22
  "test": "bun test src"
22
23
  },
23
24
  "dependencies": {
24
- "@anureo/sdk": "0.3.3",
25
- "@anureo/protocol": "0.3.2",
25
+ "@anureo/sdk": "0.3.7",
26
+ "@anureo/protocol": "0.3.7",
26
27
  "ajv": "8.20.0",
27
28
  "zod": "4.6.7"
28
29
  },
29
30
  "devDependencies": {
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"
31
+ "@anureo/conformance": "0.3.7",
32
+ "@anureo/adapter-claude": "0.3.7",
33
+ "@anureo/adapter-codex": "0.3.7",
34
+ "@anureo/adapter-acp": "0.3.7",
35
+ "@anureo/adapter-pi": "0.3.7"
35
36
  },
36
37
  "engines": {
37
38
  "node": ">=22"
@@ -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,228 @@
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
+ * Positive observation timeouts in milliseconds, up to 2,147,483,647 (the default).
28
+ * The association wait begins at submission and the result wait begins after association.
29
+ * Expiry rejects with an unknown outcome and does not interrupt native execution.
30
+ * These limits do not affect journal replay identity.
31
+ */
32
+ wait?: { associationMs?: number; resultMs?: number }
33
+ }
34
+
35
+ const LONG_OBSERVATION_TIMEOUT_MS = 0x7fffffff
36
+
37
+ /** Capture session settings and prepare structured output before any asynchronous work. */
38
+ export function prepareAgentCall(options: AgentOptions) {
39
+ const { client, cwd, model, instructions, permissionMode, schema, outputFallback, wait } = options
40
+ const timeouts = wait && { associationMs: wait.associationMs, resultMs: wait.resultMs }
41
+ for (const timeout of [timeouts?.associationMs, timeouts?.resultMs]) {
42
+ if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0 || timeout > LONG_OBSERVATION_TIMEOUT_MS)) {
43
+ throw new HarnessSdkError('INVALID_PARAMS', 'Agent observation timeouts must be positive and at most 2,147,483,647 ms')
44
+ }
45
+ }
46
+ return {
47
+ client, cwd, model, instructions, permissionMode, outputFallback,
48
+ wait: timeouts,
49
+ output: schema === undefined ? undefined : prepareOutputSchema(schema),
50
+ }
51
+ }
52
+
53
+ export type PreparedAgentCall = ReturnType<typeof prepareAgentCall>
54
+
55
+ /**
56
+ * Run a fresh call for agent outside a workflow or for executeJournaledAgent after it publishes
57
+ * its started marker and rechecks dispatch. Release the acquired session before returning the
58
+ * completed or dropped outcome or throwing an execution or release failure.
59
+ */
60
+ export async function executeAgent(prompt: string, call: PreparedAgentCall): Promise<SettledAgentOutcome> {
61
+ const { output, outputFallback, wait } = call
62
+ const opening = openAgentSession(call)
63
+ let session: Session
64
+ try {
65
+ session = await opening
66
+ } catch (cause) {
67
+ if (isStartupBlockException(cause)) return { status: 'dropped', error: summarizeAgentError(cause) }
68
+ throw cause
69
+ }
70
+ const outcome = await observeAgentTurn({ session, prompt, output, outputFallback, wait })
71
+ const cleanupErrors = await releaseAgentSession(session)
72
+ return settleAgentOutcome(outcome, cleanupErrors)
73
+ }
74
+
75
+ /** Completed or dropped execution after successful session release. */
76
+ type SettledAgentOutcome =
77
+ | { status: 'completed'; value: string | Record<string, unknown> }
78
+ | { status: 'dropped'; error: AgentErrorSummary }
79
+
80
+ type AgentOutcome =
81
+ | SettledAgentOutcome
82
+ | { status: 'failed'; error: HarnessSdkError }
83
+
84
+ /** Safe diagnostics retained from cleanup and dropped terminals without native messages. */
85
+ interface AgentErrorSummary {
86
+ code: string
87
+ outcomeUnknown: boolean
88
+ }
89
+
90
+ interface AgentTurnRequest {
91
+ session: Session
92
+ prompt: string
93
+ output: AgentOutputSchema | undefined
94
+ outputFallback: AgentOptions['outputFallback']
95
+ wait: AgentOptions['wait']
96
+ }
97
+
98
+ /** Request a fresh session and give executeAgent ownership when it attaches. */
99
+ function openAgentSession({ client, cwd, model, instructions, permissionMode }: Pick<
100
+ AgentOptions, 'client' | 'cwd' | 'model' | 'instructions' | 'permissionMode'
101
+ >): Promise<Session> {
102
+ return client.sessions.create({
103
+ cwd,
104
+ ...(model !== undefined ? { model } : {}),
105
+ ...(instructions !== undefined ? { instructions } : {}),
106
+ ...(permissionMode !== undefined ? { permissionMode } : {}),
107
+ })
108
+ }
109
+
110
+ /**
111
+ * Submit once, then await the associated turn's retained terminal result and any local validation.
112
+ * Return execution evidence to executeAgent, which owns session release and final settlement.
113
+ */
114
+ async function observeAgentTurn(request: AgentTurnRequest): Promise<AgentOutcome> {
115
+ const { session, output, wait } = request
116
+ try {
117
+ const submission = agentSubmission(request)
118
+ const turn = await session.submit(submission, { timeoutMs: wait?.associationMs ?? LONG_OBSERVATION_TIMEOUT_MS })
119
+ const result = await turn.result({ timeoutMs: wait?.resultMs ?? LONG_OBSERVATION_TIMEOUT_MS })
120
+ if (result.status === 'completed') {
121
+ return { status: 'completed', value: output ? await output.parse(result.text) : result.text }
122
+ }
123
+ return classifyTerminalFailure(result.status, result.error)
124
+ } catch (cause) {
125
+ if (isStartupBlockException(cause)) return { status: 'dropped', error: summarizeAgentError(cause) }
126
+ return { status: 'failed', error: sdkError(cause, 'AGENT_FAILED', true) }
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Build observeAgentTurn's single submission using the attached session's capabilities.
132
+ * With structured output requested, use its schema route or the opted-in JSON text prompt.
133
+ * Throw CAPABILITY_UNSUPPORTED before submission if neither route is available.
134
+ */
135
+ function agentSubmission({ session, prompt, output, outputFallback }: AgentTurnRequest): SubmitOptions {
136
+ if (!output) return { input: prompt }
137
+ if (session.capabilities.turn?.outputSchema) return { input: prompt, outputSchema: output.schema }
138
+ if (outputFallback !== 'json-text') {
139
+ throw new HarnessSdkError('CAPABILITY_UNSUPPORTED', 'Session does not support structured output')
140
+ }
141
+ const instruction = 'Return the final answer as a single JSON object that matches this JSON Schema. Do not include Markdown fences or surrounding prose.'
142
+ return { input: `${prompt}\n\n${instruction}\n${JSON.stringify(output.schema)}` }
143
+ }
144
+
145
+ /**
146
+ * Classify a retained failed or interrupted terminal for observeAgentTurn to return to executeAgent.
147
+ * Only confirmed outcomes qualify for a drop. Tagged startup denial qualifies in either status,
148
+ * explicit skip applies to interruption, and the terminal API allowlist applies to failure.
149
+ * Retain other errors for rejection after cleanup and supply AGENT_INTERRUPTED when details are absent.
150
+ */
151
+ function classifyTerminalFailure(status: 'failed' | 'interrupted', error: HarnessError | undefined): AgentOutcome {
152
+ if (!error) return { status: 'failed', error: new HarnessSdkError('AGENT_INTERRUPTED') }
153
+ if (!error.outcomeUnknown) {
154
+ const explicitSkip = status === 'interrupted' && error.details?.workflowDisposition === 'skipped'
155
+ if (explicitSkip || isStartupBlocked(error) || (status === 'failed' && terminalApiErrors.has(error.code))) {
156
+ return { status: 'dropped', error: summarizeAgentError(error) }
157
+ }
158
+ }
159
+ return {
160
+ status: 'failed',
161
+ error: new HarnessSdkError(error.code, error.message, error.retryable, error.outcomeUnknown, error.details),
162
+ }
163
+ }
164
+
165
+ /** Project errors to the code and uncertainty exposed in agent's cleanup diagnostics. */
166
+ function summarizeAgentError(error: AgentErrorSummary): AgentErrorSummary {
167
+ return { code: error.code, outcomeUnknown: error.outcomeUnknown }
168
+ }
169
+
170
+ /**
171
+ * Release executeAgent's session in close/dispose order. Attempt disposal after close failure
172
+ * and return distinct normalized SDK error instances as safe diagnostics in encounter order.
173
+ */
174
+ async function releaseAgentSession(session: Session): Promise<AgentErrorSummary[]> {
175
+ const cleanupErrors = new Set<HarnessSdkError>()
176
+ for (const method of ['close', 'dispose'] as const) {
177
+ try {
178
+ await session[method]()
179
+ } catch (cause) {
180
+ cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true))
181
+ }
182
+ }
183
+ return [...cleanupErrors].map(summarizeAgentError)
184
+ }
185
+
186
+ /**
187
+ * Settle executeAgent after both release attempts. Return completed or dropped outcomes on successful cleanup.
188
+ * Throw the primary failure with any cleanup diagnostics, or RESOURCE_RELEASE_FAILED if cleanup
189
+ * was the only failure.
190
+ */
191
+ function settleAgentOutcome(outcome: AgentOutcome, errors: AgentErrorSummary[]): SettledAgentOutcome {
192
+ if (errors.length) {
193
+ if (outcome.status === 'failed') {
194
+ const failure = outcome.error
195
+ const prior = failure.details?.cleanupErrors
196
+ throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown,
197
+ { ...failure.details, cleanupErrors: [...(Array.isArray(prior) ? prior : []), ...errors] })
198
+ }
199
+ throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false,
200
+ errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) })
201
+ }
202
+ if (outcome.status === 'failed') throw outcome.error
203
+ return outcome
204
+ }
205
+
206
+ /** Share the startup-denial rule between classifyTerminalFailure and isStartupBlockException.
207
+ * The adapter must supply the dedicated code, a confirmed outcome and the startup disposition. */
208
+ function isStartupBlocked(error: Pick<HarnessSdkError, 'code' | 'outcomeUnknown' | 'details'>): boolean {
209
+ return !error.outcomeUnknown && error.code === 'AGENT_STARTUP_BLOCKED' && error.details?.workflowDisposition === 'startup_blocked'
210
+ }
211
+
212
+ /** Recognize a thrown SDK startup denial during session creation or turn observation. */
213
+ export function isStartupBlockException(cause: unknown): cause is HarnessSdkError {
214
+ return cause instanceof HarnessSdkError && isStartupBlocked(cause)
215
+ }
216
+
217
+ /** Report whether a retained terminal matches the confirmed-drop rules shared with
218
+ * adapter-owned journaled primitives (beer). Mirrors classifyTerminalFailure's drop branch. */
219
+ export function isDroppedOutcome(error: HarnessError, status: 'failed' | 'interrupted'): boolean {
220
+ if (error.outcomeUnknown) return false
221
+ if (status === 'interrupted') return error.details?.workflowDisposition === 'skipped'
222
+ return isStartupBlocked(error) || terminalApiErrors.has(error.code)
223
+ }
224
+
225
+ // Only apply to native failed terminal results, never open/submit/observation failures.
226
+ const terminalApiErrors = new Set([
227
+ 'AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE',
228
+ ])