Merge ticket/t3-dag-runs: execute workflow plans as DAG jobs
This commit is contained in:
commit
b09c649604
13 files changed
+1100
-64
No files matched your search
+10
-1
@@ -2,6 +2,10 @@ import { formatUsageStats } from "./render.ts";
|
||||
import type { JobSnapshot, TaskSnapshot } from "./types.ts";
|
||||
|
||||
function taskOutput(task: TaskSnapshot): string {
|
||||
if (task.status === "skipped") {
|
||||
const reason = task.errorMessage?.replace(/^Skipped because /, "");
|
||||
return reason ? `(skipped: ${reason})` : "(skipped)";
|
||||
}
|
||||
if (task.errorMessage) return `Error: ${task.errorMessage}${task.output ? `\n\n${task.output}` : ""}`;
|
||||
if (task.output) return task.output;
|
||||
if (task.stderr) return task.stderr;
|
||||
@@ -16,7 +20,12 @@ export function formatJob(job: JobSnapshot): string {
|
||||
];
|
||||
if (job.errorMessage) lines.push(`Job error: ${job.errorMessage}`);
|
||||
for (const [index, task] of job.results.entries()) {
|
||||
const label = job.mode === "chain" ? `Step ${task.step ?? index + 1}` : `Task ${index + 1}`;
|
||||
const label =
|
||||
job.mode === "chain"
|
||||
? `Step ${task.step ?? index + 1}`
|
||||
: job.mode === "workflow"
|
||||
? `Step ${task.stepId ?? index + 1}`
|
||||
: `Task ${index + 1}`;
|
||||
lines.push("", `### ${label}: ${task.agent} — ${task.status}`);
|
||||
lines.push(`Task: ${task.task}`);
|
||||
lines.push(taskOutput(task));
|
||||
|
||||
+192
-1
@@ -2,6 +2,7 @@ import { truncateUtf8Head } from "./output.ts";
|
||||
import {
|
||||
emptyUsage,
|
||||
isTerminalJob,
|
||||
isTerminalTask,
|
||||
type InvocationMode,
|
||||
type JobSnapshot,
|
||||
type JobStatus,
|
||||
@@ -16,6 +17,13 @@ import {
|
||||
type SyncOutcome,
|
||||
type SyncRunOptions,
|
||||
} from "./types.ts";
|
||||
import {
|
||||
interpolateWorkflowTask,
|
||||
workflowRunConcurrency,
|
||||
type PreparedWorkflowInvocation,
|
||||
type WorkflowRunSpec,
|
||||
type WorkflowStartResult,
|
||||
} from "./workflow.ts";
|
||||
|
||||
const DEFAULT_MAX_WORKERS = 4;
|
||||
const DEFAULT_MAX_ACTIVE_JOBS = 64;
|
||||
@@ -29,6 +37,8 @@ interface InternalTask {
|
||||
snapshot: TaskSnapshot;
|
||||
controller?: AbortController;
|
||||
result?: RunResult;
|
||||
/** A workflow step submitted to the FIFO, whether or not a worker picked it up yet. */
|
||||
submitted?: boolean;
|
||||
}
|
||||
|
||||
interface Execution {
|
||||
@@ -43,6 +53,7 @@ interface Execution {
|
||||
errorMessage?: string;
|
||||
isAsync: boolean;
|
||||
cancelRequested: boolean;
|
||||
workflow?: WorkflowRunSpec;
|
||||
onUpdate?: (outcome: SyncOutcome) => void;
|
||||
completion?: Promise<unknown>;
|
||||
}
|
||||
@@ -73,6 +84,7 @@ function initialTask(prepared: PreparedTask, now: number): InternalTask {
|
||||
task: prepared.task,
|
||||
cwd: prepared.cwd,
|
||||
step: prepared.step,
|
||||
stepId: prepared.stepId,
|
||||
status: "queued",
|
||||
exitCode: null,
|
||||
messages: [],
|
||||
@@ -86,6 +98,7 @@ function initialTask(prepared: PreparedTask, now: number): InternalTask {
|
||||
task: prepared.task,
|
||||
cwd: prepared.cwd,
|
||||
step: prepared.step,
|
||||
stepId: prepared.stepId,
|
||||
status: "queued",
|
||||
exitCode: null,
|
||||
output: "",
|
||||
@@ -127,6 +140,25 @@ export class SubagentManager {
|
||||
}
|
||||
|
||||
startAsync(request: PreparedInvocation): JobSnapshot {
|
||||
return this.snapshot(this.startAsyncExecution(request));
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a workflow run. Async-only: the caller gets the run id and the
|
||||
* expanded plan immediately, then uses the ordinary job surface to wait.
|
||||
*/
|
||||
startWorkflow(request: PreparedWorkflowInvocation): WorkflowStartResult {
|
||||
const concurrency = workflowRunConcurrency(this.maxWorkers);
|
||||
if (concurrency < 1) {
|
||||
throw new Error(
|
||||
`Workflow runs require at least 2 workers (the per-run cap is maxWorkers - 1); PI_SUBAGENT_MAX_WORKERS is ${this.maxWorkers}.`,
|
||||
);
|
||||
}
|
||||
const execution = this.startAsyncExecution(request);
|
||||
return { id: execution.id, job: this.snapshot(execution), plan: request.workflow.expandedPlan };
|
||||
}
|
||||
|
||||
private startAsyncExecution(request: PreparedInvocation): Execution {
|
||||
if (!this.accepting) throw new Error("Subagent manager is shutting down");
|
||||
const active = Array.from(this.jobs.values()).filter((job) => job.isAsync && !isTerminalJob(job.status)).length;
|
||||
if (active >= this.maxActiveJobs) throw new Error(`Too many active async jobs (${active}); maximum is ${this.maxActiveJobs}`);
|
||||
@@ -135,7 +167,7 @@ export class SubagentManager {
|
||||
execution.errorMessage = error instanceof Error ? error.message : String(error);
|
||||
this.finalize(execution, "failed");
|
||||
});
|
||||
return this.snapshot(execution);
|
||||
return execution;
|
||||
}
|
||||
|
||||
async runSync(request: PreparedInvocation, options: SyncRunOptions = {}): Promise<SyncOutcome> {
|
||||
@@ -226,6 +258,7 @@ export class SubagentManager {
|
||||
task: result.task,
|
||||
cwd: result.cwd,
|
||||
step: result.step,
|
||||
stepId: result.stepId,
|
||||
};
|
||||
const task = initialTask(prepared, this.now());
|
||||
task.snapshot = structuredClone(result);
|
||||
@@ -330,6 +363,16 @@ export class SubagentManager {
|
||||
scheduled.task.result = this.cancelledResult(scheduled.task);
|
||||
scheduled.resolve(scheduled.task.result);
|
||||
}
|
||||
if (execution.request.mode === "workflow") {
|
||||
// Steps held back by the DAG or the run cap were never submitted to
|
||||
// the FIFO; cancellation is still terminal for every one of them.
|
||||
for (const task of execution.tasks) {
|
||||
if (task.snapshot.status !== "queued") continue;
|
||||
task.snapshot.status = "cancelled";
|
||||
task.snapshot.finishedAt = this.now();
|
||||
task.result = this.cancelledResult(task);
|
||||
}
|
||||
}
|
||||
for (const task of execution.tasks) {
|
||||
if (task.snapshot.status === "running") task.controller?.abort();
|
||||
}
|
||||
@@ -345,6 +388,7 @@ export class SubagentManager {
|
||||
task: task.prepared.task,
|
||||
cwd: task.prepared.cwd,
|
||||
step: task.prepared.step,
|
||||
stepId: task.prepared.stepId,
|
||||
exitCode: null,
|
||||
messages: [],
|
||||
output: "",
|
||||
@@ -368,6 +412,9 @@ export class SubagentManager {
|
||||
isAsync,
|
||||
cancelRequested: false,
|
||||
};
|
||||
if (request.mode === "workflow") {
|
||||
execution.workflow = (request as PreparedWorkflowInvocation).workflow;
|
||||
}
|
||||
this.activeExecutions.add(execution);
|
||||
if (isAsync) {
|
||||
this.jobs.set(id, execution);
|
||||
@@ -387,6 +434,10 @@ export class SubagentManager {
|
||||
this.finalize(execution, results.some(failed) ? "failed" : "succeeded");
|
||||
return;
|
||||
}
|
||||
if (execution.request.mode === "workflow") {
|
||||
await this.executeWorkflow(execution);
|
||||
return;
|
||||
}
|
||||
let previous = "";
|
||||
for (let index = 0; index < execution.request.tasks.length; index++) {
|
||||
if (index > 0) {
|
||||
@@ -410,6 +461,143 @@ export class SubagentManager {
|
||||
this.finalize(execution, "succeeded");
|
||||
}
|
||||
|
||||
private async executeWorkflow(execution: Execution): Promise<void> {
|
||||
const spec = execution.workflow;
|
||||
if (!spec) {
|
||||
execution.errorMessage = "Workflow run is missing its plan";
|
||||
this.finalize(execution, "failed");
|
||||
return;
|
||||
}
|
||||
|
||||
const taskByStep = new Map<string, InternalTask>();
|
||||
for (const task of execution.tasks) {
|
||||
if (task.prepared.stepId) taskByStep.set(task.prepared.stepId, task);
|
||||
}
|
||||
const concurrency = workflowRunConcurrency(this.maxWorkers);
|
||||
const inFlight = new Map<string, Promise<void>>();
|
||||
|
||||
while (true) {
|
||||
for (const [stepId] of inFlight) {
|
||||
const task = taskByStep.get(stepId);
|
||||
if (!task || isTerminalTask(task.snapshot.status)) inFlight.delete(stepId);
|
||||
}
|
||||
|
||||
if (isTerminalJob(execution.status)) return;
|
||||
if (execution.cancelRequested) {
|
||||
if (inFlight.size === 0) {
|
||||
this.finalize(execution, "cancelled");
|
||||
return;
|
||||
}
|
||||
await Promise.race(inFlight.values());
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.propagateWorkflowSkips(execution, spec, taskByStep)) this.emit(execution);
|
||||
|
||||
if (execution.tasks.every((task) => isTerminalTask(task.snapshot.status))) {
|
||||
const outcome = execution.tasks.some((task) => task.snapshot.status === "failed") ? "failed" : "succeeded";
|
||||
this.finalize(execution, outcome);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.releaseWorkflowSteps(execution, spec, taskByStep, inFlight, concurrency)) this.emit(execution);
|
||||
|
||||
if (inFlight.size === 0) {
|
||||
// A validated DAG plus a complete skip cascade always leaves a
|
||||
// releasable or running step. Failing loudly beats hanging.
|
||||
throw new Error(`Workflow run ${execution.id} stalled with no releasable steps.`);
|
||||
}
|
||||
|
||||
await Promise.race(inFlight.values());
|
||||
}
|
||||
}
|
||||
|
||||
private propagateWorkflowSkips(
|
||||
execution: Execution,
|
||||
spec: WorkflowRunSpec,
|
||||
taskByStep: Map<string, InternalTask>,
|
||||
): boolean {
|
||||
let changed = false;
|
||||
let pass = true;
|
||||
while (pass) {
|
||||
pass = false;
|
||||
for (const step of spec.steps) {
|
||||
const task = taskByStep.get(step.id);
|
||||
if (!task || task.snapshot.status !== "queued" || task.submitted) continue;
|
||||
const deadNeed = step.needs.some((need) => {
|
||||
const needTask = taskByStep.get(need);
|
||||
return Boolean(
|
||||
needTask &&
|
||||
isTerminalTask(needTask.snapshot.status) &&
|
||||
needTask.snapshot.status !== "succeeded",
|
||||
);
|
||||
});
|
||||
if (!deadNeed) continue;
|
||||
const result = this.skippedResult(task);
|
||||
task.snapshot.status = "skipped";
|
||||
task.snapshot.finishedAt = this.now();
|
||||
task.snapshot.errorMessage = result.errorMessage;
|
||||
task.result = result;
|
||||
changed = true;
|
||||
pass = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private releaseWorkflowSteps(
|
||||
execution: Execution,
|
||||
spec: WorkflowRunSpec,
|
||||
taskByStep: Map<string, InternalTask>,
|
||||
inFlight: Map<string, Promise<void>>,
|
||||
concurrency: number,
|
||||
): boolean {
|
||||
let slots = concurrency - inFlight.size;
|
||||
if (slots <= 0) return false;
|
||||
let released = false;
|
||||
|
||||
for (const step of spec.steps) {
|
||||
if (slots <= 0) break;
|
||||
const task = taskByStep.get(step.id);
|
||||
if (!task || task.snapshot.status !== "queued" || task.submitted) continue;
|
||||
const needsSucceeded = step.needs.every(
|
||||
(need) => taskByStep.get(need)?.snapshot.status === "succeeded",
|
||||
);
|
||||
if (!needsSucceeded) continue;
|
||||
|
||||
const outputs = new Map<string, string>();
|
||||
for (const need of step.needs) outputs.set(need, taskByStep.get(need)?.snapshot.output ?? "");
|
||||
const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs });
|
||||
task.prepared = { ...step.prepared, task: brief, stepId: step.id };
|
||||
task.snapshot.task = brief;
|
||||
if (task.result) task.result = { ...task.result, task: brief, stepId: step.id };
|
||||
task.submitted = true;
|
||||
inFlight.set(step.id, this.schedule(execution, task).then(() => undefined));
|
||||
released = true;
|
||||
slots--;
|
||||
}
|
||||
|
||||
return released;
|
||||
}
|
||||
|
||||
private skippedResult(task: InternalTask): RunResult {
|
||||
return {
|
||||
agent: task.prepared.agent.name,
|
||||
agentSource: task.prepared.agent.source,
|
||||
task: task.prepared.task,
|
||||
cwd: task.prepared.cwd,
|
||||
step: task.prepared.step,
|
||||
stepId: task.prepared.stepId,
|
||||
exitCode: null,
|
||||
messages: [],
|
||||
output: "",
|
||||
stderr: "",
|
||||
usage: emptyUsage(),
|
||||
status: "skipped",
|
||||
errorMessage: "Skipped because a required step did not succeed",
|
||||
};
|
||||
}
|
||||
|
||||
private schedule(execution: Execution, task: InternalTask): Promise<RunResult> {
|
||||
return new Promise((resolve) => {
|
||||
this.queue.push({ execution, task, resolve });
|
||||
@@ -469,6 +657,7 @@ export class SubagentManager {
|
||||
task: task.prepared.task,
|
||||
cwd: task.prepared.cwd,
|
||||
step: task.prepared.step,
|
||||
stepId: task.prepared.stepId,
|
||||
exitCode: 1,
|
||||
messages: [],
|
||||
output: "",
|
||||
@@ -486,6 +675,8 @@ export class SubagentManager {
|
||||
|
||||
private applyResult(execution: Execution, task: InternalTask, result: RunResult): void {
|
||||
task.result = execution.isAsync ? { ...result, messages: [] } : result;
|
||||
task.result.step = task.prepared.step;
|
||||
task.result.stepId = task.prepared.stepId;
|
||||
if (task.snapshot.status === "interrupted") {
|
||||
task.result.status = "interrupted";
|
||||
return;
|
||||
|
||||
+3
-2
@@ -16,9 +16,9 @@ function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object";
|
||||
}
|
||||
|
||||
const modes = new Set(["single", "parallel", "chain"]);
|
||||
const modes = new Set(["single", "parallel", "chain", "workflow"]);
|
||||
const jobStatuses = new Set(["queued", "running", "cancelling", "succeeded", "failed", "cancelled", "interrupted"]);
|
||||
const taskStatuses = new Set(["queued", "running", "succeeded", "failed", "cancelled", "interrupted"]);
|
||||
const taskStatuses = new Set(["queued", "running", "succeeded", "failed", "skipped", "cancelled", "interrupted"]);
|
||||
const usageKeys = ["input", "output", "cacheRead", "cacheWrite", "cost", "contextTokens", "turns"] as const;
|
||||
|
||||
function validUsage(value: unknown): boolean {
|
||||
@@ -31,6 +31,7 @@ function validTask(value: unknown): boolean {
|
||||
&& (value.agentSource === "user" || value.agentSource === "project" || value.agentSource === "unknown")
|
||||
&& typeof value.task === "string"
|
||||
&& typeof value.cwd === "string"
|
||||
&& (value.stepId === undefined || typeof value.stepId === "string")
|
||||
&& typeof value.status === "string" && taskStatuses.has(value.status)
|
||||
&& (typeof value.exitCode === "number" || value.exitCode === null)
|
||||
&& typeof value.output === "string"
|
||||
|
||||
+152
-44
@@ -18,6 +18,14 @@ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
||||
import { type AgentScope, discoverAgents } from "./agents.ts";
|
||||
import type { SubagentParamsType } from "./schemas.ts";
|
||||
import type { DispatchDefaults, PreparedInvocation, PreparedTask } from "./types.ts";
|
||||
import {
|
||||
expandWorkflowPlan,
|
||||
validateWorkflowArgs,
|
||||
validateWorkflowRunShape,
|
||||
type PreparedWorkflowInvocation,
|
||||
type PreparedWorkflowStep,
|
||||
} from "./workflow.ts";
|
||||
import { validateWorkflowExpansion, type WorkflowPlan } from "./workflows.ts";
|
||||
|
||||
const MAX_PARALLEL_TASKS = 8;
|
||||
|
||||
@@ -183,6 +191,76 @@ function resolveTaskCwd(baseCwd: string, itemCwd: string | undefined): string {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function resolvePreparedTask(
|
||||
agentName: string,
|
||||
taskText: string,
|
||||
itemCwd: string | undefined,
|
||||
baseCwd: string,
|
||||
agentScope: AgentScope,
|
||||
): { task: PreparedTask; projectAgentsDir: string | null } {
|
||||
const cwd = resolveTaskCwd(baseCwd, itemCwd);
|
||||
|
||||
// Discovery is per task: agents are a property of the task's effective
|
||||
// working directory, not of the caller's cwd.
|
||||
const discovery = discoverAgents(cwd, agentScope);
|
||||
const agent = discovery.agents.find((candidate) => candidate.name === agentName);
|
||||
if (!agent) {
|
||||
const available = discovery.agents.map((candidate) => `"${candidate.name}"`).join(", ") || "none";
|
||||
throw new InvalidInvocationError(`Unknown agent: "${agentName}". Available agents: ${available}.`);
|
||||
}
|
||||
|
||||
return {
|
||||
task: { agent, task: taskText, cwd },
|
||||
projectAgentsDir: agent.source === "project" ? discovery.projectAgentsDir : null,
|
||||
};
|
||||
}
|
||||
|
||||
function collectProjectAgent(
|
||||
projectAgentsByDir: Map<string, Set<string>>,
|
||||
task: PreparedTask,
|
||||
projectAgentsDir: string | null,
|
||||
): void {
|
||||
if (!projectAgentsDir) return;
|
||||
const names = projectAgentsByDir.get(projectAgentsDir) ?? new Set<string>();
|
||||
names.add(task.agent.name);
|
||||
projectAgentsByDir.set(projectAgentsDir, names);
|
||||
}
|
||||
|
||||
/** Confirm every distinct repo-controlled agent source before anything starts. */
|
||||
async function confirmProjectAgentSources(
|
||||
projectAgentsByDir: Map<string, Set<string>>,
|
||||
ctx: PrepareContext,
|
||||
agentScope: AgentScope,
|
||||
confirmProjectAgents: boolean,
|
||||
): Promise<string[]> {
|
||||
const projectAgentsDirs = Array.from(projectAgentsByDir.keys());
|
||||
const trustedDiscovery = ctx.isProjectTrusted() ? discoverAgents(ctx.cwd, agentScope) : null;
|
||||
const trustedProjectAgentsDir = trustedDiscovery?.projectAgentsDir
|
||||
? fs.realpathSync(trustedDiscovery.projectAgentsDir)
|
||||
: undefined;
|
||||
|
||||
if (agentScope !== "user" && confirmProjectAgents && ctx.hasUI && projectAgentsDirs.length > 0) {
|
||||
for (const directory of projectAgentsDirs) {
|
||||
if (trustedProjectAgentsDir && fs.realpathSync(directory) === trustedProjectAgentsDir) continue;
|
||||
const agents = Array.from(projectAgentsByDir.get(directory) ?? []);
|
||||
const approved = await ctx.ui.confirm(
|
||||
"Run project-local agents?",
|
||||
`Agents: ${agents.join(", ")}\nSource: ${directory}\n\nProject agent prompts are repo-controlled. Only continue for repositories you trust.`,
|
||||
);
|
||||
if (!approved) throw new ProjectAgentDeclinedError(directory, agents);
|
||||
}
|
||||
}
|
||||
|
||||
return projectAgentsDirs;
|
||||
}
|
||||
|
||||
function dispatchDefaultsFor(ctx: PrepareContext): DispatchDefaults {
|
||||
return {
|
||||
model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
|
||||
thinkingLevel: ctx.thinkingLevel,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a subagent invocation.
|
||||
*
|
||||
@@ -202,51 +280,18 @@ export async function prepareInvocation(
|
||||
|
||||
for (let index = 0; index < request.items.length; index++) {
|
||||
const item = request.items[index];
|
||||
const cwd = resolveTaskCwd(ctx.cwd, item.cwd);
|
||||
|
||||
// Discovery is per task: agents are a property of the task's effective
|
||||
// working directory, not of the caller's cwd.
|
||||
const discovery = discoverAgents(cwd, agentScope);
|
||||
const agent = discovery.agents.find((candidate) => candidate.name === item.agent);
|
||||
if (!agent) {
|
||||
const available = discovery.agents.map((candidate) => `"${candidate.name}"`).join(", ") || "none";
|
||||
throw new InvalidInvocationError(`Unknown agent: "${item.agent}". Available agents: ${available}.`);
|
||||
}
|
||||
|
||||
if (agent.source === "project" && discovery.projectAgentsDir) {
|
||||
const names = projectAgentsByDir.get(discovery.projectAgentsDir) ?? new Set<string>();
|
||||
names.add(agent.name);
|
||||
projectAgentsByDir.set(discovery.projectAgentsDir, names);
|
||||
}
|
||||
|
||||
const task: PreparedTask = { agent, task: item.task, cwd };
|
||||
if (request.mode === "chain") task.step = index + 1;
|
||||
tasks.push(task);
|
||||
const resolved = resolvePreparedTask(item.agent, item.task, item.cwd, ctx.cwd, agentScope);
|
||||
collectProjectAgent(projectAgentsByDir, resolved.task, resolved.projectAgentsDir);
|
||||
if (request.mode === "chain") resolved.task.step = index + 1;
|
||||
tasks.push(resolved.task);
|
||||
}
|
||||
|
||||
const projectAgentsDirs = Array.from(projectAgentsByDir.keys());
|
||||
const confirmProjectAgents = params.confirmProjectAgents ?? true;
|
||||
const trustedDiscovery = ctx.isProjectTrusted() ? discoverAgents(ctx.cwd, agentScope) : null;
|
||||
const trustedProjectAgentsDir = trustedDiscovery?.projectAgentsDir
|
||||
? fs.realpathSync(trustedDiscovery.projectAgentsDir)
|
||||
: undefined;
|
||||
|
||||
if (agentScope !== "user" && confirmProjectAgents && ctx.hasUI && projectAgentsDirs.length > 0) {
|
||||
for (const directory of projectAgentsDirs) {
|
||||
if (trustedProjectAgentsDir && fs.realpathSync(directory) === trustedProjectAgentsDir) continue;
|
||||
const agents = Array.from(projectAgentsByDir.get(directory) ?? []);
|
||||
const approved = await ctx.ui.confirm(
|
||||
"Run project-local agents?",
|
||||
`Agents: ${agents.join(", ")}\nSource: ${directory}\n\nProject agent prompts are repo-controlled. Only continue for repositories you trust.`,
|
||||
);
|
||||
if (!approved) throw new ProjectAgentDeclinedError(directory, agents);
|
||||
}
|
||||
}
|
||||
|
||||
const dispatchDefaults: DispatchDefaults = {
|
||||
model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
|
||||
thinkingLevel: ctx.thinkingLevel,
|
||||
};
|
||||
const projectAgentsDirs = await confirmProjectAgentSources(
|
||||
projectAgentsByDir,
|
||||
ctx,
|
||||
agentScope,
|
||||
params.confirmProjectAgents ?? true,
|
||||
);
|
||||
|
||||
return {
|
||||
mode: request.mode,
|
||||
@@ -254,6 +299,69 @@ export async function prepareInvocation(
|
||||
agentScope,
|
||||
projectAgentsDir: projectAgentsDirs[0] ?? null,
|
||||
projectAgentsDirs,
|
||||
dispatchDefaults,
|
||||
dispatchDefaults: dispatchDefaultsFor(ctx),
|
||||
};
|
||||
}
|
||||
|
||||
export interface PrepareWorkflowOptions {
|
||||
/** Agent directories a workflow may resolve. Default: both, project over user. */
|
||||
agentScope?: AgentScope;
|
||||
/** Prompt before running repo-controlled agents. Default: true. */
|
||||
confirmProjectAgents?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a workflow run: validate arguments and run shape, resolve every
|
||||
* step's agent and cwd, and confirm repo-controlled sources. All failures
|
||||
* happen before the manager creates a job, so no child can spawn.
|
||||
*/
|
||||
export async function prepareWorkflowInvocation(
|
||||
plan: WorkflowPlan,
|
||||
args: Readonly<Record<string, string>>,
|
||||
ctx: PrepareContext,
|
||||
options: PrepareWorkflowOptions = {},
|
||||
): Promise<PreparedWorkflowInvocation> {
|
||||
validateWorkflowRunShape(plan);
|
||||
const resolvedArgs = validateWorkflowArgs(plan, args);
|
||||
validateWorkflowExpansion(plan, {});
|
||||
|
||||
const agentScope = options.agentScope ?? "both";
|
||||
const projectAgentsByDir = new Map<string, Set<string>>();
|
||||
const steps: PreparedWorkflowStep[] = plan.steps.map((step) => {
|
||||
const resolved = resolvePreparedTask(step.agent, step.task, step.cwd, ctx.cwd, agentScope);
|
||||
const prepared: PreparedTask = {
|
||||
...resolved.task,
|
||||
stepId: step.id,
|
||||
model: step.model,
|
||||
};
|
||||
collectProjectAgent(projectAgentsByDir, prepared, resolved.projectAgentsDir);
|
||||
return {
|
||||
id: step.id,
|
||||
needs: [...step.needs],
|
||||
template: step.task,
|
||||
prepared,
|
||||
};
|
||||
});
|
||||
|
||||
const projectAgentsDirs = await confirmProjectAgentSources(
|
||||
projectAgentsByDir,
|
||||
ctx,
|
||||
agentScope,
|
||||
options.confirmProjectAgents ?? true,
|
||||
);
|
||||
|
||||
return {
|
||||
mode: "workflow",
|
||||
tasks: steps.map((step) => step.prepared),
|
||||
agentScope,
|
||||
projectAgentsDir: projectAgentsDirs[0] ?? null,
|
||||
projectAgentsDirs,
|
||||
dispatchDefaults: dispatchDefaultsFor(ctx),
|
||||
workflow: {
|
||||
plan,
|
||||
args: resolvedArgs,
|
||||
steps,
|
||||
expandedPlan: expandWorkflowPlan(plan),
|
||||
},
|
||||
};
|
||||
}
|
||||
+30
-11
@@ -187,6 +187,10 @@ export function isFailedStatus(status: TaskStatus | undefined): boolean {
|
||||
return status === "failed" || status === "cancelled" || status === "interrupted";
|
||||
}
|
||||
|
||||
export function isSkippedStatus(status: TaskStatus | undefined): boolean {
|
||||
return status === "skipped";
|
||||
}
|
||||
|
||||
/**
|
||||
* Running/queued placeholders have a null exit code but are not failures. For
|
||||
* every other result, null or nonzero exits are failures, as are explicit
|
||||
@@ -194,6 +198,7 @@ export function isFailedStatus(status: TaskStatus | undefined): boolean {
|
||||
*/
|
||||
export function isFailedResult(result: ResultStatusFields): boolean {
|
||||
if (isRunningStatus(result.status)) return false;
|
||||
if (isSkippedStatus(result.status)) return false;
|
||||
if (isFailedStatus(result.status)) return true;
|
||||
if (result.exitCode === null || (result.exitCode !== undefined && result.exitCode !== 0)) return true;
|
||||
return result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal);
|
||||
@@ -204,7 +209,7 @@ export function isRunningResult(result: ResultStatusFields): boolean {
|
||||
}
|
||||
|
||||
export function isSuccessfulResult(result: ResultStatusFields): boolean {
|
||||
return !isRunningResult(result) && !isFailedResult(result);
|
||||
return !isRunningResult(result) && !isFailedResult(result) && !isSkippedStatus(result.status);
|
||||
}
|
||||
|
||||
interface ResultOutputFields extends ResultStatusFields {
|
||||
@@ -215,6 +220,7 @@ interface ResultOutputFields extends ResultStatusFields {
|
||||
}
|
||||
|
||||
export function getResultOutput(result: ResultOutputFields): string {
|
||||
if (isSkippedStatus(result.status)) return "(skipped)";
|
||||
const output = result.output || getFinalOutput(result.messages);
|
||||
if (isFailedResult(result)) {
|
||||
return result.errorMessage || result.stderr || output || "(no output)";
|
||||
@@ -237,7 +243,9 @@ export function formatParallelSummary(results: readonly RunResult[]): string {
|
||||
? `failed${result.stopReason && result.stopReason !== "end" ? ` (${result.stopReason})` : ""}`
|
||||
: isRunningResult(result)
|
||||
? "running"
|
||||
: "completed";
|
||||
: isSkippedStatus(result.status)
|
||||
? "skipped"
|
||||
: "completed";
|
||||
return `### [${result.agent}] ${status}\n\n${output}`;
|
||||
});
|
||||
return `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n---\n\n")}`;
|
||||
@@ -430,7 +438,11 @@ export function renderSubagentResult(
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
const rIcon = isFailedResult(r) ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
||||
const rIcon = isSkippedStatus(r.status)
|
||||
? theme.fg("muted", "–")
|
||||
: isFailedResult(r)
|
||||
? theme.fg("error", "✗")
|
||||
: theme.fg("success", "✓");
|
||||
const displayItems = getDisplayItems(r.messages);
|
||||
const finalOutput = resultOutput(r);
|
||||
|
||||
@@ -488,7 +500,7 @@ export function renderSubagentResult(
|
||||
return new Text(text, 0, 0);
|
||||
}
|
||||
|
||||
if (mode === "parallel") {
|
||||
if (mode === "parallel" || mode === "workflow") {
|
||||
const running = results.filter((r) => resultIsRunning(r, overallActive)).length;
|
||||
const successCount = results.filter((r) => !resultIsRunning(r, overallActive) && isSuccessfulResult(r)).length;
|
||||
const failCount = results.filter((r) => !resultIsRunning(r, overallActive) && isFailedResult(r)).length;
|
||||
@@ -498,18 +510,23 @@ export function renderSubagentResult(
|
||||
: failCount > 0
|
||||
? theme.fg("warning", "◐")
|
||||
: theme.fg("success", "✓");
|
||||
const unit = mode === "workflow" ? "steps" : "tasks";
|
||||
const status = isRunning
|
||||
? `${successCount + failCount}/${results.length} done, ${running} running`
|
||||
: `${successCount}/${results.length} tasks`;
|
||||
: `${successCount}/${results.length} ${unit}`;
|
||||
|
||||
if (expanded && !isRunning) {
|
||||
const container = new Container();
|
||||
container.addChild(
|
||||
new Text(`${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`, 0, 0),
|
||||
new Text(`${icon} ${theme.fg("toolTitle", theme.bold(`${mode} `))}${theme.fg("accent", status)}`, 0, 0),
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
const rIcon = isFailedResult(r) ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
||||
const rIcon = isSkippedStatus(r.status)
|
||||
? theme.fg("muted", "–")
|
||||
: isFailedResult(r)
|
||||
? theme.fg("error", "✗")
|
||||
: theme.fg("success", "✓");
|
||||
const displayItems = getDisplayItems(r.messages);
|
||||
const finalOutput = resultOutput(r);
|
||||
|
||||
@@ -542,14 +559,16 @@ export function renderSubagentResult(
|
||||
return container;
|
||||
}
|
||||
|
||||
let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`;
|
||||
let text = `${icon} ${theme.fg("toolTitle", theme.bold(`${mode} `))}${theme.fg("accent", status)}`;
|
||||
for (const r of results) {
|
||||
const rRunning = resultIsRunning(r, overallActive);
|
||||
const rIcon = rRunning
|
||||
? theme.fg("warning", "⏳")
|
||||
: isFailedResult(r)
|
||||
? theme.fg("error", "✗")
|
||||
: theme.fg("success", "✓");
|
||||
: isSkippedStatus(r.status)
|
||||
? theme.fg("muted", "–")
|
||||
: isFailedResult(r)
|
||||
? theme.fg("error", "✗")
|
||||
: theme.fg("success", "✓");
|
||||
const displayItems = getDisplayItems(r.messages);
|
||||
const finalOutput = resultOutput(r);
|
||||
text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
|
||||
|
||||
+4
-3
@@ -235,13 +235,14 @@ export class ProcessRunner implements TaskRunner {
|
||||
task: task.task,
|
||||
cwd: task.cwd,
|
||||
step: task.step,
|
||||
stepId: task.stepId,
|
||||
exitCode: 0,
|
||||
messages: [],
|
||||
output: "",
|
||||
stderr: "",
|
||||
stderrTruncated: false,
|
||||
usage: emptyUsage(),
|
||||
model: task.agent.model ?? defaults.model,
|
||||
model: task.model ?? task.agent.model ?? defaults.model,
|
||||
};
|
||||
|
||||
let tempDir: string | undefined;
|
||||
@@ -262,8 +263,8 @@ export class ProcessRunner implements TaskRunner {
|
||||
|
||||
private buildArgs(task: PreparedTask, defaults: DispatchDefaults, promptPath: string | undefined): string[] {
|
||||
const args: string[] = ["--mode", "json", "-p", "--no-session", "--exclude-tools", "subagent*"];
|
||||
const inheritsDispatchConfig = !task.agent.model;
|
||||
const model = task.agent.model ?? defaults.model;
|
||||
const inheritsDispatchConfig = !task.model && !task.agent.model;
|
||||
const model = task.model ?? task.agent.model ?? defaults.model;
|
||||
if (model) args.push("--model", model);
|
||||
if (inheritsDispatchConfig && defaults.thinkingLevel) args.push("--thinking", defaults.thinkingLevel);
|
||||
if (task.agent.tools && task.agent.tools.length > 0) args.push("--tools", task.agent.tools.join(","));
|
||||
|
||||
+18
-2
@@ -2,9 +2,9 @@ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
||||
import type { Message } from "@earendil-works/pi-ai";
|
||||
import type { AgentConfig, AgentScope } from "./agents.ts";
|
||||
|
||||
export type InvocationMode = "single" | "parallel" | "chain";
|
||||
export type InvocationMode = "single" | "parallel" | "chain" | "workflow";
|
||||
export type JobStatus = "queued" | "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "interrupted";
|
||||
export type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "cancelled" | "interrupted";
|
||||
export type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "skipped" | "cancelled" | "interrupted";
|
||||
|
||||
export interface DispatchDefaults {
|
||||
model?: string;
|
||||
@@ -16,6 +16,9 @@ export interface PreparedTask {
|
||||
task: string;
|
||||
cwd: string;
|
||||
step?: number;
|
||||
stepId?: string;
|
||||
/** Per-step model override (step -> agent -> parent precedence). */
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface PreparedInvocation {
|
||||
@@ -43,6 +46,7 @@ export interface RunResult {
|
||||
task: string;
|
||||
cwd: string;
|
||||
step?: number;
|
||||
stepId?: string;
|
||||
exitCode: number | null;
|
||||
messages: Message[];
|
||||
output: string;
|
||||
@@ -71,6 +75,7 @@ export interface TaskSnapshot {
|
||||
task: string;
|
||||
cwd: string;
|
||||
step?: number;
|
||||
stepId?: string;
|
||||
status: TaskStatus;
|
||||
exitCode: number | null;
|
||||
output: string;
|
||||
@@ -132,11 +137,22 @@ export interface ManagerOptions {
|
||||
}
|
||||
|
||||
export const TERMINAL_JOB_STATUSES: ReadonlySet<JobStatus> = new Set(["succeeded", "failed", "cancelled", "interrupted"]);
|
||||
export const TERMINAL_TASK_STATUSES: ReadonlySet<TaskStatus> = new Set([
|
||||
"succeeded",
|
||||
"failed",
|
||||
"skipped",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
]);
|
||||
|
||||
export function isTerminalJob(status: JobStatus): boolean {
|
||||
return TERMINAL_JOB_STATUSES.has(status);
|
||||
}
|
||||
|
||||
export function isTerminalTask(status: TaskStatus): boolean {
|
||||
return TERMINAL_TASK_STATUSES.has(status);
|
||||
}
|
||||
|
||||
export function emptyUsage(): UsageStats {
|
||||
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* Workflow run preparation, validation, and release-time templating.
|
||||
*
|
||||
* The plan module (`workflows.ts`) owns file parsing and structural validation.
|
||||
* This module owns the run-specific rules that need the manager's vocabulary:
|
||||
* declared arguments, step-output references, run budgets, and the expanded
|
||||
* plan returned at start. Nothing here spawns a child or mutates a job.
|
||||
*/
|
||||
|
||||
import { truncateUtf8Head } from "./output.ts";
|
||||
import type { JobSnapshot, PreparedInvocation, PreparedTask } from "./types.ts";
|
||||
import { WorkflowValidationError, type WorkflowPlan } from "./workflows.ts";
|
||||
|
||||
/** The design ceiling for one run, independent of the global worker pool. */
|
||||
export const WORKFLOW_MAX_CONCURRENCY = 4;
|
||||
|
||||
/** Standard task-output budget: one prior output may not crowd out the rest. */
|
||||
export const MAX_INTERPOLATED_STEP_OUTPUT_BYTES = 50 * 1024;
|
||||
|
||||
/** Expanded step prompts are bounded to keep the child brief sane. */
|
||||
export const MAX_EXPANDED_STEP_PROMPT_BYTES = 100 * 1024;
|
||||
|
||||
export interface ExpandedWorkflowStep {
|
||||
id: string;
|
||||
agent: string;
|
||||
needs: string[];
|
||||
task: string;
|
||||
}
|
||||
|
||||
/** The run's steps as admission units, after item fan-out is resolved. */
|
||||
export interface ExpandedWorkflowPlan {
|
||||
name: string;
|
||||
description: string;
|
||||
args: string[];
|
||||
steps: ExpandedWorkflowStep[];
|
||||
}
|
||||
|
||||
export interface PreparedWorkflowStep {
|
||||
id: string;
|
||||
needs: string[];
|
||||
template: string;
|
||||
prepared: PreparedTask;
|
||||
}
|
||||
|
||||
export interface WorkflowRunSpec {
|
||||
plan: WorkflowPlan;
|
||||
args: Record<string, string>;
|
||||
steps: PreparedWorkflowStep[];
|
||||
expandedPlan: ExpandedWorkflowPlan;
|
||||
}
|
||||
|
||||
export interface PreparedWorkflowInvocation extends PreparedInvocation {
|
||||
mode: "workflow";
|
||||
workflow: WorkflowRunSpec;
|
||||
}
|
||||
|
||||
export interface WorkflowStartResult {
|
||||
id: string;
|
||||
job: JobSnapshot;
|
||||
plan: ExpandedWorkflowPlan;
|
||||
}
|
||||
|
||||
export interface WorkflowTemplateContext {
|
||||
args: Readonly<Record<string, string>>;
|
||||
outputs: ReadonlyMap<string, string>;
|
||||
}
|
||||
|
||||
const PLACEHOLDER = /\{steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output\}|\{args\.([A-Za-z_][A-Za-z0-9_-]*)\}/g;
|
||||
const STEP_OUTPUT_REFERENCE = /\{steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output\}/g;
|
||||
|
||||
function fail(plan: WorkflowPlan, message: string, stepId?: string): never {
|
||||
throw new WorkflowValidationError(`Workflow "${plan.name}" (${plan.filePath}): ${message}`, {
|
||||
filePath: plan.filePath,
|
||||
stepId,
|
||||
});
|
||||
}
|
||||
|
||||
/** The per-run reservation inside the shared worker pool (ADR 0002). */
|
||||
export function workflowRunConcurrency(maxWorkers: number): number {
|
||||
return Math.min(maxWorkers - 1, WORKFLOW_MAX_CONCURRENCY);
|
||||
}
|
||||
|
||||
/** The expanded plan is one admission unit per step until each-steps land. */
|
||||
export function expandWorkflowPlan(plan: WorkflowPlan): ExpandedWorkflowPlan {
|
||||
return {
|
||||
name: plan.name,
|
||||
description: plan.description,
|
||||
args: [...plan.args],
|
||||
steps: plan.steps.map((step) => ({
|
||||
id: step.id,
|
||||
agent: step.agent,
|
||||
needs: [...step.needs],
|
||||
task: step.task,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** Validate run arguments against the plan's declaration (all declared args are required). */
|
||||
export function validateWorkflowArgs(plan: WorkflowPlan, args: Readonly<Record<string, string>>): Record<string, string> {
|
||||
const declared = new Set(plan.args);
|
||||
const unknown = Object.keys(args).filter((name) => !declared.has(name));
|
||||
|
||||
if (unknown.length > 0) {
|
||||
const names = unknown.map((name) => `"${name}"`).join(", ");
|
||||
fail(
|
||||
plan,
|
||||
`unknown argument${unknown.length === 1 ? "" : "s"} ${names}. Declared args: ${plan.args.length > 0 ? plan.args.join(", ") : "none"}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const missing = plan.args.filter((name) => !Object.hasOwn(args, name));
|
||||
if (missing.length > 0) {
|
||||
fail(
|
||||
plan,
|
||||
`missing required argument${missing.length === 1 ? "" : "s"} ${missing.map((name) => `"${name}"`).join(", ")}. Provide ${missing.length === 1 ? "it" : "them"} when starting the workflow.`,
|
||||
);
|
||||
}
|
||||
|
||||
return Object.fromEntries(plan.args.map((name) => [name, args[name]]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the parts of the plan only a run can know: each-steps are not
|
||||
* implemented yet, and every step-output reference must be a declared need so
|
||||
* the value exists when the step is released.
|
||||
*/
|
||||
export function validateWorkflowRunShape(plan: WorkflowPlan): void {
|
||||
const byId = new Map(plan.steps.map((step) => [step.id, step]));
|
||||
|
||||
for (const [index, step] of plan.steps.entries()) {
|
||||
if (step.each !== undefined) {
|
||||
fail(
|
||||
plan,
|
||||
`steps[${index}] ("${step.id}") declares each: {steps.${step.each}.output}; each-steps are not supported yet (line fan-out lands in ticket #8).`,
|
||||
step.id,
|
||||
);
|
||||
}
|
||||
|
||||
for (const match of step.task.matchAll(STEP_OUTPUT_REFERENCE)) {
|
||||
const source = match[1];
|
||||
if (!byId.has(source)) {
|
||||
fail(
|
||||
plan,
|
||||
`steps[${index}] ("${step.id}").task references unknown step "${source}". Available steps: ${plan.steps.map((candidate) => `"${candidate.id}"`).join(", ")}.`,
|
||||
step.id,
|
||||
);
|
||||
}
|
||||
if (!step.needs.includes(source)) {
|
||||
fail(
|
||||
plan,
|
||||
`steps[${index}] ("${step.id}").task references {steps.${source}.output} but "${source}" is not in its needs (${step.needs.length > 0 ? step.needs.map((need) => `"${need}"`).join(", ") : "none"}). Add "${source}" to needs.`,
|
||||
step.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function appendMarker(text: string, marker: string): string {
|
||||
return `${text}\n\n${marker}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand one step brief at release time.
|
||||
*
|
||||
* Substitutions are single-pass, so a value that happens to contain another
|
||||
* placeholder is inserted literally. Each prior output is bounded to the
|
||||
* standard task-output budget, then the whole brief to the expanded-prompt
|
||||
* budget; both truncations carry a visible marker.
|
||||
*/
|
||||
export function interpolateWorkflowTask(template: string, context: WorkflowTemplateContext): string {
|
||||
const expanded = template.replace(PLACEHOLDER, (_match, stepId: string | undefined, argName: string | undefined) => {
|
||||
if (stepId !== undefined) {
|
||||
const output = context.outputs.get(stepId) ?? "";
|
||||
const bounded = truncateUtf8Head(output, MAX_INTERPOLATED_STEP_OUTPUT_BYTES);
|
||||
return bounded.truncated
|
||||
? appendMarker(bounded.text, `[Output truncated: ${bounded.bytesOmitted} bytes omitted]`)
|
||||
: output;
|
||||
}
|
||||
return context.args[argName ?? ""] ?? "";
|
||||
});
|
||||
|
||||
const bounded = truncateUtf8Head(expanded, MAX_EXPANDED_STEP_PROMPT_BYTES);
|
||||
return bounded.truncated
|
||||
? appendMarker(bounded.text, `[Prompt truncated: ${bounded.bytesOmitted} bytes omitted]`)
|
||||
: expanded;
|
||||
}
|
||||
@@ -53,3 +53,31 @@ test("persistence wraps snapshots and ignores foreign or malformed entries", ()
|
||||
]);
|
||||
assert.deepEqual(restored, [job]);
|
||||
});
|
||||
|
||||
test("workflow formatting and persistence keep step ids and skipped steps", () => {
|
||||
const workflowJob: JobSnapshot = {
|
||||
...job,
|
||||
mode: "workflow",
|
||||
status: "failed",
|
||||
plannedTaskCount: 2,
|
||||
results: [
|
||||
{ ...job.results[0], stepId: "scan", task: "scan", errorMessage: "scan exploded" },
|
||||
{
|
||||
...job.results[0],
|
||||
stepId: "audit",
|
||||
task: "audit {steps.scan.output}",
|
||||
status: "skipped",
|
||||
exitCode: null,
|
||||
errorMessage: "Skipped because a required step did not succeed",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const text = formatJob(workflowJob);
|
||||
assert.match(text, /### Step scan/);
|
||||
assert.match(text, /### Step audit/);
|
||||
assert.match(text, /\(skipped: a required step did not succeed\)/);
|
||||
|
||||
const entry = { type: "custom", customType: SUBAGENT_JOB_ENTRY, data: persistedJob("session-a", workflowJob) };
|
||||
assert.deepEqual(extractJobSnapshots([entry]), [workflowJob]);
|
||||
});
|
||||
@@ -170,3 +170,19 @@ test("call previews preserve mode, scope, and task summaries", () => {
|
||||
assert.match(single, /scout/);
|
||||
assert.match(single, /inspect this/);
|
||||
});
|
||||
|
||||
test("skipped tasks are terminal but neither failed nor successful", () => {
|
||||
const result = runResult({ status: "skipped", exitCode: null, output: "" });
|
||||
assert.equal(isRunningResult(result), false);
|
||||
assert.equal(isFailedResult(result), false);
|
||||
assert.equal(isSuccessfulResult(result), false);
|
||||
});
|
||||
|
||||
test("parallel summary labels skipped tasks instead of counting them as completed", () => {
|
||||
const summary = formatParallelSummary([
|
||||
runResult({ agent: "one", status: "succeeded", output: "finished" }),
|
||||
runResult({ agent: "two", status: "skipped", exitCode: null, output: "" }),
|
||||
]);
|
||||
assert.match(summary, /^Parallel: 1\/2 succeeded/m);
|
||||
assert.match(summary, /### \[two\] skipped\n\n\(skipped\)/);
|
||||
});
|
||||
@@ -373,3 +373,26 @@ test(
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("a step model overrides the agent and dispatch model without inheriting thinking", async () => {
|
||||
let captured: string[] = [];
|
||||
const runner = makeRunner(
|
||||
{ FAKE_PI_MODE: "success" },
|
||||
{
|
||||
invocation: (args) => {
|
||||
captured = args;
|
||||
return { command: process.execPath, args: [fixturePath, ...args] };
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const agent = makeAgent({ model: "agent-model" });
|
||||
const defaults: DispatchDefaults = { model: "dispatch-model", thinkingLevel: "high" };
|
||||
const result = await runner.run(makeTask({ agent, model: "step-model", stepId: "scan" }), defaults, runOptions());
|
||||
|
||||
assert.equal(result.exitCode, 0);
|
||||
assert.equal(captured[captured.indexOf("--model") + 1], "step-model");
|
||||
assert.equal(captured.includes("--thinking"), false);
|
||||
assert.equal(result.model, "step-model");
|
||||
assert.equal(result.stepId, "scan");
|
||||
});
|
||||
@@ -0,0 +1,366 @@
|
||||
import assert from "node:assert/strict";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import test, { after } from "node:test";
|
||||
import { SubagentManager } from "../src/manager.ts";
|
||||
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
||||
import { parseWorkflow, WorkflowValidationError, type WorkflowPlan } from "../src/workflows.ts";
|
||||
import { FakeRunner } from "./helpers.ts";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
after(() => {
|
||||
for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function makeWorkspace(agentNames = ["scout"]): { cwd: string; ctx: PrepareContext } {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-workflow-run-"));
|
||||
tempRoots.push(root);
|
||||
const agentsDir = path.join(root, ".pi", "agents");
|
||||
fs.mkdirSync(agentsDir, { recursive: true });
|
||||
for (const name of agentNames) {
|
||||
fs.writeFileSync(
|
||||
path.join(agentsDir, `${name}.md`),
|
||||
`---\nname: ${name}\ndescription: ${name} agent\n---\nYou are ${name}.\n`,
|
||||
"utf-8",
|
||||
);
|
||||
}
|
||||
return {
|
||||
cwd: root,
|
||||
ctx: {
|
||||
cwd: root,
|
||||
hasUI: false,
|
||||
isProjectTrusted: () => true,
|
||||
ui: { confirm: async () => true },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makePlan(steps: Array<Record<string, unknown>>, args: string[] = []): WorkflowPlan {
|
||||
const content = `---\n${JSON.stringify({ name: "test-workflow", description: "Test workflow", args, steps }, null, 2)}\n---\n\nNotes.\n`;
|
||||
return parseWorkflow(content, { source: "user", filePath: "/tmp/test-workflow.md" });
|
||||
}
|
||||
|
||||
function pending(runner: FakeRunner, stepId: string) {
|
||||
const call = runner.calls.find((candidate) => candidate.task.stepId === stepId && !candidate.settled);
|
||||
if (!call) throw new Error(`No pending step ${stepId}; running: ${runner.calls.map((c) => `${c.task.stepId}:${c.settled}`).join(", ")}`);
|
||||
return call;
|
||||
}
|
||||
|
||||
function completeStep(runner: FakeRunner, stepId: string, output = "done", overrides: Record<string, unknown> = {}): void {
|
||||
const call = pending(runner, stepId);
|
||||
runner.complete(call.task.task, output, overrides);
|
||||
}
|
||||
|
||||
test("run releases steps only when needs succeed, interpolating outputs in plan order", async () => {
|
||||
const { cwd, ctx } = makeWorkspace();
|
||||
const plan = makePlan(
|
||||
[
|
||||
{ id: "scan", agent: "scout", task: "scan sources" },
|
||||
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
||||
{ id: "merge", agent: "scout", task: "merge {steps.audit.output}", needs: ["audit"] },
|
||||
{ id: "notify", agent: "scout", task: "notify {args.channel}", needs: [] },
|
||||
],
|
||||
["channel"],
|
||||
);
|
||||
const runner = new FakeRunner();
|
||||
const manager = new SubagentManager(runner);
|
||||
const prepared = await prepareWorkflowInvocation(plan, { channel: "#ops" }, ctx, {
|
||||
agentScope: "project",
|
||||
confirmProjectAgents: false,
|
||||
});
|
||||
|
||||
const started = manager.startWorkflow(prepared);
|
||||
assert.equal(started.id, started.job.id);
|
||||
assert.deepEqual(started.plan.steps.map((step) => step.id), ["scan", "audit", "merge", "notify"]);
|
||||
assert.deepEqual(started.plan.steps[1].needs, ["scan"]);
|
||||
|
||||
assert.deepEqual(runner.calls.map((call) => call.task.stepId), ["scan", "notify"]);
|
||||
assert.equal(runner.calls[1].task.task, "notify #ops");
|
||||
|
||||
completeStep(runner, "scan", "src/a.ts\nsrc/b.ts");
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.deepEqual(runner.calls.map((call) => call.task.stepId), ["scan", "notify", "audit"]);
|
||||
assert.equal(pending(runner, "audit").task.task, "audit src/a.ts\nsrc/b.ts");
|
||||
|
||||
completeStep(runner, "audit", "missing auth");
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(pending(runner, "merge").task.task, "merge missing auth");
|
||||
|
||||
completeStep(runner, "notify", "sent");
|
||||
completeStep(runner, "merge", "ranked");
|
||||
|
||||
const terminal = await manager.wait(started.id, 1);
|
||||
assert.equal(terminal.status, "succeeded");
|
||||
assert.deepEqual(terminal.results.map((result) => result.stepId), ["scan", "audit", "merge", "notify"]);
|
||||
assert.deepEqual(terminal.results.map((result) => result.status), ["succeeded", "succeeded", "succeeded", "succeeded"]);
|
||||
assert.equal(terminal.mode, "workflow");
|
||||
});
|
||||
|
||||
test("a failed step skips dependents transitively while independent branches finish and settle the run", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([
|
||||
{ id: "scan", agent: "scout", task: "scan" },
|
||||
{ id: "notify", agent: "scout", task: "notify" },
|
||||
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
||||
{ id: "report", agent: "scout", task: "report {steps.audit.output}", needs: ["audit"] },
|
||||
{ id: "publish", agent: "scout", task: "publish {steps.notify.output}", needs: ["notify"] },
|
||||
]);
|
||||
const runner = new FakeRunner();
|
||||
const manager = new SubagentManager(runner);
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
|
||||
completeStep(runner, "scan", "partial", { exitCode: 1, errorMessage: "scan exploded" });
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
const midRun = manager.get(started.id);
|
||||
assert.deepEqual(midRun.results.map((result) => result.status), ["failed", "running", "skipped", "skipped", "queued"]);
|
||||
assert.equal(midRun.status, "running");
|
||||
assert.equal(runner.calls.some((call) => call.task.stepId === "audit" || call.task.stepId === "report"), false);
|
||||
|
||||
completeStep(runner, "notify", "ready");
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(pending(runner, "publish").task.task, "publish ready");
|
||||
completeStep(runner, "publish", "published");
|
||||
|
||||
const terminal = await manager.wait(started.id, 1);
|
||||
assert.equal(terminal.status, "failed");
|
||||
assert.deepEqual(
|
||||
terminal.results.map((result) => [result.stepId, result.status]),
|
||||
[
|
||||
["scan", "failed"],
|
||||
["notify", "succeeded"],
|
||||
["audit", "skipped"],
|
||||
["report", "skipped"],
|
||||
["publish", "succeeded"],
|
||||
],
|
||||
);
|
||||
assert.equal(terminal.results.every((result) => result.finishedAt !== undefined), true);
|
||||
assert.match(terminal.results[2].errorMessage ?? "", /Skipped/);
|
||||
});
|
||||
|
||||
test("the per-run cap holds under fewer workers and the global FIFO releases the next step", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([
|
||||
{ id: "a", agent: "scout", task: "a" },
|
||||
{ id: "b", agent: "scout", task: "b" },
|
||||
{ id: "c", agent: "scout", task: "c" },
|
||||
{ id: "d", agent: "scout", task: "d" },
|
||||
]);
|
||||
const runner = new FakeRunner();
|
||||
const manager = new SubagentManager(runner, { maxWorkers: 3 });
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
|
||||
assert.equal(runner.calls.length, 2);
|
||||
completeStep(runner, "a");
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(runner.calls.length, 3);
|
||||
assert.equal(manager.get(started.id).results.find((result) => result.stepId === "c")?.status, "running");
|
||||
|
||||
completeStep(runner, "b");
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(runner.calls.length, 4);
|
||||
completeStep(runner, "c");
|
||||
completeStep(runner, "d");
|
||||
assert.equal((await manager.wait(started.id, 1)).status, "succeeded");
|
||||
});
|
||||
|
||||
test("a single-worker pool rejects workflow runs instead of reserving zero capacity", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([{ id: "only", agent: "scout", task: "only" }]);
|
||||
const runner = new FakeRunner();
|
||||
const manager = new SubagentManager(runner, { maxWorkers: 1 });
|
||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, {
|
||||
agentScope: "project",
|
||||
confirmProjectAgents: false,
|
||||
});
|
||||
|
||||
assert.throws(() => manager.startWorkflow(prepared), /at least 2 workers/);
|
||||
assert.equal(runner.calls.length, 0);
|
||||
});
|
||||
|
||||
test("cancel mid-run aborts released steps and cancels queued steps without hanging", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([
|
||||
{ id: "a", agent: "scout", task: "a" },
|
||||
{ id: "b", agent: "scout", task: "b" },
|
||||
{ id: "child", agent: "scout", task: "child {steps.a.output}", needs: ["a"] },
|
||||
{ id: "held", agent: "scout", task: "held" },
|
||||
]);
|
||||
const runner = new FakeRunner();
|
||||
const manager = new SubagentManager(runner, { maxWorkers: 3 });
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
assert.deepEqual(runner.calls.map((call) => call.task.stepId), ["a", "b"]);
|
||||
|
||||
const cancelling = manager.cancel(started.id);
|
||||
assert.equal(cancelling.status, "cancelling");
|
||||
assert.deepEqual(
|
||||
cancelling.results.map((result) => [result.stepId, result.status]),
|
||||
[
|
||||
["a", "running"],
|
||||
["b", "running"],
|
||||
["child", "cancelled"],
|
||||
["held", "cancelled"],
|
||||
],
|
||||
);
|
||||
|
||||
const terminal = await manager.wait(started.id, 1);
|
||||
assert.equal(terminal.status, "cancelled");
|
||||
assert.deepEqual(
|
||||
terminal.results.map((result) => [result.stepId, result.status]),
|
||||
[
|
||||
["a", "cancelled"],
|
||||
["b", "cancelled"],
|
||||
["child", "cancelled"],
|
||||
["held", "cancelled"],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(runner.aborted.sort(), ["a", "b"]);
|
||||
assert.equal(runner.calls.length, 2);
|
||||
assert.equal(manager.cancel(started.id).status, "cancelled");
|
||||
});
|
||||
|
||||
test("start rejects undeclared, missing, and malformed run inputs before any child spawns", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const runner = new FakeRunner();
|
||||
const manager = new SubagentManager(runner);
|
||||
const argsPlan = makePlan([{ id: "scan", agent: "scout", task: "scan {args.glob}" }], ["glob"]);
|
||||
|
||||
await assert.rejects(
|
||||
prepareWorkflowInvocation(argsPlan, { glob: "src/**", extra: "no" }, ctx, {
|
||||
agentScope: "project",
|
||||
confirmProjectAgents: false,
|
||||
}),
|
||||
(error: unknown) => error instanceof WorkflowValidationError && /unknown argument "extra".*Declared args: glob/.test(error.message),
|
||||
);
|
||||
await assert.rejects(
|
||||
prepareWorkflowInvocation(argsPlan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
(error: unknown) => error instanceof WorkflowValidationError && /missing required argument "glob"/.test(error.message),
|
||||
);
|
||||
|
||||
const eachPlan = makePlan([
|
||||
{ id: "scan", agent: "scout", task: "scan" },
|
||||
{ id: "audit", agent: "scout", task: "audit {item}", needs: ["scan"], each: "{steps.scan.output}" },
|
||||
]);
|
||||
await assert.rejects(
|
||||
prepareWorkflowInvocation(eachPlan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
(error: unknown) =>
|
||||
error instanceof WorkflowValidationError &&
|
||||
/each-steps are not supported yet/.test(error.message) &&
|
||||
/"audit"/.test(error.message),
|
||||
);
|
||||
|
||||
const badReference = makePlan([
|
||||
{ id: "scan", agent: "scout", task: "scan" },
|
||||
{ id: "merge", agent: "scout", task: "merge {steps.scan.output}" },
|
||||
]);
|
||||
await assert.rejects(
|
||||
prepareWorkflowInvocation(badReference, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
(error: unknown) =>
|
||||
error instanceof WorkflowValidationError &&
|
||||
/references \{steps\.scan\.output\} but "scan" is not in its needs/.test(error.message),
|
||||
);
|
||||
|
||||
const unknownReference = makePlan([{ id: "merge", agent: "scout", task: "merge {steps.ghost.output}" }]);
|
||||
await assert.rejects(
|
||||
prepareWorkflowInvocation(unknownReference, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
(error: unknown) => error instanceof WorkflowValidationError && /references unknown step "ghost"/.test(error.message),
|
||||
);
|
||||
|
||||
assert.equal(runner.calls.length, 0);
|
||||
assert.equal(manager.list().length, 0);
|
||||
});
|
||||
|
||||
test("start resolves step-local cwd and model precedence while validating every agent", async () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-workflow-cwd-"));
|
||||
tempRoots.push(root);
|
||||
const project = path.join(root, "project");
|
||||
const nested = path.join(project, "nested");
|
||||
fs.mkdirSync(path.join(project, ".pi", "agents"), { recursive: true });
|
||||
fs.mkdirSync(nested, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(project, ".pi", "agents", "scout.md"),
|
||||
"---\nname: scout\ndescription: scout agent\nmodel: agent-model\n---\nYou are scout.\n",
|
||||
"utf-8",
|
||||
);
|
||||
const ctx: PrepareContext = {
|
||||
cwd: root,
|
||||
hasUI: false,
|
||||
isProjectTrusted: () => true,
|
||||
ui: { confirm: async () => true },
|
||||
};
|
||||
const plan = makePlan([
|
||||
{ id: "scan", agent: "scout", task: "scan", cwd: "project", model: "step-model" },
|
||||
{ id: "merge", agent: "scout", task: "merge {steps.scan.output}", needs: ["scan"], cwd: "project/nested" },
|
||||
]);
|
||||
|
||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, {
|
||||
agentScope: "project",
|
||||
confirmProjectAgents: false,
|
||||
});
|
||||
assert.deepEqual(prepared.tasks.map((task) => task.cwd), [project, nested]);
|
||||
assert.equal(prepared.tasks[0].model, "step-model");
|
||||
assert.equal(prepared.tasks[1].model, undefined);
|
||||
assert.equal(prepared.tasks[1].agent.model, "agent-model");
|
||||
});
|
||||
|
||||
test("reload interruption marks every unfinished workflow step interrupted and preserves step ids", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([
|
||||
{ id: "a", agent: "scout", task: "a" },
|
||||
{ id: "b", agent: "scout", task: "b" },
|
||||
]);
|
||||
const runner = new FakeRunner();
|
||||
const manager = new SubagentManager(runner, { maxWorkers: 2 });
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
assert.deepEqual(manager.get(started.id).results.map((result) => result.status), ["running", "queued"]);
|
||||
|
||||
const restoredRunner = new FakeRunner();
|
||||
const restoredManager = new SubagentManager(restoredRunner);
|
||||
restoredManager.restore([manager.get(started.id)]);
|
||||
const restored = restoredManager.get(started.id);
|
||||
assert.equal(restored.status, "interrupted");
|
||||
assert.deepEqual(
|
||||
restored.results.map((result) => [result.stepId, result.status]),
|
||||
[
|
||||
["a", "interrupted"],
|
||||
["b", "interrupted"],
|
||||
],
|
||||
);
|
||||
assert.equal(restoredRunner.calls.length, 0);
|
||||
manager.cancel(started.id);
|
||||
await manager.wait(started.id, 1);
|
||||
});
|
||||
|
||||
test("a fan-in step waits for every need and interpolates all of them", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([
|
||||
{ id: "scan", agent: "scout", task: "scan" },
|
||||
{ id: "audit", agent: "scout", task: "audit" },
|
||||
{ id: "merge", agent: "scout", task: "merge {steps.scan.output} + {steps.audit.output}", needs: ["scan", "audit"] },
|
||||
]);
|
||||
const runner = new FakeRunner();
|
||||
const manager = new SubagentManager(runner);
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
|
||||
completeStep(runner, "scan", "files");
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(runner.calls.length, 2);
|
||||
|
||||
completeStep(runner, "audit", "findings");
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(pending(runner, "merge").task.task, "merge files + findings");
|
||||
completeStep(runner, "merge", "ranked");
|
||||
assert.equal((await manager.wait(started.id, 1)).status, "succeeded");
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
MAX_EXPANDED_STEP_PROMPT_BYTES,
|
||||
MAX_INTERPOLATED_STEP_OUTPUT_BYTES,
|
||||
interpolateWorkflowTask,
|
||||
workflowRunConcurrency,
|
||||
} from "../src/workflow.ts";
|
||||
|
||||
// Independent of the exported constants so a changed budget fails the test.
|
||||
const OUTPUT_BUDGET = 50 * 1024;
|
||||
const PROMPT_BUDGET = 100 * 1024;
|
||||
|
||||
function context(args: Record<string, string> = {}, outputs: Record<string, string> = {}) {
|
||||
return { args, outputs: new Map(Object.entries(outputs)) };
|
||||
}
|
||||
|
||||
test("step outputs and args interpolate at release time in one pass", () => {
|
||||
const template = "Audit {args.glob}: {steps.scan.output}\nThen {steps.scan.output}";
|
||||
assert.equal(
|
||||
interpolateWorkflowTask(template, context({ glob: "src/**" }, { scan: "a.ts\nb.ts" })),
|
||||
"Audit src/**: a.ts\nb.ts\nThen a.ts\nb.ts",
|
||||
);
|
||||
assert.equal(interpolateWorkflowTask("no placeholders", context()), "no placeholders");
|
||||
assert.equal(interpolateWorkflowTask("{previous} stays literal", context()), "{previous} stays literal");
|
||||
});
|
||||
|
||||
test("substituted values are never re-expanded and placeholder-like text stays literal", () => {
|
||||
const output = "keep {args.glob} and {steps.other.output} literal";
|
||||
const args = { glob: "{steps.scan.output}", other: "$&" };
|
||||
const result = interpolateWorkflowTask("{steps.scan.output}|{args.glob}|{args.other}", context(args, { scan: output }));
|
||||
assert.equal(result, `${output}|{steps.scan.output}|$&`);
|
||||
assert.equal(interpolateWorkflowTask("{item}", context()), "{item}");
|
||||
});
|
||||
|
||||
test("a single output is bounded to the standard task-output budget with a marker", () => {
|
||||
assert.equal(MAX_INTERPOLATED_STEP_OUTPUT_BYTES, OUTPUT_BUDGET);
|
||||
const original = "😀a".repeat(OUTPUT_BUDGET);
|
||||
const result = interpolateWorkflowTask("{steps.scan.output}", context({}, { scan: original }));
|
||||
const [prefix, note] = result.split("\n\n[Output truncated: ");
|
||||
|
||||
assert.ok(Buffer.byteLength(prefix, "utf8") <= OUTPUT_BUDGET);
|
||||
assert.equal(prefix.includes("\uFFFD"), false);
|
||||
assert.equal(original.startsWith(prefix), true);
|
||||
const omitted = Buffer.byteLength(original, "utf8") - Buffer.byteLength(prefix, "utf8");
|
||||
assert.equal(note, `${omitted} bytes omitted]`);
|
||||
});
|
||||
|
||||
test("the whole expanded brief is bounded to the prompt budget with a visible marker", () => {
|
||||
assert.equal(MAX_EXPANDED_STEP_PROMPT_BYTES, PROMPT_BUDGET);
|
||||
const piece = "x".repeat(49 * 1024);
|
||||
const result = interpolateWorkflowTask(
|
||||
"{steps.a.output}{steps.b.output}{steps.c.output}",
|
||||
context({}, { a: piece, b: piece, c: piece }),
|
||||
);
|
||||
const [prefix, note] = result.split("\n\n[Prompt truncated: ");
|
||||
|
||||
assert.ok(Buffer.byteLength(prefix, "utf8") <= PROMPT_BUDGET);
|
||||
assert.notEqual(note, undefined);
|
||||
assert.match(note, /^\d+ bytes omitted\]$/);
|
||||
const omitted = Buffer.byteLength(`${piece}${piece}${piece}`, "utf8") - Buffer.byteLength(prefix, "utf8");
|
||||
assert.equal(note, `${omitted} bytes omitted]`);
|
||||
assert.equal(prefix.includes("\uFFFD"), false);
|
||||
});
|
||||
|
||||
test("the per-run reservation is min(maxWorkers - 1, 4)", () => {
|
||||
assert.equal(workflowRunConcurrency(2), 1);
|
||||
assert.equal(workflowRunConcurrency(3), 2);
|
||||
assert.equal(workflowRunConcurrency(5), 4);
|
||||
assert.equal(workflowRunConcurrency(32), 4);
|
||||
});
|
||||
Reference in new issue
Block a user