@anureo/workflow 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -70
- package/package.json +17 -16
- package/src/agent-adapters.test.ts +121 -0
- package/src/agent-execution.ts +201 -0
- package/src/agent.test.ts +333 -0
- package/src/agent.ts +135 -0
- package/src/fixtures/workflow-crash.ts +53 -0
- package/src/index.ts +9 -0
- package/src/output-schema.test.ts +147 -0
- package/src/output-schema.ts +231 -0
- package/src/parallel.test.ts +96 -0
- package/src/parallel.ts +33 -0
- package/src/persistence/checkpoint-files.ts +82 -0
- package/src/persistence/journal.ts +111 -0
- package/src/persistence/json.ts +83 -0
- package/src/persistence/records.ts +97 -0
- package/src/persistence/replay.ts +91 -0
- package/src/persistence/store.ts +286 -0
- package/src/pipeline.test.ts +201 -0
- package/src/pipeline.ts +99 -0
- package/src/test-helpers.ts +23 -0
- package/src/workflow-state.ts +130 -0
- package/src/workflow-types.ts +38 -0
- package/src/workflow.test.ts +376 -0
- package/src/workflow.ts +112 -0
- package/tsconfig.json +13 -0
- package/LICENSE +0 -201
- package/src/agent-outcome.d.ts +0 -15
- package/src/agent-outcome.js +0 -28
- package/src/agent.d.ts +0 -49
- package/src/agent.js +0 -206
- package/src/index.d.ts +0 -6
- package/src/index.js +0 -5
- package/src/output-schema.d.ts +0 -27
- package/src/output-schema.js +0 -192
- package/src/parallel.d.ts +0 -18
- package/src/parallel.js +0 -25
- package/src/persistence/atomic.d.ts +0 -9
- package/src/persistence/atomic.js +0 -48
- package/src/persistence/journal.d.ts +0 -54
- package/src/persistence/journal.js +0 -106
- package/src/persistence/json.d.ts +0 -17
- package/src/persistence/json.js +0 -75
- package/src/persistence/read-json.d.ts +0 -11
- package/src/persistence/read-json.js +0 -46
- package/src/persistence/records.d.ts +0 -92
- package/src/persistence/records.js +0 -70
- package/src/persistence/replay.d.ts +0 -11
- package/src/persistence/replay.js +0 -79
- package/src/persistence/store.d.ts +0 -45
- package/src/persistence/store.js +0 -238
- package/src/pipeline.d.ts +0 -41
- package/src/pipeline.js +0 -24
- package/src/run-context.d.ts +0 -16
- package/src/run-context.js +0 -13
- package/src/test-helpers.d.ts +0 -11
- package/src/test-helpers.js +0 -21
- package/src/workflow-state.d.ts +0 -44
- package/src/workflow-state.js +0 -96
- package/src/workflow-types.d.ts +0 -39
- package/src/workflow-types.js +0 -0
- package/src/workflow.d.ts +0 -17
- package/src/workflow.js +0 -104
package/src/output-schema.js
DELETED
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import Ajv from 'ajv';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { HarnessSdkError } from '@anureo/sdk';
|
|
4
|
-
/**
|
|
5
|
-
* Compile a Zod object into a draft-07 schema and a parser for the same output type.
|
|
6
|
-
* Require closed objects and required JSON fields. Reject conversion schemas. JSON-compatible
|
|
7
|
-
* defaults may be declared, and raw validation still requires their fields. Unsupported or
|
|
8
|
-
* unrepresentable schemas synchronously throw INVALID_PARAMS with a safe rule code.
|
|
9
|
-
* executeAgent prepares the pair before acquiring its session and passes it to observeAgentTurn.
|
|
10
|
-
* memoizedAgent prepares it before deriving the journal key and uses the parser on typed hits.
|
|
11
|
-
*/
|
|
12
|
-
export function prepareOutputSchema(source) {
|
|
13
|
-
const { schema, validate } = compileSchema(source);
|
|
14
|
-
return {
|
|
15
|
-
schema,
|
|
16
|
-
async parse(text) {
|
|
17
|
-
const value = parseRawOutput(text, validate);
|
|
18
|
-
let parsed;
|
|
19
|
-
try {
|
|
20
|
-
parsed = await source.safeParseAsync(value);
|
|
21
|
-
}
|
|
22
|
-
catch {
|
|
23
|
-
throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED');
|
|
24
|
-
}
|
|
25
|
-
if (!parsed.success) {
|
|
26
|
-
throw outputMismatch(parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })));
|
|
27
|
-
}
|
|
28
|
-
return parsed.data;
|
|
29
|
-
},
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Decode one JSON value and require a schema-valid object before parse runs any Zod checks.
|
|
34
|
-
* Throw the missing, malformed or invalid output error synchronously and capture Ajv's
|
|
35
|
-
* current diagnostics before the parser can yield.
|
|
36
|
-
*/
|
|
37
|
-
function parseRawOutput(text, validate) {
|
|
38
|
-
if (!text.trim())
|
|
39
|
-
throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_MISSING');
|
|
40
|
-
let value;
|
|
41
|
-
try {
|
|
42
|
-
value = JSON.parse(text);
|
|
43
|
-
}
|
|
44
|
-
catch {
|
|
45
|
-
throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_NOT_JSON');
|
|
46
|
-
}
|
|
47
|
-
if (!value || typeof value !== 'object' || Array.isArray(value) || !validate(value)) {
|
|
48
|
-
const issues = validate.errors?.map(error => ({ path: error.instancePath, code: error.keyword })) ?? [];
|
|
49
|
-
throw outputMismatch(issues);
|
|
50
|
-
}
|
|
51
|
-
return value;
|
|
52
|
-
}
|
|
53
|
-
/** Use the same failure envelope for Ajv and Zod with only issue paths and codes. */
|
|
54
|
-
function outputMismatch(issues) {
|
|
55
|
-
return new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_INVALID', 'Agent output does not match its schema', false, false, { issues });
|
|
56
|
-
}
|
|
57
|
-
/** Let compileSchema preserve known preflight rule codes while sanitizing user callback exceptions. */
|
|
58
|
-
class SchemaParameterError extends HarnessSdkError {
|
|
59
|
-
constructor(rule) { super('INVALID_PARAMS', 'Unsupported agent output schema', false, false, { rule }); }
|
|
60
|
-
}
|
|
61
|
-
function rejectSchema(rule) {
|
|
62
|
-
throw new SchemaParameterError(rule);
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Give prepareOutputSchema a detached draft-07 schema and a synchronous validator.
|
|
66
|
-
* Check the Zod source before conversion, then check portability before compiling. Ajv leaves
|
|
67
|
-
* fields as supplied and skips format assertions so Zod can run its own format checks.
|
|
68
|
-
* Sanitize unexpected failures from conversion, schema callbacks and Ajv into INVALID_PARAMS.
|
|
69
|
-
*/
|
|
70
|
-
function compileSchema(source) {
|
|
71
|
-
if (!(source instanceof z.ZodObject))
|
|
72
|
-
rejectSchema('objectRootRequired');
|
|
73
|
-
try {
|
|
74
|
-
checkZodSource(source);
|
|
75
|
-
const schema = structuredClone(z.toJSONSchema(source, { target: 'draft-7', io: 'output', unrepresentable: 'throw' }));
|
|
76
|
-
delete schema.$schema;
|
|
77
|
-
if (schema.type !== 'object')
|
|
78
|
-
rejectSchema('objectRootRequired');
|
|
79
|
-
checkJsonSchema(schema);
|
|
80
|
-
const validate = new Ajv({ allErrors: true, validateFormats: false, multipleOfPrecision: 6, logger: false }).compile(schema);
|
|
81
|
-
return { schema, validate };
|
|
82
|
-
}
|
|
83
|
-
catch (cause) {
|
|
84
|
-
if (cause instanceof SchemaParameterError)
|
|
85
|
-
throw cause;
|
|
86
|
-
rejectSchema('invalidOrUnrepresentableSchema');
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
/** Reject conversions and nonportable types in the source graph before Zod's output-mode converter can hide them. */
|
|
90
|
-
function checkZodSource(root) {
|
|
91
|
-
const seen = new WeakSet();
|
|
92
|
-
const nonportableTypes = new Set(['optional', 'record', 'tuple', 'pipe', 'transform', 'catch', 'prefault',
|
|
93
|
-
'date', 'bigint', 'symbol', 'map', 'set', 'nan', 'undefined', 'void', 'custom', 'function', 'promise', 'file']);
|
|
94
|
-
/** Follow definition fields and invoke lazy getters once per visited lazy node. Propagate getter failures to compileSchema. */
|
|
95
|
-
function visitZodNode(value) {
|
|
96
|
-
if (!value || typeof value !== 'object' || seen.has(value))
|
|
97
|
-
return;
|
|
98
|
-
seen.add(value);
|
|
99
|
-
if (!(value instanceof z.ZodType)) {
|
|
100
|
-
for (const child of Object.values(value))
|
|
101
|
-
visitZodNode(child);
|
|
102
|
-
return;
|
|
103
|
-
}
|
|
104
|
-
const def = value._zod.def;
|
|
105
|
-
if (nonportableTypes.has(def.type) || ('coerce' in def && def.coerce)) {
|
|
106
|
-
rejectSchema('valueConversionOrNonportableType');
|
|
107
|
-
}
|
|
108
|
-
if (def.checks?.some(check => check._zod.def.check === 'overwrite'))
|
|
109
|
-
rejectSchema('valueConversion');
|
|
110
|
-
if (value instanceof z.ZodLazy)
|
|
111
|
-
visitZodNode(value._zod.def.getter());
|
|
112
|
-
// Skip the checks list when walking child schemas because refinements can be ZodCustom instances.
|
|
113
|
-
for (const [key, child] of Object.entries(def)) {
|
|
114
|
-
if (key !== 'checks')
|
|
115
|
-
visitZodNode(child);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
visitZodNode(root);
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Reject portability violations before Ajv compiles the generated schema. Follow only
|
|
122
|
-
* subschema keywords because examples, defaults and enum values may contain schema-like keys.
|
|
123
|
-
*/
|
|
124
|
-
function checkJsonSchema(node) {
|
|
125
|
-
if (!node || typeof node !== 'object' || Array.isArray(node))
|
|
126
|
-
return;
|
|
127
|
-
const schema = node;
|
|
128
|
-
if (schema.$async || (typeof schema.$ref === 'string' && !schema.$ref.startsWith('#'))) {
|
|
129
|
-
rejectSchema('externalOrAsyncSchema');
|
|
130
|
-
}
|
|
131
|
-
checkObjectProperties(schema);
|
|
132
|
-
if (Array.isArray(schema.items) || schema.prefixItems)
|
|
133
|
-
rejectSchema('tuple');
|
|
134
|
-
checkSchemaBounds(schema);
|
|
135
|
-
for (const key of ['properties', 'patternProperties', 'definitions', '$defs', 'dependentSchemas']) {
|
|
136
|
-
const children = schema[key];
|
|
137
|
-
if (children && typeof children === 'object' && !Array.isArray(children)) {
|
|
138
|
-
Object.values(children).forEach(checkJsonSchema);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
for (const key of ['allOf', 'anyOf', 'oneOf']) {
|
|
142
|
-
const children = schema[key];
|
|
143
|
-
if (Array.isArray(children))
|
|
144
|
-
children.forEach(checkJsonSchema);
|
|
145
|
-
}
|
|
146
|
-
for (const key of ['items', 'contains', 'additionalProperties', 'propertyNames', 'not', 'if', 'then', 'else']) {
|
|
147
|
-
checkJsonSchema(schema[key]);
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
/** Reject open/optional objects and required keys that a closed object cannot admit, including pattern keys. */
|
|
151
|
-
function checkObjectProperties(schema) {
|
|
152
|
-
if (schema.type !== 'object' && !(Array.isArray(schema.type) && schema.type.includes('object')))
|
|
153
|
-
return;
|
|
154
|
-
if (schema.additionalProperties !== false)
|
|
155
|
-
rejectSchema('openObject');
|
|
156
|
-
const properties = schema.properties;
|
|
157
|
-
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
158
|
-
if (properties && Object.keys(properties).some(key => !required.has(key)))
|
|
159
|
-
rejectSchema('optionalProperty');
|
|
160
|
-
const patterns = schema.patternProperties && typeof schema.patternProperties === 'object'
|
|
161
|
-
? Object.keys(schema.patternProperties).map(pattern => new RegExp(pattern, 'u')) : [];
|
|
162
|
-
if (Array.isArray(schema.required) && schema.required.some(key => typeof key === 'string'
|
|
163
|
-
&& !Object.hasOwn(properties ?? {}, key) && !patterns.some(pattern => pattern.test(key)))) {
|
|
164
|
-
rejectSchema('unsatisfiableRequired');
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
/** Check bounds for the declared type because other types' keywords do not constrain the instance. */
|
|
168
|
-
function checkSchemaBounds(schema) {
|
|
169
|
-
switch (schema.type) {
|
|
170
|
-
case 'string': return checkSizeBounds(schema.minLength, schema.maxLength);
|
|
171
|
-
case 'array': return checkSizeBounds(schema.minItems, schema.maxItems);
|
|
172
|
-
case 'object': return checkSizeBounds(schema.minProperties, schema.maxProperties);
|
|
173
|
-
case 'number':
|
|
174
|
-
case 'integer': return checkNumericBounds(schema);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
/** Reject contradictory sizes. Ajv checks the validity of the individual keyword values. */
|
|
178
|
-
function checkSizeBounds(lower, upper) {
|
|
179
|
-
if (typeof lower === 'number' && typeof upper === 'number' && lower > upper) {
|
|
180
|
-
rejectSchema('unsatisfiableBounds');
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
/** Reject crossed bounds or a shared endpoint excluded by either bound. */
|
|
184
|
-
function checkNumericBounds(schema) {
|
|
185
|
-
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum } = schema;
|
|
186
|
-
const lower = Math.max(typeof minimum === 'number' ? minimum : -Infinity, typeof exclusiveMinimum === 'number' ? exclusiveMinimum : -Infinity);
|
|
187
|
-
const upper = Math.min(typeof maximum === 'number' ? maximum : Infinity, typeof exclusiveMaximum === 'number' ? exclusiveMaximum : Infinity);
|
|
188
|
-
const equalBoundsExcludeValue = lower === upper && (exclusiveMinimum === lower || exclusiveMaximum === upper);
|
|
189
|
-
if (lower > upper || equalBoundsExcludeValue) {
|
|
190
|
-
rejectSchema('unsatisfiableBounds');
|
|
191
|
-
}
|
|
192
|
-
}
|
package/src/parallel.d.ts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Start a batch of zero-argument callbacks and collect their awaited results in input order.
|
|
3
|
-
* Callbacks start without waiting for earlier ones to finish. The promise resolves after all
|
|
4
|
-
* callbacks settle and preserves the result type at each tuple position. An empty batch resolves to [].
|
|
5
|
-
*
|
|
6
|
-
* A synchronous throw or rejection produces null at that position, just like an explicit null result.
|
|
7
|
-
* Other falsy values are preserved. Handle errors inside a callback if you need the original cause,
|
|
8
|
-
* and arrange any concurrency limits, cancellation, retries and resource cleanup in the callback.
|
|
9
|
-
*
|
|
10
|
-
* The function snapshots the task array and rejects with TypeError for a non-array argument
|
|
11
|
-
* or a non-function entry before invoking any callback.
|
|
12
|
-
*/
|
|
13
|
-
export declare function parallel<const Tasks extends readonly (() => unknown)[]>(tasks: Tasks): Promise<ParallelResults<Tasks>>;
|
|
14
|
-
/** Preserve each callback's awaited type and allow a failed callback to yield null in any slot. */
|
|
15
|
-
type ParallelResults<Tasks extends readonly (() => unknown)[]> = {
|
|
16
|
-
-readonly [K in keyof Tasks]: Awaited<ReturnType<Tasks[K]>> | null;
|
|
17
|
-
};
|
|
18
|
-
export {};
|
package/src/parallel.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Start a batch of zero-argument callbacks and collect their awaited results in input order.
|
|
3
|
-
* Callbacks start without waiting for earlier ones to finish. The promise resolves after all
|
|
4
|
-
* callbacks settle and preserves the result type at each tuple position. An empty batch resolves to [].
|
|
5
|
-
*
|
|
6
|
-
* A synchronous throw or rejection produces null at that position, just like an explicit null result.
|
|
7
|
-
* Other falsy values are preserved. Handle errors inside a callback if you need the original cause,
|
|
8
|
-
* and arrange any concurrency limits, cancellation, retries and resource cleanup in the callback.
|
|
9
|
-
*
|
|
10
|
-
* The function snapshots the task array and rejects with TypeError for a non-array argument
|
|
11
|
-
* or a non-function entry before invoking any callback.
|
|
12
|
-
*/
|
|
13
|
-
export async function parallel(tasks) {
|
|
14
|
-
if (!Array.isArray(tasks))
|
|
15
|
-
throw new TypeError('parallel expects an array of functions');
|
|
16
|
-
const callbacks = [...tasks];
|
|
17
|
-
for (const task of callbacks) {
|
|
18
|
-
if (typeof task !== 'function') {
|
|
19
|
-
throw new TypeError('parallel expects functions, not promises; wrap each call in () => task()');
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
// An async wrapper captures synchronous throws without skipping later callbacks.
|
|
23
|
-
const results = await Promise.allSettled(callbacks.map(async (task) => task()));
|
|
24
|
-
return results.map(result => result.status === 'fulfilled' ? result.value : null);
|
|
25
|
-
}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
/** Flush directory-entry changes and close the directory handle. I/O failures reject.
|
|
2
|
-
* On Windows this resolves without a flush because Node does not provide directory fsync. */
|
|
3
|
-
export declare function syncDirectory(path: string): Promise<void>;
|
|
4
|
-
/** Replace a checkpoint with canonical JSON after flushing a sibling temporary file, then
|
|
5
|
-
* flush its parent directory where supported. The caller must create the parent and serialize
|
|
6
|
-
* competing writes to the same path. Invalid JSON rejects before any file I/O.
|
|
7
|
-
* A directory flush can fail after replacement.
|
|
8
|
-
* If temporary-file cleanup fails, the rejection includes both failures. */
|
|
9
|
-
export declare function atomicPublish(path: string, value: unknown): Promise<void>;
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { open, rename, unlink } from 'node:fs/promises';
|
|
3
|
-
import { dirname } from 'node:path';
|
|
4
|
-
import { canonicalJson } from "./json.js";
|
|
5
|
-
/** Flush directory-entry changes and close the directory handle. I/O failures reject.
|
|
6
|
-
* On Windows this resolves without a flush because Node does not provide directory fsync. */
|
|
7
|
-
export async function syncDirectory(path) {
|
|
8
|
-
if (process.platform === 'win32')
|
|
9
|
-
return;
|
|
10
|
-
const directory = await open(path, 'r');
|
|
11
|
-
try {
|
|
12
|
-
await directory.sync();
|
|
13
|
-
}
|
|
14
|
-
finally {
|
|
15
|
-
await directory.close();
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
/** Replace a checkpoint with canonical JSON after flushing a sibling temporary file, then
|
|
19
|
-
* flush its parent directory where supported. The caller must create the parent and serialize
|
|
20
|
-
* competing writes to the same path. Invalid JSON rejects before any file I/O.
|
|
21
|
-
* A directory flush can fail after replacement.
|
|
22
|
-
* If temporary-file cleanup fails, the rejection includes both failures. */
|
|
23
|
-
export async function atomicPublish(path, value) {
|
|
24
|
-
const text = `${canonicalJson(value)}\n`;
|
|
25
|
-
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
26
|
-
// An exclusive open establishes ownership. Cleanup must leave an existing file alone.
|
|
27
|
-
const file = await open(temporary, 'wx', 0o600);
|
|
28
|
-
try {
|
|
29
|
-
try {
|
|
30
|
-
await file.writeFile(text, 'utf8');
|
|
31
|
-
await file.sync();
|
|
32
|
-
}
|
|
33
|
-
finally {
|
|
34
|
-
await file.close();
|
|
35
|
-
}
|
|
36
|
-
await rename(temporary, path);
|
|
37
|
-
}
|
|
38
|
-
catch (cause) {
|
|
39
|
-
try {
|
|
40
|
-
await unlink(temporary);
|
|
41
|
-
}
|
|
42
|
-
catch (cleanup) {
|
|
43
|
-
throw new AggregateError([cause, cleanup], 'Atomic publish failed');
|
|
44
|
-
}
|
|
45
|
-
throw cause;
|
|
46
|
-
}
|
|
47
|
-
await syncDirectory(dirname(path));
|
|
48
|
-
}
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import { type JsonValue } from "./json.js";
|
|
2
|
-
import type { JournalEvent } from "./records.js";
|
|
3
|
-
/** Prior terminal failure returned to memoizedAgent on a miss. */
|
|
4
|
-
export interface PriorFailure {
|
|
5
|
-
code: string;
|
|
6
|
-
/** The backend outcome is uncertain, so memoizedAgent rejects before redispatch. */
|
|
7
|
-
outcomeUnknown: boolean;
|
|
8
|
-
}
|
|
9
|
-
/** Replay lookup built from validated events. A key left at started can be respawned. */
|
|
10
|
-
export interface JournalIndex {
|
|
11
|
-
results: Map<string, JsonValue>;
|
|
12
|
-
started: Set<string>;
|
|
13
|
-
failures: Map<string, PriorFailure>;
|
|
14
|
-
}
|
|
15
|
-
/** Fold validated events in file order. Clear the earlier entry for each key so a newer
|
|
16
|
-
* start or failure supersedes any older result when AgentJournal initializes its replay lookup. */
|
|
17
|
-
export declare function indexJournal(events: readonly JournalEvent[]): JournalIndex;
|
|
18
|
-
/**
|
|
19
|
-
* Internal agent-call journal created by publishInitialRun for a new run and exposed
|
|
20
|
-
* by workflow through the ambient run context.
|
|
21
|
-
* memoizedAgent reserves keys in invocation order, checks replay, and awaits markers before
|
|
22
|
-
* dispatch or settlement. Each key hashes its predecessor, prompt and semantic options,
|
|
23
|
-
* so upstream changes invalidate later call identities. The run handle owns the writer lock.
|
|
24
|
-
* workflow drains registered agent work before final publication and closure.
|
|
25
|
-
*/
|
|
26
|
-
export declare class AgentJournal {
|
|
27
|
-
private readonly path;
|
|
28
|
-
/** Copy validated source events into a new run's journal; construction performs no file I/O. */
|
|
29
|
-
constructor(path: string, source: readonly JournalEvent[]);
|
|
30
|
-
/** Advance the chain synchronously before memoizedAgent's first await, including cache hits.
|
|
31
|
-
* Options must be strict JSON. If canonicalJson throws, the chain stays unchanged. */
|
|
32
|
-
nextKey(prompt: string, canonicalOptions: JsonValue): string;
|
|
33
|
-
/** Return an isolated cached result while reuse remains open, or undefined for execution.
|
|
34
|
-
* memoizedAgent revalidates typed hits against the current output schema before returning them. */
|
|
35
|
-
resultFor(key: string): JsonValue | undefined;
|
|
36
|
-
/** Record a miss after resultFor returns undefined. A source key left at started can be
|
|
37
|
-
* respawned while preserving eligibility for later keys. Any other miss closes result reuse
|
|
38
|
-
* for the rest of the run. Return the exact key's prior terminal failure, if any, so
|
|
39
|
-
* memoizedAgent can reject an unknown outcome before dispatch. */
|
|
40
|
-
beginExecution(key: string): PriorFailure | undefined;
|
|
41
|
-
/** Queue a copied event and await serialized atomic publication before indexing terminal data.
|
|
42
|
-
* memoizedAgent awaits started before dispatch and terminals before settlement. Keep the
|
|
43
|
-
* event unchanged until settlement and its result payload immutable while the lookup retains it.
|
|
44
|
-
* On publication failure the event remains queued. Non-SDK I/O failures reject as
|
|
45
|
-
* WORKFLOW_STORAGE_FAILED and stop subsequent workflow dispatch. */
|
|
46
|
-
append(event: JournalEvent): Promise<void>;
|
|
47
|
-
private readonly events;
|
|
48
|
-
private readonly index;
|
|
49
|
-
private previousKey;
|
|
50
|
-
private reuseOpen;
|
|
51
|
-
private publishQueue;
|
|
52
|
-
}
|
|
53
|
-
/** Generate a UUID suitable for a journal event's agentId; this does not reserve a cache key. */
|
|
54
|
-
export declare function newAgentId(): string;
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { HarnessSdkError } from '@anureo/sdk';
|
|
3
|
-
import { atomicPublish } from "./atomic.js";
|
|
4
|
-
import { canonicalJson, jsonCopy } from "./json.js";
|
|
5
|
-
/** Fold validated events in file order. Clear the earlier entry for each key so a newer
|
|
6
|
-
* start or failure supersedes any older result when AgentJournal initializes its replay lookup. */
|
|
7
|
-
export function indexJournal(events) {
|
|
8
|
-
const index = { results: new Map(), started: new Set(), failures: new Map() };
|
|
9
|
-
for (const event of events) {
|
|
10
|
-
index.started.delete(event.key);
|
|
11
|
-
index.failures.delete(event.key);
|
|
12
|
-
index.results.delete(event.key);
|
|
13
|
-
if (event.type === 'started')
|
|
14
|
-
index.started.add(event.key);
|
|
15
|
-
else
|
|
16
|
-
indexTerminalEvent(index, event);
|
|
17
|
-
}
|
|
18
|
-
return index;
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Internal agent-call journal created by publishInitialRun for a new run and exposed
|
|
22
|
-
* by workflow through the ambient run context.
|
|
23
|
-
* memoizedAgent reserves keys in invocation order, checks replay, and awaits markers before
|
|
24
|
-
* dispatch or settlement. Each key hashes its predecessor, prompt and semantic options,
|
|
25
|
-
* so upstream changes invalidate later call identities. The run handle owns the writer lock.
|
|
26
|
-
* workflow drains registered agent work before final publication and closure.
|
|
27
|
-
*/
|
|
28
|
-
export class AgentJournal {
|
|
29
|
-
path;
|
|
30
|
-
/** Copy validated source events into a new run's journal; construction performs no file I/O. */
|
|
31
|
-
constructor(path, source) {
|
|
32
|
-
this.path = path;
|
|
33
|
-
this.events.push(...jsonCopy(source));
|
|
34
|
-
this.index = indexJournal(this.events);
|
|
35
|
-
}
|
|
36
|
-
/** Advance the chain synchronously before memoizedAgent's first await, including cache hits.
|
|
37
|
-
* Options must be strict JSON. If canonicalJson throws, the chain stays unchanged. */
|
|
38
|
-
nextKey(prompt, canonicalOptions) {
|
|
39
|
-
const key = `v1:${createHash('sha256')
|
|
40
|
-
.update(this.previousKey).update('\0')
|
|
41
|
-
.update(prompt).update('\0')
|
|
42
|
-
.update(canonicalJson(canonicalOptions)).digest('hex')}`;
|
|
43
|
-
this.previousKey = key;
|
|
44
|
-
return key;
|
|
45
|
-
}
|
|
46
|
-
/** Return an isolated cached result while reuse remains open, or undefined for execution.
|
|
47
|
-
* memoizedAgent revalidates typed hits against the current output schema before returning them. */
|
|
48
|
-
resultFor(key) {
|
|
49
|
-
if (!this.reuseOpen)
|
|
50
|
-
return undefined;
|
|
51
|
-
const result = this.index.results.get(key);
|
|
52
|
-
return result === undefined ? undefined : jsonCopy(result);
|
|
53
|
-
}
|
|
54
|
-
/** Record a miss after resultFor returns undefined. A source key left at started can be
|
|
55
|
-
* respawned while preserving eligibility for later keys. Any other miss closes result reuse
|
|
56
|
-
* for the rest of the run. Return the exact key's prior terminal failure, if any, so
|
|
57
|
-
* memoizedAgent can reject an unknown outcome before dispatch. */
|
|
58
|
-
beginExecution(key) {
|
|
59
|
-
if (!this.index.started.has(key))
|
|
60
|
-
this.reuseOpen = false;
|
|
61
|
-
return this.index.failures.get(key);
|
|
62
|
-
}
|
|
63
|
-
/** Queue a copied event and await serialized atomic publication before indexing terminal data.
|
|
64
|
-
* memoizedAgent awaits started before dispatch and terminals before settlement. Keep the
|
|
65
|
-
* event unchanged until settlement and its result payload immutable while the lookup retains it.
|
|
66
|
-
* On publication failure the event remains queued. Non-SDK I/O failures reject as
|
|
67
|
-
* WORKFLOW_STORAGE_FAILED and stop subsequent workflow dispatch. */
|
|
68
|
-
async append(event) {
|
|
69
|
-
this.events.push(jsonCopy(event));
|
|
70
|
-
// Concurrent callers must not race atomic renames: an earlier snapshot
|
|
71
|
-
// landing last would silently drop later events from the published file.
|
|
72
|
-
const publish = this.publishQueue.catch(() => { }).then(async () => {
|
|
73
|
-
try {
|
|
74
|
-
await atomicPublish(this.path, this.events);
|
|
75
|
-
}
|
|
76
|
-
catch (cause) {
|
|
77
|
-
if (cause instanceof HarnessSdkError)
|
|
78
|
-
throw cause;
|
|
79
|
-
throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED');
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
this.publishQueue = publish;
|
|
83
|
-
await publish;
|
|
84
|
-
if (event.type !== 'started')
|
|
85
|
-
indexTerminalEvent(this.index, event);
|
|
86
|
-
}
|
|
87
|
-
events = [];
|
|
88
|
-
index;
|
|
89
|
-
previousKey = '';
|
|
90
|
-
reuseOpen = true;
|
|
91
|
-
publishQueue = Promise.resolve();
|
|
92
|
-
}
|
|
93
|
-
/** Generate a UUID suitable for a journal event's agentId; this does not reserve a cache key. */
|
|
94
|
-
export function newAgentId() {
|
|
95
|
-
return randomUUID();
|
|
96
|
-
}
|
|
97
|
-
/** Populate the terminal lookup. The replay fold clears superseded entries before calling
|
|
98
|
-
* this helper. Live append retains the source prefix markers for miss handling. */
|
|
99
|
-
function indexTerminalEvent(index, event) {
|
|
100
|
-
if (event.type === 'result') {
|
|
101
|
-
index.results.set(event.key, event.result);
|
|
102
|
-
}
|
|
103
|
-
else {
|
|
104
|
-
index.failures.set(event.key, { code: event.code, outcomeUnknown: event.outcomeUnknown });
|
|
105
|
-
}
|
|
106
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
/** Workflow JSON data shape. The encoder also checks runtime properties and rejects cycles. */
|
|
2
|
-
export type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
3
|
-
[key: string]: JsonValue;
|
|
4
|
-
};
|
|
5
|
-
/** Encode strict JSON with sorted object keys for persistence and cache identity.
|
|
6
|
-
* Throws WORKFLOW_NON_JSON_VALUE for unsupported values such as non-finite numbers, sparse
|
|
7
|
-
* arrays, cycles, non-plain objects, symbol keys, accessors and hidden data fields.
|
|
8
|
-
* Shared acyclic references encode by value. Encoding never calls toJSON. */
|
|
9
|
-
export declare function canonicalJson(value: unknown): string;
|
|
10
|
-
/** Return a detached copy of JSON-compatible data. Unsupported values throw as in canonicalJson.
|
|
11
|
-
* Shared references are copied by value. */
|
|
12
|
-
export declare function jsonCopy<T>(value: T): T;
|
|
13
|
-
/** Deeply freeze an already validated, acyclic JSON value in place and return it.
|
|
14
|
-
* prepareRun passes an owned copy for workflow to expose to the body. */
|
|
15
|
-
export declare function freezeJson<T>(value: T): T;
|
|
16
|
-
/** Hash canonical JSON as lowercase SHA-256 hex; unsupported values throw as in canonicalJson. */
|
|
17
|
-
export declare function digest(value: unknown): string;
|
package/src/persistence/json.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { HarnessSdkError } from '@anureo/sdk';
|
|
3
|
-
/** Encode strict JSON with sorted object keys for persistence and cache identity.
|
|
4
|
-
* Throws WORKFLOW_NON_JSON_VALUE for unsupported values such as non-finite numbers, sparse
|
|
5
|
-
* arrays, cycles, non-plain objects, symbol keys, accessors and hidden data fields.
|
|
6
|
-
* Shared acyclic references encode by value. Encoding never calls toJSON. */
|
|
7
|
-
export function canonicalJson(value) {
|
|
8
|
-
return encodeJson(value, new Set());
|
|
9
|
-
}
|
|
10
|
-
/** Return a detached copy of JSON-compatible data. Unsupported values throw as in canonicalJson.
|
|
11
|
-
* Shared references are copied by value. */
|
|
12
|
-
export function jsonCopy(value) {
|
|
13
|
-
return JSON.parse(canonicalJson(value));
|
|
14
|
-
}
|
|
15
|
-
/** Deeply freeze an already validated, acyclic JSON value in place and return it.
|
|
16
|
-
* prepareRun passes an owned copy for workflow to expose to the body. */
|
|
17
|
-
export function freezeJson(value) {
|
|
18
|
-
if (value && typeof value === 'object') {
|
|
19
|
-
for (const child of Object.values(value))
|
|
20
|
-
freezeJson(child);
|
|
21
|
-
Object.freeze(value);
|
|
22
|
-
}
|
|
23
|
-
return value;
|
|
24
|
-
}
|
|
25
|
-
/** Hash canonical JSON as lowercase SHA-256 hex; unsupported values throw as in canonicalJson. */
|
|
26
|
-
export function digest(value) {
|
|
27
|
-
return createHash('sha256').update(canonicalJson(value)).digest('hex');
|
|
28
|
-
}
|
|
29
|
-
/** Track only the current ancestry so repeated references encode normally while cycles reject. */
|
|
30
|
-
function encodeJson(item, ancestors) {
|
|
31
|
-
if (item === null)
|
|
32
|
-
return 'null';
|
|
33
|
-
if (typeof item === 'string' || typeof item === 'boolean')
|
|
34
|
-
return JSON.stringify(item);
|
|
35
|
-
if (typeof item === 'number')
|
|
36
|
-
return Number.isFinite(item) ? JSON.stringify(item) : invalidJson();
|
|
37
|
-
if (typeof item !== 'object' || ancestors.has(item))
|
|
38
|
-
return invalidJson();
|
|
39
|
-
if (Reflect.ownKeys(item).some(key => typeof key !== 'string'))
|
|
40
|
-
return invalidJson();
|
|
41
|
-
const descriptors = Object.getOwnPropertyDescriptors(item);
|
|
42
|
-
ancestors.add(item);
|
|
43
|
-
try {
|
|
44
|
-
return Array.isArray(item)
|
|
45
|
-
? encodeArray(item, descriptors, ancestors)
|
|
46
|
-
: encodeObject(item, descriptors, ancestors);
|
|
47
|
-
}
|
|
48
|
-
finally {
|
|
49
|
-
ancestors.delete(item);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
/** Dense array slots must be the only own properties besides length to avoid silent data loss. */
|
|
53
|
-
function encodeArray(item, descriptors, ancestors) {
|
|
54
|
-
if (Object.keys(descriptors).length !== item.length + 1)
|
|
55
|
-
return invalidJson();
|
|
56
|
-
const values = [];
|
|
57
|
-
for (let i = 0; i < item.length; i++) {
|
|
58
|
-
values.push(encodeDataProperty(descriptors[String(i)], ancestors));
|
|
59
|
-
}
|
|
60
|
-
return `[${values.join(',')}]`;
|
|
61
|
-
}
|
|
62
|
-
/** Restrict objects to plain data and sort their keys so insertion order cannot change identity. */
|
|
63
|
-
function encodeObject(item, descriptors, ancestors) {
|
|
64
|
-
const prototype = Object.getPrototypeOf(item);
|
|
65
|
-
if (prototype !== Object.prototype && prototype !== null)
|
|
66
|
-
return invalidJson();
|
|
67
|
-
return `{${Object.keys(descriptors).sort().map(key => `${JSON.stringify(key)}:${encodeDataProperty(descriptors[key], ancestors)}`).join(',')}}`;
|
|
68
|
-
}
|
|
69
|
-
/** Inspect descriptors instead of reading properties so getters never supply persisted data. */
|
|
70
|
-
function encodeDataProperty(field, ancestors) {
|
|
71
|
-
if (!field || !field.enumerable || !('value' in field))
|
|
72
|
-
return invalidJson();
|
|
73
|
-
return encodeJson(field.value, ancestors);
|
|
74
|
-
}
|
|
75
|
-
function invalidJson() { throw new HarnessSdkError('WORKFLOW_NON_JSON_VALUE'); }
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { type JsonValue } from "./json.js";
|
|
2
|
-
/** Read strict JSON from a regular file and always close its descriptor. Check the final
|
|
3
|
-
* component with lstat and verify the opened inode to catch replacement during open.
|
|
4
|
-
* Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
|
|
5
|
-
* filesystem failures and validates the returned value against the checkpoint schema. */
|
|
6
|
-
export declare function readJson(path: string): Promise<JsonValue>;
|
|
7
|
-
/** Require the source's final path component to be a real directory. Other file kinds
|
|
8
|
-
* reject as WORKFLOW_CHECKPOINT_INVALID before replay reads it. Filesystem errors propagate. */
|
|
9
|
-
export declare function regularDirectory(path: string): Promise<void>;
|
|
10
|
-
/** Test for ENOENT so replay can allow an absent writer lock and reject absent required files. */
|
|
11
|
-
export declare function missing(cause: unknown): boolean;
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
// Checks the filesystem entries that replay reads before validating checkpoint schemas.
|
|
2
|
-
import { constants } from 'node:fs';
|
|
3
|
-
import { lstat, open } from 'node:fs/promises';
|
|
4
|
-
import { canonicalJson } from "./json.js";
|
|
5
|
-
import { invalidCheckpoint } from "./records.js";
|
|
6
|
-
/** Read strict JSON from a regular file and always close its descriptor. Check the final
|
|
7
|
-
* component with lstat and verify the opened inode to catch replacement during open.
|
|
8
|
-
* Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
|
|
9
|
-
* filesystem failures and validates the returned value against the checkpoint schema. */
|
|
10
|
-
export async function readJson(path) {
|
|
11
|
-
const before = await lstat(path);
|
|
12
|
-
if (!before.isFile())
|
|
13
|
-
return invalidCheckpoint();
|
|
14
|
-
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
15
|
-
try {
|
|
16
|
-
const current = await file.stat();
|
|
17
|
-
if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino)
|
|
18
|
-
return invalidCheckpoint();
|
|
19
|
-
return parseCheckpointJson(await file.readFile('utf8'));
|
|
20
|
-
}
|
|
21
|
-
finally {
|
|
22
|
-
await file.close();
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
/** Require the source's final path component to be a real directory. Other file kinds
|
|
26
|
-
* reject as WORKFLOW_CHECKPOINT_INVALID before replay reads it. Filesystem errors propagate. */
|
|
27
|
-
export async function regularDirectory(path) {
|
|
28
|
-
if (!(await lstat(path)).isDirectory())
|
|
29
|
-
invalidCheckpoint();
|
|
30
|
-
}
|
|
31
|
-
/** Test for ENOENT so replay can allow an absent writer lock and reject absent required files. */
|
|
32
|
-
export function missing(cause) {
|
|
33
|
-
return cause?.code === 'ENOENT';
|
|
34
|
-
}
|
|
35
|
-
/** Map malformed or nonrepresentable JSON to checkpoint corruption before schema validation.
|
|
36
|
-
* JSON.parse alone accepts number literals that overflow to Infinity. */
|
|
37
|
-
function parseCheckpointJson(text) {
|
|
38
|
-
try {
|
|
39
|
-
const value = JSON.parse(text);
|
|
40
|
-
canonicalJson(value);
|
|
41
|
-
return value;
|
|
42
|
-
}
|
|
43
|
-
catch {
|
|
44
|
-
return invalidCheckpoint();
|
|
45
|
-
}
|
|
46
|
-
}
|