Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 58 additions & 12 deletions src/workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,19 @@ export async function runWorkflow<T = unknown>(
Math.min(options.concurrency ?? Math.max(1, (globalThis.navigator?.hardwareConcurrency ?? 8) - 2), 16),
);
const limiter = createLimiter(concurrency);
const pendingAgentRuns = new Set<Promise<unknown>>();

const log = (message: string) => {
const text = String(message);
state.logs.push(text);
options.onLog?.(text);
};

const phase = (title: string) => {
state.currentPhase = title;
if (!state.phases.includes(title)) state.phases.push(title);
options.onPhase?.(title);
const phase = (title: unknown) => {
const text = requireString(title, "phase title");
state.currentPhase = text;
if (!state.phases.includes(text)) state.phases.push(text);
options.onPhase?.(text);
};

const budget = Object.freeze({
Expand All @@ -95,22 +97,24 @@ export async function runWorkflow<T = unknown>(
if (options.signal?.aborted) throw new Error("workflow aborted");
};

const agent = async (prompt: string, agentOptions: AgentOptions = {}) => {
const agent = async (prompt: unknown, agentOptions: unknown = {}) => {
throwIfAborted();
if (budget.total !== null && budget.remaining() <= 0) throw new Error("workflow token budget exhausted");
const assignedPhase = agentOptions.phase ?? state.currentPhase;
const requestedLabel = agentOptions.label?.trim();
return limiter(async () => {
const taskPrompt = requireString(prompt, "agent prompt");
const normalizedOptions = normalizeAgentOptions(agentOptions);
const assignedPhase = normalizedOptions.phase ?? state.currentPhase;
const requestedLabel = normalizedOptions.label?.trim();
const run = limiter(async () => {
state.agentCount++;
const label = requestedLabel || defaultAgentLabel(assignedPhase, state.agentCount);
options.onAgentStart?.({ label, phase: assignedPhase, prompt });
options.onAgentStart?.({ label, phase: assignedPhase, prompt: taskPrompt });
try {
throwIfAborted();
const result = await agentRunner.run(prompt, {
const result = await agentRunner.run(taskPrompt, {
label,
schema: agentOptions.schema,
schema: normalizedOptions.schema,
signal: options.signal,
instructions: buildAgentInstructions(assignedPhase, agentOptions),
instructions: buildAgentInstructions(assignedPhase, normalizedOptions),
} as any);
throwIfAborted();
state.spent += estimateTokens(result);
Expand All @@ -123,6 +127,12 @@ export async function runWorkflow<T = unknown>(
return null;
}
});
pendingAgentRuns.add(run);
run.then(
() => pendingAgentRuns.delete(run),
() => pendingAgentRuns.delete(run),
);
return run;
};

const parallel = async (thunks: Array<() => Promise<unknown>>) => {
Expand Down Expand Up @@ -202,6 +212,8 @@ export async function runWorkflow<T = unknown>(

const wrapped = `(async () => {\n${body}\n})()`;
const result = await new vm.Script(wrapped, { filename: `${meta.name || "workflow"}.js` }).runInContext(context);
await Promise.allSettled([...pendingAgentRuns]);
assertStructuredCloneable(result, "workflow result");
return {
meta,
result: result as T,
Expand Down Expand Up @@ -334,6 +346,40 @@ function createLimiter(limit: number) {
};
}

function requireString(value: unknown, name: string): string {
if (typeof value !== "string") throw new TypeError(`${name} must be a string`);
return value;
}

function optionalString(value: unknown, name: string): string | undefined {
if (value === undefined) return undefined;
return requireString(value, name);
}

function normalizeAgentOptions(value: unknown): AgentOptions {
if (!value || typeof value !== "object") throw new TypeError("agent options must be an object");
const options = value as AgentOptions;
return {
...options,
label: optionalString(options.label, "agent label"),
phase: optionalString(options.phase, "agent phase"),
model: optionalString(options.model, "agent model"),
isolation: options.isolation,
agentType: optionalString(options.agentType, "agent type"),
};
}

function assertStructuredCloneable(value: unknown, name: string): void {
try {
structuredClone(value);
} catch (error) {
const detail = error instanceof Error ? ` ${error.message}` : "";
throw new Error(
`${name} must be structured-cloneable; did you forget to await agent(), parallel(), or pipeline()?${detail}`,
);
}
}

function defaultAgentLabel(phase: string | undefined, index: number): string {
return phase ? `${phase} agent ${index}` : `agent ${index}`;
}
Expand Down
46 changes: 46 additions & 0 deletions tests/workflow-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,49 @@ return { ok: true }
assert.deepEqual(result.phases, ["Inspect API", "Inspect UI"]);
assert.equal(result.agentCount, 2);
});

test("runWorkflow rejects unawaited nested agent promises before returning details", async () => {
let ended = 0;

await assert.rejects(
() =>
runWorkflow(
`export const meta = {
name: 'promise_leak',
description: 'Return an unawaited agent promise'
}

phase('Leak promise')
const scan = agent('scan', { label: 'scan' })
return { scan }
`,
{
agent: fakeAgent,
onAgentEnd() {
ended++;
},
},
),
/workflow result must be structured-cloneable; did you forget to await agent\(\), parallel\(\), or pipeline\(\)\?.*Promise.*cloned/,
);

assert.equal(ended, 1);
});

test("runWorkflow rejects non-string runtime phase titles", async () => {
await assert.rejects(
() =>
runWorkflow(
`export const meta = {
name: 'bad_phase',
description: 'Use a non-string phase title'
}

phase(Promise.resolve('Scan'))
return { ok: true }
`,
{ agent: fakeAgent },
),
/phase title must be a string/,
);
});
Loading