@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
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
import { type JsonValue } from "./json.js";
|
|
3
|
-
/** Check target and source basenames before joining paths. Reject blanks, separators,
|
|
4
|
-
* control characters, dot traversal and names over 255 UTF-8 bytes. Unicode and spaces
|
|
5
|
-
* support caller-assigned CLI basenames. */
|
|
6
|
-
export declare const runIdSchema: z.ZodString;
|
|
7
|
-
/** UUID rule shared by journal agent identities and writer-lock ownership tokens. */
|
|
8
|
-
export declare const uuidSchema: z.ZodString;
|
|
9
|
-
/** Persist only safe failure metadata; diagnostic messages and details stay out of manifests. */
|
|
10
|
-
export declare const failureSchema: z.ZodObject<{
|
|
11
|
-
code: z.ZodString;
|
|
12
|
-
retryable: z.ZodBoolean;
|
|
13
|
-
outcomeUnknown: z.ZodBoolean;
|
|
14
|
-
cleanupFailed: z.ZodBoolean;
|
|
15
|
-
}, z.core.$strict>;
|
|
16
|
-
/** Versioned chained SHA-256 identity for an agent call, independent of its execution UUID. */
|
|
17
|
-
export declare const journalKeySchema: z.ZodString;
|
|
18
|
-
/** Validated manifest shape; its digest and referenced result still require separate verification. */
|
|
19
|
-
export type Manifest = z.output<typeof manifestSchema>;
|
|
20
|
-
/** Persist only failure classification from workflow aborts, without diagnostic text. */
|
|
21
|
-
export type StoredFailure = z.output<typeof failureSchema>;
|
|
22
|
-
/** Internal validated event persisted before dispatch or before exposing an agent outcome. */
|
|
23
|
-
export type JournalEvent = z.output<typeof journalEventSchema>;
|
|
24
|
-
/** Reject unusable recovery material without treating corruption as an empty cache. */
|
|
25
|
-
export declare function invalidCheckpoint(): never;
|
|
26
|
-
/** Add a digest of the supplied JSON payload for a lock or manifest. Callers must omit
|
|
27
|
-
* recordDigest so the payload matches what verifyRecord later hashes. Strict JSON errors throw. */
|
|
28
|
-
export declare function record<T extends object>(value: T): T & {
|
|
29
|
-
recordDigest: string;
|
|
30
|
-
};
|
|
31
|
-
/** Return parsed lock or manifest data after verifying the payload digest. A schema
|
|
32
|
-
* mismatch or different digest throws WORKFLOW_CHECKPOINT_INVALID. The schema must
|
|
33
|
-
* yield strict JSON with a recordDigest field. */
|
|
34
|
-
export declare function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.output<S>;
|
|
35
|
-
/** Format-v2 writer claim. Replay checks host/PID liveness; release checks the held inode. */
|
|
36
|
-
export declare const lockSchema: z.ZodObject<{
|
|
37
|
-
checkpointFormatVersion: z.ZodLiteral<2>;
|
|
38
|
-
token: z.ZodString;
|
|
39
|
-
hostname: z.ZodString;
|
|
40
|
-
pid: z.ZodNumber;
|
|
41
|
-
createdAt: z.ZodString;
|
|
42
|
-
recordDigest: z.ZodString;
|
|
43
|
-
}, z.core.$strict>;
|
|
44
|
-
/** Format-v2 run metadata. Replay rejects earlier formats, checks recordDigest with verifyRecord,
|
|
45
|
-
* and checks resultDigest against result.json for completed and incomplete runs. */
|
|
46
|
-
export declare const manifestSchema: z.ZodObject<{
|
|
47
|
-
checkpointFormatVersion: z.ZodLiteral<2>;
|
|
48
|
-
identity: z.ZodObject<{
|
|
49
|
-
runId: z.ZodString;
|
|
50
|
-
directory: z.ZodString;
|
|
51
|
-
name: z.ZodString;
|
|
52
|
-
revision: z.ZodString;
|
|
53
|
-
input: z.ZodType<JsonValue, unknown, z.core.$ZodTypeInternals<JsonValue, unknown>>;
|
|
54
|
-
}, z.core.$strict>;
|
|
55
|
-
createdAt: z.ZodString;
|
|
56
|
-
resumedFrom: z.ZodNullable<z.ZodObject<{
|
|
57
|
-
directory: z.ZodString;
|
|
58
|
-
runId: z.ZodString;
|
|
59
|
-
}, z.core.$strict>>;
|
|
60
|
-
status: z.ZodEnum<{
|
|
61
|
-
running: "running";
|
|
62
|
-
completed: "completed";
|
|
63
|
-
failed: "failed";
|
|
64
|
-
incomplete: "incomplete";
|
|
65
|
-
}>;
|
|
66
|
-
resultDigest: z.ZodNullable<z.ZodString>;
|
|
67
|
-
failure: z.ZodNullable<z.ZodObject<{
|
|
68
|
-
code: z.ZodString;
|
|
69
|
-
retryable: z.ZodBoolean;
|
|
70
|
-
outcomeUnknown: z.ZodBoolean;
|
|
71
|
-
cleanupFailed: z.ZodBoolean;
|
|
72
|
-
}, z.core.$strict>>;
|
|
73
|
-
recordDigest: z.ZodString;
|
|
74
|
-
}, z.core.$strict>;
|
|
75
|
-
/** Strict persisted events. Replay validates the entire array before handing it to AgentJournal.
|
|
76
|
-
* The chained key determines reuse. The execution UUID is recorded as agentId. */
|
|
77
|
-
export declare const journalEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
78
|
-
type: z.ZodLiteral<"started">;
|
|
79
|
-
key: z.ZodString;
|
|
80
|
-
agentId: z.ZodString;
|
|
81
|
-
}, z.core.$strict>, z.ZodObject<{
|
|
82
|
-
type: z.ZodLiteral<"result">;
|
|
83
|
-
key: z.ZodString;
|
|
84
|
-
agentId: z.ZodString;
|
|
85
|
-
result: z.ZodType<JsonValue, unknown, z.core.$ZodTypeInternals<JsonValue, unknown>>;
|
|
86
|
-
}, z.core.$strict>, z.ZodObject<{
|
|
87
|
-
type: z.ZodLiteral<"failed">;
|
|
88
|
-
key: z.ZodString;
|
|
89
|
-
agentId: z.ZodString;
|
|
90
|
-
code: z.ZodString;
|
|
91
|
-
outcomeUnknown: z.ZodBoolean;
|
|
92
|
-
}, z.core.$strict>], "type">;
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
import { HarnessSdkError } from '@anureo/sdk';
|
|
3
|
-
import { digest } from "./json.js";
|
|
4
|
-
/** Check target and source basenames before joining paths. Reject blanks, separators,
|
|
5
|
-
* control characters, dot traversal and names over 255 UTF-8 bytes. Unicode and spaces
|
|
6
|
-
* support caller-assigned CLI basenames. */
|
|
7
|
-
export const runIdSchema = z.string().min(1).refine(value => value !== '.' && value !== '..'
|
|
8
|
-
&& value.trim().length > 0 && !/[\\/\x00-\x1f\x7f]/.test(value) && Buffer.byteLength(value) <= 255);
|
|
9
|
-
/** UUID rule shared by journal agent identities and writer-lock ownership tokens. */
|
|
10
|
-
export const uuidSchema = z.string().uuid();
|
|
11
|
-
/** Persist only safe failure metadata; diagnostic messages and details stay out of manifests. */
|
|
12
|
-
export const failureSchema = z.strictObject({
|
|
13
|
-
code: z.string(),
|
|
14
|
-
retryable: z.boolean(),
|
|
15
|
-
/** The failure left execution's outcome uncertain. */
|
|
16
|
-
outcomeUnknown: z.boolean(),
|
|
17
|
-
/** Resource release failed even if execution itself had a known outcome. */
|
|
18
|
-
cleanupFailed: z.boolean(),
|
|
19
|
-
});
|
|
20
|
-
/** Versioned chained SHA-256 identity for an agent call, independent of its execution UUID. */
|
|
21
|
-
export const journalKeySchema = z.string().regex(/^v1:[a-f0-9]{64}$/);
|
|
22
|
-
/** Reject unusable recovery material without treating corruption as an empty cache. */
|
|
23
|
-
export function invalidCheckpoint() { throw new HarnessSdkError('WORKFLOW_CHECKPOINT_INVALID'); }
|
|
24
|
-
/** Add a digest of the supplied JSON payload for a lock or manifest. Callers must omit
|
|
25
|
-
* recordDigest so the payload matches what verifyRecord later hashes. Strict JSON errors throw. */
|
|
26
|
-
export function record(value) {
|
|
27
|
-
return { ...value, recordDigest: digest(value) };
|
|
28
|
-
}
|
|
29
|
-
/** Return parsed lock or manifest data after verifying the payload digest. A schema
|
|
30
|
-
* mismatch or different digest throws WORKFLOW_CHECKPOINT_INVALID. The schema must
|
|
31
|
-
* yield strict JSON with a recordDigest field. */
|
|
32
|
-
export function verifyRecord(schema, value) {
|
|
33
|
-
const parsed = schema.safeParse(value);
|
|
34
|
-
if (!parsed.success)
|
|
35
|
-
return invalidCheckpoint();
|
|
36
|
-
const { recordDigest, ...payload } = parsed.data;
|
|
37
|
-
if (digest(payload) !== recordDigest)
|
|
38
|
-
return invalidCheckpoint();
|
|
39
|
-
return parsed.data;
|
|
40
|
-
}
|
|
41
|
-
// These schemas must be initialized before the exported record schemas that compose them.
|
|
42
|
-
const hashSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
|
43
|
-
const jsonSchema = z.lazy(() => z.union([
|
|
44
|
-
z.null(), z.boolean(), z.number().finite(), z.string(), z.array(jsonSchema), z.record(z.string(), jsonSchema),
|
|
45
|
-
]));
|
|
46
|
-
const identitySchema = z.strictObject({
|
|
47
|
-
runId: runIdSchema, directory: z.string(), name: z.string().min(1), revision: z.string().min(1), input: jsonSchema,
|
|
48
|
-
});
|
|
49
|
-
/** Format-v2 writer claim. Replay checks host/PID liveness; release checks the held inode. */
|
|
50
|
-
export const lockSchema = z.strictObject({
|
|
51
|
-
checkpointFormatVersion: z.literal(2), token: uuidSchema, hostname: z.string(),
|
|
52
|
-
pid: z.number().int().positive(), createdAt: z.string().datetime(), recordDigest: hashSchema,
|
|
53
|
-
});
|
|
54
|
-
/** Format-v2 run metadata. Replay rejects earlier formats, checks recordDigest with verifyRecord,
|
|
55
|
-
* and checks resultDigest against result.json for completed and incomplete runs. */
|
|
56
|
-
export const manifestSchema = z.strictObject({
|
|
57
|
-
checkpointFormatVersion: z.literal(2),
|
|
58
|
-
identity: identitySchema, createdAt: z.string().datetime(),
|
|
59
|
-
resumedFrom: z.strictObject({ directory: z.string(), runId: runIdSchema }).nullable(),
|
|
60
|
-
status: z.enum(['running', 'completed', 'incomplete', 'failed']),
|
|
61
|
-
resultDigest: hashSchema.nullable(), failure: failureSchema.nullable(), recordDigest: hashSchema,
|
|
62
|
-
});
|
|
63
|
-
/** Strict persisted events. Replay validates the entire array before handing it to AgentJournal.
|
|
64
|
-
* The chained key determines reuse. The execution UUID is recorded as agentId. */
|
|
65
|
-
export const journalEventSchema = z.discriminatedUnion('type', [
|
|
66
|
-
z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema }),
|
|
67
|
-
z.strictObject({ type: z.literal('result'), key: journalKeySchema, agentId: uuidSchema, result: jsonSchema }),
|
|
68
|
-
z.strictObject({ type: z.literal('failed'), key: journalKeySchema, agentId: uuidSchema,
|
|
69
|
-
code: z.string().min(1), outcomeUnknown: z.boolean() }),
|
|
70
|
-
]);
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { type Manifest, type JournalEvent } from "./records.js";
|
|
2
|
-
/** Load an inactive source run's validated events without modifying its files.
|
|
3
|
-
* publishInitialRun calls this while holding the target lock, then copies the events
|
|
4
|
-
* into the new journal. A mismatched run ID or invalid required record rejects as
|
|
5
|
-
* WORKFLOW_CHECKPOINT_INVALID. Mismatched name or revision rejects as WORKFLOW_INCOMPATIBLE_RUN.
|
|
6
|
-
* A valid lock without evidence of a dead local writer rejects as WORKFLOW_SOURCE_ACTIVE.
|
|
7
|
-
* Other filesystem errors propagate. Failed and running sources need no result file.
|
|
8
|
-
* The caller supplies a separate target directory. This check acquires no source lock. */
|
|
9
|
-
export declare function loadSourceJournal(directory: string, identity: SourceIdentity): Promise<JournalEvent[]>;
|
|
10
|
-
type SourceIdentity = Pick<Manifest['identity'], 'name' | 'revision' | 'runId'>;
|
|
11
|
-
export {};
|
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import { HarnessSdkError } from '@anureo/sdk';
|
|
2
|
-
import { hostname } from 'node:os';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
import { digest } from "./json.js";
|
|
5
|
-
import { readJson, regularDirectory, missing } from "./read-json.js";
|
|
6
|
-
import { journalEventSchema, lockSchema, manifestSchema, invalidCheckpoint, verifyRecord, } from "./records.js";
|
|
7
|
-
/** Load an inactive source run's validated events without modifying its files.
|
|
8
|
-
* publishInitialRun calls this while holding the target lock, then copies the events
|
|
9
|
-
* into the new journal. A mismatched run ID or invalid required record rejects as
|
|
10
|
-
* WORKFLOW_CHECKPOINT_INVALID. Mismatched name or revision rejects as WORKFLOW_INCOMPATIBLE_RUN.
|
|
11
|
-
* A valid lock without evidence of a dead local writer rejects as WORKFLOW_SOURCE_ACTIVE.
|
|
12
|
-
* Other filesystem errors propagate. Failed and running sources need no result file.
|
|
13
|
-
* The caller supplies a separate target directory. This check acquires no source lock. */
|
|
14
|
-
export async function loadSourceJournal(directory, identity) {
|
|
15
|
-
await regularDirectory(directory);
|
|
16
|
-
await assertInactive(directory);
|
|
17
|
-
const manifest = verifyRecord(manifestSchema, await requiredJson(join(directory, 'run.json')));
|
|
18
|
-
assertCompatibleIdentity(manifest.identity, identity);
|
|
19
|
-
const raw = await requiredJson(join(directory, 'journal.json'));
|
|
20
|
-
const parsed = journalEventSchema.array().safeParse(raw);
|
|
21
|
-
if (!parsed.success)
|
|
22
|
-
invalidCheckpoint();
|
|
23
|
-
if (manifest.status === 'completed' || manifest.status === 'incomplete') {
|
|
24
|
-
if (digest(await requiredJson(join(directory, 'result.json'))) !== manifest.resultDigest)
|
|
25
|
-
invalidCheckpoint();
|
|
26
|
-
}
|
|
27
|
-
return parsed.data;
|
|
28
|
-
}
|
|
29
|
-
/** Check that the manifest belongs to the selected run before checking workflow compatibility.
|
|
30
|
-
* A misplaced manifest is checkpoint corruption even if its workflow name or revision differs. */
|
|
31
|
-
function assertCompatibleIdentity(actual, expected) {
|
|
32
|
-
if (actual.runId !== expected.runId)
|
|
33
|
-
invalidCheckpoint();
|
|
34
|
-
if (actual.name !== expected.name || actual.revision !== expected.revision) {
|
|
35
|
-
throw new HarnessSdkError('WORKFLOW_INCOMPATIBLE_RUN');
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
/** Classify missing recovery files and final symlinks as invalid checkpoints.
|
|
39
|
-
* Other failures reach openFileRun for storage error normalization. */
|
|
40
|
-
async function requiredJson(path) {
|
|
41
|
-
try {
|
|
42
|
-
return await readJson(path);
|
|
43
|
-
}
|
|
44
|
-
catch (cause) {
|
|
45
|
-
if (missing(cause) || cause?.code === 'ELOOP')
|
|
46
|
-
invalidCheckpoint();
|
|
47
|
-
throw cause;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
/** Permit an absent writer lock or a validated local claim whose PID no longer exists.
|
|
51
|
-
* An invalid lock rejects through verifyRecord. A valid lock that fails the liveness
|
|
52
|
-
* check blocks loadSourceJournal before it reads the manifest. */
|
|
53
|
-
async function assertInactive(directory) {
|
|
54
|
-
let lock;
|
|
55
|
-
try {
|
|
56
|
-
lock = verifyRecord(lockSchema, await readJson(join(directory, 'writer.lock')));
|
|
57
|
-
}
|
|
58
|
-
catch (cause) {
|
|
59
|
-
if (missing(cause))
|
|
60
|
-
return;
|
|
61
|
-
throw cause;
|
|
62
|
-
}
|
|
63
|
-
if (!localWriterExited(lock))
|
|
64
|
-
throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE');
|
|
65
|
-
}
|
|
66
|
-
/** Only a local PID probe returning ESRCH proves the recorded process is gone.
|
|
67
|
-
* A foreign host, live or reused PID, or refused probe leaves inactivity unproven.
|
|
68
|
-
* This evidence is limited to the writer process and cannot confirm backend termination. */
|
|
69
|
-
function localWriterExited(lock) {
|
|
70
|
-
if (lock.hostname !== hostname())
|
|
71
|
-
return false;
|
|
72
|
-
try {
|
|
73
|
-
process.kill(lock.pid, 0);
|
|
74
|
-
return false;
|
|
75
|
-
}
|
|
76
|
-
catch (cause) {
|
|
77
|
-
return cause.code === 'ESRCH';
|
|
78
|
-
}
|
|
79
|
-
}
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import type { WorkflowOptions } from "../workflow-types.js";
|
|
2
|
-
import { type JsonValue } from "./json.js";
|
|
3
|
-
import { AgentJournal } from "./journal.js";
|
|
4
|
-
import { type StoredFailure } from "./records.js";
|
|
5
|
-
/** Internal identity saved before workflow enters its body. */
|
|
6
|
-
export interface RunIdentity {
|
|
7
|
-
/** Validated basename of the run within directory. */
|
|
8
|
-
runId: string;
|
|
9
|
-
/** Canonical parent containing the run's subdirectory. */
|
|
10
|
-
directory: string;
|
|
11
|
-
name: string;
|
|
12
|
-
revision: string;
|
|
13
|
-
/** Isolated persistence snapshot. The body receives its own frozen copy from prepareRun. */
|
|
14
|
-
input: JsonValue;
|
|
15
|
-
}
|
|
16
|
-
/** Internal storage ownership returned to workflow. Drain agent work before finish or abort,
|
|
17
|
-
* and always await close in finally. Only manifest operations are serialized by this handle. */
|
|
18
|
-
export interface RunHandle {
|
|
19
|
-
/** Provides the canonical storage directory for workflow's error details. */
|
|
20
|
-
readonly identity: RunIdentity;
|
|
21
|
-
/** Installed by completeRun as the journal for agent calls in the body. */
|
|
22
|
-
readonly journal: AgentJournal;
|
|
23
|
-
/** Publish result.json before the terminal manifest and resolve after both publications.
|
|
24
|
-
* A rejection may leave a result or manifest already replaced. A queued call that starts
|
|
25
|
-
* after closure rejects with WORKFLOW_CLOSED. */
|
|
26
|
-
finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void>;
|
|
27
|
-
/** Publish a failed manifest and keep any earlier result file and the writer lock.
|
|
28
|
-
* Publication failures reject, as does a queued call that starts after closure. */
|
|
29
|
-
abort(failure: StoredFailure): Promise<void>;
|
|
30
|
-
/** Wait for queued manifests, then release the owned writer lock and close its descriptor.
|
|
31
|
-
* Lock-release failures reject. Sequential repeats are no-ops, including after rejection.
|
|
32
|
-
* Callers must finish scheduling work before closure. */
|
|
33
|
-
close(): Promise<void>;
|
|
34
|
-
}
|
|
35
|
-
/** Create a fresh file-backed run for workflow, publishing its journal and running manifest
|
|
36
|
-
* before returning. An optional inactive source supplies replay events, never the final result.
|
|
37
|
-
* The returned handle owns the writer lock and must be closed after registered agent work drains.
|
|
38
|
-
* SDK errors propagate unless lock rollback fails. Rollback failures and otherwise unclassified
|
|
39
|
-
* I/O failures reject as WORKFLOW_STORAGE_FAILED. If publication left run files behind,
|
|
40
|
-
* a later attempt on the same target rejects with WORKFLOW_RUN_EXISTS. */
|
|
41
|
-
export declare function openFileRun(options: FileRunOptions): Promise<RunHandle>;
|
|
42
|
-
type FileRunOptions = WorkflowOptions<JsonValue> & {
|
|
43
|
-
runId: string;
|
|
44
|
-
};
|
|
45
|
-
export {};
|
package/src/persistence/store.js
DELETED
|
@@ -1,238 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { hostname } from 'node:os';
|
|
3
|
-
import { lstat, mkdir, open, readdir, realpath, unlink } from 'node:fs/promises';
|
|
4
|
-
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
-
import { HarnessSdkError } from '@anureo/sdk';
|
|
6
|
-
import { atomicPublish, syncDirectory } from "./atomic.js";
|
|
7
|
-
import { canonicalJson, digest, jsonCopy } from "./json.js";
|
|
8
|
-
import { AgentJournal } from "./journal.js";
|
|
9
|
-
import { invalidCheckpoint, record, runIdSchema } from "./records.js";
|
|
10
|
-
import { loadSourceJournal } from "./replay.js";
|
|
11
|
-
/** Create a fresh file-backed run for workflow, publishing its journal and running manifest
|
|
12
|
-
* before returning. An optional inactive source supplies replay events, never the final result.
|
|
13
|
-
* The returned handle owns the writer lock and must be closed after registered agent work drains.
|
|
14
|
-
* SDK errors propagate unless lock rollback fails. Rollback failures and otherwise unclassified
|
|
15
|
-
* I/O failures reject as WORKFLOW_STORAGE_FAILED. If publication left run files behind,
|
|
16
|
-
* a later attempt on the same target rejects with WORKFLOW_RUN_EXISTS. */
|
|
17
|
-
export async function openFileRun(options) {
|
|
18
|
-
validateRunOptions(options);
|
|
19
|
-
try {
|
|
20
|
-
const prepared = await prepareRunStorage(options);
|
|
21
|
-
return await initializeLockedRun({ options, prepared });
|
|
22
|
-
}
|
|
23
|
-
catch (cause) {
|
|
24
|
-
throw storageError(cause);
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
/** Own the open lock descriptor and serialize manifest transitions until workflow releases it. */
|
|
28
|
-
class FileRunHandle {
|
|
29
|
-
/** Take ownership only after initial publication; initialization retains rollback responsibility. */
|
|
30
|
-
constructor({ identity, path, lock, manifest, journal }) {
|
|
31
|
-
this.identity = identity;
|
|
32
|
-
this.path = path;
|
|
33
|
-
this.lock = lock;
|
|
34
|
-
this.manifest = manifest;
|
|
35
|
-
this.journal = journal;
|
|
36
|
-
}
|
|
37
|
-
/** completeRun awaits both publications before returning the body result to workflow.
|
|
38
|
-
* The manifest comes last so it refers to an already published result. */
|
|
39
|
-
async finish(status, result) {
|
|
40
|
-
await this.updateManifest(async () => {
|
|
41
|
-
await atomicPublish(join(this.path, 'result.json'), result);
|
|
42
|
-
await this.publishManifest({ status, resultDigest: digest(result), failure: null });
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
/** abortRun awaits this after draining. Replay treats the failed manifest as authoritative
|
|
46
|
-
* even if finish left an earlier result file. */
|
|
47
|
-
async abort(failure) {
|
|
48
|
-
await this.updateManifest(async () => {
|
|
49
|
-
await this.publishManifest({ status: 'failed', resultDigest: null, failure });
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
/** workflow awaits this in finally and records any rejection as a storage failure.
|
|
53
|
-
* A failed publication already reached finish or abort, so proceed with lock release. */
|
|
54
|
-
async close() {
|
|
55
|
-
if (this.closed)
|
|
56
|
-
return;
|
|
57
|
-
try {
|
|
58
|
-
await this.manifestQueue.catch(() => { });
|
|
59
|
-
await releaseLock(join(this.path, 'writer.lock'), this.lock);
|
|
60
|
-
}
|
|
61
|
-
catch (cause) {
|
|
62
|
-
throw storageError(cause);
|
|
63
|
-
}
|
|
64
|
-
finally {
|
|
65
|
-
this.closed = true;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
identity;
|
|
69
|
-
journal;
|
|
70
|
-
closed = false;
|
|
71
|
-
manifestQueue = Promise.resolve();
|
|
72
|
-
path;
|
|
73
|
-
lock;
|
|
74
|
-
manifest;
|
|
75
|
-
/** Run finish/abort's publication callback in order, checking closure when it actually starts.
|
|
76
|
-
* A rejected predecessor does not poison later abort publication; non-SDK failures are normalized. */
|
|
77
|
-
updateManifest(update) {
|
|
78
|
-
const next = this.manifestQueue.catch(() => { }).then(async () => {
|
|
79
|
-
if (this.closed)
|
|
80
|
-
throw new HarnessSdkError('WORKFLOW_CLOSED');
|
|
81
|
-
try {
|
|
82
|
-
await update();
|
|
83
|
-
}
|
|
84
|
-
catch (cause) {
|
|
85
|
-
throw storageError(cause);
|
|
86
|
-
}
|
|
87
|
-
});
|
|
88
|
-
this.manifestQueue = next;
|
|
89
|
-
return next;
|
|
90
|
-
}
|
|
91
|
-
/** Recompute the digest from payload only for every terminal transition, then publish it.
|
|
92
|
-
* Keep the in-memory transition even if publication rejects, as abort may follow a failed finish. */
|
|
93
|
-
async publishManifest(update) {
|
|
94
|
-
const { recordDigest: _, ...payload } = this.manifest;
|
|
95
|
-
this.manifest = record({ ...payload, ...update });
|
|
96
|
-
await atomicPublish(join(this.path, 'run.json'), this.manifest);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
/** Throw INVALID_PARAMS for malformed target identity before copying input or touching storage. */
|
|
100
|
-
function validateRunOptions(options) {
|
|
101
|
-
if (!runIdSchema.safeParse(options.runId).success || typeof options.name !== 'string' || !options.name
|
|
102
|
-
|| typeof options.revision !== 'string' || !options.revision || typeof options.directory !== 'string' || !options.directory) {
|
|
103
|
-
throw new HarnessSdkError('INVALID_PARAMS');
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
/** Snapshot input, resolve parent/source paths, and create a real target directory before locking.
|
|
107
|
-
* Flush the parent when creating the target. Initialization checks existing contents under the lock. */
|
|
108
|
-
async function prepareRunStorage(options) {
|
|
109
|
-
const input = jsonCopy(options.input);
|
|
110
|
-
await mkdir(resolve(options.directory), { recursive: true, mode: 0o700 });
|
|
111
|
-
const directory = await realpath(resolve(options.directory));
|
|
112
|
-
const path = join(directory, options.runId);
|
|
113
|
-
const source = await resolveSourceRun({ options, directory, path });
|
|
114
|
-
try {
|
|
115
|
-
await mkdir(path, { mode: 0o700 });
|
|
116
|
-
await syncDirectory(directory);
|
|
117
|
-
}
|
|
118
|
-
catch (cause) {
|
|
119
|
-
if (cause.code !== 'EEXIST')
|
|
120
|
-
throw cause;
|
|
121
|
-
}
|
|
122
|
-
if (!(await lstat(path)).isDirectory())
|
|
123
|
-
invalidCheckpoint();
|
|
124
|
-
return { directory, path, input, source };
|
|
125
|
-
}
|
|
126
|
-
/** Resolve optional replay coordinates before target creation so overlapping source/target trees
|
|
127
|
-
* reject before a writer claim. Omission selects fresh execution. A string uses the target's
|
|
128
|
-
* canonical parent, while an object supplies its own parent to resolve. */
|
|
129
|
-
async function resolveSourceRun({ options, directory, path }) {
|
|
130
|
-
if (options.resumeFrom === undefined)
|
|
131
|
-
return null;
|
|
132
|
-
const reference = typeof options.resumeFrom === 'string'
|
|
133
|
-
? { directory, runId: options.resumeFrom } : options.resumeFrom;
|
|
134
|
-
if (!reference || !runIdSchema.safeParse(reference.runId).success || typeof reference.directory !== 'string') {
|
|
135
|
-
throw new HarnessSdkError('INVALID_PARAMS');
|
|
136
|
-
}
|
|
137
|
-
const source = { directory: await realpath(resolve(reference.directory)), runId: reference.runId };
|
|
138
|
-
if (overlaps(path, join(source.directory, source.runId)))
|
|
139
|
-
throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS');
|
|
140
|
-
return source;
|
|
141
|
-
}
|
|
142
|
-
/** Exclusively claim and initialize the lock before inspecting target contents or source records.
|
|
143
|
-
* Transfer ownership only on successful publication; rollback also covers partial lock writes.
|
|
144
|
-
* Cleanup failure takes precedence as WORKFLOW_STORAGE_FAILED; other failures reach openFileRun. */
|
|
145
|
-
async function initializeLockedRun({ options, prepared }) {
|
|
146
|
-
const lockPath = join(prepared.path, 'writer.lock');
|
|
147
|
-
const lock = await open(lockPath, 'wx', 0o600).catch(cause => {
|
|
148
|
-
if (cause.code === 'EEXIST')
|
|
149
|
-
throw new HarnessSdkError('WORKFLOW_RUN_EXISTS');
|
|
150
|
-
throw cause;
|
|
151
|
-
});
|
|
152
|
-
try {
|
|
153
|
-
await writeWriterClaim(lock);
|
|
154
|
-
if ((await readdir(prepared.path)).some(name => name !== 'writer.lock')) {
|
|
155
|
-
throw new HarnessSdkError('WORKFLOW_RUN_EXISTS');
|
|
156
|
-
}
|
|
157
|
-
return await publishInitialRun({ options, prepared, lock });
|
|
158
|
-
}
|
|
159
|
-
catch (cause) {
|
|
160
|
-
try {
|
|
161
|
-
await releaseLock(lockPath, lock);
|
|
162
|
-
}
|
|
163
|
-
catch {
|
|
164
|
-
throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED');
|
|
165
|
-
}
|
|
166
|
-
throw cause;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
/** Write and flush the claim on the exclusively opened descriptor. Replay validates this
|
|
170
|
-
* record before probing its writer, and initializeLockedRun owns rollback on rejection. */
|
|
171
|
-
async function writeWriterClaim(lock) {
|
|
172
|
-
const claim = record({
|
|
173
|
-
checkpointFormatVersion: 2,
|
|
174
|
-
token: randomUUID(),
|
|
175
|
-
hostname: hostname(),
|
|
176
|
-
pid: process.pid,
|
|
177
|
-
createdAt: new Date().toISOString(),
|
|
178
|
-
});
|
|
179
|
-
await lock.writeFile(`${canonicalJson(claim)}\n`);
|
|
180
|
-
await lock.sync();
|
|
181
|
-
}
|
|
182
|
-
/** Validate replay under the target lock, publish a self-contained journal before its manifest,
|
|
183
|
-
* then hand the descriptor to FileRunHandle. Failures leave lock cleanup to initializeLockedRun. */
|
|
184
|
-
async function publishInitialRun({ options, prepared, lock }) {
|
|
185
|
-
const { directory, path, input, source } = prepared;
|
|
186
|
-
const inherited = source
|
|
187
|
-
? await loadSourceJournal(join(source.directory, source.runId), {
|
|
188
|
-
name: options.name, revision: options.revision, runId: source.runId,
|
|
189
|
-
})
|
|
190
|
-
: [];
|
|
191
|
-
const journalPath = join(path, 'journal.json');
|
|
192
|
-
const journal = new AgentJournal(journalPath, inherited);
|
|
193
|
-
await atomicPublish(journalPath, [...inherited]);
|
|
194
|
-
const identity = { runId: options.runId, directory, name: options.name, revision: options.revision, input };
|
|
195
|
-
const manifest = record({
|
|
196
|
-
checkpointFormatVersion: 2,
|
|
197
|
-
identity,
|
|
198
|
-
createdAt: new Date().toISOString(),
|
|
199
|
-
resumedFrom: source,
|
|
200
|
-
status: 'running',
|
|
201
|
-
resultDigest: null,
|
|
202
|
-
failure: null,
|
|
203
|
-
});
|
|
204
|
-
await atomicPublish(join(path, 'run.json'), manifest);
|
|
205
|
-
return new FileRunHandle({ identity, path, lock, manifest, journal });
|
|
206
|
-
}
|
|
207
|
-
/** Preserve deliberate SDK failures while hiding filesystem-specific errors from workflow consumers. */
|
|
208
|
-
function storageError(cause) {
|
|
209
|
-
if (cause instanceof HarnessSdkError)
|
|
210
|
-
return cause;
|
|
211
|
-
return new HarnessSdkError('WORKFLOW_STORAGE_FAILED');
|
|
212
|
-
}
|
|
213
|
-
/** Detect equal or nested run trees in either direction. resolveSourceRun uses canonical
|
|
214
|
-
* parent directories so writes cannot overlap the selected source tree. */
|
|
215
|
-
function overlaps(a, b) {
|
|
216
|
-
const inside = (parent, child) => {
|
|
217
|
-
const path = relative(parent, child);
|
|
218
|
-
return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));
|
|
219
|
-
};
|
|
220
|
-
return inside(a, b) || inside(b, a);
|
|
221
|
-
}
|
|
222
|
-
/** Compare the on-disk entry with the held descriptor before unlinking, so rollback also works
|
|
223
|
-
* for a partially written lock. Flush the parent after unlinking and always close the descriptor.
|
|
224
|
-
* An observed inode or file kind mismatch rejects as WORKFLOW_LOCK_OWNERSHIP_LOST. */
|
|
225
|
-
async function releaseLock(path, handle) {
|
|
226
|
-
try {
|
|
227
|
-
const held = await handle.stat();
|
|
228
|
-
const actual = await lstat(path);
|
|
229
|
-
if (actual.dev !== held.dev || actual.ino !== held.ino || !actual.isFile()) {
|
|
230
|
-
throw new HarnessSdkError('WORKFLOW_LOCK_OWNERSHIP_LOST');
|
|
231
|
-
}
|
|
232
|
-
await unlink(path);
|
|
233
|
-
await syncDirectory(dirname(path));
|
|
234
|
-
}
|
|
235
|
-
finally {
|
|
236
|
-
await handle.close();
|
|
237
|
-
}
|
|
238
|
-
}
|
package/src/pipeline.d.ts
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Run each input through sequential stages, letting items advance independently without a stage barrier.
|
|
3
|
-
* Each stage receives the awaited input or prior result, the original unawaited input entry and its
|
|
4
|
-
* zero-based index. Inline stages infer their input types through six stages. Longer chains can
|
|
5
|
-
* use typed functions that accept the preceding stage's awaited, non-null result.
|
|
6
|
-
*
|
|
7
|
-
* The promise resolves after all item chains settle and returns their final values in input order.
|
|
8
|
-
* A null input or stage result skips the remaining stages for that item. A rejected input, thrown
|
|
9
|
-
* stage error or rejected stage result also skips the remaining stages and yields null for that item.
|
|
10
|
-
* Sibling chains continue after a failure. Other falsy values advance normally. With zero stages,
|
|
11
|
-
* return awaited inputs with rejections as null.
|
|
12
|
-
*
|
|
13
|
-
* Handle input and stage failures before they reach the pipeline if you need the original cause.
|
|
14
|
-
* Arrange any concurrency limits, cancellation, retries and resource cleanup for input work and stages.
|
|
15
|
-
*
|
|
16
|
-
* A non-array input rejects with TypeError. The function snapshots the array and resolves to []
|
|
17
|
-
* for an empty snapshot. For nonempty input, a non-function stage rejects with TypeError before
|
|
18
|
-
* item processing starts.
|
|
19
|
-
*/
|
|
20
|
-
export declare function pipeline<Input>(items: readonly Input[]): Promise<(Awaited<Input> | null)[]>;
|
|
21
|
-
export declare function pipeline<A, B>(items: readonly A[], first: Stage<A, A, B>): Promise<(Awaited<B> | null)[]>;
|
|
22
|
-
export declare function pipeline<A, B, C>(items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>): Promise<(Awaited<C> | null)[]>;
|
|
23
|
-
export declare function pipeline<A, B, C, D>(items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>, third: Stage<C, A, D>): Promise<(Awaited<D> | null)[]>;
|
|
24
|
-
export declare function pipeline<A, B, C, D, E>(items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>, third: Stage<C, A, D>, fourth: Stage<D, A, E>): Promise<(Awaited<E> | null)[]>;
|
|
25
|
-
export declare function pipeline<A, B, C, D, E, F>(items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>, third: Stage<C, A, D>, fourth: Stage<D, A, E>, fifth: Stage<E, A, F>): Promise<(Awaited<F> | null)[]>;
|
|
26
|
-
export declare function pipeline<A, B, C, D, E, F, G>(items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>, third: Stage<C, A, D>, fourth: Stage<D, A, E>, fifth: Stage<E, A, F>, sixth: Stage<F, A, G>): Promise<(Awaited<G> | null)[]>;
|
|
27
|
-
/** Use a chain of typed stages of any length, with each stage checked against its predecessor. */
|
|
28
|
-
export declare function pipeline<Input, Outputs extends readonly unknown[]>(items: readonly Input[], ...stages: Stages<Input, Outputs> & {
|
|
29
|
-
0: Stage<Input, Input, unknown>;
|
|
30
|
-
}): Promise<(LastAwaitedOutput<Outputs> | null)[]>;
|
|
31
|
-
/** Align each stage with its predecessor's output by prepending the original input type. */
|
|
32
|
-
type PreviousStageOutput<Input, Outputs extends readonly unknown[], K> = K extends '0' ? Input : [Input, ...Outputs][K & keyof [Input, ...Outputs]];
|
|
33
|
-
/** Check each variadic stage against the preceding output while retaining the original input context. */
|
|
34
|
-
type Stages<Input, Outputs extends readonly unknown[]> = {
|
|
35
|
-
[K in keyof Outputs]: Stage<PreviousStageOutput<Input, Outputs, K>, Input, Outputs[K]>;
|
|
36
|
-
};
|
|
37
|
-
/** Infer the pipeline's resolved value type from the final stage of a typed chain. */
|
|
38
|
-
type LastAwaitedOutput<Outputs extends readonly unknown[]> = Outputs extends readonly [...unknown[], infer Output] ? Awaited<Output> : never;
|
|
39
|
-
/** Exclude only null from a stage's awaited input because null short-circuits the item at runtime. */
|
|
40
|
-
type Stage<Previous, Input, Output> = (value: Exclude<Awaited<Previous>, null>, originalItem: Input, index: number) => Output;
|
|
41
|
-
export {};
|
package/src/pipeline.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
export async function pipeline(items, ...stages) {
|
|
2
|
-
if (!Array.isArray(items))
|
|
3
|
-
throw new TypeError('pipeline expects an array as the first argument');
|
|
4
|
-
const inputs = [...items];
|
|
5
|
-
if (!inputs.length)
|
|
6
|
-
return [];
|
|
7
|
-
if (stages.some(stage => typeof stage !== 'function'))
|
|
8
|
-
throw new TypeError('pipeline stages must be functions');
|
|
9
|
-
// The overloads check compatibility between adjacent stages. The runner only needs their order.
|
|
10
|
-
const itemStages = stages;
|
|
11
|
-
const results = await Promise.allSettled(inputs.map((originalItem, index) => runItem(originalItem, index, itemStages)));
|
|
12
|
-
return results.map(result => result.status === 'fulfilled' ? result.value : null);
|
|
13
|
-
}
|
|
14
|
-
/** Run one item chain with its original entry and index. A null value ends the chain early.
|
|
15
|
-
* Input and stage errors reject the chain so pipeline can preserve its slot as null. */
|
|
16
|
-
async function runItem(originalItem, index, stages) {
|
|
17
|
-
let value = await originalItem;
|
|
18
|
-
for (const stage of stages) {
|
|
19
|
-
if (value === null)
|
|
20
|
-
break;
|
|
21
|
-
value = await stage(value, originalItem, index);
|
|
22
|
-
}
|
|
23
|
-
return value;
|
|
24
|
-
}
|
package/src/run-context.d.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { AgentJournal } from "./persistence/journal.js";
|
|
2
|
-
import type { RunState } from "./workflow-state.js";
|
|
3
|
-
/** Internal run context installed for the workflow body and inherited by agent calls. */
|
|
4
|
-
export interface RunContext {
|
|
5
|
-
/** Source replay and target journal used by memoizedAgent. */
|
|
6
|
-
readonly journal: AgentJournal;
|
|
7
|
-
/** Admission, pending work and failure state shared with workflow. */
|
|
8
|
-
readonly state: RunState;
|
|
9
|
-
}
|
|
10
|
-
/** Invoke completeRun's body callback with context inherited by asynchronous descendants.
|
|
11
|
-
* Return the callback's promise or propagate a synchronous throw. The calling context is
|
|
12
|
-
* restored when the callback returns or throws, while completeRun owns the subsequent drain. */
|
|
13
|
-
export declare function runWith<T>(context: RunContext, body: () => Promise<T>): Promise<T>;
|
|
14
|
-
/** Read the current async context so agent can choose journaled or ordinary execution.
|
|
15
|
-
* Async descendants can retain a closed context. RunState.track then rejects admission. */
|
|
16
|
-
export declare function currentRun(): RunContext | undefined;
|
package/src/run-context.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
-
/** Invoke completeRun's body callback with context inherited by asynchronous descendants.
|
|
3
|
-
* Return the callback's promise or propagate a synchronous throw. The calling context is
|
|
4
|
-
* restored when the callback returns or throws, while completeRun owns the subsequent drain. */
|
|
5
|
-
export function runWith(context, body) {
|
|
6
|
-
return storage.run(context, body);
|
|
7
|
-
}
|
|
8
|
-
/** Read the current async context so agent can choose journaled or ordinary execution.
|
|
9
|
-
* Async descendants can retain a closed context. RunState.track then rejects admission. */
|
|
10
|
-
export function currentRun() {
|
|
11
|
-
return storage.getStore();
|
|
12
|
-
}
|
|
13
|
-
const storage = new AsyncLocalStorage();
|
package/src/test-helpers.d.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { type Client } from '@anureo/sdk';
|
|
2
|
-
import { type FakeAdapterOptions } from '@anureo/conformance';
|
|
3
|
-
/**
|
|
4
|
-
* Give the agent and workflow suites a factory for initialized scripted clients. Register each
|
|
5
|
-
* successful client for the suite's afterEach disposal. Initialization failures reject without
|
|
6
|
-
* adding a client to the registry.
|
|
7
|
-
*/
|
|
8
|
-
export declare function createFixture(clients: Client[]): (options?: FakeAdapterOptions) => Promise<{
|
|
9
|
-
client: Client;
|
|
10
|
-
adapter: import("@anureo/conformance").ScriptedHarnessAdapter;
|
|
11
|
-
}>;
|