@anureo/workflow 0.0.0-stage → 0.3.0
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/LICENSE +201 -0
- package/README.md +172 -2
- package/package.json +36 -4
- package/src/agent-outcome.d.ts +15 -0
- package/src/agent-outcome.js +28 -0
- package/src/agent.d.ts +49 -0
- package/src/agent.js +206 -0
- package/src/index.d.ts +6 -0
- package/src/index.js +5 -0
- package/src/output-schema.d.ts +27 -0
- package/src/output-schema.js +192 -0
- package/src/parallel.d.ts +18 -0
- package/src/parallel.js +25 -0
- package/src/persistence/atomic.d.ts +9 -0
- package/src/persistence/atomic.js +48 -0
- package/src/persistence/journal.d.ts +54 -0
- package/src/persistence/journal.js +106 -0
- package/src/persistence/json.d.ts +17 -0
- package/src/persistence/json.js +75 -0
- package/src/persistence/read-json.d.ts +11 -0
- package/src/persistence/read-json.js +46 -0
- package/src/persistence/records.d.ts +92 -0
- package/src/persistence/records.js +70 -0
- package/src/persistence/replay.d.ts +11 -0
- package/src/persistence/replay.js +79 -0
- package/src/persistence/store.d.ts +45 -0
- package/src/persistence/store.js +238 -0
- package/src/pipeline.d.ts +41 -0
- package/src/pipeline.js +24 -0
- package/src/run-context.d.ts +16 -0
- package/src/run-context.js +13 -0
- package/src/test-helpers.d.ts +11 -0
- package/src/test-helpers.js +21 -0
- package/src/workflow-state.d.ts +44 -0
- package/src/workflow-state.js +96 -0
- package/src/workflow-types.d.ts +39 -0
- package/src/workflow-types.js +0 -0
- package/src/workflow.d.ts +17 -0
- package/src/workflow.js +104 -0
package/src/agent.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { JsonObject } from '@anureo/protocol';
|
|
3
|
+
/** Package-internal schema and parser for agent execution and journal replay. */
|
|
4
|
+
export interface AgentOutputSchema<S extends z.ZodObject = z.ZodObject> {
|
|
5
|
+
/** Closed draft-07 object schema for submission, JSON-text fallback prompts and journal cache keys. */
|
|
6
|
+
schema: JsonObject;
|
|
7
|
+
/**
|
|
8
|
+
* Validate a complete JSON object before Zod can strip extra fields or fill omitted fields.
|
|
9
|
+
* Resolve with the typed value after local Zod checks, including async refinements.
|
|
10
|
+
* Blank text, malformed JSON and schema mismatches reject with AGENT_STRUCTURED_OUTPUT_MISSING,
|
|
11
|
+
* AGENT_STRUCTURED_OUTPUT_NOT_JSON and AGENT_STRUCTURED_OUTPUT_INVALID, respectively. Exceptions
|
|
12
|
+
* from Zod reject with AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED and omit the original cause.
|
|
13
|
+
* observeAgentTurn awaits this parser for completed turns and retains failures for settlement
|
|
14
|
+
* after session cleanup. memoizedAgent returns this promise for typed cache hits without opening
|
|
15
|
+
* a session.
|
|
16
|
+
*/
|
|
17
|
+
parse(text: string): Promise<z.output<S>>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Compile a Zod object into a draft-07 schema and a parser for the same output type.
|
|
21
|
+
* Require closed objects and required JSON fields. Reject conversion schemas. JSON-compatible
|
|
22
|
+
* defaults may be declared, and raw validation still requires their fields. Unsupported or
|
|
23
|
+
* unrepresentable schemas synchronously throw INVALID_PARAMS with a safe rule code.
|
|
24
|
+
* executeAgent prepares the pair before acquiring its session and passes it to observeAgentTurn.
|
|
25
|
+
* memoizedAgent prepares it before deriving the journal key and uses the parser on typed hits.
|
|
26
|
+
*/
|
|
27
|
+
export declare function prepareOutputSchema<S extends z.ZodObject>(source: S): AgentOutputSchema<S>;
|
|
@@ -0,0 +1,192 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
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>;
|
|
@@ -0,0 +1,48 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
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;
|