@anureo/workflow 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +96 -70
  2. package/package.json +18 -16
  3. package/src/agent-adapters.test.ts +121 -0
  4. package/src/agent-execution.ts +220 -0
  5. package/src/agent.test.ts +470 -0
  6. package/src/agent.ts +136 -0
  7. package/src/fixtures/workflow-crash.ts +69 -0
  8. package/src/index.ts +9 -0
  9. package/src/output-schema.test.ts +159 -0
  10. package/src/output-schema.ts +237 -0
  11. package/src/parallel.test.ts +96 -0
  12. package/src/parallel.ts +33 -0
  13. package/src/persistence/checkpoint-files.ts +83 -0
  14. package/src/persistence/journal.ts +132 -0
  15. package/src/persistence/json.ts +83 -0
  16. package/src/persistence/records.ts +103 -0
  17. package/src/persistence/replay.ts +93 -0
  18. package/src/persistence/store.ts +315 -0
  19. package/src/pipeline.test.ts +201 -0
  20. package/src/pipeline.ts +99 -0
  21. package/src/test-helpers.ts +23 -0
  22. package/src/workflow-state.ts +131 -0
  23. package/src/workflow-types.ts +38 -0
  24. package/src/workflow.test.ts +503 -0
  25. package/src/workflow.ts +112 -0
  26. package/tsconfig.json +13 -0
  27. package/LICENSE +0 -201
  28. package/src/agent-outcome.d.ts +0 -15
  29. package/src/agent-outcome.js +0 -28
  30. package/src/agent.d.ts +0 -49
  31. package/src/agent.js +0 -206
  32. package/src/index.d.ts +0 -6
  33. package/src/index.js +0 -5
  34. package/src/output-schema.d.ts +0 -27
  35. package/src/output-schema.js +0 -192
  36. package/src/parallel.d.ts +0 -18
  37. package/src/parallel.js +0 -25
  38. package/src/persistence/atomic.d.ts +0 -9
  39. package/src/persistence/atomic.js +0 -48
  40. package/src/persistence/journal.d.ts +0 -54
  41. package/src/persistence/journal.js +0 -106
  42. package/src/persistence/json.d.ts +0 -17
  43. package/src/persistence/json.js +0 -75
  44. package/src/persistence/read-json.d.ts +0 -11
  45. package/src/persistence/read-json.js +0 -46
  46. package/src/persistence/records.d.ts +0 -92
  47. package/src/persistence/records.js +0 -70
  48. package/src/persistence/replay.d.ts +0 -11
  49. package/src/persistence/replay.js +0 -79
  50. package/src/persistence/store.d.ts +0 -45
  51. package/src/persistence/store.js +0 -238
  52. package/src/pipeline.d.ts +0 -41
  53. package/src/pipeline.js +0 -24
  54. package/src/run-context.d.ts +0 -16
  55. package/src/run-context.js +0 -13
  56. package/src/test-helpers.d.ts +0 -11
  57. package/src/test-helpers.js +0 -21
  58. package/src/workflow-state.d.ts +0 -44
  59. package/src/workflow-state.js +0 -96
  60. package/src/workflow-types.d.ts +0 -39
  61. package/src/workflow-types.js +0 -0
  62. package/src/workflow.d.ts +0 -17
  63. package/src/workflow.js +0 -104
@@ -0,0 +1,112 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { HarnessSdkError, sdkError } from '@anureo/sdk'
3
+ import type { WorkflowContext, WorkflowOptions, WorkflowResult } from './workflow-types'
4
+ import { RunState, runWith, storedFailure } from './workflow-state'
5
+ import { freezeJson, jsonCopy, type JsonValue } from './persistence/json'
6
+ import { openFileRun, type RunHandle } from './persistence/store'
7
+
8
+ /**
9
+ * Run a body with a durable identity, frozen JSON input and journaled agent calls. The body
10
+ * receives the new run's ID and input after initial publication. On resume the body starts from
11
+ * the beginning and eligible agent calls reuse saved results. Account for repeated side effects
12
+ * from body code and agent calls that execute again.
13
+ * Supply strict JSON for the input and awaited body result. Await your own background work inside
14
+ * the body. Keep borrowed clients alive until the workflow promise settles, then dispose them separately.
15
+ *
16
+ * Resolve with a JSON copy of the body result after registered agent work settles, publication
17
+ * succeeds and the writer lock is released. A drop or an ordinary failure in registered work can
18
+ * yield an incomplete result if the body still returns. Invalid inputs, uncaught body errors,
19
+ * fatal agent failures, and storage failures reject. Run failures report the run ID and storage
20
+ * root in SDK error details, using the supplied directory if initialization fails. A
21
+ * lock-release failure can reject after the result and terminal manifest have been published.
22
+ */
23
+ export async function workflow<Input, Result>(
24
+ options: WorkflowOptions<Input>,
25
+ body: (run: WorkflowContext<Input>) => Result | Promise<Result>,
26
+ ): Promise<WorkflowResult<Awaited<Result>>> {
27
+ const runId = options?.runId ?? randomUUID()
28
+ const state = new RunState()
29
+ let handle: RunHandle | undefined
30
+ let publishedResult: Awaited<Result> | undefined
31
+ try {
32
+ const { storageOptions, context } = prepareRun(options, body, runId)
33
+ handle = await openFileRun(storageOptions)
34
+ publishedResult = await completeRun({ handle, state, body, context })
35
+ } catch (cause) {
36
+ await abortRun({ cause, state, handle })
37
+ } finally {
38
+ if (handle) {
39
+ try { await handle.close() }
40
+ catch { state.noteStorageFailure() }
41
+ }
42
+ }
43
+ const failure = state.failure
44
+ if (failure) {
45
+ throw new HarnessSdkError(failure.code, failure.message, false, failure.outcomeUnknown, {
46
+ ...failure.details,
47
+ runId,
48
+ directory: handle?.identity.directory ?? options?.directory,
49
+ })
50
+ }
51
+ // A failed publication also stops the run, so only published results reach this return.
52
+ return { runId, status: state.status, result: publishedResult as Awaited<Result> }
53
+ }
54
+
55
+ /** Snapshot input and an object source reference before workflow awaits storage. The body gets a
56
+ * frozen input and the writer snapshots it separately. Malformed options, a non-function body or
57
+ * non-JSON input throw before storage opens. */
58
+ function prepareRun<Input, Result>(
59
+ options: WorkflowOptions<Input>,
60
+ body: (run: WorkflowContext<Input>) => Result | Promise<Result>,
61
+ runId: string,
62
+ ): { storageOptions: WorkflowOptions<JsonValue> & { runId: string }; context: WorkflowContext<Input> } {
63
+ if (!options || typeof options !== 'object' || typeof body !== 'function') {
64
+ throw new HarnessSdkError('INVALID_PARAMS')
65
+ }
66
+ const input = freezeJson(jsonCopy(options.input))
67
+ const resumeFrom = options.resumeFrom && typeof options.resumeFrom === 'object'
68
+ ? { ...options.resumeFrom } : options.resumeFrom
69
+ return {
70
+ storageOptions: { ...options, runId, input: input as JsonValue, resumeFrom },
71
+ context: { runId, input },
72
+ }
73
+ }
74
+
75
+ /** Give the body access to the journal through the async context. Stop dispatch on an uncaught
76
+ * body failure and drain before choosing the terminal outcome, since settling agents can still
77
+ * change it. Return the JSON result after publication. workflow routes rejections through abortRun. */
78
+ async function completeRun<Input, Result>({ handle, state, body, context }: {
79
+ handle: RunHandle
80
+ state: RunState
81
+ body: (run: WorkflowContext<Input>) => Result | Promise<Result>
82
+ context: WorkflowContext<Input>
83
+ }): Promise<Awaited<Result>> {
84
+ let value: Awaited<Result> | undefined
85
+ try {
86
+ value = await runWith({ journal: handle.journal, state }, async () => body(context))
87
+ }
88
+ catch (cause) { state.stop(sdkError(cause, 'WORKFLOW_BODY_FAILED')) }
89
+ await state.closeAndDrain()
90
+ const failure = state.failure
91
+ if (failure) throw failure
92
+ const result = jsonCopy(value)
93
+ await handle.finish(state.status, result as JsonValue)
94
+ return result as Awaited<Result>
95
+ }
96
+
97
+ /** Record workflow's failure and drain before publishing the aggregate to an acquired handle.
98
+ * Initialization failures can arrive before a handle exists. An abort publication error is
99
+ * recorded as a storage failure. workflow still releases the handle and reports the final aggregate. */
100
+ async function abortRun({ cause, state, handle }: {
101
+ cause: unknown
102
+ state: RunState
103
+ handle: RunHandle | undefined
104
+ }): Promise<void> {
105
+ const error = sdkError(cause, 'WORKFLOW_FAILED')
106
+ state.stop(error)
107
+ await state.closeAndDrain()
108
+ if (handle) {
109
+ try { await handle.abort(storedFailure(state.failure ?? error)) }
110
+ catch { state.noteStorageFailure() }
111
+ }
112
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "Preserve",
5
+ "moduleResolution": "Bundler",
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "allowImportingTsExtensions": true,
10
+ "types": ["bun", "node"]
11
+ },
12
+ "include": ["src"]
13
+ }
package/LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright 2026 Yoichi
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
@@ -1,15 +0,0 @@
1
- import type { HarnessError } from '@anureo/protocol';
2
- import { HarnessSdkError } from '@anureo/sdk';
3
- /**
4
- * Let classifyAgentFailure identify terminal candidates for agent's null result after cleanup.
5
- * Only known outcomes qualify. Interrupted terminals require an explicit skip, and failed
6
- * terminals require a startup denial or a code from the terminal API allowlist.
7
- */
8
- export declare function isDroppedOutcome(error: HarnessError, status: 'failed' | 'interrupted'): boolean;
9
- /** Check the dedicated code and adapter disposition required for a known startup denial. */
10
- export declare function isStartupBlocked(error: Pick<HarnessSdkError, 'code' | 'outcomeUnknown' | 'details'>): boolean;
11
- /**
12
- * Recognize a thrown SDK startup denial. openAgentSession returns null for a matching rejection
13
- * from session creation. observeAgentTurn records a drop candidate and leaves settlement to cleanup.
14
- */
15
- export declare function isStartupBlockException(cause: unknown): cause is HarnessSdkError;
@@ -1,28 +0,0 @@
1
- import { HarnessSdkError } from '@anureo/sdk';
2
- /**
3
- * Let classifyAgentFailure identify terminal candidates for agent's null result after cleanup.
4
- * Only known outcomes qualify. Interrupted terminals require an explicit skip, and failed
5
- * terminals require a startup denial or a code from the terminal API allowlist.
6
- */
7
- export function isDroppedOutcome(error, status) {
8
- if (error.outcomeUnknown)
9
- return false;
10
- if (status === 'interrupted')
11
- return error.details?.workflowDisposition === 'skipped';
12
- return isStartupBlocked(error) || terminalApiErrors.has(error.code);
13
- }
14
- /** Check the dedicated code and adapter disposition required for a known startup denial. */
15
- export function isStartupBlocked(error) {
16
- return !error.outcomeUnknown && error.code === 'AGENT_STARTUP_BLOCKED' && error.details?.workflowDisposition === 'startup_blocked';
17
- }
18
- /**
19
- * Recognize a thrown SDK startup denial. openAgentSession returns null for a matching rejection
20
- * from session creation. observeAgentTurn records a drop candidate and leaves settlement to cleanup.
21
- */
22
- export function isStartupBlockException(cause) {
23
- return cause instanceof HarnessSdkError && isStartupBlocked(cause);
24
- }
25
- // Only apply to native failed terminal results, never open/submit/observation failures.
26
- const terminalApiErrors = new Set([
27
- 'AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE',
28
- ]);
package/src/agent.d.ts DELETED
@@ -1,49 +0,0 @@
1
- import { type Client } from '@anureo/sdk';
2
- import type { z } from 'zod';
3
- /** Configure an independent agent call. Keep the client usable until settlement and dispose it separately. */
4
- export interface AgentOptions<S extends z.ZodObject = z.ZodObject> {
5
- /** Initialized, borrowed client selecting the backend; agent releases only its own session. */
6
- client: Client;
7
- /** Working directory forwarded to the fresh session. */
8
- cwd: string;
9
- /** Backend model selection; omission leaves selection to the session/backend. */
10
- model?: string;
11
- /** Session instructions, separate from the input prompt. */
12
- instructions?: string;
13
- /** Permission mode forwarded to the fresh session. Accepted values and defaults depend on the backend. */
14
- permissionMode?: string;
15
- /** Portable Zod object schema with closed objects and required JSON fields. Omit to return text. */
16
- schema?: S;
17
- /**
18
- * With a schema, ask for JSON in the prompt when the session lacks structured output.
19
- * Without this opt-in, an unsupported session rejects before submission.
20
- */
21
- outputFallback?: 'json-text';
22
- }
23
- /**
24
- * Run a prompt in a fresh session and return the SDK's final text, which can be empty.
25
- * Await the associated turn's terminal result. Once a session is acquired, close and dispose it
26
- * before settling, including when submission or observation fails.
27
- * Return null for confirmed terminal authentication, usage/rate-limit or native service unavailability,
28
- * explicit skip or startup denial; unknown outcomes, other execution failures and cleanup failures reject.
29
- * Cleanup failures preserve a primary execution error with details.cleanupErrors, or reject with
30
- * RESOURCE_RELEASE_FAILED. Input is never automatically retried or interrupted, and releasing
31
- * observation does not confirm native execution stopped.
32
- * Inside workflow(), journal calls in invocation order and reuse eligible saved results on resume
33
- * without opening a session. New executions wait for terminal journal publication. A previous
34
- * unknown outcome rejects with WORKFLOW_RECONCILIATION_REQUIRED. The caller still owns the client.
35
- */
36
- export declare function agent(prompt: string, options: AgentOptions<never> & {
37
- schema?: undefined;
38
- }): Promise<string | null>;
39
- /**
40
- * Return locally validated typed output with the same lifecycle and journal behavior as text mode.
41
- * Unsupported schemas reject before opening. Validation awaits async refinements for fresh and
42
- * replayed results. Missing, malformed or invalid JSON rejects without replaying input.
43
- * Defaults never fill omitted answers.
44
- */
45
- export declare function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S> & {
46
- schema: S;
47
- }): Promise<z.output<S> | null>;
48
- /** Select text or typed output from an optional schema, retaining agent's cleanup and failure contract. */
49
- export declare function agent<S extends z.ZodObject>(prompt: string, options: AgentOptions<S>): Promise<string | z.output<S> | null>;
package/src/agent.js DELETED
@@ -1,206 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { HarnessSdkError, sdkError } from '@anureo/sdk';
3
- import { prepareOutputSchema } from "./output-schema.js";
4
- import { isDroppedOutcome, isStartupBlockException } from "./agent-outcome.js";
5
- import { currentRun } from "./run-context.js";
6
- import { isFatal } from "./workflow-state.js";
7
- import { canonicalJson, jsonCopy } from "./persistence/json.js";
8
- export async function agent(prompt, options) {
9
- const context = currentRun();
10
- if (context)
11
- return memoizedAgent(context, prompt, options);
12
- return executeAgent(prompt, options);
13
- }
14
- // Give association and terminal observation the longest supported timer delay for model execution.
15
- const LONG_OBSERVATION_TIMEOUT_MS = 0x7fffffff;
16
- /** Build the options memoizedAgent hashes with the prompt. Include client identity and the converted schema. */
17
- function canonicalOptions(options, schema) {
18
- return {
19
- model: options.model ?? null,
20
- instructions: options.instructions ?? null,
21
- permissionMode: options.permissionMode ?? null,
22
- schema: schema ?? null,
23
- ...(options.outputFallback ? { outputFallback: options.outputFallback } : {}),
24
- cwd: options.cwd,
25
- client: options.client.identity,
26
- };
27
- }
28
- /**
29
- * Reserve the key in invocation order when agent inherits a workflow run. Register replay or
30
- * execution with RunState so workflow drains the call even if the body leaves it unawaited.
31
- * Return saved text or revalidate saved data on a cache hit. Reject prior uncertain failures for
32
- * reconciliation before opening a session.
33
- */
34
- async function memoizedAgent(context, prompt, options) {
35
- const { journal, state } = context;
36
- const output = options.schema === undefined ? undefined : prepareOutputSchema(options.schema);
37
- // The key advances synchronously here: host invocation order fixes the chain.
38
- const key = journal.nextKey(prompt, canonicalOptions(options, output?.schema));
39
- return state.track(() => {
40
- state.assertDispatch();
41
- const hit = journal.resultFor(key);
42
- if (hit !== undefined)
43
- return replayAgentResult(hit, output);
44
- const prior = journal.beginExecution(key);
45
- if (prior?.outcomeUnknown) {
46
- throw new HarnessSdkError('WORKFLOW_RECONCILIATION_REQUIRED', 'A previous run left this agent call with an unknown outcome; reconcile it before resuming', false, true);
47
- }
48
- return executeJournaledAgent({ context, key, prompt, options });
49
- });
50
- }
51
- /** Decode memoizedAgent's cache hit. Typed hits can reject if the current schema rejects the saved data. */
52
- async function replayAgentResult(hit, output) {
53
- return output ? output.parse(canonicalJson(hit)) : hit;
54
- }
55
- /**
56
- * Execute memoizedAgent's cache miss after saving its started marker and rechecking dispatch.
57
- * After execution settles, publish a result or failure before returning. Drops mark the run
58
- * incomplete. Fatal failures stop later dispatch, and WORKFLOW_STORAGE_FAILED rejects without
59
- * a second terminal write.
60
- */
61
- async function executeJournaledAgent({ context, key, prompt, options }) {
62
- const { journal, state } = context;
63
- const agentId = randomUUID();
64
- await journal.append({ type: 'started', key, agentId });
65
- state.assertDispatch();
66
- try {
67
- // Cache identity was computed at invocation. Fresh execution reads options after publication.
68
- const value = await executeAgent(prompt, options);
69
- if (value === null) {
70
- await journal.append({ type: 'failed', key, agentId, code: 'AGENT_DROPPED', outcomeUnknown: false });
71
- state.noteIncomplete();
72
- return null;
73
- }
74
- const stored = jsonCopy(value);
75
- await journal.append({ type: 'result', key, agentId, result: stored });
76
- return jsonCopy(stored);
77
- }
78
- catch (cause) {
79
- const error = sdkError(cause, 'AGENT_FAILED');
80
- if (isFatal(error))
81
- state.stop(error);
82
- // The storage layer may have published a terminal record already.
83
- if (error.code !== 'WORKFLOW_STORAGE_FAILED') {
84
- await journal.append({ type: 'failed', key, agentId,
85
- code: error.code, outcomeUnknown: error.outcomeUnknown === true });
86
- }
87
- throw error;
88
- }
89
- }
90
- /**
91
- * Run a fresh call for agent or executeJournaledAgent. Validate the schema before opening, then
92
- * release the acquired session before returning text, data or null or rejecting with a failure.
93
- */
94
- async function executeAgent(prompt, options) {
95
- const { client, cwd, model, instructions, permissionMode, schema } = options;
96
- const output = schema === undefined ? undefined : prepareOutputSchema(schema);
97
- const session = await openAgentSession({ client, cwd, model, instructions, permissionMode });
98
- if (!session)
99
- return null; // A failed open never hands session ownership to this call.
100
- const outcome = await observeAgentTurn({ session, prompt, output, outputFallback: options.outputFallback });
101
- const cleanupErrors = await releaseAgentSession(session);
102
- return settleAgentOutcome(outcome, cleanupErrors);
103
- }
104
- /**
105
- * Give executeAgent ownership of the attached session. A confirmed startup denial from the open
106
- * promise resolves to null. Other rejections and synchronous request setup errors propagate.
107
- */
108
- function openAgentSession({ client, cwd, model, instructions, permissionMode }) {
109
- return client.sessions.create({
110
- cwd,
111
- ...(model !== undefined ? { model } : {}),
112
- ...(instructions !== undefined ? { instructions } : {}),
113
- ...(permissionMode !== undefined ? { permissionMode } : {}),
114
- })
115
- .catch(cause => {
116
- if (isStartupBlockException(cause))
117
- return null;
118
- throw cause;
119
- });
120
- }
121
- /**
122
- * Submit once and await terminal evidence plus local validation. Capture execution failures so
123
- * executeAgent can release the session before exposing the outcome; this phase never retries or closes it.
124
- */
125
- async function observeAgentTurn({ session, prompt, output, outputFallback }) {
126
- try {
127
- const submission = agentSubmission({ session, prompt, output, outputFallback });
128
- const turn = await session.submit(submission, { timeoutMs: LONG_OBSERVATION_TIMEOUT_MS });
129
- const result = await turn.result({ timeoutMs: LONG_OBSERVATION_TIMEOUT_MS });
130
- if (result.status === 'completed') {
131
- return { status: 'completed', value: output ? await output.parse(result.text) : result.text };
132
- }
133
- return classifyAgentFailure(result.status, result.error);
134
- }
135
- catch (cause) {
136
- if (isStartupBlockException(cause))
137
- return { status: 'dropped', error: summarizeAgentError(cause) };
138
- return { status: 'failed', error: sdkError(cause, 'AGENT_FAILED', true) };
139
- }
140
- }
141
- /**
142
- * Build observeAgentTurn's single submission using the attached session's capabilities.
143
- * With structured output requested, use its schema route or the opted-in JSON text prompt.
144
- * Throw CAPABILITY_UNSUPPORTED before submission if neither route is available.
145
- */
146
- function agentSubmission({ session, prompt, output, outputFallback }) {
147
- if (!output)
148
- return { input: prompt };
149
- if (session.capabilities.turn?.outputSchema)
150
- return { input: prompt, outputSchema: output.schema };
151
- if (outputFallback !== 'json-text') {
152
- throw new HarnessSdkError('CAPABILITY_UNSUPPORTED', 'Session does not support structured output');
153
- }
154
- const instruction = 'Return the final answer as a single JSON object that matches this JSON Schema. Do not include Markdown fences or surrounding prose.';
155
- return { input: `${prompt}\n\n${instruction}\n${JSON.stringify(output.schema)}` };
156
- }
157
- /**
158
- * Classify a retained failed or interrupted terminal. Return drop evidence for settlement after
159
- * cleanup, or throw the terminal's SDK error through observeAgentTurn's startup-denial guard.
160
- */
161
- function classifyAgentFailure(status, error) {
162
- if (!error)
163
- throw new HarnessSdkError('AGENT_INTERRUPTED');
164
- if (isDroppedOutcome(error, status))
165
- return { status: 'dropped', error: summarizeAgentError(error) };
166
- throw new HarnessSdkError(error.code, error.message, error.retryable, error.outcomeUnknown, error.details);
167
- }
168
- /** Project errors to the code and uncertainty exposed in agent's cleanup diagnostics. */
169
- function summarizeAgentError(error) {
170
- return { code: error.code, outcomeUnknown: error.outcomeUnknown };
171
- }
172
- /**
173
- * Release executeAgent's session in close/dispose order. Attempt disposal after close failure
174
- * and return distinct normalized SDK error instances as safe diagnostics in encounter order.
175
- */
176
- async function releaseAgentSession(session) {
177
- const cleanupErrors = new Set();
178
- for (const method of ['close', 'dispose']) {
179
- try {
180
- await session[method]();
181
- }
182
- catch (cause) {
183
- cleanupErrors.add(sdkError(cause, 'RESOURCE_RELEASE_FAILED', true));
184
- }
185
- }
186
- return [...cleanupErrors].map(summarizeAgentError);
187
- }
188
- /**
189
- * Settle executeAgent after both release attempts. Return text/data or null on successful cleanup.
190
- * Throw the primary failure with any cleanup diagnostics, or RESOURCE_RELEASE_FAILED if cleanup
191
- * was the only failure.
192
- */
193
- function settleAgentOutcome(outcome, errors) {
194
- if (errors.length) {
195
- if (outcome.status === 'failed') {
196
- const failure = outcome.error;
197
- throw new HarnessSdkError(failure.code, failure.message, failure.retryable, failure.outcomeUnknown, { ...failure.details, cleanupErrors: errors });
198
- }
199
- throw new HarnessSdkError('RESOURCE_RELEASE_FAILED', 'Agent session cleanup failed', false, errors.some(error => error.outcomeUnknown), { errors, ...(outcome.status === 'dropped' ? { droppedError: outcome.error } : {}) });
200
- }
201
- switch (outcome.status) {
202
- case 'completed': return outcome.value;
203
- case 'dropped': return null;
204
- case 'failed': throw outcome.error;
205
- }
206
- }
package/src/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- /** Independent agent/composition primitives and the durable workflow API for applications. */
2
- export { agent, type AgentOptions } from "./agent.js";
3
- export { parallel } from "./parallel.js";
4
- export { pipeline } from "./pipeline.js";
5
- export { workflow } from "./workflow.js";
6
- export type { WorkflowOptions, WorkflowContext, WorkflowResult } from "./workflow-types.js";
package/src/index.js DELETED
@@ -1,5 +0,0 @@
1
- /** Independent agent/composition primitives and the durable workflow API for applications. */
2
- export { agent } from "./agent.js";
3
- export { parallel } from "./parallel.js";
4
- export { pipeline } from "./pipeline.js";
5
- export { workflow } from "./workflow.js";