Fix workflow-layer review findings
Correctness: exclude workflow dispatch from child sessions, surface invalid workflow item configuration, reject {item} outside each-steps, and confirm every untrusted project directory once per workflow start. Refactors: share task settlement, status icons, validation failures, task identity construction, and workflow run state; normalize item counts to a map. Document YAML repair leniency and glossary wording.
This commit is contained in:
1 parent
688ae96dfe
commit
d4eb164b03
13 files changed
+415
-308
No files matched your search
@@ -68,7 +68,7 @@ Three placeholders exist. All are substituted in one pass when the step is relea
|
||||
|
||||
- `{steps.<id>.output}` — the final output of another step. `<id>` must be listed in this step's `needs`; a reference to an unknown step or to a step not in `needs` is rejected at start.
|
||||
- `{args.<name>}` — the value of a declared argument. A reference to an undeclared argument is rejected when the file is loaded.
|
||||
- `{item}` — the current line for an each-step's child. Every occurrence in the step's `task` is replaced. In a step without `each` it stays literal.
|
||||
- `{item}` — the current line for an each-step's child. Every occurrence in the step's `task` is replaced. A step without `each` may not use `{item}`; it is a validation error.
|
||||
|
||||
`{previous}` is not a workflow placeholder — it belongs to chain mode and stays literal in a workflow step. A fan-in step names its inputs with `{steps.<id>.output}`.
|
||||
|
||||
@@ -77,7 +77,7 @@ Both directions are bounded with a visible marker, and truncation is UTF-8 safe:
|
||||
- each substituted step output is capped at 50 KiB; an oversized one keeps a prefix plus `[Output truncated: N bytes omitted]`.
|
||||
- the whole expanded brief is capped at 100 KiB; an oversized one keeps a prefix plus `[Prompt truncated: N bytes omitted]`.
|
||||
|
||||
Values are parsed as YAML. Write a `task` that contains `: ` or starts with a placeholder either quoted (`task: "Merge these: {steps.a.output}"`) or as a block scalar (`task: |`). The loader repairs those common ambiguous scalars, but quoting is the form that cannot surprise you.
|
||||
Values are parsed as YAML. Write a `task` that contains `: ` or starts with a placeholder either quoted (`task: "Merge these: {steps.a.output}"`) or as a block scalar (`task: |`). Unquoted `each` values and scalar values containing `{steps...}` are also accepted via a repair pass, but quoting is the form that cannot surprise you.
|
||||
|
||||
## Caps and bounds
|
||||
|
||||
@@ -114,7 +114,7 @@ A project workflow overrides a user workflow with the same `name`. A file whose
|
||||
|
||||
User workflow files are yours, so they run without a prompt, exactly like user agents.
|
||||
|
||||
Project workflow files are repo-controlled. In an interactive session, starting a project workflow asks once per distinct project workflows directory — approving one run approves later runs from that same directory, and declining aborts before any child spawns. A session that already trusts the project is exempt from the prompt for that project's own workflows directory; a workflow loaded from a foreign directory still asks. Noninteractive print/JSON sessions show no prompt. Steps that resolve project agents go through the same project-agent confirmation as any other subagent invocation.
|
||||
Project workflow files and project agents are repo-controlled. In an interactive session, a start asks once: one confirmation names every untrusted project directory involved in that run — the workflow directory and any project agent directories — and approving it covers each directory for later starts. A session that already trusts the project is exempt from the prompt for that project's own workflow and agent directories; sources loaded from a foreign directory still ask. Noninteractive print/JSON sessions show no prompt.
|
||||
|
||||
## Starting a run
|
||||
|
||||
@@ -124,7 +124,7 @@ Tool call — validates everything, creates the async **run**, and returns immed
|
||||
{ "action": "start", "name": "audit-routes", "args": { "glob": "src/**" }, "cwd": "packages/api" }
|
||||
```
|
||||
|
||||
`args` and `cwd` are optional; `cwd` sets the directory used for workflow discovery and step resolution. The result carries the job id and the **expanded plan** (step ids, agents, needs, and each sources). Starting never blocks on step execution.
|
||||
`args` and `cwd` are optional; `cwd` sets the directory used for workflow discovery and step resolution. The result carries the job id and the **expanded plan** (step ids, agents, needs, and each sources). Starting never blocks on step completion.
|
||||
|
||||
Slash command — same path, for routine runs outside the model turn:
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ A workflow is a declarative plan in a markdown file, executed as a DAG of agent
|
||||
|
||||
A project workflow overrides a user workflow with the same `name`, so a repository can tailor a shared plan. Files are looked up by their frontmatter `name`, not by file name.
|
||||
|
||||
A file is YAML frontmatter — `name`, `description`, optional `args`, and a `steps` list — plus a free-form body that is ignored at run time. Step fields are `id`, `agent`, `task`, `needs`, `each`, `model`, and `cwd`. Steps form a DAG: a step starts once every step in its `needs` succeeded; earlier results reach it through `{steps.<id>.output}`, declared arguments through `{args.<name>}`, and an each-step’s current line through `{item}`. An each-step (`each: {steps.<id>.output}`) fans out over the nonblank lines of a needed step’s output, one child per line.
|
||||
A file is YAML frontmatter — `name`, `description`, optional `args`, and a `steps` list — plus a free-form body that is ignored at run time. Step fields are `id`, `agent`, `task`, `needs`, `each`, `model`, and `cwd`. Unquoted `each` values and scalar values containing `{steps...}` are accepted via a repair pass, though quoting them is the form that cannot surprise you. Steps form a DAG: a step starts once every step in its `needs` succeeded; earlier results reach it through `{steps.<id>.output}`, declared arguments through `{args.<name>}`, and an each-step’s current line through `{item}`. An each-step (`each: {steps.<id>.output}`) fans out over the nonblank lines of a needed step’s output, one child per line.
|
||||
|
||||
### Starting a run
|
||||
|
||||
@@ -98,7 +98,7 @@ A file is YAML frontmatter — `name`, `description`, optional `args`, and a `st
|
||||
|
||||
Both surfaces validate the file, its arguments, its step-output references, the agents, and the working directories before any child spawns, then return immediately with the run’s job ID and the expanded plan. The tool accepts an optional `cwd` for discovery and step resolution; the slash command takes `key=value` arguments, quoted when a value contains spaces.
|
||||
|
||||
A project workflow is repo-controlled: an interactive session prompts once per distinct project workflows directory before its first run, and declining leaves no child behind. User workflows are trusted like user agents and never prompt.
|
||||
A project workflow and its project agents are repo-controlled: an interactive session asks once, naming every untrusted project directory involved in that start, and approving covers each directory for later starts. User workflows and user agents are trusted and never prompt.
|
||||
|
||||
### Managing runs
|
||||
|
||||
|
||||
+16
-21
@@ -14,11 +14,11 @@ import {
|
||||
getAgentDir,
|
||||
} from "@earendil-works/pi-coding-agent";
|
||||
import { Text } from "@earendil-works/pi-tui";
|
||||
import { readMaxWorkers } from "./config.ts";
|
||||
import { readMaxWorkers, readMaxWorkflowItems } from "./config.ts";
|
||||
import { formatJob, formatJobList } from "./job-format.ts";
|
||||
import { SubagentManager } from "./manager.ts";
|
||||
import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts";
|
||||
import { InvalidInvocationError, confirmProjectWorkflowSource, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.ts";
|
||||
import { InvalidInvocationError, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.ts";
|
||||
import {
|
||||
formatParallelSummary,
|
||||
getResultOutput,
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
import { ProcessRunner } from "./runner.ts";
|
||||
import { SubagentJobsParams, SubagentParams, WorkflowParams, type SubagentParamsType, type WorkflowParamsType } from "./schemas.ts";
|
||||
import { type JobSnapshot, type PreparedInvocation, type SubagentDetails, type SyncOutcome, type TaskRunner } from "./types.ts";
|
||||
import { formatWorkflowStart, parseWorkflowCommand, validateWorkflowArgs, validateWorkflowRunShape, type WorkflowStartResult } from "./workflow.ts";
|
||||
import { formatWorkflowStart, parseWorkflowCommand, type WorkflowStartResult } from "./workflow.ts";
|
||||
import { loadWorkflow } from "./workflows.ts";
|
||||
|
||||
function textResult(text: string, details?: unknown, isError?: boolean): AgentToolResult<any> {
|
||||
@@ -102,8 +102,11 @@ function jobResult(job: JobSnapshot): AgentToolResult<{ job: JobSnapshot }> {
|
||||
|
||||
export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
||||
const workerConfig = readMaxWorkers(process.env.PI_SUBAGENT_MAX_WORKERS);
|
||||
const workflowItemsConfig = readMaxWorkflowItems(process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS);
|
||||
let currentContext: ExtensionContext | undefined;
|
||||
let configurationWarning = workerConfig.warning;
|
||||
let configurationWarnings = [workerConfig.warning, workflowItemsConfig.warning].filter(
|
||||
(warning): warning is string => warning !== undefined,
|
||||
);
|
||||
|
||||
const updateStatus = (ctx: ExtensionContext | undefined = currentContext): void => {
|
||||
if (!ctx) return;
|
||||
@@ -132,13 +135,14 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
||||
},
|
||||
});
|
||||
|
||||
const approvedProjectWorkflowDirs = new Set<string>();
|
||||
const approvedProjectDirs = new Set<string>();
|
||||
|
||||
/**
|
||||
* The single start path shared by the tool and the slash command.
|
||||
*
|
||||
* Loading, argument validation, and project-workflow trust all happen before
|
||||
* the manager creates a run, so any failure leaves no child behind.
|
||||
* Loading, validation, and the combined project-source trust gate all
|
||||
* happen before the manager creates a run, so any failure leaves no child
|
||||
* behind. One start prompts at most once, for every untrusted directory.
|
||||
*/
|
||||
async function startWorkflow(
|
||||
request: Pick<WorkflowParamsType, "name" | "args" | "cwd">,
|
||||
@@ -148,17 +152,10 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
||||
const plan = loadWorkflow(request.name, effectiveCwd);
|
||||
const args = request.args ?? {};
|
||||
|
||||
// Validate run-specific failures before asking the user to trust a project.
|
||||
validateWorkflowRunShape(plan);
|
||||
validateWorkflowArgs(plan, args);
|
||||
|
||||
await confirmProjectWorkflowSource(plan, ctx, {
|
||||
cwd: effectiveCwd,
|
||||
approvedDirectories: approvedProjectWorkflowDirs,
|
||||
});
|
||||
|
||||
const prepareContext: PrepareContext = { ...ctx, cwd: effectiveCwd };
|
||||
const prepared = await prepareWorkflowInvocation(plan, args, prepareContext);
|
||||
const prepared = await prepareWorkflowInvocation(plan, args, prepareContext, {
|
||||
approvedDirectories: approvedProjectDirs,
|
||||
});
|
||||
return manager.startWorkflow(prepared);
|
||||
}
|
||||
|
||||
@@ -166,10 +163,8 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
||||
currentContext = ctx;
|
||||
manager.restore(extractJobSnapshots(ctx.sessionManager.getBranch()));
|
||||
updateStatus(ctx);
|
||||
if (configurationWarning) {
|
||||
ctx.ui.notify(configurationWarning, "warning");
|
||||
configurationWarning = undefined;
|
||||
}
|
||||
for (const warning of configurationWarnings) ctx.ui.notify(warning, "warning");
|
||||
configurationWarnings = [];
|
||||
});
|
||||
|
||||
pi.on("session_shutdown", async () => {
|
||||
|
||||
+99
-173
@@ -1,9 +1,12 @@
|
||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||
import { buildWorkflowJournal, type WorkflowJournal } from "./journal.ts";
|
||||
import {
|
||||
emptyRunResult,
|
||||
emptyTaskSnapshot,
|
||||
emptyUsage,
|
||||
isTerminalJob,
|
||||
isTerminalTask,
|
||||
taskIdentityExtras,
|
||||
type InvocationMode,
|
||||
type JobSnapshot,
|
||||
type JobStatus,
|
||||
@@ -69,6 +72,18 @@ interface ScheduledTask {
|
||||
resolve: (result: RunResult) => void;
|
||||
}
|
||||
|
||||
/** One workflow execution's mutable DAG state, passed through its scheduler helpers. */
|
||||
interface WorkflowRunState {
|
||||
execution: Execution;
|
||||
spec: WorkflowRunSpec;
|
||||
stepTasks: Map<string, InternalTask>;
|
||||
activeChildren: Map<InternalTask, Promise<void>>;
|
||||
itemTasks: Map<string, InternalTask[]>;
|
||||
pendingItems: Map<string, InternalTask[]>;
|
||||
itemCounts: Map<string, number>;
|
||||
concurrency: number;
|
||||
}
|
||||
|
||||
interface Waiter {
|
||||
resolve: (snapshot: JobSnapshot) => void;
|
||||
reject: (error: Error) => void;
|
||||
@@ -83,38 +98,8 @@ function initialTask(prepared: PreparedTask, now: number): InternalTask {
|
||||
void now;
|
||||
return {
|
||||
prepared,
|
||||
result: {
|
||||
agent: prepared.agent.name,
|
||||
agentSource: prepared.agent.source,
|
||||
task: prepared.task,
|
||||
cwd: prepared.cwd,
|
||||
step: prepared.step,
|
||||
stepId: prepared.stepId,
|
||||
item: prepared.item,
|
||||
status: "queued",
|
||||
exitCode: null,
|
||||
messages: [],
|
||||
output: "",
|
||||
stderr: "",
|
||||
usage: emptyUsage(),
|
||||
},
|
||||
snapshot: {
|
||||
agent: prepared.agent.name,
|
||||
agentSource: prepared.agent.source,
|
||||
task: prepared.task,
|
||||
cwd: prepared.cwd,
|
||||
step: prepared.step,
|
||||
stepId: prepared.stepId,
|
||||
item: prepared.item,
|
||||
status: "queued",
|
||||
exitCode: null,
|
||||
output: "",
|
||||
outputTruncated: false,
|
||||
outputBytesOmitted: 0,
|
||||
stderr: "",
|
||||
stderrTruncated: false,
|
||||
usage: emptyUsage(),
|
||||
},
|
||||
result: { ...emptyRunResult(prepared), status: "queued" },
|
||||
snapshot: emptyTaskSnapshot(prepared),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -266,9 +251,7 @@ export class SubagentManager {
|
||||
},
|
||||
task: result.task,
|
||||
cwd: result.cwd,
|
||||
step: result.step,
|
||||
stepId: result.stepId,
|
||||
item: result.item,
|
||||
...taskIdentityExtras(result),
|
||||
};
|
||||
const task = initialTask(prepared, this.now());
|
||||
task.snapshot = structuredClone(result);
|
||||
@@ -369,27 +352,21 @@ export class SubagentManager {
|
||||
const scheduled = this.queue[index];
|
||||
if (scheduled.execution !== execution) continue;
|
||||
this.queue.splice(index, 1);
|
||||
scheduled.task.snapshot.status = "cancelled";
|
||||
scheduled.task.snapshot.finishedAt = this.now();
|
||||
scheduled.task.result = this.cancelledResult(scheduled.task);
|
||||
scheduled.resolve(scheduled.task.result);
|
||||
const result = this.settleTask(scheduled.task, "cancelled", this.cancelledResult(scheduled.task));
|
||||
scheduled.resolve(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);
|
||||
this.settleTask(task, "cancelled", this.cancelledResult(task));
|
||||
}
|
||||
// An each-step's coordinator row has no child process of its own;
|
||||
// cancellation still makes it terminal immediately.
|
||||
for (const task of execution.tasks) {
|
||||
if (task.snapshot.status !== "running" || task.controller) continue;
|
||||
task.snapshot.status = "cancelled";
|
||||
task.snapshot.finishedAt = this.now();
|
||||
task.result = this.cancelledResult(task);
|
||||
this.settleTask(task, "cancelled", this.cancelledResult(task));
|
||||
}
|
||||
}
|
||||
for (const task of execution.tasks) {
|
||||
@@ -400,20 +377,27 @@ export class SubagentManager {
|
||||
if (!execution.tasks.some((task) => task.snapshot.status === "running")) this.finalize(execution, "cancelled");
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a task to a terminal snapshot and its matching result in one step.
|
||||
* Every settlement that is not a runner completion goes through here, so
|
||||
* status, finish time, and result status cannot drift apart.
|
||||
*/
|
||||
private settleTask(
|
||||
task: InternalTask,
|
||||
status: TaskStatus,
|
||||
result: RunResult,
|
||||
snapshot: Partial<TaskSnapshot> = {},
|
||||
): RunResult {
|
||||
task.snapshot.status = status;
|
||||
Object.assign(task.snapshot, snapshot);
|
||||
task.snapshot.finishedAt = this.now();
|
||||
task.result = { ...result, status };
|
||||
return task.result;
|
||||
}
|
||||
|
||||
private cancelledResult(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,
|
||||
item: task.prepared.item,
|
||||
exitCode: null,
|
||||
messages: [],
|
||||
output: "",
|
||||
stderr: "",
|
||||
usage: emptyUsage(),
|
||||
...emptyRunResult(task.prepared),
|
||||
status: "cancelled",
|
||||
stopReason: "aborted",
|
||||
errorMessage: "Cancelled by caller",
|
||||
@@ -489,37 +473,41 @@ export class SubagentManager {
|
||||
return;
|
||||
}
|
||||
|
||||
const stepTasks = new Map<string, InternalTask>();
|
||||
const state: WorkflowRunState = {
|
||||
execution,
|
||||
spec,
|
||||
stepTasks: new Map(),
|
||||
activeChildren: new Map(),
|
||||
itemTasks: new Map(),
|
||||
pendingItems: new Map(),
|
||||
itemCounts: new Map(),
|
||||
concurrency: workflowRunConcurrency(this.maxWorkers),
|
||||
};
|
||||
for (const task of execution.tasks) {
|
||||
if (task.prepared.stepId) stepTasks.set(task.prepared.stepId, task);
|
||||
if (task.prepared.stepId) state.stepTasks.set(task.prepared.stepId, task);
|
||||
}
|
||||
const concurrency = workflowRunConcurrency(this.maxWorkers);
|
||||
const activeChildren = new Map<InternalTask, Promise<void>>();
|
||||
const itemTasks = new Map<string, InternalTask[]>();
|
||||
const pendingItems = new Map<string, InternalTask[]>();
|
||||
const itemCounts = new Map<string, number>();
|
||||
for (const step of spec.steps) {
|
||||
if (step.each !== undefined) itemCounts.set(step.id, 0);
|
||||
if (step.each !== undefined) state.itemCounts.set(step.id, 0);
|
||||
}
|
||||
|
||||
while (true) {
|
||||
for (const [task] of activeChildren) {
|
||||
if (isTerminalTask(task.snapshot.status)) activeChildren.delete(task);
|
||||
for (const [task] of state.activeChildren) {
|
||||
if (isTerminalTask(task.snapshot.status)) state.activeChildren.delete(task);
|
||||
}
|
||||
|
||||
if (isTerminalJob(execution.status)) return;
|
||||
if (execution.cancelRequested) {
|
||||
if (activeChildren.size === 0) {
|
||||
if (state.activeChildren.size === 0) {
|
||||
this.finalize(execution, "cancelled");
|
||||
return;
|
||||
}
|
||||
await Promise.race(activeChildren.values());
|
||||
await Promise.race(state.activeChildren.values());
|
||||
continue;
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
if (this.propagateWorkflowSkips(execution, spec, stepTasks)) changed = true;
|
||||
if (this.settleWorkflowItemSteps(execution, spec, stepTasks, itemTasks)) changed = true;
|
||||
if (this.propagateWorkflowSkips(state)) changed = true;
|
||||
if (this.settleWorkflowItemSteps(state)) changed = true;
|
||||
|
||||
if (execution.tasks.every((task) => isTerminalTask(task.snapshot.status))) {
|
||||
const outcome = execution.tasks.some((task) => task.snapshot.status === "failed") ? "failed" : "succeeded";
|
||||
@@ -527,32 +515,26 @@ export class SubagentManager {
|
||||
return;
|
||||
}
|
||||
|
||||
if (concurrency - activeChildren.size > 0) {
|
||||
if (this.releaseWorkflowSteps(execution, spec, stepTasks, activeChildren, itemCounts, pendingItems, itemTasks, concurrency)) {
|
||||
changed = true;
|
||||
}
|
||||
if (this.launchWorkflowItems(execution, spec, stepTasks, activeChildren, pendingItems, concurrency)) changed = true;
|
||||
if (state.concurrency - state.activeChildren.size > 0) {
|
||||
if (this.releaseWorkflowSteps(state)) changed = true;
|
||||
if (this.launchWorkflowItems(state)) changed = true;
|
||||
}
|
||||
|
||||
if (changed) this.emit(execution);
|
||||
|
||||
if (activeChildren.size === 0) {
|
||||
if (state.activeChildren.size === 0) {
|
||||
if (changed) continue;
|
||||
// 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(activeChildren.values());
|
||||
await Promise.race(state.activeChildren.values());
|
||||
}
|
||||
}
|
||||
|
||||
private propagateWorkflowSkips(
|
||||
execution: Execution,
|
||||
spec: WorkflowRunSpec,
|
||||
stepTasks: Map<string, InternalTask>,
|
||||
): boolean {
|
||||
void execution;
|
||||
private propagateWorkflowSkips(state: WorkflowRunState): boolean {
|
||||
const { spec, stepTasks } = state;
|
||||
let changed = false;
|
||||
let pass = true;
|
||||
while (pass) {
|
||||
@@ -570,10 +552,7 @@ export class SubagentManager {
|
||||
});
|
||||
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;
|
||||
this.settleTask(task, "skipped", result, { errorMessage: result.errorMessage });
|
||||
changed = true;
|
||||
pass = true;
|
||||
}
|
||||
@@ -581,17 +560,9 @@ export class SubagentManager {
|
||||
return changed;
|
||||
}
|
||||
|
||||
private releaseWorkflowSteps(
|
||||
execution: Execution,
|
||||
spec: WorkflowRunSpec,
|
||||
stepTasks: Map<string, InternalTask>,
|
||||
activeChildren: Map<InternalTask, Promise<void>>,
|
||||
itemCounts: Map<string, number>,
|
||||
pendingItems: Map<string, InternalTask[]>,
|
||||
itemTasks: Map<string, InternalTask[]>,
|
||||
concurrency: number,
|
||||
): boolean {
|
||||
let slots = concurrency - activeChildren.size;
|
||||
private releaseWorkflowSteps(state: WorkflowRunState): boolean {
|
||||
const { execution, spec, stepTasks, itemCounts } = state;
|
||||
let slots = state.concurrency - state.activeChildren.size;
|
||||
if (slots <= 0) return false;
|
||||
let released = false;
|
||||
|
||||
@@ -642,8 +613,8 @@ export class SubagentManager {
|
||||
task.snapshot.startedAt = this.now();
|
||||
execution.tasks.push(...children);
|
||||
execution.plannedTaskCount += children.length;
|
||||
itemTasks.set(step.id, children);
|
||||
pendingItems.set(step.id, [...children]);
|
||||
state.itemTasks.set(step.id, children);
|
||||
state.pendingItems.set(step.id, [...children]);
|
||||
released = true;
|
||||
continue;
|
||||
}
|
||||
@@ -653,7 +624,7 @@ export class SubagentManager {
|
||||
task.snapshot.task = brief;
|
||||
if (task.result) task.result = { ...task.result, task: brief, stepId: step.id };
|
||||
task.submitted = true;
|
||||
activeChildren.set(task, this.schedule(execution, task).then(() => undefined));
|
||||
state.activeChildren.set(task, this.schedule(execution, task).then(() => undefined));
|
||||
released = true;
|
||||
slots--;
|
||||
}
|
||||
@@ -661,15 +632,9 @@ export class SubagentManager {
|
||||
return released;
|
||||
}
|
||||
|
||||
private launchWorkflowItems(
|
||||
execution: Execution,
|
||||
spec: WorkflowRunSpec,
|
||||
stepTasks: Map<string, InternalTask>,
|
||||
activeChildren: Map<InternalTask, Promise<void>>,
|
||||
pendingItems: Map<string, InternalTask[]>,
|
||||
concurrency: number,
|
||||
): boolean {
|
||||
let slots = concurrency - activeChildren.size;
|
||||
private launchWorkflowItems(state: WorkflowRunState): boolean {
|
||||
const { execution, spec, stepTasks, pendingItems } = state;
|
||||
let slots = state.concurrency - state.activeChildren.size;
|
||||
if (slots <= 0) return false;
|
||||
let launched = false;
|
||||
let pass = true;
|
||||
@@ -692,7 +657,7 @@ export class SubagentManager {
|
||||
stepTask.snapshot.startedAt = this.now();
|
||||
if (stepTask.result) stepTask.result = { ...stepTask.result, status: "running" };
|
||||
}
|
||||
activeChildren.set(child, this.schedule(execution, child).then(() => undefined));
|
||||
state.activeChildren.set(child, this.schedule(execution, child).then(() => undefined));
|
||||
launched = true;
|
||||
slots--;
|
||||
}
|
||||
@@ -701,13 +666,8 @@ export class SubagentManager {
|
||||
return launched;
|
||||
}
|
||||
|
||||
private settleWorkflowItemSteps(
|
||||
execution: Execution,
|
||||
spec: WorkflowRunSpec,
|
||||
stepTasks: Map<string, InternalTask>,
|
||||
itemTasks: Map<string, InternalTask[]>,
|
||||
): boolean {
|
||||
void execution;
|
||||
private settleWorkflowItemSteps(state: WorkflowRunState): boolean {
|
||||
const { spec, stepTasks, itemTasks } = state;
|
||||
let changed = false;
|
||||
|
||||
for (const step of spec.steps) {
|
||||
@@ -725,14 +685,9 @@ export class SubagentManager {
|
||||
|
||||
if (interrupted || cancelled) {
|
||||
const status = interrupted ? "interrupted" : "cancelled";
|
||||
task.snapshot.status = status;
|
||||
task.snapshot.errorMessage = interrupted ? "Interrupted by session shutdown" : "Cancelled by caller";
|
||||
task.result = {
|
||||
...(task.result ?? this.cancelledResult(task)),
|
||||
status,
|
||||
output: "",
|
||||
errorMessage: task.snapshot.errorMessage,
|
||||
};
|
||||
const message = interrupted ? "Interrupted by session shutdown" : "Cancelled by caller";
|
||||
const result = { ...(task.result ?? this.cancelledResult(task)), output: "", errorMessage: message };
|
||||
this.settleTask(task, status, result, { errorMessage: message });
|
||||
} else {
|
||||
const output = joinWorkflowItemOutputs(
|
||||
items.map((item) => ({
|
||||
@@ -741,23 +696,17 @@ export class SubagentManager {
|
||||
output: item.snapshot.status === "succeeded" ? item.snapshot.output : "",
|
||||
})),
|
||||
);
|
||||
task.snapshot.output = output;
|
||||
task.snapshot.outputTruncated = false;
|
||||
task.snapshot.outputBytesOmitted = 0;
|
||||
const snapshot = { output, outputTruncated: false, outputBytesOmitted: 0 };
|
||||
if (succeeded > 0) {
|
||||
task.snapshot.status = "succeeded";
|
||||
task.snapshot.errorMessage = undefined;
|
||||
task.result = { ...task.result!, status: "succeeded", output, errorMessage: undefined, exitCode: 0 };
|
||||
const result = { ...task.result!, output, errorMessage: undefined, exitCode: 0 };
|
||||
this.settleTask(task, "succeeded", result, { ...snapshot, errorMessage: undefined });
|
||||
} else {
|
||||
const message = `All ${items.length} item${items.length === 1 ? "" : "s"} failed`;
|
||||
task.snapshot.status = "failed";
|
||||
task.snapshot.exitCode = 1;
|
||||
task.snapshot.errorMessage = message;
|
||||
task.result = { ...task.result!, status: "failed", output, errorMessage: message, exitCode: 1 };
|
||||
const result = { ...task.result!, output, errorMessage: message, exitCode: 1 };
|
||||
this.settleTask(task, "failed", result, { ...snapshot, exitCode: 1, errorMessage: message });
|
||||
}
|
||||
}
|
||||
|
||||
task.snapshot.finishedAt = this.now();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
@@ -765,27 +714,17 @@ export class SubagentManager {
|
||||
}
|
||||
|
||||
private failWorkflowStep(task: InternalTask, message: string): void {
|
||||
task.snapshot.status = "failed";
|
||||
task.snapshot.exitCode = 1;
|
||||
task.snapshot.errorMessage = message;
|
||||
task.snapshot.finishedAt = this.now();
|
||||
task.result = { ...task.result!, status: "failed", exitCode: 1, errorMessage: message };
|
||||
this.settleTask(
|
||||
task,
|
||||
"failed",
|
||||
{ ...task.result!, exitCode: 1, errorMessage: message },
|
||||
{ exitCode: 1, errorMessage: message },
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
item: task.prepared.item,
|
||||
exitCode: null,
|
||||
messages: [],
|
||||
output: "",
|
||||
stderr: "",
|
||||
usage: emptyUsage(),
|
||||
...emptyRunResult(task.prepared),
|
||||
status: "skipped",
|
||||
errorMessage: "Skipped because a required step did not succeed",
|
||||
};
|
||||
@@ -805,9 +744,7 @@ export class SubagentManager {
|
||||
const { execution, task } = scheduled;
|
||||
if (isTerminalJob(execution.status) || execution.cancelRequested) {
|
||||
const result = execution.status === "interrupted" ? this.interruptedResult(task) : this.cancelledResult(task);
|
||||
task.snapshot.status = result.status ?? "cancelled";
|
||||
task.snapshot.finishedAt = this.now();
|
||||
task.result = execution.isAsync ? { ...result, messages: [] } : result;
|
||||
this.settleTask(task, result.status ?? "cancelled", execution.isAsync ? { ...result, messages: [] } : result);
|
||||
scheduled.resolve(result);
|
||||
this.emit(execution);
|
||||
this.emitSync(execution);
|
||||
@@ -845,17 +782,8 @@ export class SubagentManager {
|
||||
resolve(result);
|
||||
} catch (error) {
|
||||
const result: RunResult = {
|
||||
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,
|
||||
...emptyRunResult(task.prepared),
|
||||
exitCode: 1,
|
||||
messages: [],
|
||||
output: "",
|
||||
stderr: "",
|
||||
usage: emptyUsage(),
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
this.applyResult(execution, task, result);
|
||||
@@ -867,10 +795,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;
|
||||
task.result.item = task.prepared.item;
|
||||
const settled = execution.isAsync ? { ...result, messages: [] } : result;
|
||||
task.result = { ...settled, ...taskIdentityExtras(task.prepared) };
|
||||
if (task.snapshot.status === "interrupted") {
|
||||
task.result.status = "interrupted";
|
||||
return;
|
||||
@@ -973,7 +899,7 @@ export class SubagentManager {
|
||||
try {
|
||||
this.onWorkflowJournal(buildWorkflowJournal(this.snapshot(execution), spec));
|
||||
} catch {
|
||||
// Persistence failures cannot change run execution.
|
||||
// Persistence failures cannot change how a run proceeds.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+116
-55
@@ -63,13 +63,10 @@ export class ProjectWorkflowDeclinedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export interface ConfirmProjectWorkflowOptions {
|
||||
/** Prompt before running repo-controlled workflows. Default: true. */
|
||||
confirmProjectWorkflows?: boolean;
|
||||
/** Base cwd for the trusted project's own workflow directory. Default: ctx.cwd. */
|
||||
cwd?: string;
|
||||
/** Directories already approved in this session, so each prompts once. */
|
||||
approvedDirectories?: Set<string>;
|
||||
interface ProjectSource {
|
||||
directory: string;
|
||||
workflow?: string;
|
||||
agents: string[];
|
||||
}
|
||||
|
||||
function canonicalDirectory(directory: string): string {
|
||||
@@ -80,38 +77,81 @@ function canonicalDirectory(directory: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function trustedProjectAgentsDirectory(ctx: PrepareContext, agentScope: AgentScope): string | undefined {
|
||||
if (!ctx.isProjectTrusted()) return undefined;
|
||||
const discovery = discoverAgents(ctx.cwd, agentScope);
|
||||
return discovery.projectAgentsDir ? canonicalDirectory(discovery.projectAgentsDir) : undefined;
|
||||
}
|
||||
|
||||
function trustedProjectWorkflowsDirectory(ctx: PrepareContext): string | undefined {
|
||||
if (!ctx.isProjectTrusted()) return undefined;
|
||||
const discovery = discoverWorkflows(ctx.cwd, "both");
|
||||
return discovery.projectWorkflowsDir ? canonicalDirectory(discovery.projectWorkflowsDir) : undefined;
|
||||
}
|
||||
|
||||
/** The source of one confirmation prompt: every untrusted directory in a start. */
|
||||
function confirmationMessage(sources: readonly ProjectSource[]): string {
|
||||
const lines = ["Project-controlled resources are repo-controlled. Only continue for repositories you trust."];
|
||||
for (const source of sources) {
|
||||
lines.push("", `Directory: ${source.directory}`);
|
||||
if (source.workflow !== undefined) lines.push(`Workflow: ${source.workflow}`);
|
||||
if (source.agents.length > 0) lines.push(`Agents: ${source.agents.join(", ")}`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm a project workflow's directory once, mirroring the project-agent gate.
|
||||
* Confirm all untrusted directories for one start in a single prompt.
|
||||
*
|
||||
* User-level workflows are trusted and never prompt. A trusted session exempts
|
||||
* only its own project workflows directory; a foreign project selected through
|
||||
* the start cwd still prompts. No UI keeps the existing no-prompt behavior.
|
||||
* Approving adds every directory to the session set, so later starts prompt
|
||||
* only for directories they have not already approved. No UI keeps the
|
||||
* existing no-prompt behavior.
|
||||
*/
|
||||
export async function confirmProjectWorkflowSource(
|
||||
plan: WorkflowPlan,
|
||||
async function confirmProjectSources(
|
||||
sources: readonly ProjectSource[],
|
||||
ctx: PrepareContext,
|
||||
options: ConfirmProjectWorkflowOptions = {},
|
||||
): Promise<string | null> {
|
||||
if (plan.source !== "project") return null;
|
||||
approvedDirectories?: Set<string>,
|
||||
): Promise<void> {
|
||||
if (sources.length === 0 || !ctx.hasUI) return;
|
||||
|
||||
const directory = canonicalDirectory(path.dirname(plan.filePath));
|
||||
if (options.approvedDirectories?.has(directory)) return directory;
|
||||
|
||||
const trustedDiscovery = ctx.isProjectTrusted() ? discoverWorkflows(options.cwd ?? ctx.cwd, "both") : null;
|
||||
const trustedDirectory = trustedDiscovery?.projectWorkflowsDir
|
||||
? canonicalDirectory(trustedDiscovery.projectWorkflowsDir)
|
||||
: undefined;
|
||||
|
||||
if (trustedDirectory !== directory && (options.confirmProjectWorkflows ?? true) && ctx.hasUI) {
|
||||
const approved = await ctx.ui.confirm(
|
||||
"Run project workflow?",
|
||||
`Workflow: ${plan.name}\nSource: ${directory}\n\nProject workflows are repo-controlled. Only continue for repositories you trust.`,
|
||||
);
|
||||
if (!approved) throw new ProjectWorkflowDeclinedError(directory, plan.name);
|
||||
const approved = await ctx.ui.confirm("Run project-controlled resources?", confirmationMessage(sources));
|
||||
if (!approved) {
|
||||
const workflow = sources.find((source) => source.workflow !== undefined);
|
||||
if (workflow) throw new ProjectWorkflowDeclinedError(workflow.directory, workflow.workflow!);
|
||||
const agents = sources.find((source) => source.agents.length > 0)!;
|
||||
throw new ProjectAgentDeclinedError(agents.directory, agents.agents);
|
||||
}
|
||||
|
||||
options.approvedDirectories?.add(directory);
|
||||
return directory;
|
||||
for (const source of sources) approvedDirectories?.add(source.directory);
|
||||
}
|
||||
|
||||
function mergeProjectSources(sources: ReadonlyArray<ProjectSource | null>): ProjectSource[] {
|
||||
const merged = new Map<string, ProjectSource>();
|
||||
for (const source of sources) {
|
||||
if (!source) continue;
|
||||
const existing = merged.get(source.directory);
|
||||
if (!existing) {
|
||||
merged.set(source.directory, { ...source, agents: [...source.agents] });
|
||||
continue;
|
||||
}
|
||||
if (source.workflow !== undefined) existing.workflow = source.workflow;
|
||||
existing.agents.push(...source.agents);
|
||||
}
|
||||
return Array.from(merged.values());
|
||||
}
|
||||
|
||||
/** Project workflow directories use the same gate as project agents. */
|
||||
function projectWorkflowSource(
|
||||
plan: WorkflowPlan,
|
||||
ctx: PrepareContext,
|
||||
approvedDirectories: Set<string> | undefined,
|
||||
confirmProjectWorkflows: boolean,
|
||||
): ProjectSource | null {
|
||||
if (plan.source !== "project" || !confirmProjectWorkflows) return null;
|
||||
const directory = canonicalDirectory(path.dirname(plan.filePath));
|
||||
if (approvedDirectories?.has(directory)) return null;
|
||||
if (directory === trustedProjectWorkflowsDirectory(ctx)) return null;
|
||||
return { directory, workflow: plan.name, agents: [] };
|
||||
}
|
||||
|
||||
export interface PrepareUIContext {
|
||||
@@ -290,31 +330,37 @@ function collectProjectAgent(
|
||||
projectAgentsByDir.set(projectAgentsDir, names);
|
||||
}
|
||||
|
||||
/** The project-agent directories that still need confirmation for this start. */
|
||||
function projectAgentSources(
|
||||
projectAgentsByDir: Map<string, Set<string>>,
|
||||
ctx: PrepareContext,
|
||||
agentScope: AgentScope,
|
||||
confirmProjectAgents: boolean,
|
||||
approvedDirectories?: Set<string>,
|
||||
): ProjectSource[] {
|
||||
if (agentScope === "user" || !confirmProjectAgents || !ctx.hasUI) return [];
|
||||
const trustedDirectory = trustedProjectAgentsDirectory(ctx, agentScope);
|
||||
const sources: ProjectSource[] = [];
|
||||
for (const [directory, names] of projectAgentsByDir) {
|
||||
const canonical = canonicalDirectory(directory);
|
||||
if (approvedDirectories?.has(canonical) || canonical === trustedDirectory) continue;
|
||||
sources.push({ directory: canonical, agents: Array.from(names) });
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
/** Confirm every distinct repo-controlled agent source before anything starts. */
|
||||
async function confirmProjectAgentSources(
|
||||
projectAgentsByDir: Map<string, Set<string>>,
|
||||
ctx: PrepareContext,
|
||||
agentScope: AgentScope,
|
||||
confirmProjectAgents: boolean,
|
||||
approvedDirectories?: Set<string>,
|
||||
): 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);
|
||||
}
|
||||
for (const source of projectAgentSources(projectAgentsByDir, ctx, agentScope, confirmProjectAgents, approvedDirectories)) {
|
||||
await confirmProjectSources([source], ctx, approvedDirectories);
|
||||
}
|
||||
|
||||
return projectAgentsDirs;
|
||||
}
|
||||
|
||||
@@ -372,6 +418,10 @@ export interface PrepareWorkflowOptions {
|
||||
agentScope?: AgentScope;
|
||||
/** Prompt before running repo-controlled agents. Default: true. */
|
||||
confirmProjectAgents?: boolean;
|
||||
/** Prompt before running repo-controlled workflows. Default: true. */
|
||||
confirmProjectWorkflows?: boolean;
|
||||
/** Directories already approved in this session, so each prompts once. */
|
||||
approvedDirectories?: Set<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -392,7 +442,7 @@ export async function prepareWorkflowInvocation(
|
||||
// the real counts before any item child spawns.
|
||||
validateWorkflowExpansion(
|
||||
plan,
|
||||
Object.fromEntries(plan.steps.filter((step) => step.each !== undefined).map((step) => [step.id, 0])),
|
||||
new Map(plan.steps.filter((step) => step.each !== undefined).map((step): [string, number] => [step.id, 0])),
|
||||
);
|
||||
|
||||
const agentScope = options.agentScope ?? "both";
|
||||
@@ -414,12 +464,23 @@ export async function prepareWorkflowInvocation(
|
||||
};
|
||||
});
|
||||
|
||||
const projectAgentsDirs = await confirmProjectAgentSources(
|
||||
projectAgentsByDir,
|
||||
ctx,
|
||||
agentScope,
|
||||
options.confirmProjectAgents ?? true,
|
||||
);
|
||||
const projectAgentsDirs = Array.from(projectAgentsByDir.keys());
|
||||
const sources = mergeProjectSources([
|
||||
projectWorkflowSource(
|
||||
plan,
|
||||
ctx,
|
||||
options.approvedDirectories,
|
||||
options.confirmProjectWorkflows ?? true,
|
||||
),
|
||||
...projectAgentSources(
|
||||
projectAgentsByDir,
|
||||
ctx,
|
||||
agentScope,
|
||||
options.confirmProjectAgents ?? true,
|
||||
options.approvedDirectories,
|
||||
),
|
||||
]);
|
||||
await confirmProjectSources(sources, ctx, options.approvedDirectories);
|
||||
|
||||
return {
|
||||
mode: "workflow",
|
||||
|
||||
+12
-17
@@ -325,6 +325,15 @@ function resultOutput(result: RunResult): string {
|
||||
return result.output || getFinalOutput(result.messages);
|
||||
}
|
||||
|
||||
/** The terminal status icon shared by chain and parallel/workflow rows. */
|
||||
function resultStatusIcon(result: RunResult, theme: SubagentRenderTheme): string {
|
||||
return isSkippedStatus(result.status)
|
||||
? theme.fg("muted", "–")
|
||||
: isFailedResult(result)
|
||||
? theme.fg("error", "✗")
|
||||
: theme.fg("success", "✓");
|
||||
}
|
||||
|
||||
export function renderSubagentResult(
|
||||
result: SubagentResultLike,
|
||||
options: SubagentRenderOptions,
|
||||
@@ -438,11 +447,7 @@ export function renderSubagentResult(
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
const rIcon = isSkippedStatus(r.status)
|
||||
? theme.fg("muted", "–")
|
||||
: isFailedResult(r)
|
||||
? theme.fg("error", "✗")
|
||||
: theme.fg("success", "✓");
|
||||
const rIcon = resultStatusIcon(r, theme);
|
||||
const displayItems = getDisplayItems(r.messages);
|
||||
const finalOutput = resultOutput(r);
|
||||
|
||||
@@ -522,11 +527,7 @@ export function renderSubagentResult(
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
const rIcon = isSkippedStatus(r.status)
|
||||
? theme.fg("muted", "–")
|
||||
: isFailedResult(r)
|
||||
? theme.fg("error", "✗")
|
||||
: theme.fg("success", "✓");
|
||||
const rIcon = resultStatusIcon(r, theme);
|
||||
const displayItems = getDisplayItems(r.messages);
|
||||
const finalOutput = resultOutput(r);
|
||||
|
||||
@@ -562,13 +563,7 @@ export function renderSubagentResult(
|
||||
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", "⏳")
|
||||
: isSkippedStatus(r.status)
|
||||
? theme.fg("muted", "–")
|
||||
: isFailedResult(r)
|
||||
? theme.fg("error", "✗")
|
||||
: theme.fg("success", "✓");
|
||||
const rIcon = rRunning ? theme.fg("warning", "⏳") : resultStatusIcon(r, theme);
|
||||
const displayItems = getDisplayItems(r.messages);
|
||||
const finalOutput = resultOutput(r);
|
||||
text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
|
||||
|
||||
+6
-13
@@ -12,7 +12,7 @@ import * as path from "node:path";
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
import type { Message } from "@earendil-works/pi-ai";
|
||||
import {
|
||||
emptyUsage,
|
||||
emptyRunResult,
|
||||
type DispatchDefaults,
|
||||
type PreparedTask,
|
||||
type RunOptions,
|
||||
@@ -23,6 +23,9 @@ import {
|
||||
const DEFAULT_KILL_GRACE_MS = 5000;
|
||||
const DEFAULT_STDERR_LIMIT_BYTES = 64 * 1024;
|
||||
|
||||
/** Child sessions never delegate: no nested subagents and no nested workflow runs. */
|
||||
const EXCLUDED_CHILD_TOOLS = "subagent*,workflow";
|
||||
|
||||
export interface ProcessInvocation {
|
||||
command: string;
|
||||
args: string[];
|
||||
@@ -230,19 +233,9 @@ export class ProcessRunner implements TaskRunner {
|
||||
|
||||
async run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise<RunResult> {
|
||||
const result: RunResult = {
|
||||
agent: task.agent.name,
|
||||
agentSource: task.agent.source,
|
||||
task: task.task,
|
||||
cwd: task.cwd,
|
||||
step: task.step,
|
||||
stepId: task.stepId,
|
||||
item: task.item,
|
||||
...emptyRunResult(task),
|
||||
exitCode: 0,
|
||||
messages: [],
|
||||
output: "",
|
||||
stderr: "",
|
||||
stderrTruncated: false,
|
||||
usage: emptyUsage(),
|
||||
model: task.model ?? task.agent.model ?? defaults.model,
|
||||
};
|
||||
|
||||
@@ -263,7 +256,7 @@ 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 args: string[] = ["--mode", "json", "-p", "--no-session", "--exclude-tools", EXCLUDED_CHILD_TOOLS];
|
||||
const inheritsDispatchConfig = !task.model && !task.agent.model;
|
||||
const model = task.model ?? task.agent.model ?? defaults.model;
|
||||
if (model) args.push("--model", model);
|
||||
|
||||
@@ -97,6 +97,64 @@ export interface TaskSnapshot {
|
||||
finishedAt?: number;
|
||||
}
|
||||
|
||||
/** Identity fields shared by a task's prepared form, result, and snapshot. */
|
||||
export interface TaskIdentity {
|
||||
agent: string;
|
||||
agentSource: "user" | "project" | "unknown";
|
||||
task: string;
|
||||
cwd: string;
|
||||
step?: number;
|
||||
stepId?: string;
|
||||
item?: number;
|
||||
}
|
||||
|
||||
/** The step-identity subset, so adding a field changes one mapping here. */
|
||||
export function taskIdentityExtras(source: {
|
||||
step?: number;
|
||||
stepId?: string;
|
||||
item?: number;
|
||||
}): Pick<TaskIdentity, "step" | "stepId" | "item"> {
|
||||
return { step: source.step, stepId: source.stepId, item: source.item };
|
||||
}
|
||||
|
||||
/** Build the identity a fresh result or snapshot inherits from its prepared task. */
|
||||
export function taskIdentity(prepared: PreparedTask): TaskIdentity {
|
||||
return {
|
||||
agent: prepared.agent.name,
|
||||
agentSource: prepared.agent.source,
|
||||
task: prepared.task,
|
||||
cwd: prepared.cwd,
|
||||
...taskIdentityExtras(prepared),
|
||||
};
|
||||
}
|
||||
|
||||
/** A result before a child has run: no output, no usage, no exit. */
|
||||
export function emptyRunResult(prepared: PreparedTask): RunResult {
|
||||
return {
|
||||
...taskIdentity(prepared),
|
||||
exitCode: null,
|
||||
messages: [],
|
||||
output: "",
|
||||
stderr: "",
|
||||
usage: emptyUsage(),
|
||||
};
|
||||
}
|
||||
|
||||
/** A snapshot before a child has run: queued and empty. */
|
||||
export function emptyTaskSnapshot(prepared: PreparedTask): TaskSnapshot {
|
||||
return {
|
||||
...taskIdentity(prepared),
|
||||
status: "queued",
|
||||
exitCode: null,
|
||||
output: "",
|
||||
outputTruncated: false,
|
||||
outputBytesOmitted: 0,
|
||||
stderr: "",
|
||||
stderrTruncated: false,
|
||||
usage: emptyUsage(),
|
||||
};
|
||||
}
|
||||
|
||||
export interface JobSnapshot {
|
||||
id: string;
|
||||
mode: InvocationMode;
|
||||
|
||||
+2
-5
@@ -9,7 +9,7 @@
|
||||
|
||||
import { truncateUtf8Head } from "./output.ts";
|
||||
import type { JobSnapshot, PreparedInvocation, PreparedTask } from "./types.ts";
|
||||
import { WorkflowValidationError, type WorkflowPlan } from "./workflows.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;
|
||||
@@ -79,10 +79,7 @@ const PLACEHOLDER =
|
||||
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,
|
||||
});
|
||||
throw workflowValidationError(plan, message, stepId);
|
||||
}
|
||||
|
||||
/** The per-run reservation inside the shared worker pool (ADR 0002). */
|
||||
|
||||
+20
-13
@@ -57,7 +57,7 @@ export interface WorkflowDiscoveryResult {
|
||||
projectWorkflowsDir: string | null;
|
||||
}
|
||||
|
||||
export type WorkflowItemCounts = ReadonlyMap<string, number> | Readonly<Record<string, number>>;
|
||||
export type WorkflowItemCounts = ReadonlyMap<string, number>;
|
||||
|
||||
export interface WorkflowExpansionOptions {
|
||||
maxItemsPerEach?: number;
|
||||
@@ -89,6 +89,19 @@ export class WorkflowValidationError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** One shape for every plan-validation failure, with the plan and step named. */
|
||||
export function workflowValidationError(
|
||||
plan: { name?: string; filePath: string },
|
||||
message: string,
|
||||
stepId?: string,
|
||||
): WorkflowValidationError {
|
||||
const where = plan.name ? `Workflow "${plan.name}"` : "Workflow";
|
||||
return new WorkflowValidationError(`${where} (${plan.filePath}): ${message}`, {
|
||||
filePath: plan.filePath,
|
||||
stepId,
|
||||
});
|
||||
}
|
||||
|
||||
const TOP_LEVEL_FIELDS = ["name", "description", "args", "steps"] as const;
|
||||
const STEP_FIELDS = ["id", "agent", "task", "needs", "each", "model", "cwd"] as const;
|
||||
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
||||
@@ -165,8 +178,7 @@ export function parseWorkflow(content: string, options: ParseWorkflowOptions): W
|
||||
let name: string | undefined;
|
||||
|
||||
function fail(message: string, stepId?: string): never {
|
||||
const where = name ? `Workflow "${name}"` : "Workflow";
|
||||
throw new WorkflowValidationError(`${where} (${filePath}): ${message}`, { filePath, stepId });
|
||||
throw workflowValidationError({ name, filePath }, message, stepId);
|
||||
}
|
||||
|
||||
if (!hasFrontmatterBlock(content)) {
|
||||
@@ -274,6 +286,9 @@ export function parseWorkflow(content: string, options: ParseWorkflowOptions): W
|
||||
fail(`${label}.each must be a "{steps.<id>.output}" reference, got ${JSON.stringify(stepRecord.each)}.`, id);
|
||||
}
|
||||
}
|
||||
if (each === undefined && task.includes("{item}")) {
|
||||
fail(`${label}.task contains {item}, but {item} is only valid in a step with \`each\`.`, id);
|
||||
}
|
||||
|
||||
let model: string | undefined;
|
||||
const modelValue = stepRecord.model;
|
||||
@@ -472,16 +487,8 @@ export function loadWorkflow(name: string, cwd: string, scope: WorkflowScope = "
|
||||
return parseWorkflow(content, { source: file.source, filePath: file.filePath });
|
||||
}
|
||||
|
||||
function itemCountFor(items: WorkflowItemCounts, stepId: string): number | undefined {
|
||||
if (items instanceof Map) return items.get(stepId);
|
||||
return Object.hasOwn(items, stepId) ? (items as Readonly<Record<string, number>>)[stepId] : undefined;
|
||||
}
|
||||
|
||||
function failPlan(plan: WorkflowPlan, message: string, stepId?: string): never {
|
||||
throw new WorkflowValidationError(`Workflow "${plan.name}" (${plan.filePath}): ${message}`, {
|
||||
filePath: plan.filePath,
|
||||
stepId,
|
||||
});
|
||||
throw workflowValidationError(plan, message, stepId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -509,7 +516,7 @@ export function validateWorkflowExpansion(
|
||||
continue;
|
||||
}
|
||||
|
||||
const count = itemCountFor(items, step.id);
|
||||
const count = items.get(step.id);
|
||||
if (count === undefined) {
|
||||
failPlan(plan, `steps[${index}] ("${step.id}") has no item count for its "{steps.${step.each}.output}" fan-out.`, step.id);
|
||||
}
|
||||
|
||||
+65
-1
@@ -192,6 +192,31 @@ test("session restart restores persisted interrupted history without starting a
|
||||
}
|
||||
});
|
||||
|
||||
test("invalid workflow item configuration is surfaced as a warning at session start", async () => {
|
||||
const previous = process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS;
|
||||
try {
|
||||
for (const [value, warning] of [["0", true], ["257", true], ["1", false], ["256", false]] as const) {
|
||||
process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS = value;
|
||||
const h = await harness();
|
||||
try {
|
||||
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
|
||||
if (warning) {
|
||||
assert.equal(h.notifications.length, 1, value);
|
||||
assert.match(h.notifications[0], /PI_SUBAGENT_WORKFLOW_MAX_ITEMS/);
|
||||
assert.match(h.notifications[0], /using 32/);
|
||||
} else {
|
||||
assert.equal(h.notifications.length, 0, value);
|
||||
}
|
||||
} finally {
|
||||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS;
|
||||
else process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test("session_tree replaces history from the active branch", async () => {
|
||||
const h = await harness();
|
||||
try {
|
||||
@@ -346,7 +371,7 @@ test("project workflows prompt once per directory while user workflows are trust
|
||||
assert.notEqual(user.isError, true);
|
||||
|
||||
assert.equal(h.confirmations.length, 1);
|
||||
assert.match(h.confirmations[0].title, /project workflow/i);
|
||||
assert.match(h.confirmations[0].title, /project/i);
|
||||
assert.ok(h.confirmations[0].message.includes(path.dirname(projectFile)));
|
||||
assert.ok(h.confirmations[0].message.includes("project-flow"));
|
||||
assert.match(h.confirmations[0].message, /repo-controlled/);
|
||||
@@ -359,6 +384,45 @@ test("project workflows prompt once per directory while user workflows are trust
|
||||
}
|
||||
});
|
||||
|
||||
test("one workflow start confirms every untrusted project directory only once", async () => {
|
||||
const h = await harness([], { trusted: false });
|
||||
try {
|
||||
const projectFile = writeProjectWorkflow(h.cwd, "project-flow", {
|
||||
steps: [{ id: "run", agent: "scout", task: "project run" }],
|
||||
});
|
||||
|
||||
const first = await h.tools.get("workflow")!.execute(
|
||||
"wf-1",
|
||||
{ action: "start", name: "project-flow" },
|
||||
undefined,
|
||||
undefined,
|
||||
h.ctx,
|
||||
);
|
||||
assert.notEqual(first.isError, true);
|
||||
|
||||
const workflowDir = path.dirname(projectFile);
|
||||
const agentsDir = path.join(h.cwd, ".pi", "agents");
|
||||
assert.equal(h.confirmations.length, 1);
|
||||
assert.ok(h.confirmations[0].message.includes(workflowDir));
|
||||
assert.ok(h.confirmations[0].message.includes(agentsDir));
|
||||
assert.match(h.confirmations[0].message, /repo-controlled/);
|
||||
|
||||
const second = await h.tools.get("workflow")!.execute(
|
||||
"wf-2",
|
||||
{ action: "start", name: "project-flow" },
|
||||
undefined,
|
||||
undefined,
|
||||
h.ctx,
|
||||
);
|
||||
assert.notEqual(second.isError, true);
|
||||
assert.equal(h.confirmations.length, 1);
|
||||
assert.equal(h.runner.calls.length, 2);
|
||||
} finally {
|
||||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("declining project workflow trust aborts before any child spawns", async () => {
|
||||
const h = await harness([], { trusted: false, confirmResult: false });
|
||||
try {
|
||||
|
||||
+6
-4
@@ -171,7 +171,7 @@ test("bounds stderr to a valid UTF-8 64 KiB tail", async () => {
|
||||
assert.equal(Buffer.from(result.stderr, "utf8").toString("utf8"), result.stderr);
|
||||
});
|
||||
|
||||
test("child arguments exclude subagent tools and do not inherit thinking with an explicit model", async () => {
|
||||
test("child arguments exclude subagent and workflow tools and do not inherit thinking with an explicit model", async () => {
|
||||
let captured: string[] = [];
|
||||
let promptPath: string | undefined;
|
||||
let promptContent: string | undefined;
|
||||
@@ -206,7 +206,7 @@ test("child arguments exclude subagent tools and do not inherit thinking with an
|
||||
"-p",
|
||||
"--no-session",
|
||||
"--exclude-tools",
|
||||
"subagent*",
|
||||
"subagent*,workflow",
|
||||
]);
|
||||
assert.equal(captured[captured.indexOf("--model") + 1], "agent-model");
|
||||
assert.equal(captured.includes("--thinking"), false);
|
||||
@@ -244,7 +244,7 @@ test("child arguments inherit the dispatch model and thinking only without an ex
|
||||
"-p",
|
||||
"--no-session",
|
||||
"--exclude-tools",
|
||||
"subagent*",
|
||||
"subagent*,workflow",
|
||||
]);
|
||||
assert.equal(captured[captured.indexOf("--model") + 1], "dispatch-model");
|
||||
assert.equal(captured[captured.indexOf("--thinking") + 1], "high");
|
||||
@@ -271,7 +271,9 @@ test("child arguments omit optional model and thinking flags when nothing is con
|
||||
assert.equal(captured.includes("--model"), false);
|
||||
assert.equal(captured.includes("--thinking"), false);
|
||||
assert.equal(captured.includes("--exclude-tools"), true);
|
||||
assert.equal(captured[captured.indexOf("--exclude-tools") + 1], "subagent*");
|
||||
const excluded = captured[captured.indexOf("--exclude-tools") + 1].split(",");
|
||||
assert.ok(excluded.includes("subagent*"), "child cannot dispatch subagents");
|
||||
assert.ok(excluded.includes("workflow"), "child cannot start workflow runs");
|
||||
assert.equal(captured.at(-1), "Task: do the thing");
|
||||
});
|
||||
|
||||
|
||||
@@ -155,6 +155,15 @@ test("undeclared argument references are rejected", () => {
|
||||
assert.equal(error.stepId, "scan");
|
||||
});
|
||||
|
||||
test("{item} is rejected in a step without each", () => {
|
||||
const error = validationError(plan([step("scan", { task: "Audit {item} for auth." })]));
|
||||
assert.match(error.message, /\{item\} is only valid in a step with `each`/);
|
||||
assert.equal(error.stepId, "scan");
|
||||
|
||||
const each = eachPlan([1]);
|
||||
assert.equal(each.steps[1].task, "Audit {item}.");
|
||||
});
|
||||
|
||||
test("each requires a step-output reference and a needed source step", () => {
|
||||
assert.match(validationError(plan([step("scan"), step("audit", { each: "scan" })])).message, /each must be a "\{steps\.<id>\.output\}" reference/);
|
||||
assert.match(validationError(plan([step("scan"), step("audit", { each: "{steps.missing.output}", needs: ["scan"] })])).message, /each references unknown step "missing"/);
|
||||
|
||||
Reference in new issue
Block a user