Make the workflow supervisor host seam real
Move Execution, InternalTask, and the status predicates into job-state.ts; the supervisor now creates, schedules, and settles shared rows only through its host. Concentrate cancellation and shutdown settlement in one supervisor policy, make restored rows honest (no fabricated AgentConfig), and thread load-time cap limits through WorkflowRunSpec so release enforcement and the review card share one value. Agent discovery is memoized per cwd within a prepare call.
This commit is contained in:
1 parent
23c9f84650
commit
621f6e2579
21 files changed
+610
-409
No files matched your search
@@ -116,3 +116,24 @@ export function readUltraGuideline(value: string | undefined): { value: UltraGui
|
|||||||
warning: `Invalid PI_SUBAGENT_ULTRA_GUIDELINE="${value}"; using ${DEFAULT_ULTRA_GUIDELINE}.`,
|
warning: `Invalid PI_SUBAGENT_ULTRA_GUIDELINE="${value}"; using ${DEFAULT_ULTRA_GUIDELINE}.`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every load-time setting, read from the process environment exactly once. */
|
||||||
|
export function readEnvironmentConfig(env: NodeJS.ProcessEnv = process.env) {
|
||||||
|
return {
|
||||||
|
maxWorkers: readMaxWorkers(env.PI_SUBAGENT_MAX_WORKERS),
|
||||||
|
workflowItems: readMaxWorkflowItems(env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS),
|
||||||
|
ultra: readUltraEnabled(env.PI_SUBAGENT_ULTRA),
|
||||||
|
ultraNotify: readUltraNotify(env.PI_SUBAGENT_ULTRA_NOTIFY),
|
||||||
|
ultraMode: readUltraMode(env.PI_SUBAGENT_ULTRACODE),
|
||||||
|
ultraGuideline: readUltraGuideline(env.PI_SUBAGENT_ULTRA_GUIDELINE),
|
||||||
|
ultraKeyword: readUltraKeyword(env.PI_SUBAGENT_ULTRA_KEYWORD),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The parent environment a child process inherits when the caller does not
|
||||||
|
* override it. Kept here so no execution module reads `process.env` itself.
|
||||||
|
*/
|
||||||
|
export function inheritedEnvironment(): NodeJS.ProcessEnv {
|
||||||
|
return process.env;
|
||||||
|
}
|
||||||
+2
-1
@@ -8,7 +8,8 @@ import {
|
|||||||
wrapTextWithAnsi,
|
wrapTextWithAnsi,
|
||||||
} from "@earendil-works/pi-tui";
|
} from "@earendil-works/pi-tui";
|
||||||
import { formatUsageStats, type SubagentRenderTheme } from "./render.ts";
|
import { formatUsageStats, type SubagentRenderTheme } from "./render.ts";
|
||||||
import { isTerminalTask, type JobSnapshot, type JobStatus, type TaskSnapshot, type TaskStatus } from "./types.ts";
|
import { isTerminalTask } from "./job-state.ts";
|
||||||
|
import type { JobSnapshot, JobStatus, TaskSnapshot, TaskStatus } from "./types.ts";
|
||||||
|
|
||||||
const JOB_PAGE_SIZE = 4;
|
const JOB_PAGE_SIZE = 4;
|
||||||
const TASK_PAGE_SIZE = 4;
|
const TASK_PAGE_SIZE = 4;
|
||||||
|
|||||||
+18
-19
@@ -14,24 +14,16 @@ import {
|
|||||||
getAgentDir,
|
getAgentDir,
|
||||||
} from "@earendil-works/pi-coding-agent";
|
} from "@earendil-works/pi-coding-agent";
|
||||||
import { Text } from "@earendil-works/pi-tui";
|
import { Text } from "@earendil-works/pi-tui";
|
||||||
import {
|
import { readEnvironmentConfig } from "./config.ts";
|
||||||
readMaxWorkers,
|
|
||||||
readMaxWorkflowItems,
|
|
||||||
readUltraEnabled,
|
|
||||||
readUltraGuideline,
|
|
||||||
readUltraKeyword,
|
|
||||||
readUltraMode,
|
|
||||||
readUltraNotify,
|
|
||||||
} from "./config.ts";
|
|
||||||
import { SubagentDashboard } from "./dashboard.ts";
|
import { SubagentDashboard } from "./dashboard.ts";
|
||||||
import { formatJob, formatJobList } from "./job-format.ts";
|
import { formatJob, formatJobList } from "./job-format.ts";
|
||||||
import { SubagentManager } from "./manager.ts";
|
import { SubagentManager } from "./manager.ts";
|
||||||
import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts";
|
import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts";
|
||||||
import { InvalidInvocationError, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.ts";
|
import { InvalidInvocationError, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.ts";
|
||||||
|
import { isFailedResult } from "./job-state.ts";
|
||||||
import {
|
import {
|
||||||
formatParallelSummary,
|
formatParallelSummary,
|
||||||
getResultOutput,
|
getResultOutput,
|
||||||
isFailedResult,
|
|
||||||
isRunningResult,
|
isRunningResult,
|
||||||
renderSubagentCall,
|
renderSubagentCall,
|
||||||
renderSubagentResult,
|
renderSubagentResult,
|
||||||
@@ -52,7 +44,7 @@ import { UltraKeywordTrigger } from "./ultra-keyword.ts";
|
|||||||
import { formatUltraReviewCard, formatUltraStart, UltraDeclinedError } from "./ultra.ts";
|
import { formatUltraReviewCard, formatUltraStart, UltraDeclinedError } from "./ultra.ts";
|
||||||
import { buildUltraNotice, ULTRA_DONE_MESSAGE_TYPE, type UltraNoticeDetails } from "./ultra-notify.ts";
|
import { buildUltraNotice, ULTRA_DONE_MESSAGE_TYPE, type UltraNoticeDetails } from "./ultra-notify.ts";
|
||||||
import { formatWorkflowStart, parseWorkflowCommand } from "./workflow-command.ts";
|
import { formatWorkflowStart, parseWorkflowCommand } from "./workflow-command.ts";
|
||||||
import { loadWorkflow, parseInlineWorkflow } from "./workflow-plan.ts";
|
import { loadWorkflow, MAX_EXPANDED_CHILDREN, parseInlineWorkflow } from "./workflow-plan.ts";
|
||||||
import type { WorkflowStartResult } from "./workflow-run.ts";
|
import type { WorkflowStartResult } from "./workflow-run.ts";
|
||||||
|
|
||||||
function textResult(text: string, details?: unknown, isError?: boolean): AgentToolResult<any> {
|
function textResult(text: string, details?: unknown, isError?: boolean): AgentToolResult<any> {
|
||||||
@@ -123,13 +115,18 @@ function jobResult(job: JobSnapshot): AgentToolResult<{ job: JobSnapshot }> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
||||||
const workerConfig = readMaxWorkers(process.env.PI_SUBAGENT_MAX_WORKERS);
|
const environment = readEnvironmentConfig();
|
||||||
const workflowItemsConfig = readMaxWorkflowItems(process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS);
|
const workerConfig = environment.maxWorkers;
|
||||||
const ultraConfig = readUltraEnabled(process.env.PI_SUBAGENT_ULTRA);
|
const workflowItemsConfig = environment.workflowItems;
|
||||||
const ultraNotifyConfig = readUltraNotify(process.env.PI_SUBAGENT_ULTRA_NOTIFY);
|
const ultraConfig = environment.ultra;
|
||||||
const ultraModeConfig = readUltraMode(process.env.PI_SUBAGENT_ULTRACODE);
|
const ultraNotifyConfig = environment.ultraNotify;
|
||||||
const ultraGuidelineConfig = readUltraGuideline(process.env.PI_SUBAGENT_ULTRA_GUIDELINE);
|
const ultraModeConfig = environment.ultraMode;
|
||||||
const ultraKeywordConfig = readUltraKeyword(process.env.PI_SUBAGENT_ULTRA_KEYWORD);
|
const ultraGuidelineConfig = environment.ultraGuideline;
|
||||||
|
const ultraKeywordConfig = environment.ultraKeyword;
|
||||||
|
const workflowLimits = {
|
||||||
|
maxItemsPerEach: workflowItemsConfig.value,
|
||||||
|
maxExpandedChildren: MAX_EXPANDED_CHILDREN,
|
||||||
|
};
|
||||||
const ultraMode = new UltraMode(ultraModeConfig.value);
|
const ultraMode = new UltraMode(ultraModeConfig.value);
|
||||||
const ultraKeyword = new UltraKeywordTrigger();
|
const ultraKeyword = new UltraKeywordTrigger();
|
||||||
let currentContext: ExtensionContext | undefined;
|
let currentContext: ExtensionContext | undefined;
|
||||||
@@ -203,6 +200,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
|||||||
const prepareContext: PrepareContext = { ...ctx, cwd: effectiveCwd };
|
const prepareContext: PrepareContext = { ...ctx, cwd: effectiveCwd };
|
||||||
const prepared = await prepareWorkflowInvocation(plan, args, prepareContext, {
|
const prepared = await prepareWorkflowInvocation(plan, args, prepareContext, {
|
||||||
approvedDirectories: approvedProjectDirs,
|
approvedDirectories: approvedProjectDirs,
|
||||||
|
limits: workflowLimits,
|
||||||
});
|
});
|
||||||
return manager.startWorkflow(prepared);
|
return manager.startWorkflow(prepared);
|
||||||
}
|
}
|
||||||
@@ -225,9 +223,10 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
|||||||
const prepareContext: PrepareContext = { ...ctx, cwd: effectiveCwd };
|
const prepareContext: PrepareContext = { ...ctx, cwd: effectiveCwd };
|
||||||
const prepared = await prepareWorkflowInvocation(plan, request.args ?? {}, prepareContext, {
|
const prepared = await prepareWorkflowInvocation(plan, request.args ?? {}, prepareContext, {
|
||||||
approvedDirectories: approvedProjectDirs,
|
approvedDirectories: approvedProjectDirs,
|
||||||
|
limits: workflowLimits,
|
||||||
});
|
});
|
||||||
if (prepareContext.hasUI && !ultraMode.on) {
|
if (prepareContext.hasUI && !ultraMode.on) {
|
||||||
const card = formatUltraReviewCard(prepared, { maxItemsPerEach: workflowItemsConfig.value });
|
const card = formatUltraReviewCard(prepared);
|
||||||
if (!(await ctx.ui.confirm(card.title, card.message))) throw new UltraDeclinedError(plan.name);
|
if (!(await ctx.ui.confirm(card.title, card.message))) throw new UltraDeclinedError(plan.name);
|
||||||
}
|
}
|
||||||
return manager.startWorkflow(prepared);
|
return manager.startWorkflow(prepared);
|
||||||
|
|||||||
@@ -0,0 +1,217 @@
|
|||||||
|
/**
|
||||||
|
* Shared job and task state.
|
||||||
|
*
|
||||||
|
* `Execution` is the flat job record the manager owns; `InternalTask` is one
|
||||||
|
* row of that record. A workflow's supervisor holds the same rows by reference
|
||||||
|
* in its own DAG index and settles them through its host seam. The status
|
||||||
|
* predicates and the small record mutations both adapters need live here, so
|
||||||
|
* "terminal", "failed", and "the row is running" mean one thing everywhere.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
emptyUsage,
|
||||||
|
type JobStatus,
|
||||||
|
type PreparedInvocation,
|
||||||
|
type PreparedTask,
|
||||||
|
type RunResult,
|
||||||
|
type SyncOutcome,
|
||||||
|
type TaskIdentity,
|
||||||
|
type TaskSnapshot,
|
||||||
|
type TaskStatus,
|
||||||
|
} from "./types.ts";
|
||||||
|
import type { WorkflowRunSpec } from "./workflow-run.ts";
|
||||||
|
|
||||||
|
export interface InternalTask {
|
||||||
|
/**
|
||||||
|
* The resolved brief behind a live row. Absent on restored rows: a
|
||||||
|
* persisted terminal snapshot cannot reconstruct its AgentConfig, and
|
||||||
|
* restored rows are never launched again.
|
||||||
|
*/
|
||||||
|
prepared?: PreparedTask;
|
||||||
|
snapshot: TaskSnapshot;
|
||||||
|
controller?: AbortController;
|
||||||
|
result?: RunResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Execution {
|
||||||
|
id: string;
|
||||||
|
request: PreparedInvocation;
|
||||||
|
status: JobStatus;
|
||||||
|
plannedTaskCount: number;
|
||||||
|
tasks: InternalTask[];
|
||||||
|
createdAt: number;
|
||||||
|
startedAt?: number;
|
||||||
|
finishedAt?: number;
|
||||||
|
errorMessage?: string;
|
||||||
|
isAsync: boolean;
|
||||||
|
cancelRequested: boolean;
|
||||||
|
workflow?: WorkflowRunSpec;
|
||||||
|
onUpdate?: (outcome: SyncOutcome) => void;
|
||||||
|
completion?: Promise<unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The step/item-identity subset, so adding a field changes one mapping here. */
|
||||||
|
export function taskIdentityExtras(source: {
|
||||||
|
step?: number;
|
||||||
|
stepId?: string;
|
||||||
|
item?: number;
|
||||||
|
itemValue?: string;
|
||||||
|
}): Pick<TaskIdentity, "step" | "stepId" | "item" | "itemValue"> {
|
||||||
|
return { step: source.step, stepId: source.stepId, item: source.item, itemValue: source.itemValue };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
activity: [],
|
||||||
|
usage: emptyUsage(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A queued row for a live task that has a resolved brief. */
|
||||||
|
export function initialTask(prepared: PreparedTask): InternalTask {
|
||||||
|
return {
|
||||||
|
prepared,
|
||||||
|
result: { ...emptyRunResult(prepared), status: "queued" },
|
||||||
|
snapshot: emptyTaskSnapshot(prepared),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const TERMINAL_JOB_STATUSES: ReadonlySet<JobStatus> = new Set(["succeeded", "failed", "cancelled", "interrupted"]);
|
||||||
|
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 interface ResultStatusFields {
|
||||||
|
status?: TaskStatus;
|
||||||
|
exitCode?: number | null;
|
||||||
|
stopReason?: string;
|
||||||
|
terminationSignal?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* error/aborted stop reasons, termination signals, and failure statuses.
|
||||||
|
*
|
||||||
|
* This is the one failure predicate: the manager's completion decision and the
|
||||||
|
* renderers ask the same question here.
|
||||||
|
*/
|
||||||
|
export function isFailedResult(result: ResultStatusFields): boolean {
|
||||||
|
if (result.status === "queued" || result.status === "running") return false;
|
||||||
|
if (result.status === "skipped") return false;
|
||||||
|
if (result.status === "failed" || result.status === "cancelled" || result.status === "interrupted") return true;
|
||||||
|
if (result.exitCode === null || (result.exitCode !== undefined && result.exitCode !== 0)) return true;
|
||||||
|
return result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The shared row's current status; the supervisor reads through this seam. */
|
||||||
|
export function taskStatus(task: InternalTask): TaskStatus {
|
||||||
|
return task.snapshot.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The shared row's current output; the supervisor reads through this seam. */
|
||||||
|
export function taskOutput(task: InternalTask): string {
|
||||||
|
return task.snapshot.output;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The source line behind an each-step item child, if this row has one. */
|
||||||
|
export function taskItemValue(task: InternalTask): string | undefined {
|
||||||
|
return task.snapshot.itemValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a running row owns a child process (and so an abort controller). */
|
||||||
|
export function taskHasController(task: InternalTask): boolean {
|
||||||
|
return task.controller !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The row's latest result, once it has one. */
|
||||||
|
export function taskResult(task: InternalTask): RunResult | undefined {
|
||||||
|
return task.result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A neutral result carrying the row's identity. Live rows build it from their
|
||||||
|
* prepared brief; restored rows have only their snapshot to inherit from.
|
||||||
|
*/
|
||||||
|
export function taskBaseResult(task: InternalTask): RunResult {
|
||||||
|
if (task.prepared) return emptyRunResult(task.prepared);
|
||||||
|
const { agent, agentSource, task: text, cwd, step, stepId, item, itemValue } = task.snapshot;
|
||||||
|
return {
|
||||||
|
agent,
|
||||||
|
agentSource,
|
||||||
|
task: text,
|
||||||
|
cwd,
|
||||||
|
step,
|
||||||
|
stepId,
|
||||||
|
item,
|
||||||
|
itemValue,
|
||||||
|
exitCode: null,
|
||||||
|
messages: [],
|
||||||
|
output: "",
|
||||||
|
stderr: "",
|
||||||
|
usage: emptyUsage(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A step's release-time brief becomes the row's brief, snapshot, and result text. */
|
||||||
|
export function setTaskBrief(task: InternalTask, prepared: PreparedTask): void {
|
||||||
|
task.prepared = prepared;
|
||||||
|
task.snapshot.task = prepared.task;
|
||||||
|
if (task.result) task.result = { ...task.result, task: prepared.task, stepId: prepared.stepId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An each-step coordinator starts when it fans out, before its first item runs. */
|
||||||
|
export function markCoordinatorStarted(task: InternalTask, now: number): void {
|
||||||
|
task.snapshot.startedAt = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mark a coordinator running once it has a live item child. */
|
||||||
|
export function markTaskRunning(task: InternalTask, now: number): void {
|
||||||
|
task.snapshot.status = "running";
|
||||||
|
task.snapshot.startedAt = now;
|
||||||
|
if (task.result) task.result = { ...task.result, status: "running" };
|
||||||
|
}
|
||||||
+7
-48
@@ -11,57 +11,16 @@
|
|||||||
|
|
||||||
import { createHash } from "node:crypto";
|
import { createHash } from "node:crypto";
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||||
import type { JobSnapshot, JobStatus, TaskSnapshot, TaskStatus, UsageStats } from "./types.ts";
|
import type {
|
||||||
|
JobSnapshot,
|
||||||
|
TaskSnapshot,
|
||||||
|
WorkflowJournal,
|
||||||
|
WorkflowJournalItem,
|
||||||
|
WorkflowJournalStep,
|
||||||
|
} from "./types.ts";
|
||||||
import type { WorkflowPlan, WorkflowStep } from "./workflow-plan.ts";
|
import type { WorkflowPlan, WorkflowStep } from "./workflow-plan.ts";
|
||||||
import type { WorkflowRunSpec } from "./workflow-run.ts";
|
import type { WorkflowRunSpec } from "./workflow-run.ts";
|
||||||
|
|
||||||
/** One fanned-out item child of an each-step, as the journal records it. */
|
|
||||||
export interface WorkflowJournalItem {
|
|
||||||
/** One-based item index within the step's fan-out. */
|
|
||||||
item: number;
|
|
||||||
/** The source line this item was fanned out from. */
|
|
||||||
input: string;
|
|
||||||
/** Stable across identical item inputs, so a replay layer can key on it. */
|
|
||||||
inputHash: string;
|
|
||||||
status: TaskStatus;
|
|
||||||
/** Children started for this item; always 0 or 1 while no retry exists. */
|
|
||||||
attempts: number;
|
|
||||||
output: string;
|
|
||||||
outputTruncated: boolean;
|
|
||||||
outputBytesOmitted: number;
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WorkflowJournalStep {
|
|
||||||
id: string;
|
|
||||||
/** Stable across identical step inputs, so a replay layer can key on it. */
|
|
||||||
inputHash: string;
|
|
||||||
status: TaskStatus;
|
|
||||||
/** Children started for this step; always 0 or 1 while no retry exists. */
|
|
||||||
attempts: number;
|
|
||||||
output: string;
|
|
||||||
outputTruncated: boolean;
|
|
||||||
outputBytesOmitted: number;
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
/** One row per each-step item, in item order; empty for steps that do not fan out. */
|
|
||||||
items: WorkflowJournalItem[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WorkflowJournal {
|
|
||||||
jobId: string;
|
|
||||||
status: JobStatus;
|
|
||||||
plan: WorkflowPlan;
|
|
||||||
args: Record<string, string>;
|
|
||||||
steps: WorkflowJournalStep[];
|
|
||||||
usage: UsageStats;
|
|
||||||
createdAt: number;
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
errorMessage?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deterministic JSON: object keys sorted, `undefined` members dropped, so the
|
* Deterministic JSON: object keys sorted, `undefined` members dropped, so the
|
||||||
* same logical value always hashes to the same bytes regardless of construction
|
* same logical value always hashes to the same bytes regardless of construction
|
||||||
|
|||||||
+68
-94
@@ -1,13 +1,19 @@
|
|||||||
import { summarizeActivity } from "./activity.ts";
|
import { summarizeActivity } from "./activity.ts";
|
||||||
import { DEFAULT_MAX_WORKERS } from "./config.ts";
|
import { DEFAULT_MAX_WORKERS } from "./config.ts";
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
|
||||||
import { buildWorkflowJournal, type WorkflowJournal } from "./journal.ts";
|
|
||||||
import {
|
import {
|
||||||
emptyRunResult,
|
initialTask,
|
||||||
emptyTaskSnapshot,
|
isFailedResult,
|
||||||
emptyUsage,
|
|
||||||
isTerminalJob,
|
isTerminalJob,
|
||||||
|
isTerminalTask,
|
||||||
|
taskBaseResult,
|
||||||
taskIdentityExtras,
|
taskIdentityExtras,
|
||||||
|
type Execution,
|
||||||
|
type InternalTask,
|
||||||
|
} from "./job-state.ts";
|
||||||
|
import { buildWorkflowJournal } from "./journal.ts";
|
||||||
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||||
|
import {
|
||||||
|
emptyUsage,
|
||||||
type JobSnapshot,
|
type JobSnapshot,
|
||||||
type JobStatus,
|
type JobStatus,
|
||||||
type ManagerOptions,
|
type ManagerOptions,
|
||||||
@@ -20,41 +26,16 @@ import {
|
|||||||
type UsageStats,
|
type UsageStats,
|
||||||
type SyncOutcome,
|
type SyncOutcome,
|
||||||
type SyncRunOptions,
|
type SyncRunOptions,
|
||||||
|
type WorkflowJournal,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
import type { PreparedWorkflowInvocation, WorkflowRunSpec, WorkflowStartResult } from "./workflow-run.ts";
|
import type { PreparedWorkflowInvocation, WorkflowRunSpec, WorkflowStartResult } from "./workflow-run.ts";
|
||||||
import { WorkflowSupervisor } from "./workflow-supervisor.ts";
|
import { WorkflowSupervisor, type WorkflowTermination } from "./workflow-supervisor.ts";
|
||||||
|
|
||||||
const DEFAULT_MAX_ACTIVE_JOBS = 64;
|
const DEFAULT_MAX_ACTIVE_JOBS = 64;
|
||||||
const DEFAULT_HISTORY_LIMIT = 50;
|
const DEFAULT_HISTORY_LIMIT = 50;
|
||||||
const DEFAULT_WAIT_SECONDS = 30;
|
const DEFAULT_WAIT_SECONDS = 30;
|
||||||
const MAX_WAIT_SECONDS = 300;
|
const MAX_WAIT_SECONDS = 300;
|
||||||
|
|
||||||
export interface InternalTask {
|
|
||||||
prepared: PreparedTask;
|
|
||||||
snapshot: TaskSnapshot;
|
|
||||||
controller?: AbortController;
|
|
||||||
result?: RunResult;
|
|
||||||
/** A workflow step submitted to the FIFO, whether or not a worker picked it up yet. */
|
|
||||||
submitted?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Execution {
|
|
||||||
id: string;
|
|
||||||
request: PreparedInvocation;
|
|
||||||
status: JobStatus;
|
|
||||||
plannedTaskCount: number;
|
|
||||||
tasks: InternalTask[];
|
|
||||||
createdAt: number;
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
errorMessage?: string;
|
|
||||||
isAsync: boolean;
|
|
||||||
cancelRequested: boolean;
|
|
||||||
workflow?: WorkflowRunSpec;
|
|
||||||
onUpdate?: (outcome: SyncOutcome) => void;
|
|
||||||
completion?: Promise<unknown>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ScheduledTask {
|
interface ScheduledTask {
|
||||||
execution: Execution;
|
execution: Execution;
|
||||||
task: InternalTask;
|
task: InternalTask;
|
||||||
@@ -71,19 +52,6 @@ function cloneSnapshot(snapshot: JobSnapshot): JobSnapshot {
|
|||||||
return structuredClone(snapshot);
|
return structuredClone(snapshot);
|
||||||
}
|
}
|
||||||
|
|
||||||
function initialTask(prepared: PreparedTask, now: number): InternalTask {
|
|
||||||
void now;
|
|
||||||
return {
|
|
||||||
prepared,
|
|
||||||
result: { ...emptyRunResult(prepared), status: "queued" },
|
|
||||||
snapshot: emptyTaskSnapshot(prepared),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function failed(result: RunResult): boolean {
|
|
||||||
return result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal);
|
|
||||||
}
|
|
||||||
|
|
||||||
export class SubagentManager {
|
export class SubagentManager {
|
||||||
private readonly runner: TaskRunner;
|
private readonly runner: TaskRunner;
|
||||||
private readonly maxWorkers: number;
|
private readonly maxWorkers: number;
|
||||||
@@ -115,9 +83,9 @@ export class SubagentManager {
|
|||||||
this.workflows = new WorkflowSupervisor(
|
this.workflows = new WorkflowSupervisor(
|
||||||
{
|
{
|
||||||
schedule: (execution, task) => this.schedule(execution, task),
|
schedule: (execution, task) => this.schedule(execution, task),
|
||||||
createTask: (prepared) => initialTask(prepared, this.now()),
|
createTask: (execution, prepared) => this.createTask(execution, prepared),
|
||||||
settleTask: (task, status, result, snapshot) => this.settleTask(task, status, result, snapshot),
|
settleTask: (task, status, result, snapshot) => this.settleTask(task, status, result, snapshot),
|
||||||
cancelledResult: (task) => this.cancelledResult(task),
|
cancelledResult: (task, status) => this.cancelledResult(task, status),
|
||||||
finalize: (execution, status) => this.finalize(execution, status),
|
finalize: (execution, status) => this.finalize(execution, status),
|
||||||
emit: (execution) => this.emit(execution),
|
emit: (execution) => this.emit(execution),
|
||||||
now: () => this.now(),
|
now: () => this.now(),
|
||||||
@@ -126,6 +94,14 @@ export class SubagentManager {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Create a run row through the host seam and register it in the flat job record. */
|
||||||
|
private createTask(execution: Execution, prepared: PreparedTask): InternalTask {
|
||||||
|
const task = initialTask(prepared);
|
||||||
|
execution.tasks.push(task);
|
||||||
|
execution.plannedTaskCount += 1;
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
|
||||||
startAsync(request: PreparedInvocation): JobSnapshot {
|
startAsync(request: PreparedInvocation): JobSnapshot {
|
||||||
return this.snapshot(this.startAsyncExecution(request));
|
return this.snapshot(this.startAsyncExecution(request));
|
||||||
}
|
}
|
||||||
@@ -227,22 +203,10 @@ export class SubagentManager {
|
|||||||
const existing = this.jobs.get(saved.id);
|
const existing = this.jobs.get(saved.id);
|
||||||
if (existing && this.activeExecutions.has(existing)) continue;
|
if (existing && this.activeExecutions.has(existing)) continue;
|
||||||
const interrupted = !isTerminalJob(saved.status);
|
const interrupted = !isTerminalJob(saved.status);
|
||||||
const tasks = saved.results.map((result) => {
|
const tasks: InternalTask[] = saved.results.map((result) => {
|
||||||
const source = result.agentSource === "unknown" ? "user" : result.agentSource;
|
// A persisted snapshot is the record: there is no AgentConfig to
|
||||||
const prepared: PreparedTask = {
|
// reconstruct, and restored rows are terminal so none is launched.
|
||||||
agent: {
|
const task: InternalTask = { snapshot: structuredClone(result) };
|
||||||
name: result.agent,
|
|
||||||
description: "Restored agent",
|
|
||||||
systemPrompt: "",
|
|
||||||
source,
|
|
||||||
filePath: "",
|
|
||||||
},
|
|
||||||
task: result.task,
|
|
||||||
cwd: result.cwd,
|
|
||||||
...taskIdentityExtras(result),
|
|
||||||
};
|
|
||||||
const task = initialTask(prepared, this.now());
|
|
||||||
task.snapshot = structuredClone(result);
|
|
||||||
if (interrupted && (task.snapshot.status === "queued" || task.snapshot.status === "running")) {
|
if (interrupted && (task.snapshot.status === "queued" || task.snapshot.status === "running")) {
|
||||||
task.snapshot.status = "interrupted";
|
task.snapshot.status = "interrupted";
|
||||||
task.snapshot.finishedAt = this.now();
|
task.snapshot.finishedAt = this.now();
|
||||||
@@ -253,7 +217,7 @@ export class SubagentManager {
|
|||||||
id: saved.id,
|
id: saved.id,
|
||||||
request: {
|
request: {
|
||||||
mode: saved.mode,
|
mode: saved.mode,
|
||||||
tasks: tasks.map((task) => task.prepared),
|
tasks: [],
|
||||||
agentScope: saved.agentScope,
|
agentScope: saved.agentScope,
|
||||||
projectAgentsDir: saved.projectAgentsDir,
|
projectAgentsDir: saved.projectAgentsDir,
|
||||||
projectAgentsDirs: saved.projectAgentsDirs,
|
projectAgentsDirs: saved.projectAgentsDirs,
|
||||||
@@ -299,12 +263,18 @@ export class SubagentManager {
|
|||||||
scheduled.task.result = this.interruptedResult(scheduled.task);
|
scheduled.task.result = this.interruptedResult(scheduled.task);
|
||||||
scheduled.resolve(scheduled.task.result);
|
scheduled.resolve(scheduled.task.result);
|
||||||
}
|
}
|
||||||
for (const task of execution.tasks) {
|
// Workflow rows are settled by the supervisor's one termination
|
||||||
if (task.snapshot.status === "succeeded" || task.snapshot.status === "failed" || task.snapshot.status === "cancelled" || task.snapshot.status === "interrupted") continue;
|
// policy; the manager supplies the pool effects and the job outcome.
|
||||||
task.snapshot.status = "interrupted";
|
if (execution.request.mode === "workflow") {
|
||||||
task.snapshot.finishedAt = this.now();
|
this.workflows.interrupt(execution);
|
||||||
task.controller?.abort();
|
} else {
|
||||||
|
for (const task of execution.tasks) {
|
||||||
|
if (isTerminalTask(task.snapshot.status)) continue;
|
||||||
|
task.snapshot.status = "interrupted";
|
||||||
|
task.snapshot.finishedAt = this.now();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
for (const task of execution.tasks) task.controller?.abort();
|
||||||
this.activeExecutions.delete(execution);
|
this.activeExecutions.delete(execution);
|
||||||
this.emit(execution);
|
this.emit(execution);
|
||||||
this.resolveWaiters(execution);
|
this.resolveWaiters(execution);
|
||||||
@@ -317,12 +287,7 @@ export class SubagentManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private interruptedResult(task: InternalTask): RunResult {
|
private interruptedResult(task: InternalTask): RunResult {
|
||||||
return {
|
return this.cancelledResult(task, "interrupted");
|
||||||
...this.cancelledResult(task),
|
|
||||||
status: "interrupted",
|
|
||||||
stopReason: "aborted",
|
|
||||||
errorMessage: "Interrupted by session shutdown",
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cancel(jobId: string): JobSnapshot {
|
cancel(jobId: string): JobSnapshot {
|
||||||
@@ -372,34 +337,39 @@ export class SubagentManager {
|
|||||||
return task.result;
|
return task.result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private cancelledResult(task: InternalTask): RunResult {
|
private cancelledResult(task: InternalTask, status: WorkflowTermination = "cancelled"): RunResult {
|
||||||
return {
|
return {
|
||||||
...emptyRunResult(task.prepared),
|
...taskBaseResult(task),
|
||||||
status: "cancelled",
|
status,
|
||||||
stopReason: "aborted",
|
stopReason: "aborted",
|
||||||
errorMessage: "Cancelled by caller",
|
errorMessage: status === "interrupted" ? "Interrupted by session shutdown" : "Cancelled by caller",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private createExecution(request: PreparedInvocation, isAsync: boolean): Execution {
|
private createExecution(request: PreparedInvocation, isAsync: boolean): Execution {
|
||||||
const id = `job_${String(this.nextJobId++).padStart(4, "0")}`;
|
const id = `job_${String(this.nextJobId++).padStart(4, "0")}`;
|
||||||
|
const isWorkflow = request.mode === "workflow";
|
||||||
const execution: Execution = {
|
const execution: Execution = {
|
||||||
id,
|
id,
|
||||||
request,
|
request,
|
||||||
status: "queued",
|
status: "queued",
|
||||||
plannedTaskCount: request.tasks.length,
|
// A workflow creates every row through the supervisor's host seam,
|
||||||
tasks: (request.mode === "chain" ? request.tasks.slice(0, 1) : request.tasks).map((task) => initialTask(task, this.now())),
|
// starting with the plan's step rows.
|
||||||
|
plannedTaskCount: isWorkflow ? 0 : request.tasks.length,
|
||||||
|
tasks: isWorkflow
|
||||||
|
? []
|
||||||
|
: (request.mode === "chain" ? request.tasks.slice(0, 1) : request.tasks).map((task) => initialTask(task)),
|
||||||
createdAt: this.now(),
|
createdAt: this.now(),
|
||||||
isAsync,
|
isAsync,
|
||||||
cancelRequested: false,
|
cancelRequested: false,
|
||||||
};
|
};
|
||||||
if (request.mode === "workflow") {
|
if (isWorkflow) {
|
||||||
execution.workflow = (request as PreparedWorkflowInvocation).workflow;
|
execution.workflow = (request as PreparedWorkflowInvocation).workflow;
|
||||||
}
|
}
|
||||||
this.activeExecutions.add(execution);
|
this.activeExecutions.add(execution);
|
||||||
if (isAsync) {
|
if (isAsync) {
|
||||||
this.jobs.set(id, execution);
|
this.jobs.set(id, execution);
|
||||||
this.emit(execution);
|
if (!isWorkflow) this.emit(execution);
|
||||||
}
|
}
|
||||||
return execution;
|
return execution;
|
||||||
}
|
}
|
||||||
@@ -407,12 +377,12 @@ export class SubagentManager {
|
|||||||
private async execute(execution: Execution): Promise<void> {
|
private async execute(execution: Execution): Promise<void> {
|
||||||
if (execution.request.mode === "single") {
|
if (execution.request.mode === "single") {
|
||||||
const result = await this.schedule(execution, execution.tasks[0]);
|
const result = await this.schedule(execution, execution.tasks[0]);
|
||||||
this.finalize(execution, failed(result) ? "failed" : "succeeded");
|
this.finalize(execution, isFailedResult(result) ? "failed" : "succeeded");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (execution.request.mode === "parallel") {
|
if (execution.request.mode === "parallel") {
|
||||||
const results = await Promise.all(execution.tasks.map((task) => this.schedule(execution, task)));
|
const results = await Promise.all(execution.tasks.map((task) => this.schedule(execution, task)));
|
||||||
this.finalize(execution, results.some(failed) ? "failed" : "succeeded");
|
this.finalize(execution, results.some(isFailedResult) ? "failed" : "succeeded");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (execution.request.mode === "workflow") {
|
if (execution.request.mode === "workflow") {
|
||||||
@@ -432,14 +402,14 @@ export class SubagentManager {
|
|||||||
...execution.request.tasks[index],
|
...execution.request.tasks[index],
|
||||||
task: execution.request.tasks[index].task.replace(/\{previous\}/g, previous),
|
task: execution.request.tasks[index].task.replace(/\{previous\}/g, previous),
|
||||||
};
|
};
|
||||||
execution.tasks.push(initialTask(prepared, this.now()));
|
execution.tasks.push(initialTask(prepared));
|
||||||
}
|
}
|
||||||
const result = await this.schedule(execution, execution.tasks[index]);
|
const result = await this.schedule(execution, execution.tasks[index]);
|
||||||
if (execution.cancelRequested || isTerminalJob(execution.status)) {
|
if (execution.cancelRequested || isTerminalJob(execution.status)) {
|
||||||
this.finalize(execution, "cancelled");
|
this.finalize(execution, "cancelled");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (failed(result)) {
|
if (isFailedResult(result)) {
|
||||||
this.finalize(execution, "failed");
|
this.finalize(execution, "failed");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -486,7 +456,9 @@ export class SubagentManager {
|
|||||||
this.emit(execution);
|
this.emit(execution);
|
||||||
this.emitSync(execution);
|
this.emitSync(execution);
|
||||||
try {
|
try {
|
||||||
const result = await this.runner.run(task.prepared, execution.request.dispatchDefaults, {
|
const prepared = task.prepared;
|
||||||
|
if (!prepared) throw new Error("Task has no prepared brief");
|
||||||
|
const result = await this.runner.run(prepared, execution.request.dispatchDefaults, {
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
onUpdate: (partial) => {
|
onUpdate: (partial) => {
|
||||||
partial.status = "running";
|
partial.status = "running";
|
||||||
@@ -499,17 +471,19 @@ export class SubagentManager {
|
|||||||
this.emitSync(execution);
|
this.emitSync(execution);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
this.applyResult(execution, task, result);
|
this.applyResult(execution, task, result, prepared);
|
||||||
this.emit(execution);
|
this.emit(execution);
|
||||||
this.emitSync(execution);
|
this.emitSync(execution);
|
||||||
resolve(result);
|
resolve(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const result: RunResult = {
|
const result: RunResult = {
|
||||||
...emptyRunResult(task.prepared),
|
...taskBaseResult(task),
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
errorMessage: error instanceof Error ? error.message : String(error),
|
errorMessage: error instanceof Error ? error.message : String(error),
|
||||||
};
|
};
|
||||||
this.applyResult(execution, task, result);
|
const prepared = task.prepared;
|
||||||
|
if (prepared) this.applyResult(execution, task, result, prepared);
|
||||||
|
else this.settleTask(task, "failed", result, { exitCode: 1 });
|
||||||
this.emit(execution);
|
this.emit(execution);
|
||||||
this.emitSync(execution);
|
this.emitSync(execution);
|
||||||
resolve(result);
|
resolve(result);
|
||||||
@@ -534,14 +508,14 @@ export class SubagentManager {
|
|||||||
if (result.messages.length > 0) task.snapshot.activity = summarizeActivity(result.messages, this.now());
|
if (result.messages.length > 0) task.snapshot.activity = summarizeActivity(result.messages, this.now());
|
||||||
}
|
}
|
||||||
|
|
||||||
private applyResult(execution: Execution, task: InternalTask, result: RunResult): void {
|
private applyResult(execution: Execution, task: InternalTask, result: RunResult, prepared: PreparedTask): void {
|
||||||
const settled = execution.isAsync ? { ...result, messages: [] } : result;
|
const settled = execution.isAsync ? { ...result, messages: [] } : result;
|
||||||
task.result = { ...settled, ...taskIdentityExtras(task.prepared) };
|
task.result = { ...settled, ...taskIdentityExtras(prepared) };
|
||||||
if (task.snapshot.status === "interrupted") {
|
if (task.snapshot.status === "interrupted") {
|
||||||
task.result.status = "interrupted";
|
task.result.status = "interrupted";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
task.snapshot.status = execution.cancelRequested ? "cancelled" : failed(result) ? "failed" : "succeeded";
|
task.snapshot.status = execution.cancelRequested ? "cancelled" : isFailedResult(result) ? "failed" : "succeeded";
|
||||||
task.result.status = task.snapshot.status;
|
task.result.status = task.snapshot.status;
|
||||||
task.snapshot.exitCode = result.exitCode;
|
task.snapshot.exitCode = result.exitCode;
|
||||||
this.updateSnapshotFromResult(task, result);
|
this.updateSnapshotFromResult(task, result);
|
||||||
|
|||||||
+1
-2
@@ -1,5 +1,4 @@
|
|||||||
import type { WorkflowJournal, WorkflowJournalItem, WorkflowJournalStep } from "./journal.ts";
|
import type { JobSnapshot, WorkflowJournal, WorkflowJournalItem, WorkflowJournalStep } from "./types.ts";
|
||||||
import type { JobSnapshot } from "./types.ts";
|
|
||||||
|
|
||||||
export const SUBAGENT_JOB_ENTRY = "subagent-job-v1";
|
export const SUBAGENT_JOB_ENTRY = "subagent-job-v1";
|
||||||
export const WORKFLOW_RUN_ENTRY = "pi-workflow-run-v1";
|
export const WORKFLOW_RUN_ENTRY = "pi-workflow-run-v1";
|
||||||
|
|||||||
+23
-14
@@ -15,7 +15,8 @@ import * as fs from "node:fs";
|
|||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
||||||
import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
||||||
import { type AgentScope, discoverAgents } from "./agents.ts";
|
import { type AgentScope, discoverAgents, type AgentDiscoveryResult } from "./agents.ts";
|
||||||
|
import { DEFAULT_MAX_WORKFLOW_ITEMS } from "./config.ts";
|
||||||
import type { SubagentParamsType } from "./schemas.ts";
|
import type { SubagentParamsType } from "./schemas.ts";
|
||||||
import type { DispatchDefaults, PreparedInvocation, PreparedTask } from "./types.ts";
|
import type { DispatchDefaults, PreparedInvocation, PreparedTask } from "./types.ts";
|
||||||
import {
|
import {
|
||||||
@@ -25,7 +26,7 @@ import {
|
|||||||
type PreparedWorkflowInvocation,
|
type PreparedWorkflowInvocation,
|
||||||
type PreparedWorkflowStep,
|
type PreparedWorkflowStep,
|
||||||
} from "./workflow-run.ts";
|
} from "./workflow-run.ts";
|
||||||
import { validateWorkflowExpansion, discoverWorkflows, type WorkflowPlan } from "./workflow-plan.ts";
|
import { validateWorkflowExpansion, discoverWorkflows, MAX_EXPANDED_CHILDREN, type WorkflowLimits, type WorkflowPlan } from "./workflow-plan.ts";
|
||||||
|
|
||||||
const MAX_PARALLEL_TASKS = 8;
|
const MAX_PARALLEL_TASKS = 8;
|
||||||
|
|
||||||
@@ -301,12 +302,18 @@ function resolvePreparedTask(
|
|||||||
itemCwd: string | undefined,
|
itemCwd: string | undefined,
|
||||||
baseCwd: string,
|
baseCwd: string,
|
||||||
agentScope: AgentScope,
|
agentScope: AgentScope,
|
||||||
|
discoveries?: Map<string, AgentDiscoveryResult>,
|
||||||
): { task: PreparedTask; projectAgentsDir: string | null } {
|
): { task: PreparedTask; projectAgentsDir: string | null } {
|
||||||
const cwd = resolveTaskCwd(baseCwd, itemCwd);
|
const cwd = resolveTaskCwd(baseCwd, itemCwd);
|
||||||
|
|
||||||
// Discovery is per task: agents are a property of the task's effective
|
// Discovery is per effective cwd: agents are a property of the task's
|
||||||
// working directory, not of the caller's cwd.
|
// working directory, not of the caller's cwd. One prepare call memoizes the
|
||||||
const discovery = discoverAgents(cwd, agentScope);
|
// scan so a 64-step plan does not walk the agent directory 64 times.
|
||||||
|
let discovery = discoveries?.get(cwd);
|
||||||
|
if (!discovery) {
|
||||||
|
discovery = discoverAgents(cwd, agentScope);
|
||||||
|
discoveries?.set(cwd, discovery);
|
||||||
|
}
|
||||||
const agent = discovery.agents.find((candidate) => candidate.name === agentName);
|
const agent = discovery.agents.find((candidate) => candidate.name === agentName);
|
||||||
if (!agent) {
|
if (!agent) {
|
||||||
const available = discovery.agents.map((candidate) => `"${candidate.name}"`).join(", ") || "none";
|
const available = discovery.agents.map((candidate) => `"${candidate.name}"`).join(", ") || "none";
|
||||||
@@ -387,10 +394,11 @@ export async function prepareInvocation(
|
|||||||
|
|
||||||
const tasks: PreparedTask[] = [];
|
const tasks: PreparedTask[] = [];
|
||||||
const projectAgentsByDir = new Map<string, Set<string>>();
|
const projectAgentsByDir = new Map<string, Set<string>>();
|
||||||
|
const discoveries = new Map<string, AgentDiscoveryResult>();
|
||||||
|
|
||||||
for (let index = 0; index < request.items.length; index++) {
|
for (let index = 0; index < request.items.length; index++) {
|
||||||
const item = request.items[index];
|
const item = request.items[index];
|
||||||
const resolved = resolvePreparedTask(item.agent, item.task, item.cwd, ctx.cwd, agentScope);
|
const resolved = resolvePreparedTask(item.agent, item.task, item.cwd, ctx.cwd, agentScope, discoveries);
|
||||||
collectProjectAgent(projectAgentsByDir, resolved.task, resolved.projectAgentsDir);
|
collectProjectAgent(projectAgentsByDir, resolved.task, resolved.projectAgentsDir);
|
||||||
if (request.mode === "chain") resolved.task.step = index + 1;
|
if (request.mode === "chain") resolved.task.step = index + 1;
|
||||||
tasks.push(resolved.task);
|
tasks.push(resolved.task);
|
||||||
@@ -422,6 +430,8 @@ export interface PrepareWorkflowOptions {
|
|||||||
confirmProjectWorkflows?: boolean;
|
confirmProjectWorkflows?: boolean;
|
||||||
/** Directories already approved in this session, so each prompts once. */
|
/** Directories already approved in this session, so each prompts once. */
|
||||||
approvedDirectories?: Set<string>;
|
approvedDirectories?: Set<string>;
|
||||||
|
/** The run's cap limits, captured from load-time config by the caller. */
|
||||||
|
limits?: WorkflowLimits;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -437,18 +447,16 @@ export async function prepareWorkflowInvocation(
|
|||||||
): Promise<PreparedWorkflowInvocation> {
|
): Promise<PreparedWorkflowInvocation> {
|
||||||
validateWorkflowRunShape(plan);
|
validateWorkflowRunShape(plan);
|
||||||
const resolvedArgs = validateWorkflowArgs(plan, args);
|
const resolvedArgs = validateWorkflowArgs(plan, args);
|
||||||
// Item counts are only known once the source step's output exists, so the
|
const limits = options.limits ?? {
|
||||||
// static shape starts every each-step at zero. Release re-validates with
|
maxItemsPerEach: DEFAULT_MAX_WORKFLOW_ITEMS,
|
||||||
// the real counts before any item child spawns.
|
maxExpandedChildren: MAX_EXPANDED_CHILDREN,
|
||||||
validateWorkflowExpansion(
|
};
|
||||||
plan,
|
|
||||||
new Map(plan.steps.filter((step) => step.each !== undefined).map((step): [string, number] => [step.id, 0])),
|
|
||||||
);
|
|
||||||
|
|
||||||
const agentScope = options.agentScope ?? "both";
|
const agentScope = options.agentScope ?? "both";
|
||||||
const projectAgentsByDir = new Map<string, Set<string>>();
|
const projectAgentsByDir = new Map<string, Set<string>>();
|
||||||
|
const discoveries = new Map<string, AgentDiscoveryResult>();
|
||||||
const steps: PreparedWorkflowStep[] = plan.steps.map((step) => {
|
const steps: PreparedWorkflowStep[] = plan.steps.map((step) => {
|
||||||
const resolved = resolvePreparedTask(step.agent, step.task, step.cwd, ctx.cwd, agentScope);
|
const resolved = resolvePreparedTask(step.agent, step.task, step.cwd, ctx.cwd, agentScope, discoveries);
|
||||||
const prepared: PreparedTask = {
|
const prepared: PreparedTask = {
|
||||||
...resolved.task,
|
...resolved.task,
|
||||||
stepId: step.id,
|
stepId: step.id,
|
||||||
@@ -494,6 +502,7 @@ export async function prepareWorkflowInvocation(
|
|||||||
args: resolvedArgs,
|
args: resolvedArgs,
|
||||||
steps,
|
steps,
|
||||||
expandedPlan: expandWorkflowPlan(plan),
|
expandedPlan: expandWorkflowPlan(plan),
|
||||||
|
limits,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+3
-15
@@ -12,8 +12,11 @@ import { formatReadLineRange, getMarkdownTheme } from "@earendil-works/pi-coding
|
|||||||
import { Container, Markdown, Spacer, Text, type Component } from "@earendil-works/pi-tui";
|
import { Container, Markdown, Spacer, Text, type Component } from "@earendil-works/pi-tui";
|
||||||
import { truncateUtf8Head } from "./output.ts";
|
import { truncateUtf8Head } from "./output.ts";
|
||||||
import { summarizeActivity } from "./activity.ts";
|
import { summarizeActivity } from "./activity.ts";
|
||||||
|
import { isFailedResult, type ResultStatusFields } from "./job-state.ts";
|
||||||
import type { RunResult, SubagentDetails, TaskStatus, UsageStats } from "./types.ts";
|
import type { RunResult, SubagentDetails, TaskStatus, UsageStats } from "./types.ts";
|
||||||
|
|
||||||
|
export type { ResultStatusFields } from "./job-state.ts";
|
||||||
|
|
||||||
export const PER_TASK_OUTPUT_CAP = 50 * 1024;
|
export const PER_TASK_OUTPUT_CAP = 50 * 1024;
|
||||||
export const PARALLEL_OUTPUT_CAP_BYTES = PER_TASK_OUTPUT_CAP;
|
export const PARALLEL_OUTPUT_CAP_BYTES = PER_TASK_OUTPUT_CAP;
|
||||||
|
|
||||||
@@ -40,13 +43,6 @@ export interface SubagentResultLike {
|
|||||||
details?: (Partial<SubagentDetails> & { results?: readonly RunResult[] }) | undefined;
|
details?: (Partial<SubagentDetails> & { results?: readonly RunResult[] }) | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ResultStatusFields {
|
|
||||||
status?: TaskStatus;
|
|
||||||
exitCode?: number | null;
|
|
||||||
stopReason?: string;
|
|
||||||
terminationSignal?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, any> };
|
type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, any> };
|
||||||
|
|
||||||
function resolveAgentScope(value: unknown): "user" | "project" | "both" {
|
function resolveAgentScope(value: unknown): "user" | "project" | "both" {
|
||||||
@@ -195,14 +191,6 @@ export function isSkippedStatus(status: TaskStatus | undefined): boolean {
|
|||||||
* every other result, null or nonzero exits are failures, as are explicit
|
* every other result, null or nonzero exits are failures, as are explicit
|
||||||
* error/aborted stop reasons, termination signals, and failure statuses.
|
* error/aborted stop reasons, termination signals, and failure statuses.
|
||||||
*/
|
*/
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isRunningResult(result: ResultStatusFields): boolean {
|
export function isRunningResult(result: ResultStatusFields): boolean {
|
||||||
return isRunningStatus(result.status);
|
return isRunningStatus(result.status);
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-8
@@ -11,13 +11,14 @@ import * as os from "node:os";
|
|||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import { StringDecoder } from "node:string_decoder";
|
import { StringDecoder } from "node:string_decoder";
|
||||||
import type { Message } from "@earendil-works/pi-ai";
|
import type { Message } from "@earendil-works/pi-ai";
|
||||||
import {
|
import { inheritedEnvironment } from "./config.ts";
|
||||||
emptyRunResult,
|
import { emptyRunResult } from "./job-state.ts";
|
||||||
type DispatchDefaults,
|
import type {
|
||||||
type PreparedTask,
|
DispatchDefaults,
|
||||||
type RunOptions,
|
PreparedTask,
|
||||||
type RunResult,
|
RunOptions,
|
||||||
type TaskRunner,
|
RunResult,
|
||||||
|
TaskRunner,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
|
|
||||||
const DEFAULT_KILL_GRACE_MS = 5000;
|
const DEFAULT_KILL_GRACE_MS = 5000;
|
||||||
@@ -228,7 +229,7 @@ export class ProcessRunner implements TaskRunner {
|
|||||||
this.killGraceMs = Math.max(0, options.killGraceMs ?? DEFAULT_KILL_GRACE_MS);
|
this.killGraceMs = Math.max(0, options.killGraceMs ?? DEFAULT_KILL_GRACE_MS);
|
||||||
this.stderrLimitBytes = Math.max(0, Math.floor(options.stderrLimitBytes ?? DEFAULT_STDERR_LIMIT_BYTES));
|
this.stderrLimitBytes = Math.max(0, Math.floor(options.stderrLimitBytes ?? DEFAULT_STDERR_LIMIT_BYTES));
|
||||||
this.platform = options.platform ?? process.platform;
|
this.platform = options.platform ?? process.platform;
|
||||||
this.env = options.env ?? process.env;
|
this.env = options.env ?? inheritedEnvironment();
|
||||||
}
|
}
|
||||||
|
|
||||||
async run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise<RunResult> {
|
async run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise<RunResult> {
|
||||||
|
|||||||
+48
-67
@@ -1,7 +1,7 @@
|
|||||||
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
||||||
import type { Message } from "@earendil-works/pi-ai";
|
import type { Message } from "@earendil-works/pi-ai";
|
||||||
import type { AgentConfig, AgentScope } from "./agents.ts";
|
import type { AgentConfig, AgentScope } from "./agents.ts";
|
||||||
import type { WorkflowJournal } from "./journal.ts";
|
import type { WorkflowPlan } from "./workflow-plan.ts";
|
||||||
|
|
||||||
export type InvocationMode = "single" | "parallel" | "chain" | "workflow";
|
export type InvocationMode = "single" | "parallel" | "chain" | "workflow";
|
||||||
export type JobStatus = "queued" | "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "interrupted";
|
export type JobStatus = "queued" | "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "interrupted";
|
||||||
@@ -126,55 +126,6 @@ export interface TaskIdentity {
|
|||||||
itemValue?: string;
|
itemValue?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The step/item-identity subset, so adding a field changes one mapping here. */
|
|
||||||
export function taskIdentityExtras(source: {
|
|
||||||
step?: number;
|
|
||||||
stepId?: string;
|
|
||||||
item?: number;
|
|
||||||
itemValue?: string;
|
|
||||||
}): Pick<TaskIdentity, "step" | "stepId" | "item" | "itemValue"> {
|
|
||||||
return { step: source.step, stepId: source.stepId, item: source.item, itemValue: source.itemValue };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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,
|
|
||||||
activity: [],
|
|
||||||
usage: emptyUsage(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface JobSnapshot {
|
export interface JobSnapshot {
|
||||||
id: string;
|
id: string;
|
||||||
mode: InvocationMode;
|
mode: InvocationMode;
|
||||||
@@ -211,6 +162,53 @@ export interface SyncRunOptions {
|
|||||||
onUpdate?: (outcome: SyncOutcome) => void;
|
onUpdate?: (outcome: SyncOutcome) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One fanned-out item child of an each-step, as the journal records it. */
|
||||||
|
export interface WorkflowJournalItem {
|
||||||
|
/** One-based item index within the step's fan-out. */
|
||||||
|
item: number;
|
||||||
|
/** The source line this item was fanned out from. */
|
||||||
|
input: string;
|
||||||
|
/** Stable across identical item inputs, so a replay layer can key on it. */
|
||||||
|
inputHash: string;
|
||||||
|
status: TaskStatus;
|
||||||
|
/** Children started for this item; always 0 or 1 while no retry exists. */
|
||||||
|
attempts: number;
|
||||||
|
output: string;
|
||||||
|
outputTruncated: boolean;
|
||||||
|
outputBytesOmitted: number;
|
||||||
|
startedAt?: number;
|
||||||
|
finishedAt?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WorkflowJournalStep {
|
||||||
|
id: string;
|
||||||
|
/** Stable across identical step inputs, so a replay layer can key on it. */
|
||||||
|
inputHash: string;
|
||||||
|
status: TaskStatus;
|
||||||
|
/** Children started for this step; always 0 or 1 while no retry exists. */
|
||||||
|
attempts: number;
|
||||||
|
output: string;
|
||||||
|
outputTruncated: boolean;
|
||||||
|
outputBytesOmitted: number;
|
||||||
|
startedAt?: number;
|
||||||
|
finishedAt?: number;
|
||||||
|
/** One row per each-step item, in item order; empty for steps that do not fan out. */
|
||||||
|
items: WorkflowJournalItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WorkflowJournal {
|
||||||
|
jobId: string;
|
||||||
|
status: JobStatus;
|
||||||
|
plan: WorkflowPlan;
|
||||||
|
args: Record<string, string>;
|
||||||
|
steps: WorkflowJournalStep[];
|
||||||
|
usage: UsageStats;
|
||||||
|
createdAt: number;
|
||||||
|
startedAt?: number;
|
||||||
|
finishedAt?: number;
|
||||||
|
errorMessage?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ManagerOptions {
|
export interface ManagerOptions {
|
||||||
maxWorkers?: number;
|
maxWorkers?: number;
|
||||||
maxActiveJobs?: number;
|
maxActiveJobs?: number;
|
||||||
@@ -223,23 +221,6 @@ export interface ManagerOptions {
|
|||||||
onWorkflowJournal?: (journal: WorkflowJournal) => void;
|
onWorkflowJournal?: (journal: WorkflowJournal) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
export function emptyUsage(): UsageStats {
|
||||||
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
|
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
|
||||||
}
|
}
|
||||||
+1
-2
@@ -9,9 +9,8 @@
|
|||||||
* child's output or reads a task snapshot again.
|
* child's output or reads a task snapshot again.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { WorkflowJournal, WorkflowJournalStep } from "./journal.ts";
|
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||||
import type { JobStatus } from "./types.ts";
|
import type { JobStatus, WorkflowJournal, WorkflowJournalStep } from "./types.ts";
|
||||||
|
|
||||||
export const ULTRA_DONE_MESSAGE_TYPE = "pi-subagent-ultra-done";
|
export const ULTRA_DONE_MESSAGE_TYPE = "pi-subagent-ultra-done";
|
||||||
|
|
||||||
|
|||||||
+4
-12
@@ -8,7 +8,7 @@
|
|||||||
|
|
||||||
import type { UltraGuideline } from "./config.ts";
|
import type { UltraGuideline } from "./config.ts";
|
||||||
import { formatUltraGuidelineLine } from "./ultra-mode.ts";
|
import { formatUltraGuidelineLine } from "./ultra-mode.ts";
|
||||||
import { MAX_EXPANDED_CHILDREN, MAX_WORKFLOW_STEPS } from "./workflow-plan.ts";
|
import { MAX_WORKFLOW_STEPS } from "./workflow-plan.ts";
|
||||||
import type { PreparedWorkflowInvocation, WorkflowStartResult } from "./workflow-run.ts";
|
import type { PreparedWorkflowInvocation, WorkflowStartResult } from "./workflow-run.ts";
|
||||||
|
|
||||||
/** Thrown when the user declines the review card for an inline plan. */
|
/** Thrown when the user declines the review card for an inline plan. */
|
||||||
@@ -27,11 +27,6 @@ export interface UltraReviewCard {
|
|||||||
message: string;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UltraReviewOptions {
|
|
||||||
maxItemsPerEach: number;
|
|
||||||
maxExpandedChildren?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
function plural(count: number, singular: string, pluralForm = `${singular}s`): string {
|
function plural(count: number, singular: string, pluralForm = `${singular}s`): string {
|
||||||
return `${count} ${count === 1 ? singular : pluralForm}`;
|
return `${count} ${count === 1 ? singular : pluralForm}`;
|
||||||
}
|
}
|
||||||
@@ -43,13 +38,10 @@ function plural(count: number, singular: string, pluralForm = `${singular}s`): s
|
|||||||
* run — every step, its needs and fan-out source, the child-count estimate
|
* run — every step, its needs and fan-out source, the child-count estimate
|
||||||
* against the caps, and every named agent with its user/project source.
|
* against the caps, and every named agent with its user/project source.
|
||||||
*/
|
*/
|
||||||
export function formatUltraReviewCard(
|
export function formatUltraReviewCard(prepared: PreparedWorkflowInvocation): UltraReviewCard {
|
||||||
prepared: PreparedWorkflowInvocation,
|
|
||||||
options: UltraReviewOptions,
|
|
||||||
): UltraReviewCard {
|
|
||||||
const steps = prepared.workflow.steps;
|
const steps = prepared.workflow.steps;
|
||||||
const maxItemsPerEach = options.maxItemsPerEach;
|
const maxItemsPerEach = prepared.workflow.limits.maxItemsPerEach;
|
||||||
const maxExpandedChildren = options.maxExpandedChildren ?? MAX_EXPANDED_CHILDREN;
|
const maxExpandedChildren = prepared.workflow.limits.maxExpandedChildren;
|
||||||
|
|
||||||
const fanOutSteps = steps.filter((step) => step.each !== undefined).length;
|
const fanOutSteps = steps.filter((step) => step.each !== undefined).length;
|
||||||
const fixedSteps = steps.length - fanOutSteps;
|
const fixedSteps = steps.length - fanOutSteps;
|
||||||
|
|||||||
@@ -12,7 +12,6 @@
|
|||||||
import * as fs from "node:fs";
|
import * as fs from "node:fs";
|
||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
||||||
import { readMaxWorkflowItems } from "./config.ts";
|
|
||||||
|
|
||||||
export const MAX_WORKFLOW_STEPS = 64;
|
export const MAX_WORKFLOW_STEPS = 64;
|
||||||
export const MAX_EXPANDED_CHILDREN = 256;
|
export const MAX_EXPANDED_CHILDREN = 256;
|
||||||
@@ -66,9 +65,10 @@ export interface WorkflowDiscoveryResult {
|
|||||||
|
|
||||||
export type WorkflowItemCounts = ReadonlyMap<string, number>;
|
export type WorkflowItemCounts = ReadonlyMap<string, number>;
|
||||||
|
|
||||||
export interface WorkflowExpansionOptions {
|
/** The run's cap limits, captured once from load-time config and threaded here. */
|
||||||
maxItemsPerEach?: number;
|
export interface WorkflowLimits {
|
||||||
maxExpandedChildren?: number;
|
maxItemsPerEach: number;
|
||||||
|
maxExpandedChildren: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Thrown when no workflow with the requested name exists in scope. */
|
/** Thrown when no workflow with the requested name exists in scope. */
|
||||||
@@ -520,11 +520,10 @@ function failPlan(plan: WorkflowPlan, message: string, stepId?: string): never {
|
|||||||
export function validateWorkflowExpansion(
|
export function validateWorkflowExpansion(
|
||||||
plan: WorkflowPlan,
|
plan: WorkflowPlan,
|
||||||
items: WorkflowItemCounts,
|
items: WorkflowItemCounts,
|
||||||
options: WorkflowExpansionOptions = {},
|
limits: WorkflowLimits,
|
||||||
): number {
|
): number {
|
||||||
const maxItems =
|
const maxItems = limits.maxItemsPerEach;
|
||||||
options.maxItemsPerEach ?? readMaxWorkflowItems(process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS).value;
|
const maxChildren = limits.maxExpandedChildren;
|
||||||
const maxChildren = options.maxExpandedChildren ?? MAX_EXPANDED_CHILDREN;
|
|
||||||
|
|
||||||
let children = 0;
|
let children = 0;
|
||||||
for (const [index, step] of plan.steps.entries()) {
|
for (const [index, step] of plan.steps.entries()) {
|
||||||
|
|||||||
+3
-1
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
import { truncateUtf8Head } from "./output.ts";
|
import { truncateUtf8Head } from "./output.ts";
|
||||||
import type { JobSnapshot, PreparedInvocation, PreparedTask } from "./types.ts";
|
import type { JobSnapshot, PreparedInvocation, PreparedTask } from "./types.ts";
|
||||||
import { workflowValidationError, type WorkflowPlan } from "./workflow-plan.ts";
|
import { workflowValidationError, type WorkflowLimits, type WorkflowPlan } from "./workflow-plan.ts";
|
||||||
|
|
||||||
/** The design ceiling for one run, independent of the global worker pool. */
|
/** The design ceiling for one run, independent of the global worker pool. */
|
||||||
export const WORKFLOW_MAX_CONCURRENCY = 4;
|
export const WORKFLOW_MAX_CONCURRENCY = 4;
|
||||||
@@ -49,6 +49,8 @@ export interface WorkflowRunSpec {
|
|||||||
args: Record<string, string>;
|
args: Record<string, string>;
|
||||||
steps: PreparedWorkflowStep[];
|
steps: PreparedWorkflowStep[];
|
||||||
expandedPlan: StartPlan;
|
expandedPlan: StartPlan;
|
||||||
|
/** Captured once at prepare time; enforcement and the review card share it. */
|
||||||
|
limits: WorkflowLimits;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PreparedWorkflowInvocation extends PreparedInvocation {
|
export interface PreparedWorkflowInvocation extends PreparedInvocation {
|
||||||
|
|||||||
+159
-95
@@ -3,8 +3,8 @@
|
|||||||
*
|
*
|
||||||
* Owns the DAG rules for one run: which steps are ready, how skips cascade,
|
* Owns the DAG rules for one run: which steps are ready, how skips cascade,
|
||||||
* how each-step items fan out and aggregate, and when the run settles. The
|
* how each-step items fan out and aggregate, and when the run settles. The
|
||||||
* manager owns the FIFO pool and the job/task lifecycle; a run reaches them
|
* manager owns the FIFO pool and the job record; a run reaches them only
|
||||||
* only through `WorkflowSupervisorHost`. ADR 0002 stands: a run is a job on the
|
* through `WorkflowSupervisorHost`. ADR 0002 stands: a run is a job on the
|
||||||
* shared manager, not a parallel subsystem.
|
* shared manager, not a parallel subsystem.
|
||||||
*
|
*
|
||||||
* The behavior mirrors spec/SubagentJobs.tla: needs sets, the transitive skip
|
* The behavior mirrors spec/SubagentJobs.tla: needs sets, the transitive skip
|
||||||
@@ -12,16 +12,26 @@
|
|||||||
* step is terminal.
|
* step is terminal.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { Execution, InternalTask } from "./manager.ts";
|
|
||||||
import {
|
import {
|
||||||
emptyRunResult,
|
|
||||||
isTerminalJob,
|
|
||||||
isTerminalTask,
|
isTerminalTask,
|
||||||
type JobStatus,
|
markCoordinatorStarted,
|
||||||
type PreparedTask,
|
markTaskRunning,
|
||||||
type RunResult,
|
setTaskBrief,
|
||||||
type TaskSnapshot,
|
taskBaseResult,
|
||||||
type TaskStatus,
|
taskHasController,
|
||||||
|
taskItemValue,
|
||||||
|
taskOutput,
|
||||||
|
taskResult,
|
||||||
|
taskStatus,
|
||||||
|
type Execution,
|
||||||
|
type InternalTask,
|
||||||
|
} from "./job-state.ts";
|
||||||
|
import type {
|
||||||
|
JobStatus,
|
||||||
|
PreparedTask,
|
||||||
|
RunResult,
|
||||||
|
TaskSnapshot,
|
||||||
|
TaskStatus,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
import {
|
import {
|
||||||
interpolateWorkflowTask,
|
interpolateWorkflowTask,
|
||||||
@@ -32,16 +42,21 @@ import {
|
|||||||
} from "./workflow-run.ts";
|
} from "./workflow-run.ts";
|
||||||
import { validateWorkflowExpansion } from "./workflow-plan.ts";
|
import { validateWorkflowExpansion } from "./workflow-plan.ts";
|
||||||
|
|
||||||
|
/** One way an external signal ends a run. */
|
||||||
|
export type WorkflowTermination = "cancelled" | "interrupted";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The manager capabilities a run needs. Queueing, worker accounting, job
|
* The manager capabilities a run needs. Queueing, worker accounting, job
|
||||||
* admission, cancellation, snapshots, waiters, and persistence stay with the
|
* admission, snapshots, waiters, and persistence stay with the manager; the
|
||||||
* manager; the supervisor sees only this seam.
|
* supervisor sees only this seam. Apart from the clock, every method is an
|
||||||
|
* effect: the manager registers the row, starts the work, or commits the
|
||||||
|
* outcome.
|
||||||
*/
|
*/
|
||||||
export interface WorkflowSupervisorHost {
|
export interface WorkflowSupervisorHost {
|
||||||
|
/** Create a queued row, register it in the job record, and count it. */
|
||||||
|
createTask(execution: Execution, prepared: PreparedTask): InternalTask;
|
||||||
/** Submit one step or item child to the shared FIFO; resolves with its result. */
|
/** Submit one step or item child to the shared FIFO; resolves with its result. */
|
||||||
schedule(execution: Execution, task: InternalTask): Promise<RunResult>;
|
schedule(execution: Execution, task: InternalTask): Promise<RunResult>;
|
||||||
/** Build a fresh queued task for a step or an each-step item child. */
|
|
||||||
createTask(prepared: PreparedTask): InternalTask;
|
|
||||||
/** Move a task to a terminal snapshot and its matching result in one step. */
|
/** Move a task to a terminal snapshot and its matching result in one step. */
|
||||||
settleTask(
|
settleTask(
|
||||||
task: InternalTask,
|
task: InternalTask,
|
||||||
@@ -50,7 +65,7 @@ export interface WorkflowSupervisorHost {
|
|||||||
snapshot?: Partial<TaskSnapshot>,
|
snapshot?: Partial<TaskSnapshot>,
|
||||||
): RunResult;
|
): RunResult;
|
||||||
/** The result of a task the pool never ran, for cancellation settlement. */
|
/** The result of a task the pool never ran, for cancellation settlement. */
|
||||||
cancelledResult(task: InternalTask): RunResult;
|
cancelledResult(task: InternalTask, status?: WorkflowTermination): RunResult;
|
||||||
/** Commit the run's terminal status. */
|
/** Commit the run's terminal status. */
|
||||||
finalize(execution: Execution, status: JobStatus): void;
|
finalize(execution: Execution, status: JobStatus): void;
|
||||||
/** Notify job observers that the run changed. */
|
/** Notify job observers that the run changed. */
|
||||||
@@ -62,18 +77,24 @@ export interface WorkflowSupervisorHost {
|
|||||||
interface WorkflowRunState {
|
interface WorkflowRunState {
|
||||||
execution: Execution;
|
execution: Execution;
|
||||||
spec: WorkflowRunSpec;
|
spec: WorkflowRunSpec;
|
||||||
|
tasks: InternalTask[];
|
||||||
stepTasks: Map<string, InternalTask>;
|
stepTasks: Map<string, InternalTask>;
|
||||||
activeChildren: Map<InternalTask, Promise<void>>;
|
activeChildren: Map<InternalTask, Promise<void>>;
|
||||||
itemTasks: Map<string, InternalTask[]>;
|
itemTasks: Map<string, InternalTask[]>;
|
||||||
pendingItems: Map<string, InternalTask[]>;
|
pendingItems: Map<string, InternalTask[]>;
|
||||||
itemCounts: Map<string, number>;
|
itemCounts: Map<string, number>;
|
||||||
|
/** Step ids whose one release has happened, whatever its outcome. */
|
||||||
|
released: Set<string>;
|
||||||
concurrency: number;
|
concurrency: number;
|
||||||
|
termination?: WorkflowTermination;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WorkflowSupervisor {
|
export class WorkflowSupervisor {
|
||||||
private readonly host: WorkflowSupervisorHost;
|
private readonly host: WorkflowSupervisorHost;
|
||||||
private readonly maxWorkers: number;
|
private readonly maxWorkers: number;
|
||||||
private readonly concurrency: number;
|
private readonly concurrency: number;
|
||||||
|
/** Live runs by their opaque job record, so cancellation can reach their DAG state. */
|
||||||
|
private readonly runs = new Map<Execution, WorkflowRunState>();
|
||||||
|
|
||||||
constructor(host: WorkflowSupervisorHost, maxWorkers: number) {
|
constructor(host: WorkflowSupervisorHost, maxWorkers: number) {
|
||||||
this.host = host;
|
this.host = host;
|
||||||
@@ -94,60 +115,72 @@ export class WorkflowSupervisor {
|
|||||||
const state: WorkflowRunState = {
|
const state: WorkflowRunState = {
|
||||||
execution,
|
execution,
|
||||||
spec,
|
spec,
|
||||||
|
tasks: [],
|
||||||
stepTasks: new Map(),
|
stepTasks: new Map(),
|
||||||
activeChildren: new Map(),
|
activeChildren: new Map(),
|
||||||
itemTasks: new Map(),
|
itemTasks: new Map(),
|
||||||
pendingItems: new Map(),
|
pendingItems: new Map(),
|
||||||
itemCounts: new Map(),
|
itemCounts: new Map(),
|
||||||
|
released: new Set(),
|
||||||
concurrency: this.concurrency,
|
concurrency: this.concurrency,
|
||||||
};
|
};
|
||||||
for (const task of execution.tasks) {
|
|
||||||
if (task.prepared.stepId) state.stepTasks.set(task.prepared.stepId, task);
|
|
||||||
}
|
|
||||||
for (const step of spec.steps) {
|
for (const step of spec.steps) {
|
||||||
if (step.each !== undefined) state.itemCounts.set(step.id, 0);
|
if (step.each !== undefined) state.itemCounts.set(step.id, 0);
|
||||||
}
|
}
|
||||||
|
this.runs.set(execution, state);
|
||||||
|
|
||||||
while (true) {
|
try {
|
||||||
for (const [task] of state.activeChildren) {
|
// The supervisor creates every run row through the host, so the flat
|
||||||
if (isTerminalTask(task.snapshot.status)) state.activeChildren.delete(task);
|
// job record and this DAG index start from the same plan order.
|
||||||
|
for (const step of spec.steps) {
|
||||||
|
const task = this.host.createTask(execution, step.prepared);
|
||||||
|
state.stepTasks.set(step.id, task);
|
||||||
|
state.tasks.push(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isTerminalJob(execution.status)) return;
|
while (true) {
|
||||||
if (execution.cancelRequested) {
|
for (const [task] of state.activeChildren) {
|
||||||
if (state.activeChildren.size === 0) {
|
if (isTerminalTask(taskStatus(task))) state.activeChildren.delete(task);
|
||||||
this.host.finalize(execution, "cancelled");
|
}
|
||||||
|
|
||||||
|
if (state.termination === "interrupted") return;
|
||||||
|
if (state.termination === "cancelled") {
|
||||||
|
if (state.activeChildren.size === 0) {
|
||||||
|
this.host.finalize(execution, "cancelled");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await Promise.race(state.activeChildren.values());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let changed = false;
|
||||||
|
if (this.propagateWorkflowSkips(state)) changed = true;
|
||||||
|
if (this.settleWorkflowItemSteps(state)) changed = true;
|
||||||
|
|
||||||
|
if (state.tasks.every((task) => isTerminalTask(taskStatus(task)))) {
|
||||||
|
const outcome = state.tasks.some((task) => taskStatus(task) === "failed") ? "failed" : "succeeded";
|
||||||
|
this.host.finalize(execution, outcome);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (state.concurrency - state.activeChildren.size > 0) {
|
||||||
|
if (this.releaseWorkflowSteps(state)) changed = true;
|
||||||
|
if (this.launchWorkflowItems(state)) changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (changed) this.host.emit(execution);
|
||||||
|
|
||||||
|
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 "${spec.plan.name}" stalled with no releasable steps.`);
|
||||||
|
}
|
||||||
|
|
||||||
await Promise.race(state.activeChildren.values());
|
await Promise.race(state.activeChildren.values());
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
let changed = false;
|
this.runs.delete(execution);
|
||||||
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";
|
|
||||||
this.host.finalize(execution, outcome);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state.concurrency - state.activeChildren.size > 0) {
|
|
||||||
if (this.releaseWorkflowSteps(state)) changed = true;
|
|
||||||
if (this.launchWorkflowItems(state)) changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (changed) this.host.emit(execution);
|
|
||||||
|
|
||||||
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(state.activeChildren.values());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,13 +190,33 @@ export class WorkflowSupervisor {
|
|||||||
* coordinator rows (which have no child process of their own).
|
* coordinator rows (which have no child process of their own).
|
||||||
*/
|
*/
|
||||||
cancel(execution: Execution): void {
|
cancel(execution: Execution): void {
|
||||||
for (const task of execution.tasks) {
|
this.terminate(execution, "cancelled");
|
||||||
if (task.snapshot.status !== "queued") continue;
|
}
|
||||||
this.host.settleTask(task, "cancelled", this.host.cancelledResult(task));
|
|
||||||
|
/**
|
||||||
|
* Shutdown is the same settlement policy with interrupted semantics. The
|
||||||
|
* manager signals the run, this settles every unfinished row, and the
|
||||||
|
* manager aborts the child processes and commits the job status.
|
||||||
|
*/
|
||||||
|
interrupt(execution: Execution): void {
|
||||||
|
this.terminate(execution, "interrupted");
|
||||||
|
}
|
||||||
|
|
||||||
|
private terminate(execution: Execution, outcome: WorkflowTermination): void {
|
||||||
|
const state = this.runs.get(execution);
|
||||||
|
if (!state) return;
|
||||||
|
if (state.termination !== "interrupted") state.termination = outcome;
|
||||||
|
|
||||||
|
for (const task of state.tasks) {
|
||||||
|
const status = taskStatus(task);
|
||||||
|
const settles = status === "queued"
|
||||||
|
|| (status === "running" && (outcome === "interrupted" || !taskHasController(task)));
|
||||||
|
if (!settles) continue;
|
||||||
|
this.host.settleTask(task, outcome, this.host.cancelledResult(task, outcome));
|
||||||
}
|
}
|
||||||
for (const task of execution.tasks) {
|
|
||||||
if (task.snapshot.status !== "running" || task.controller) continue;
|
if (state.termination === "cancelled" && state.activeChildren.size === 0) {
|
||||||
this.host.settleTask(task, "cancelled", this.host.cancelledResult(task));
|
this.host.finalize(execution, "cancelled");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,13 +228,13 @@ export class WorkflowSupervisor {
|
|||||||
pass = false;
|
pass = false;
|
||||||
for (const step of spec.steps) {
|
for (const step of spec.steps) {
|
||||||
const task = stepTasks.get(step.id);
|
const task = stepTasks.get(step.id);
|
||||||
if (!task || task.snapshot.status !== "queued" || task.submitted) continue;
|
if (!task || taskStatus(task) !== "queued" || state.released.has(step.id)) continue;
|
||||||
const deadNeed = step.needs.some((need) => {
|
const deadNeed = step.needs.some((need) => {
|
||||||
const needTask = stepTasks.get(need);
|
const needTask = stepTasks.get(need);
|
||||||
return Boolean(
|
return Boolean(
|
||||||
needTask &&
|
needTask &&
|
||||||
isTerminalTask(needTask.snapshot.status) &&
|
isTerminalTask(taskStatus(needTask)) &&
|
||||||
needTask.snapshot.status !== "succeeded",
|
taskStatus(needTask) !== "succeeded",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
if (!deadNeed) continue;
|
if (!deadNeed) continue;
|
||||||
@@ -203,22 +256,28 @@ export class WorkflowSupervisor {
|
|||||||
for (const step of spec.steps) {
|
for (const step of spec.steps) {
|
||||||
if (slots <= 0) break;
|
if (slots <= 0) break;
|
||||||
const task = stepTasks.get(step.id);
|
const task = stepTasks.get(step.id);
|
||||||
if (!task || task.snapshot.status !== "queued" || task.submitted) continue;
|
if (!task || taskStatus(task) !== "queued" || state.released.has(step.id)) continue;
|
||||||
const needsSucceeded = step.needs.every(
|
const needsSucceeded = step.needs.every((need) => {
|
||||||
(need) => stepTasks.get(need)?.snapshot.status === "succeeded",
|
const needTask = stepTasks.get(need);
|
||||||
);
|
return needTask !== undefined && taskStatus(needTask) === "succeeded";
|
||||||
|
});
|
||||||
if (!needsSucceeded) continue;
|
if (!needsSucceeded) continue;
|
||||||
|
|
||||||
const outputs = new Map<string, string>();
|
const outputs = new Map<string, string>();
|
||||||
for (const need of step.needs) outputs.set(need, stepTasks.get(need)?.snapshot.output ?? "");
|
for (const need of step.needs) {
|
||||||
|
const needTask = stepTasks.get(need);
|
||||||
|
outputs.set(need, needTask ? taskOutput(needTask) : "");
|
||||||
|
}
|
||||||
|
|
||||||
if (step.each !== undefined) {
|
if (step.each !== undefined) {
|
||||||
const items = splitWorkflowItems(stepTasks.get(step.each)?.snapshot.output ?? "");
|
const sourceTask = stepTasks.get(step.each);
|
||||||
|
const items = splitWorkflowItems(sourceTask ? taskOutput(sourceTask) : "");
|
||||||
const nextCounts = new Map(itemCounts);
|
const nextCounts = new Map(itemCounts);
|
||||||
nextCounts.set(step.id, items.length);
|
nextCounts.set(step.id, items.length);
|
||||||
try {
|
try {
|
||||||
validateWorkflowExpansion(spec.plan, nextCounts);
|
validateWorkflowExpansion(spec.plan, nextCounts, spec.limits);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
state.released.add(step.id);
|
||||||
this.failWorkflowStep(task, error instanceof Error ? error.message : String(error));
|
this.failWorkflowStep(task, error instanceof Error ? error.message : String(error));
|
||||||
released = true;
|
released = true;
|
||||||
continue;
|
continue;
|
||||||
@@ -226,6 +285,7 @@ export class WorkflowSupervisor {
|
|||||||
itemCounts.set(step.id, items.length);
|
itemCounts.set(step.id, items.length);
|
||||||
|
|
||||||
if (items.length === 0) {
|
if (items.length === 0) {
|
||||||
|
state.released.add(step.id);
|
||||||
this.failWorkflowStep(
|
this.failWorkflowStep(
|
||||||
task,
|
task,
|
||||||
`Each-step "${step.id}": source produced no items from "{steps.${step.each}.output}".`,
|
`Each-step "${step.id}": source produced no items from "{steps.${step.each}.output}".`,
|
||||||
@@ -236,12 +296,17 @@ export class WorkflowSupervisor {
|
|||||||
|
|
||||||
const children = items.map((item, index) => {
|
const children = items.map((item, index) => {
|
||||||
const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs, item });
|
const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs, item });
|
||||||
return this.host.createTask({ ...step.prepared, task: brief, stepId: step.id, item: index + 1, itemValue: item });
|
return this.host.createTask(execution, {
|
||||||
|
...step.prepared,
|
||||||
|
task: brief,
|
||||||
|
stepId: step.id,
|
||||||
|
item: index + 1,
|
||||||
|
itemValue: item,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
task.submitted = true;
|
state.released.add(step.id);
|
||||||
task.snapshot.startedAt = this.host.now();
|
markCoordinatorStarted(task, this.host.now());
|
||||||
execution.tasks.push(...children);
|
state.tasks.push(...children);
|
||||||
execution.plannedTaskCount += children.length;
|
|
||||||
state.itemTasks.set(step.id, children);
|
state.itemTasks.set(step.id, children);
|
||||||
state.pendingItems.set(step.id, [...children]);
|
state.pendingItems.set(step.id, [...children]);
|
||||||
released = true;
|
released = true;
|
||||||
@@ -249,10 +314,8 @@ export class WorkflowSupervisor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs });
|
const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs });
|
||||||
task.prepared = { ...step.prepared, task: brief, stepId: step.id };
|
setTaskBrief(task, { ...step.prepared, task: brief, stepId: step.id });
|
||||||
task.snapshot.task = brief;
|
state.released.add(step.id);
|
||||||
if (task.result) task.result = { ...task.result, task: brief, stepId: step.id };
|
|
||||||
task.submitted = true;
|
|
||||||
state.activeChildren.set(task, this.host.schedule(execution, task).then(() => undefined));
|
state.activeChildren.set(task, this.host.schedule(execution, task).then(() => undefined));
|
||||||
released = true;
|
released = true;
|
||||||
slots--;
|
slots--;
|
||||||
@@ -276,15 +339,13 @@ export class WorkflowSupervisor {
|
|||||||
const child = queue?.shift();
|
const child = queue?.shift();
|
||||||
if (!child) continue;
|
if (!child) continue;
|
||||||
pass = true;
|
pass = true;
|
||||||
if (isTerminalTask(child.snapshot.status)) {
|
if (isTerminalTask(taskStatus(child))) {
|
||||||
launched = true;
|
launched = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const stepTask = stepTasks.get(step.id);
|
const stepTask = stepTasks.get(step.id);
|
||||||
if (stepTask && stepTask.snapshot.status === "queued") {
|
if (stepTask && taskStatus(stepTask) === "queued") {
|
||||||
stepTask.snapshot.status = "running";
|
markTaskRunning(stepTask, this.host.now());
|
||||||
stepTask.snapshot.startedAt = this.host.now();
|
|
||||||
if (stepTask.result) stepTask.result = { ...stepTask.result, status: "running" };
|
|
||||||
}
|
}
|
||||||
state.activeChildren.set(child, this.host.schedule(execution, child).then(() => undefined));
|
state.activeChildren.set(child, this.host.schedule(execution, child).then(() => undefined));
|
||||||
launched = true;
|
launched = true;
|
||||||
@@ -304,34 +365,36 @@ export class WorkflowSupervisor {
|
|||||||
const task = stepTasks.get(step.id);
|
const task = stepTasks.get(step.id);
|
||||||
const items = itemTasks.get(step.id);
|
const items = itemTasks.get(step.id);
|
||||||
if (!task || !items || items.length === 0) continue;
|
if (!task || !items || items.length === 0) continue;
|
||||||
if (task.snapshot.status !== "queued" && task.snapshot.status !== "running") continue;
|
const status = taskStatus(task);
|
||||||
if (!items.every((item) => isTerminalTask(item.snapshot.status))) continue;
|
if (status !== "queued" && status !== "running") continue;
|
||||||
|
if (!items.every((item) => isTerminalTask(taskStatus(item)))) continue;
|
||||||
|
|
||||||
const statuses = items.map((item) => item.snapshot.status);
|
const statuses = items.map((item) => taskStatus(item));
|
||||||
const succeeded = statuses.filter((status) => status === "succeeded").length;
|
const succeeded = statuses.filter((itemStatus) => itemStatus === "succeeded").length;
|
||||||
const interrupted = statuses.includes("interrupted");
|
const interrupted = statuses.includes("interrupted");
|
||||||
const cancelled = statuses.includes("cancelled");
|
const cancelled = statuses.includes("cancelled");
|
||||||
|
const base = taskResult(task) ?? this.host.cancelledResult(task);
|
||||||
|
|
||||||
if (interrupted || cancelled) {
|
if (interrupted || cancelled) {
|
||||||
const status = interrupted ? "interrupted" : "cancelled";
|
const outcome = interrupted ? "interrupted" : "cancelled";
|
||||||
const message = interrupted ? "Interrupted by session shutdown" : "Cancelled by caller";
|
const message = interrupted ? "Interrupted by session shutdown" : "Cancelled by caller";
|
||||||
const result = { ...(task.result ?? this.host.cancelledResult(task)), output: "", errorMessage: message };
|
const result = { ...base, output: "", errorMessage: message };
|
||||||
this.host.settleTask(task, status, result, { errorMessage: message });
|
this.host.settleTask(task, outcome, result, { errorMessage: message });
|
||||||
} else {
|
} else {
|
||||||
const output = joinWorkflowItemOutputs(
|
const output = joinWorkflowItemOutputs(
|
||||||
items.map((item) => ({
|
items.map((item) => ({
|
||||||
item: item.snapshot.itemValue ?? "",
|
item: taskItemValue(item) ?? "",
|
||||||
// Failed items leave an empty slot; their partial output never leaks in.
|
// Failed items leave an empty slot; their partial output never leaks in.
|
||||||
output: item.snapshot.status === "succeeded" ? item.snapshot.output : "",
|
output: taskStatus(item) === "succeeded" ? taskOutput(item) : "",
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
const snapshot = { output, outputTruncated: false, outputBytesOmitted: 0 };
|
const snapshot = { output, outputTruncated: false, outputBytesOmitted: 0 };
|
||||||
if (succeeded > 0) {
|
if (succeeded > 0) {
|
||||||
const result = { ...task.result!, output, errorMessage: undefined, exitCode: 0 };
|
const result = { ...base, output, errorMessage: undefined, exitCode: 0 };
|
||||||
this.host.settleTask(task, "succeeded", result, { ...snapshot, errorMessage: undefined });
|
this.host.settleTask(task, "succeeded", result, { ...snapshot, errorMessage: undefined });
|
||||||
} else {
|
} else {
|
||||||
const message = `All ${items.length} item${items.length === 1 ? "" : "s"} failed`;
|
const message = `All ${items.length} item${items.length === 1 ? "" : "s"} failed`;
|
||||||
const result = { ...task.result!, output, errorMessage: message, exitCode: 1 };
|
const result = { ...base, output, errorMessage: message, exitCode: 1 };
|
||||||
this.host.settleTask(task, "failed", result, { ...snapshot, exitCode: 1, errorMessage: message });
|
this.host.settleTask(task, "failed", result, { ...snapshot, exitCode: 1, errorMessage: message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -343,17 +406,18 @@ export class WorkflowSupervisor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private failWorkflowStep(task: InternalTask, message: string): void {
|
private failWorkflowStep(task: InternalTask, message: string): void {
|
||||||
|
const base = taskResult(task) ?? this.host.cancelledResult(task);
|
||||||
this.host.settleTask(
|
this.host.settleTask(
|
||||||
task,
|
task,
|
||||||
"failed",
|
"failed",
|
||||||
{ ...task.result!, exitCode: 1, errorMessage: message },
|
{ ...base, exitCode: 1, errorMessage: message },
|
||||||
{ exitCode: 1, errorMessage: message },
|
{ exitCode: 1, errorMessage: message },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private skippedResult(task: InternalTask): RunResult {
|
private skippedResult(task: InternalTask): RunResult {
|
||||||
return {
|
return {
|
||||||
...emptyRunResult(task.prepared),
|
...taskBaseResult(task),
|
||||||
status: "skipped",
|
status: "skipped",
|
||||||
errorMessage: "Skipped because a required step did not succeed",
|
errorMessage: "Skipped because a required step did not succeed",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ import assert from "node:assert/strict";
|
|||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import fc from "fast-check";
|
import fc from "fast-check";
|
||||||
import { SubagentManager } from "../src/manager.ts";
|
import { SubagentManager } from "../src/manager.ts";
|
||||||
import { isTerminalJob, type JobSnapshot, type JobStatus } from "../src/types.ts";
|
import { isTerminalJob } from "../src/job-state.ts";
|
||||||
|
import type { JobSnapshot, JobStatus } from "../src/types.ts";
|
||||||
import { FakeRunner, invocation } from "./helpers.ts";
|
import { FakeRunner, invocation } from "./helpers.ts";
|
||||||
|
|
||||||
type Action =
|
type Action =
|
||||||
|
|||||||
+1
-1
@@ -1,11 +1,11 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import type { Message } from "@earendil-works/pi-ai";
|
import type { Message } from "@earendil-works/pi-ai";
|
||||||
|
import { isFailedResult } from "../src/job-state.ts";
|
||||||
import type { SubagentDetails, RunResult } from "../src/types.ts";
|
import type { SubagentDetails, RunResult } from "../src/types.ts";
|
||||||
import {
|
import {
|
||||||
PER_TASK_OUTPUT_CAP,
|
PER_TASK_OUTPUT_CAP,
|
||||||
formatParallelSummary,
|
formatParallelSummary,
|
||||||
isFailedResult,
|
|
||||||
isRunningResult,
|
isRunningResult,
|
||||||
isSuccessfulResult,
|
isSuccessfulResult,
|
||||||
renderSubagentCall,
|
renderSubagentCall,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import test, { after } from "node:test";
|
|||||||
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
||||||
import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
||||||
import registerExtension from "../src/index.ts";
|
import registerExtension from "../src/index.ts";
|
||||||
import type { WorkflowJournal, WorkflowJournalStep } from "../src/journal.ts";
|
import type { WorkflowJournal, WorkflowJournalStep } from "../src/types.ts";
|
||||||
import { MAX_TASK_OUTPUT_BYTES } from "../src/output.ts";
|
import { MAX_TASK_OUTPUT_BYTES } from "../src/output.ts";
|
||||||
import { extractWorkflowJournals } from "../src/persistence.ts";
|
import { extractWorkflowJournals } from "../src/persistence.ts";
|
||||||
import { emptyUsage, type JobStatus, type TaskStatus } from "../src/types.ts";
|
import { emptyUsage, type JobStatus, type TaskStatus } from "../src/types.ts";
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import * as os from "node:os";
|
|||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import test, { after } from "node:test";
|
import test, { after } from "node:test";
|
||||||
import fc from "fast-check";
|
import fc from "fast-check";
|
||||||
import { buildWorkflowJournal, workflowItemInputHash, workflowStepInputHash, type WorkflowJournal, type WorkflowJournalItem, type WorkflowJournalStep } from "../src/journal.ts";
|
import { buildWorkflowJournal, workflowItemInputHash, workflowStepInputHash } from "../src/journal.ts";
|
||||||
import { SubagentManager } from "../src/manager.ts";
|
import { SubagentManager } from "../src/manager.ts";
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts";
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts";
|
||||||
import {
|
import {
|
||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
} from "../src/persistence.ts";
|
} from "../src/persistence.ts";
|
||||||
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
||||||
import { parseWorkflow, type WorkflowPlan } from "../src/workflow-plan.ts";
|
import { parseWorkflow, type WorkflowPlan } from "../src/workflow-plan.ts";
|
||||||
import { emptyUsage, type JobSnapshot, type TaskSnapshot, type TaskStatus } from "../src/types.ts";
|
import { emptyUsage, type JobSnapshot, type TaskSnapshot, type TaskStatus, type WorkflowJournal, type WorkflowJournalItem, type WorkflowJournalStep } from "../src/types.ts";
|
||||||
import { FakeRunner } from "./helpers.ts";
|
import { FakeRunner } from "./helpers.ts";
|
||||||
|
|
||||||
const tempRoots: string[] = [];
|
const tempRoots: string[] = [];
|
||||||
|
|||||||
+13
-18
@@ -276,39 +276,34 @@ function itemCounts(counts: number[]): Map<string, number> {
|
|||||||
return new Map(counts.map((count, index) => [`audit_${index}`, count]));
|
return new Map(counts.map((count, index) => [`audit_${index}`, count]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function limits(maxItemsPerEach = 32, maxExpandedChildren = MAX_EXPANDED_CHILDREN) {
|
||||||
|
return { maxItemsPerEach, maxExpandedChildren };
|
||||||
|
}
|
||||||
|
|
||||||
test("expanded children caps are validated per each-step and per run", () => {
|
test("expanded children caps are validated per each-step and per run", () => {
|
||||||
const p = eachPlan([32]);
|
const p = eachPlan([32]);
|
||||||
assert.equal(validateWorkflowExpansion(p, itemCounts([32])), 33);
|
assert.equal(validateWorkflowExpansion(p, itemCounts([32]), limits()), 33);
|
||||||
|
|
||||||
const tooManyItems = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([33]), { maxItemsPerEach: 32 }));
|
const tooManyItems = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([33]), limits(32)));
|
||||||
assert.match(tooManyItems.message, /steps\[1\] \("audit_0"\) has 33 items/);
|
assert.match(tooManyItems.message, /steps\[1\] \("audit_0"\) has 33 items/);
|
||||||
assert.match(tooManyItems.message, /max is 32 per each-step/);
|
assert.match(tooManyItems.message, /max is 32 per each-step/);
|
||||||
|
|
||||||
assert.match(
|
assert.match(
|
||||||
validationErrorFor(() =>
|
validationErrorFor(() =>
|
||||||
validateWorkflowExpansion(eachPlan(Array(8).fill(32)), itemCounts(Array(8).fill(32))),
|
validateWorkflowExpansion(eachPlan(Array(8).fill(32)), itemCounts(Array(8).fill(32)), limits()),
|
||||||
).message,
|
).message,
|
||||||
new RegExp(`expanded children \\(257\\) exceed the run cap of ${MAX_EXPANDED_CHILDREN}`),
|
new RegExp(`expanded children \\(257\\) exceed the run cap of ${MAX_EXPANDED_CHILDREN}`),
|
||||||
);
|
);
|
||||||
|
|
||||||
const accepted = eachPlan([...Array(7).fill(32), 31]);
|
const accepted = eachPlan([...Array(7).fill(32), 31]);
|
||||||
assert.equal(validateWorkflowExpansion(accepted, itemCounts([...Array(7).fill(32), 31])), 256);
|
assert.equal(validateWorkflowExpansion(accepted, itemCounts([...Array(7).fill(32), 31]), limits()), 256);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("the each-item cap honours PI_SUBAGENT_WORKFLOW_MAX_ITEMS", () => {
|
test("the each-item cap uses the injected limits", () => {
|
||||||
const previous = process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS;
|
const p = eachPlan([5]);
|
||||||
process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS = "4";
|
const error = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([5]), limits(4)));
|
||||||
try {
|
assert.match(error.message, /has 5 items/);
|
||||||
const p = eachPlan([5]);
|
assert.match(error.message, /max is 4 per each-step/);
|
||||||
assert.equal(validateWorkflowExpansion(p, itemCounts([5]), { maxItemsPerEach: 99 }), 6);
|
|
||||||
const error = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([5])));
|
|
||||||
assert.match(error.message, /has 5 items/);
|
|
||||||
assert.match(error.message, /max is 4 per each-step/);
|
|
||||||
assert.match(error.message, /PI_SUBAGENT_WORKFLOW_MAX_ITEMS/);
|
|
||||||
} finally {
|
|
||||||
if (previous === undefined) delete process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS;
|
|
||||||
else process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS = previous;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const identifierArb = fc.stringMatching(/^[A-Za-z_][A-Za-z0-9_-]{0,7}$/);
|
const identifierArb = fc.stringMatching(/^[A-Za-z_][A-Za-z0-9_-]{0,7}$/);
|
||||||
|
|||||||
Reference in new issue
Block a user