@xzzpig/pi-subagents 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +79 -0
- package/README.md +2 -0
- package/agents/reviewer.md +3 -4
- package/docs/agents.md +342 -0
- package/docs/configuration.md +328 -0
- package/docs/extension-api.md +308 -0
- package/docs/missions.md +119 -0
- package/docs/models.md +192 -0
- package/docs/observability.md +174 -0
- package/docs/tool-reference.md +343 -0
- package/docs/watchdog.md +176 -0
- package/docs/workflows.md +163 -0
- package/package.json +13 -11
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +7 -7
- package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
- package/src/agents/agents.ts +17 -8
- package/src/agents/frontmatter.ts +7 -3
- package/src/agents/skills.ts +2 -9
- package/src/api/project-panes.ts +30 -0
- package/src/extension/config.ts +28 -1
- package/src/extension/fanout-child.ts +5 -4
- package/src/extension/index.ts +75 -30
- package/src/extension/rpc.ts +7 -6
- package/src/extension/schemas.ts +29 -8
- package/src/extension/subagent-guide.ts +39 -0
- package/src/extension/tool-description.ts +30 -12
- package/src/inspectors/herdr/project-panes.ts +459 -63
- package/src/intercom/native-supervisor-channel.ts +102 -4
- package/src/missions/actions.ts +25 -2
- package/src/missions/lifecycle.ts +21 -2
- package/src/missions/store.ts +79 -2
- package/src/missions/types.ts +33 -0
- package/src/missions/workflow-state.ts +19 -13
- package/src/runs/background/active-run-index.ts +42 -0
- package/src/runs/background/async-execution.ts +17 -6
- package/src/runs/background/async-job-tracker.ts +293 -133
- package/src/runs/background/async-resume.ts +19 -3
- package/src/runs/background/async-status.ts +33 -5
- package/src/runs/background/completion-replay.ts +267 -0
- package/src/runs/background/control-channel.ts +95 -54
- package/src/runs/background/result-watcher.ts +113 -10
- package/src/runs/background/resume-guidance.ts +33 -0
- package/src/runs/background/run-status.ts +18 -0
- package/src/runs/background/scheduled-runs.ts +25 -1
- package/src/runs/background/stale-run-reconciler.ts +12 -24
- package/src/runs/background/subagent-runner.ts +69 -11
- package/src/runs/background/subagent-wait.ts +5 -2
- package/src/runs/background/wait-completions.ts +39 -5
- package/src/runs/background/wait-subscriptions.ts +21 -5
- package/src/runs/foreground/async-dismiss-action.ts +85 -0
- package/src/runs/foreground/async-steering-action.ts +7 -8
- package/src/runs/foreground/chain-execution.ts +3 -0
- package/src/runs/foreground/execution.ts +7 -0
- package/src/runs/foreground/foreground-history.ts +137 -0
- package/src/runs/foreground/subagent-executor.ts +466 -61
- package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/model-fallback.ts +8 -4
- package/src/runs/shared/model-scope.ts +12 -2
- package/src/runs/shared/parallel-utils.ts +1 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
- package/src/runs/shared/worktree.ts +3 -2
- package/src/shared/artifacts.ts +15 -15
- package/src/shared/display-text.ts +100 -0
- package/src/shared/file-coalescer.ts +9 -0
- package/src/shared/fork-context.ts +13 -0
- package/src/shared/formatters.ts +4 -6
- package/src/shared/prompt-resources.ts +51 -0
- package/src/shared/settings.ts +15 -2
- package/src/shared/types.ts +45 -2
- package/src/shared/utf8.ts +11 -0
- package/src/shared/utils.ts +43 -33
- package/src/slash/prompt-workflows.ts +2 -15
- package/src/slash/slash-commands.ts +22 -2
- package/src/tui/fleet-status.ts +22 -12
- package/src/tui/fleet.ts +135 -25
- package/src/tui/render.ts +150 -33
- package/src/watchdog/change-signature.ts +4 -3
- package/src/workflows/scripted-workflow.ts +210 -13
|
@@ -22,6 +22,7 @@ export const NATIVE_SUPERVISOR_TOOL_NAME = "subagent_supervisor";
|
|
|
22
22
|
const MAX_MESSAGE_BYTES = 64 * 1024;
|
|
23
23
|
const DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1000;
|
|
24
24
|
const CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500);
|
|
25
|
+
const CHANNEL_SAFETY_POLL_MS = 5000;
|
|
25
26
|
const STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1000;
|
|
26
27
|
const STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1000;
|
|
27
28
|
|
|
@@ -69,6 +70,13 @@ interface IntercomParams {
|
|
|
69
70
|
replyTo?: string;
|
|
70
71
|
}
|
|
71
72
|
|
|
73
|
+
type SupervisorWatch = (filename: fs.PathLike, listener: fs.WatchListener<string>) => fs.FSWatcher;
|
|
74
|
+
|
|
75
|
+
interface NativeSupervisorChannelDeps {
|
|
76
|
+
platform?: NodeJS.Platform;
|
|
77
|
+
watch?: SupervisorWatch;
|
|
78
|
+
}
|
|
79
|
+
|
|
72
80
|
const ContactSupervisorParamsSchema = Type.Object({
|
|
73
81
|
reason: Type.String({ enum: ["need_decision", "interview_request", "progress_update"] }),
|
|
74
82
|
message: Type.Optional(Type.String()),
|
|
@@ -626,10 +634,16 @@ function buildParentIntercomTool(pending: Map<string, PendingSupervisorRequest>,
|
|
|
626
634
|
};
|
|
627
635
|
}
|
|
628
636
|
|
|
629
|
-
export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState): { start: () => void; dispose: () => void; pending: Map<string, PendingSupervisorRequest> } {
|
|
637
|
+
export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState, deps: NativeSupervisorChannelDeps = {}): { start: () => void; dispose: () => void; pending: Map<string, PendingSupervisorRequest> } {
|
|
638
|
+
const watch = deps.watch ?? fs.watch;
|
|
630
639
|
const pending = new Map<string, PendingSupervisorRequest>();
|
|
631
640
|
const seenFiles = new Set<string>();
|
|
641
|
+
const requestWatchers = new Map<string, fs.FSWatcher>();
|
|
642
|
+
let rootWatcher: fs.FSWatcher | undefined;
|
|
632
643
|
let poller: ReturnType<typeof setInterval> | undefined;
|
|
644
|
+
let safetyPoller: ReturnType<typeof setInterval> | undefined;
|
|
645
|
+
let deferredWatcherRefresh: ReturnType<typeof setImmediate> | undefined;
|
|
646
|
+
let started = false;
|
|
633
647
|
let lastStaleCleanupAt = 0;
|
|
634
648
|
|
|
635
649
|
const registerParentTools = (): void => {
|
|
@@ -696,17 +710,101 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
696
710
|
}
|
|
697
711
|
};
|
|
698
712
|
|
|
713
|
+
const startPolling = (): void => {
|
|
714
|
+
if (poller) return;
|
|
715
|
+
poller = setInterval(poll, CHANNEL_POLL_MS);
|
|
716
|
+
poller.unref?.();
|
|
717
|
+
};
|
|
718
|
+
const startSafetyPolling = (): void => {
|
|
719
|
+
if (safetyPoller) return;
|
|
720
|
+
safetyPoller = setInterval(() => {
|
|
721
|
+
watchExistingRequestDirs();
|
|
722
|
+
poll();
|
|
723
|
+
}, CHANNEL_SAFETY_POLL_MS);
|
|
724
|
+
safetyPoller.unref?.();
|
|
725
|
+
};
|
|
726
|
+
const watchRequestDir = (requestsDir: string): void => {
|
|
727
|
+
if (requestWatchers.has(requestsDir)) return;
|
|
728
|
+
try {
|
|
729
|
+
const watcher = watch(requestsDir, () => poll());
|
|
730
|
+
watcher.on("error", () => {
|
|
731
|
+
try { watcher.close(); } catch {}
|
|
732
|
+
requestWatchers.delete(requestsDir);
|
|
733
|
+
startPolling();
|
|
734
|
+
});
|
|
735
|
+
watcher.unref?.();
|
|
736
|
+
requestWatchers.set(requestsDir, watcher);
|
|
737
|
+
} catch (error) {
|
|
738
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") startPolling();
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
const watchExistingRequestDirs = (): void => {
|
|
742
|
+
let channelEntries: fs.Dirent[];
|
|
743
|
+
try {
|
|
744
|
+
channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
|
|
745
|
+
} catch (error) {
|
|
746
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
747
|
+
startPolling();
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
for (const entry of channelEntries) {
|
|
751
|
+
if (entry.isDirectory()) watchRequestDir(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name, REQUESTS_DIR));
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
const scheduleWatcherRefresh = (): void => {
|
|
755
|
+
if (deferredWatcherRefresh) return;
|
|
756
|
+
deferredWatcherRefresh = setImmediate(() => {
|
|
757
|
+
deferredWatcherRefresh = undefined;
|
|
758
|
+
if (!started) return;
|
|
759
|
+
watchExistingRequestDirs();
|
|
760
|
+
poll();
|
|
761
|
+
});
|
|
762
|
+
deferredWatcherRefresh.unref?.();
|
|
763
|
+
};
|
|
764
|
+
|
|
699
765
|
return {
|
|
700
766
|
start: () => {
|
|
701
|
-
if (
|
|
767
|
+
if (started) return;
|
|
768
|
+
started = true;
|
|
702
769
|
registerParentTools();
|
|
703
770
|
poll();
|
|
704
|
-
|
|
705
|
-
|
|
771
|
+
try {
|
|
772
|
+
fs.mkdirSync(SUPERVISOR_CHANNEL_ROOT, { recursive: true });
|
|
773
|
+
if ((deps.platform ?? process.platform) === "win32") {
|
|
774
|
+
startPolling();
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
watchExistingRequestDirs();
|
|
778
|
+
rootWatcher = watch(SUPERVISOR_CHANNEL_ROOT, () => {
|
|
779
|
+
watchExistingRequestDirs();
|
|
780
|
+
poll();
|
|
781
|
+
scheduleWatcherRefresh();
|
|
782
|
+
});
|
|
783
|
+
rootWatcher.on("error", startPolling);
|
|
784
|
+
startSafetyPolling();
|
|
785
|
+
scheduleWatcherRefresh();
|
|
786
|
+
} catch {
|
|
787
|
+
startPolling();
|
|
788
|
+
}
|
|
706
789
|
},
|
|
707
790
|
dispose: () => {
|
|
791
|
+
started = false;
|
|
792
|
+
try {
|
|
793
|
+
rootWatcher?.close();
|
|
794
|
+
} catch {
|
|
795
|
+
// Best effort during shutdown.
|
|
796
|
+
}
|
|
797
|
+
rootWatcher = undefined;
|
|
798
|
+
for (const watcher of requestWatchers.values()) {
|
|
799
|
+
try { watcher.close(); } catch {}
|
|
800
|
+
}
|
|
801
|
+
requestWatchers.clear();
|
|
708
802
|
if (poller) clearInterval(poller);
|
|
709
803
|
poller = undefined;
|
|
804
|
+
if (safetyPoller) clearInterval(safetyPoller);
|
|
805
|
+
safetyPoller = undefined;
|
|
806
|
+
if (deferredWatcherRefresh) clearImmediate(deferredWatcherRefresh);
|
|
807
|
+
deferredWatcherRefresh = undefined;
|
|
710
808
|
pending.clear();
|
|
711
809
|
seenFiles.clear();
|
|
712
810
|
},
|
package/src/missions/actions.ts
CHANGED
|
@@ -34,6 +34,7 @@ export const MISSION_ACTIONS = [
|
|
|
34
34
|
"mission.list",
|
|
35
35
|
"mission.show",
|
|
36
36
|
"mission.update",
|
|
37
|
+
"mission.resolve-decision",
|
|
37
38
|
"mission.attach-run",
|
|
38
39
|
"mission.close",
|
|
39
40
|
] as const;
|
|
@@ -298,9 +299,20 @@ function formatMission(record: MissionRecord): string {
|
|
|
298
299
|
lines.push("Runs:");
|
|
299
300
|
for (const run of record.runs) lines.push(` ${run.runId} (${run.mode}${run.status ? `, ${run.status}` : ""})${run.asyncDir ? ` — ${run.asyncDir}` : ""}`);
|
|
300
301
|
}
|
|
302
|
+
if (record.workflowChildren.length) {
|
|
303
|
+
lines.push("Workflow children:");
|
|
304
|
+
for (const child of record.workflowChildren) {
|
|
305
|
+
const identity = child.runId ? `${child.key} (${child.runId})` : child.key;
|
|
306
|
+
const heartbeat = child.heartbeat ? `; heartbeat ${child.heartbeat.status ?? child.status}${child.heartbeat.phase ? `/${child.heartbeat.phase}` : ""} at ${child.heartbeat.updatedAt}` : "";
|
|
307
|
+
const recovery = child.sessionPath ? `; session ${child.sessionPath}` : child.artifactPaths.length ? `; artifacts ${child.artifactPaths.length}` : "";
|
|
308
|
+
lines.push(` ${identity}: ${child.status}${child.agent ? ` — ${child.agent}` : ""}${child.phase ? ` [${child.phase}]` : ""}; updated ${child.updatedAt}${heartbeat}${recovery}`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
301
311
|
if (record.decisions.length) {
|
|
302
312
|
lines.push("Decisions:");
|
|
303
|
-
for (const decision of record.decisions)
|
|
313
|
+
for (const decision of record.decisions) {
|
|
314
|
+
lines.push(` ${decision.id}: ${decision.status} — ${decision.title}${decision.resolution ? `; resolution: ${decision.resolution}` : ""}`);
|
|
315
|
+
}
|
|
304
316
|
}
|
|
305
317
|
if (record.artifacts.length) {
|
|
306
318
|
lines.push("Artifacts:");
|
|
@@ -351,7 +363,11 @@ export function handleMissionAction(
|
|
|
351
363
|
const listed = listMissions(location);
|
|
352
364
|
const lines = listed.records.length === 0
|
|
353
365
|
? ["No project missions."]
|
|
354
|
-
: listed.records.map((record) =>
|
|
366
|
+
: listed.records.map((record) => {
|
|
367
|
+
const open = record.decisions.filter((decision) => decision.status === "open").length;
|
|
368
|
+
const resolved = record.decisions.length - open;
|
|
369
|
+
return `${record.id} ${record.status} ${record.title} ${record.updatedAt}${record.decisions.length ? ` decisions: ${open} open, ${resolved} resolved` : ""}`;
|
|
370
|
+
});
|
|
355
371
|
if (listed.warnings.length) lines.push("", ...listed.warnings.map((warning) => `Warning: ${warning}`));
|
|
356
372
|
return textResult(lines.join("\n"), { mode: "management", results: [], missions: { records: listed.records, warnings: listed.warnings } });
|
|
357
373
|
}
|
|
@@ -372,6 +388,13 @@ export function handleMissionAction(
|
|
|
372
388
|
const record = updateMission(location, requireMissionId(params), validateMissionUpdate(params.missionUpdate));
|
|
373
389
|
return textResult(`Updated mission ${record.id}.\n\n${formatMission(record)}`, { mode: "management", results: [], missionId: record.id, missionPath: pathFor(record.id), mission: record });
|
|
374
390
|
}
|
|
391
|
+
if (action === "mission.resolve-decision") {
|
|
392
|
+
const missionId = requireMissionId(params);
|
|
393
|
+
const decisionId = validateMissionId(params.id, "id");
|
|
394
|
+
if (typeof params.summary !== "string" || !params.summary.trim()) throw new Error("mission.resolve-decision requires a non-empty summary");
|
|
395
|
+
const record = updateMission(location, missionId, { resolveDecision: { id: decisionId, resolution: params.summary.trim() } });
|
|
396
|
+
return textResult(`Resolved decision ${decisionId} for mission ${record.id}.\n\n${formatMission(record)}`, { mode: "management", results: [], missionId: record.id, missionPath: pathFor(record.id), mission: record });
|
|
397
|
+
}
|
|
375
398
|
if (action === "mission.attach-run") {
|
|
376
399
|
const missionId = requireMissionId(params);
|
|
377
400
|
const runId = params.runId ?? params.id;
|
|
@@ -160,7 +160,7 @@ function persistedBinding(binding: MissionLaunchBinding): PersistedMissionBindin
|
|
|
160
160
|
};
|
|
161
161
|
}
|
|
162
162
|
|
|
163
|
-
function
|
|
163
|
+
export function writeMissionAsyncBinding(asyncDir: string, binding: MissionLaunchBinding): void {
|
|
164
164
|
writePrivateAtomicJson(path.join(asyncDir, MISSION_BINDING_FILE), persistedBinding(binding));
|
|
165
165
|
}
|
|
166
166
|
|
|
@@ -210,7 +210,7 @@ export function attachMissionToLaunchResult(input: {
|
|
|
210
210
|
...(input.result.details.results.length === 1 && input.result.details.results[0]?.acceptance ? { acceptance: input.result.details.results[0].acceptance } : {}),
|
|
211
211
|
});
|
|
212
212
|
if (input.result.details.asyncDir) {
|
|
213
|
-
|
|
213
|
+
writeMissionAsyncBinding(input.result.details.asyncDir, input.binding);
|
|
214
214
|
const statusPath = path.join(input.result.details.asyncDir, "status.json");
|
|
215
215
|
if (fs.existsSync(statusPath)) {
|
|
216
216
|
try {
|
|
@@ -337,10 +337,29 @@ export function syncMissionFromAsyncCompletion(value: unknown): MissionRecord |
|
|
|
337
337
|
return total + (usageFromUnknown((result as { tokens?: unknown }).tokens)?.tokens ?? 0);
|
|
338
338
|
}, 0) }
|
|
339
339
|
: undefined);
|
|
340
|
+
const workflowRunId = typeof event.parentWorkflowRunId === "string" && event.parentWorkflowRunId.trim() ? event.parentWorkflowRunId.trim() : undefined;
|
|
341
|
+
const workflowKey = typeof event.workflowKey === "string" && event.workflowKey.trim() ? event.workflowKey.trim() : undefined;
|
|
342
|
+
const workflowChildStatus = runStatus === "complete" || runStatus === "completed" || event.success === true
|
|
343
|
+
? "completed"
|
|
344
|
+
: runStatus === "paused"
|
|
345
|
+
? "paused"
|
|
346
|
+
: runStatus === "stopped"
|
|
347
|
+
? "stopped"
|
|
348
|
+
: "failed";
|
|
349
|
+
const workflowChildTerminal = !["running", "queued", "active", "paused"].includes(workflowChildStatus);
|
|
340
350
|
return updateMission(binding.location, binding.missionId, {
|
|
341
351
|
status: missionStatusForRun(current, runId, runStatus),
|
|
342
352
|
addRuns: [{ runId, mode: typeof event.mode === "string" && ["single", "parallel", "chain", "workflow"].includes(event.mode) ? event.mode as SubagentRunMode : "external", asyncDir: event.asyncDir, status: runStatus, completedAt, ...(usage && usage.tokens > 0 ? { usage } : {}) }],
|
|
343
353
|
addArtifacts: artifacts,
|
|
354
|
+
...(workflowRunId && workflowKey ? { upsertWorkflowChildren: [{
|
|
355
|
+
workflowRunId,
|
|
356
|
+
key: workflowKey,
|
|
357
|
+
runId,
|
|
358
|
+
status: workflowChildStatus,
|
|
359
|
+
artifactPaths: artifacts.map((artifact) => artifact.path),
|
|
360
|
+
...(workflowChildTerminal ? { completedAt } : {}),
|
|
361
|
+
heartbeat: { status: workflowChildStatus, ...(summary ? { message: summary } : {}) },
|
|
362
|
+
}] } : {}),
|
|
344
363
|
...(summary ? { summary } : {}),
|
|
345
364
|
});
|
|
346
365
|
}
|
package/src/missions/store.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as path from "node:path";
|
|
5
|
+
import { getProjectSubagentsDir } from "../shared/artifacts.ts";
|
|
5
6
|
import { writePrivateAtomicJson } from "../shared/atomic-json.ts";
|
|
6
7
|
import { getAgentDir } from "../shared/utils.ts";
|
|
7
8
|
import {
|
|
@@ -27,6 +28,7 @@ import {
|
|
|
27
28
|
type MissionTokenBudget,
|
|
28
29
|
type MissionTokenUsage,
|
|
29
30
|
type MissionUpdateInput,
|
|
31
|
+
type MissionWorkflowChild,
|
|
30
32
|
} from "./types.ts";
|
|
31
33
|
|
|
32
34
|
const MISSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
@@ -149,6 +151,33 @@ function parseDecision(value: unknown, label: string): MissionDecision {
|
|
|
149
151
|
};
|
|
150
152
|
}
|
|
151
153
|
|
|
154
|
+
function parseWorkflowChild(value: unknown, label: string): MissionWorkflowChild {
|
|
155
|
+
const input = asObject(value, label);
|
|
156
|
+
const artifactPaths = input.artifactPaths === undefined ? [] : stringArray(input.artifactPaths, `${label}.artifactPaths`);
|
|
157
|
+
const heartbeat = input.heartbeat === undefined ? undefined : asObject(input.heartbeat, `${label}.heartbeat`);
|
|
158
|
+
return {
|
|
159
|
+
workflowRunId: requiredString(input.workflowRunId, `${label}.workflowRunId`),
|
|
160
|
+
key: validateMissionId(input.key, `${label}.key`),
|
|
161
|
+
status: requiredString(input.status, `${label}.status`),
|
|
162
|
+
startedAt: timestamp(input.startedAt, `${label}.startedAt`),
|
|
163
|
+
updatedAt: timestamp(input.updatedAt, `${label}.updatedAt`),
|
|
164
|
+
artifactPaths,
|
|
165
|
+
...(optionalString(input.runId, `${label}.runId`) ? { runId: input.runId as string } : {}),
|
|
166
|
+
...(optionalString(input.agent, `${label}.agent`) ? { agent: input.agent as string } : {}),
|
|
167
|
+
...(optionalString(input.task, `${label}.task`) ? { task: input.task as string } : {}),
|
|
168
|
+
...(optionalString(input.label, `${label}.label`) ? { label: input.label as string } : {}),
|
|
169
|
+
...(optionalString(input.phase, `${label}.phase`) ? { phase: input.phase as string } : {}),
|
|
170
|
+
...(input.completedAt !== undefined ? { completedAt: timestamp(input.completedAt, `${label}.completedAt`) } : {}),
|
|
171
|
+
...(optionalString(input.sessionPath, `${label}.sessionPath`) ? { sessionPath: input.sessionPath as string } : {}),
|
|
172
|
+
...(heartbeat ? { heartbeat: {
|
|
173
|
+
updatedAt: timestamp(heartbeat.updatedAt, `${label}.heartbeat.updatedAt`),
|
|
174
|
+
...(optionalString(heartbeat.status, `${label}.heartbeat.status`) ? { status: heartbeat.status as string } : {}),
|
|
175
|
+
...(optionalString(heartbeat.phase, `${label}.heartbeat.phase`) ? { phase: heartbeat.phase as string } : {}),
|
|
176
|
+
...(optionalString(heartbeat.message, `${label}.heartbeat.message`) ? { message: heartbeat.message as string } : {}),
|
|
177
|
+
} } : {}),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
152
181
|
function parseArtifact(value: unknown, label: string): MissionArtifact {
|
|
153
182
|
const input = asObject(value, label);
|
|
154
183
|
const kind = requiredString(input.kind, `${label}.kind`) as MissionArtifactKind;
|
|
@@ -186,10 +215,12 @@ export function parseMissionRecord(value: unknown, source = "mission record"): M
|
|
|
186
215
|
const input = asObject(value, source);
|
|
187
216
|
if (input.schemaVersion !== 1) throw new Error(`${source}.schemaVersion must be 1`);
|
|
188
217
|
if (!Array.isArray(input.runs)) throw new Error(`${source}.runs must be an array`);
|
|
218
|
+
if (input.workflowChildren !== undefined && !Array.isArray(input.workflowChildren)) throw new Error(`${source}.workflowChildren must be an array`);
|
|
189
219
|
if (!Array.isArray(input.decisions)) throw new Error(`${source}.decisions must be an array`);
|
|
190
220
|
if (!Array.isArray(input.artifacts)) throw new Error(`${source}.artifacts must be an array`);
|
|
191
221
|
if (input.receipts !== undefined && !Array.isArray(input.receipts)) throw new Error(`${source}.receipts must be an array`);
|
|
192
222
|
const runs = input.runs as unknown[];
|
|
223
|
+
const workflowChildren = (input.workflowChildren ?? []) as unknown[];
|
|
193
224
|
const decisions = input.decisions as unknown[];
|
|
194
225
|
const artifacts = input.artifacts as unknown[];
|
|
195
226
|
const receipts = (input.receipts ?? []) as unknown[];
|
|
@@ -211,6 +242,7 @@ export function parseMissionRecord(value: unknown, source = "mission record"): M
|
|
|
211
242
|
createdAt: timestamp(input.createdAt, `${source}.createdAt`),
|
|
212
243
|
updatedAt: timestamp(input.updatedAt, `${source}.updatedAt`),
|
|
213
244
|
runs: runs.map((item, index) => parseRunLink(item, `${source}.runs[${index}]`)),
|
|
245
|
+
workflowChildren: workflowChildren.map((item, index) => parseWorkflowChild(item, `${source}.workflowChildren[${index}]`)),
|
|
214
246
|
decisions: decisions.map((item, index) => parseDecision(item, `${source}.decisions[${index}]`)),
|
|
215
247
|
artifacts: artifacts.map((item, index) => parseArtifact(item, `${source}.artifacts[${index}]`)),
|
|
216
248
|
receipts: receipts.map((item, index) => parseReceipt(item, `${source}.receipts[${index}]`)),
|
|
@@ -259,7 +291,7 @@ export function resolveMissionStoreLocation(input: {
|
|
|
259
291
|
const projectRoot = path.resolve(input.projectRoot);
|
|
260
292
|
const missionDir = input.config?.directory
|
|
261
293
|
? expandConfiguredPath(input.config.directory, projectRoot)
|
|
262
|
-
: path.join(projectRoot, "
|
|
294
|
+
: path.join(getProjectSubagentsDir(projectRoot), "missions");
|
|
263
295
|
const globalIndexDir = input.config?.globalIndexDir
|
|
264
296
|
? expandConfiguredPath(input.config.globalIndexDir, projectRoot)
|
|
265
297
|
: path.join(input.agentDir ?? getAgentDir(), "missions", "index");
|
|
@@ -346,6 +378,7 @@ export function createMission(location: MissionStoreLocation, input: MissionCrea
|
|
|
346
378
|
updatedAt: createdAt,
|
|
347
379
|
cwd: location.projectRoot,
|
|
348
380
|
runs: [],
|
|
381
|
+
workflowChildren: [],
|
|
349
382
|
decisions: [],
|
|
350
383
|
artifacts: [],
|
|
351
384
|
receipts: [],
|
|
@@ -412,6 +445,28 @@ export function updateMission(location: MissionStoreLocation, missionId: string,
|
|
|
412
445
|
if (existingIndex === -1) runs.push(run);
|
|
413
446
|
else runs[existingIndex] = { ...runs[existingIndex]!, ...run };
|
|
414
447
|
}
|
|
448
|
+
const workflowChildren = [...current.workflowChildren];
|
|
449
|
+
for (const candidate of update.upsertWorkflowChildren ?? []) {
|
|
450
|
+
const nowIso = now.toISOString();
|
|
451
|
+
const parsed = parseWorkflowChild({
|
|
452
|
+
...candidate,
|
|
453
|
+
startedAt: candidate.startedAt ?? nowIso,
|
|
454
|
+
updatedAt: nowIso,
|
|
455
|
+
artifactPaths: candidate.artifactPaths ?? [],
|
|
456
|
+
...(candidate.heartbeat ? { heartbeat: { ...candidate.heartbeat, updatedAt: nowIso } } : {}),
|
|
457
|
+
}, "mission.update.upsertWorkflowChildren[]");
|
|
458
|
+
const existingIndex = workflowChildren.findIndex((child) => child.workflowRunId === parsed.workflowRunId && child.key === parsed.key);
|
|
459
|
+
if (existingIndex === -1) workflowChildren.push(parsed);
|
|
460
|
+
else {
|
|
461
|
+
const existing = workflowChildren[existingIndex]!;
|
|
462
|
+
workflowChildren[existingIndex] = parseWorkflowChild({
|
|
463
|
+
...existing,
|
|
464
|
+
...parsed,
|
|
465
|
+
startedAt: existing.startedAt,
|
|
466
|
+
artifactPaths: [...new Set([...existing.artifactPaths, ...parsed.artifactPaths])],
|
|
467
|
+
}, "mission.update.upsertWorkflowChildren[]");
|
|
468
|
+
}
|
|
469
|
+
}
|
|
415
470
|
const artifacts = [...current.artifacts];
|
|
416
471
|
for (const candidate of update.addArtifacts ?? []) {
|
|
417
472
|
const artifact = parseArtifact(candidate, "mission.update.addArtifacts[]");
|
|
@@ -439,6 +494,18 @@ export function updateMission(location: MissionStoreLocation, missionId: string,
|
|
|
439
494
|
...(decision.recommendation ? { recommendation: requiredString(decision.recommendation, "mission.update.addDecisions[].recommendation") } : {}),
|
|
440
495
|
})),
|
|
441
496
|
];
|
|
497
|
+
if (update.resolveDecision) {
|
|
498
|
+
const decisionId = validateMissionId(update.resolveDecision.id, "mission.update.resolveDecision.id");
|
|
499
|
+
const decisionIndex = decisions.findIndex((decision) => decision.id === decisionId);
|
|
500
|
+
if (decisionIndex === -1) throw new Error(`Decision '${decisionId}' was not found in mission '${missionId}'`);
|
|
501
|
+
if (decisions[decisionIndex]!.status === "resolved") throw new Error(`Decision '${decisionId}' is already resolved`);
|
|
502
|
+
decisions[decisionIndex] = {
|
|
503
|
+
...decisions[decisionIndex]!,
|
|
504
|
+
status: "resolved",
|
|
505
|
+
resolvedAt: createdAt,
|
|
506
|
+
resolution: requiredString(update.resolveDecision.resolution, "mission.update.resolveDecision.resolution").trim(),
|
|
507
|
+
};
|
|
508
|
+
}
|
|
442
509
|
const budget = update.budget !== undefined ? parseBudget(update.budget, "mission.update.budget") : current.budget;
|
|
443
510
|
const usage = update.usage !== undefined
|
|
444
511
|
? parseUsage(update.usage, "mission.update.usage")
|
|
@@ -452,10 +519,20 @@ export function updateMission(location: MissionStoreLocation, missionId: string,
|
|
|
452
519
|
? { status: "active" }
|
|
453
520
|
: goal;
|
|
454
521
|
}
|
|
522
|
+
const hasOpenDecisions = decisions.some((decision) => decision.status === "open");
|
|
523
|
+
const requestedStatus = update.status !== undefined ? missionStatus(update.status, "mission.update.status") : undefined;
|
|
524
|
+
const candidateStatus = requestedStatus
|
|
525
|
+
?? (update.addDecisions?.length && current.status === "active"
|
|
526
|
+
? "needs_decision"
|
|
527
|
+
: update.resolveDecision && current.status === "needs_decision" && !hasOpenDecisions
|
|
528
|
+
? "active"
|
|
529
|
+
: current.status);
|
|
530
|
+
const decisionStatus = hasOpenDecisions && (candidateStatus === "active" || candidateStatus === "completed") ? "needs_decision" : candidateStatus;
|
|
455
531
|
const next: MissionRecord = {
|
|
456
532
|
...current,
|
|
457
533
|
updatedAt: createdAt,
|
|
458
534
|
runs,
|
|
535
|
+
workflowChildren,
|
|
459
536
|
artifacts,
|
|
460
537
|
receipts,
|
|
461
538
|
decisions,
|
|
@@ -463,7 +540,7 @@ export function updateMission(location: MissionStoreLocation, missionId: string,
|
|
|
463
540
|
...(update.objective !== undefined ? { objective: requiredString(update.objective, "mission.update.objective").trim() } : {}),
|
|
464
541
|
...(budget ? { budget } : {}),
|
|
465
542
|
...(goal ? { goal, usage } : {}),
|
|
466
|
-
|
|
543
|
+
status: decisionStatus,
|
|
467
544
|
...(update.summary !== undefined ? { summary: requiredString(update.summary, "mission.update.summary") } : {}),
|
|
468
545
|
...(update.labels !== undefined ? { labels: stringArray(update.labels, "mission.update.labels") } : {}),
|
|
469
546
|
...(update.acceptance !== undefined ? { acceptance: update.acceptance } : {}),
|
package/src/missions/types.ts
CHANGED
|
@@ -51,6 +51,36 @@ export interface MissionDecision {
|
|
|
51
51
|
resolution?: string;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
export interface MissionChildHeartbeat {
|
|
55
|
+
updatedAt: string;
|
|
56
|
+
status?: string;
|
|
57
|
+
phase?: string;
|
|
58
|
+
message?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface MissionWorkflowChild {
|
|
62
|
+
workflowRunId: string;
|
|
63
|
+
key: string;
|
|
64
|
+
status: string;
|
|
65
|
+
startedAt: string;
|
|
66
|
+
updatedAt: string;
|
|
67
|
+
runId?: string;
|
|
68
|
+
agent?: string;
|
|
69
|
+
task?: string;
|
|
70
|
+
label?: string;
|
|
71
|
+
phase?: string;
|
|
72
|
+
completedAt?: string;
|
|
73
|
+
sessionPath?: string;
|
|
74
|
+
artifactPaths: string[];
|
|
75
|
+
heartbeat?: MissionChildHeartbeat;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type MissionWorkflowChildUpdate = Pick<MissionWorkflowChild, "workflowRunId" | "key" | "status"> & Partial<Omit<MissionWorkflowChild, "workflowRunId" | "key" | "status" | "startedAt" | "updatedAt" | "artifactPaths" | "heartbeat">> & {
|
|
79
|
+
startedAt?: string;
|
|
80
|
+
artifactPaths?: string[];
|
|
81
|
+
heartbeat?: Omit<MissionChildHeartbeat, "updatedAt"> & { updatedAt?: string };
|
|
82
|
+
};
|
|
83
|
+
|
|
54
84
|
export interface MissionArtifact {
|
|
55
85
|
kind: MissionArtifactKind;
|
|
56
86
|
path: string;
|
|
@@ -80,6 +110,7 @@ export interface MissionRecord {
|
|
|
80
110
|
cwd?: string;
|
|
81
111
|
ownerSessionId?: string;
|
|
82
112
|
runs: MissionRunLink[];
|
|
113
|
+
workflowChildren: MissionWorkflowChild[];
|
|
83
114
|
decisions: MissionDecision[];
|
|
84
115
|
artifacts: MissionArtifact[];
|
|
85
116
|
receipts: MissionReceipt[];
|
|
@@ -151,7 +182,9 @@ export interface MissionUpdateInput {
|
|
|
151
182
|
labels?: string[];
|
|
152
183
|
acceptance?: unknown;
|
|
153
184
|
addRuns?: MissionRunLink[];
|
|
185
|
+
upsertWorkflowChildren?: MissionWorkflowChildUpdate[];
|
|
154
186
|
addArtifacts?: MissionArtifact[];
|
|
155
187
|
addDecisions?: Array<Omit<MissionDecision, "id" | "status" | "createdAt">>;
|
|
188
|
+
resolveDecision?: { id: string; resolution: string };
|
|
156
189
|
addReceipts?: Array<Omit<MissionReceipt, "createdAt">>;
|
|
157
190
|
}
|
|
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
import { writePrivateAtomicJson } from "../shared/atomic-json.ts";
|
|
6
|
-
import { DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS, waitForFileSystemRetry } from "../shared/file-system-retry.ts";
|
|
6
|
+
import { DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS, isRetryableFileSystemError, waitForFileSystemRetry } from "../shared/file-system-retry.ts";
|
|
7
7
|
import { assertWorkflowJsonValue } from "../workflows/scripted-workflow.ts";
|
|
8
8
|
import type { MissionStoreLocation } from "./types.ts";
|
|
9
9
|
import { validateMissionId } from "./store.ts";
|
|
@@ -162,24 +162,30 @@ function withStateFileLock<T>(filePath: string, operation: () => T): T {
|
|
|
162
162
|
waitForStateLock(DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS[attempt], lockPath);
|
|
163
163
|
continue;
|
|
164
164
|
}
|
|
165
|
+
let acquired = false;
|
|
165
166
|
try {
|
|
166
|
-
|
|
167
|
-
owner = { pid: process.pid, token: randomUUID(), createdAt: Date.now(), ...(CURRENT_PROCESS_KEY ? { processKey: CURRENT_PROCESS_KEY } : {}) };
|
|
168
|
-
try {
|
|
169
|
-
fs.writeFileSync(path.join(lockPath, "owner.json"), JSON.stringify(owner), { encoding: "utf-8", mode: 0o600 });
|
|
170
|
-
} catch (error) {
|
|
171
|
-
removeOwnedStateLock(lockPath, owner);
|
|
172
|
-
owner = undefined;
|
|
173
|
-
throw error;
|
|
174
|
-
}
|
|
175
|
-
break;
|
|
167
|
+
acquired = tryMakeDirectory(lockPath, 0o700);
|
|
176
168
|
} catch (error) {
|
|
177
|
-
if ((error
|
|
178
|
-
|
|
169
|
+
if (isRetryableFileSystemError(error)) {
|
|
170
|
+
waitForStateLock(DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS[attempt], lockPath);
|
|
171
|
+
continue;
|
|
179
172
|
}
|
|
173
|
+
throw new Error(`Failed to acquire mission state lock '${lockPath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
174
|
+
}
|
|
175
|
+
if (!acquired) {
|
|
180
176
|
if (reclaimStaleStateLock(lockPath, reclaimPath)) continue;
|
|
181
177
|
waitForStateLock(DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS[attempt], lockPath);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
owner = { pid: process.pid, token: randomUUID(), createdAt: Date.now(), ...(CURRENT_PROCESS_KEY ? { processKey: CURRENT_PROCESS_KEY } : {}) };
|
|
181
|
+
try {
|
|
182
|
+
fs.writeFileSync(path.join(lockPath, "owner.json"), JSON.stringify(owner), { encoding: "utf-8", mode: 0o600 });
|
|
183
|
+
} catch (error) {
|
|
184
|
+
fs.rmSync(lockPath, { recursive: true, force: true });
|
|
185
|
+
owner = undefined;
|
|
186
|
+
throw error;
|
|
182
187
|
}
|
|
188
|
+
break;
|
|
183
189
|
}
|
|
184
190
|
try {
|
|
185
191
|
return operation();
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { AsyncStatus } from "../../shared/types.ts";
|
|
4
|
+
|
|
5
|
+
export const ACTIVE_RUN_INDEX_DIR = ".active-runs";
|
|
6
|
+
|
|
7
|
+
function indexDir(asyncDirRoot: string): string {
|
|
8
|
+
return path.join(asyncDirRoot, ACTIVE_RUN_INDEX_DIR);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function markerPath(asyncDir: string): string {
|
|
12
|
+
return path.join(indexDir(path.dirname(asyncDir)), path.basename(asyncDir));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isActiveAsyncState(state: AsyncStatus["state"]): boolean {
|
|
16
|
+
return state === "queued" || state === "running";
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function updateActiveRunIndex(asyncDir: string, state: AsyncStatus["state"]): void {
|
|
20
|
+
const marker = markerPath(asyncDir);
|
|
21
|
+
if (isActiveAsyncState(state)) {
|
|
22
|
+
fs.mkdirSync(path.dirname(marker), { recursive: true });
|
|
23
|
+
fs.writeFileSync(marker, "", { flag: "a" });
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
fs.rmSync(marker);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function readActiveRunIndex(asyncDirRoot: string): string[] | undefined {
|
|
34
|
+
try {
|
|
35
|
+
return fs.readdirSync(indexDir(asyncDirRoot), { withFileTypes: true })
|
|
36
|
+
.filter((entry) => entry.isFile())
|
|
37
|
+
.map((entry) => entry.name);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -15,7 +15,7 @@ import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts"
|
|
|
15
15
|
import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
|
|
16
16
|
import { applyThinkingSuffix, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
|
|
17
17
|
import { injectOutputPathSystemPrompt, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
|
|
18
|
-
import { buildChainInstructions, isCheckpointStep, isDynamicParallelStep, isParallelStep, resolveChainPath, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
|
|
18
|
+
import { buildChainInstructions, isCheckpointStep, isDynamicParallelStep, isParallelStep, resolveChainPath, resolveExistingReadPaths, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
|
|
19
19
|
import type { RunnerStep } from "../shared/parallel-utils.ts";
|
|
20
20
|
import type { ContextMode } from "../shared/context-mode.ts";
|
|
21
21
|
import { resolvePiPackageRoot } from "../shared/pi-spawn.ts";
|
|
@@ -128,6 +128,8 @@ interface AsyncExecutionContext {
|
|
|
128
128
|
interactive?: boolean;
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
|
|
132
|
+
|
|
131
133
|
interface AsyncChainParams {
|
|
132
134
|
chain: ChainStep[];
|
|
133
135
|
task?: string;
|
|
@@ -668,6 +670,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
|
|
|
668
670
|
if (resolvedToolBudget.error) throw new AsyncStartValidationError(resolvedToolBudget.error);
|
|
669
671
|
const stepCwd = resolveChildCwd(runnerCwd, s.cwd);
|
|
670
672
|
const instructionCwd = behaviorCwd ?? stepCwd;
|
|
673
|
+
const readExistenceCwd = behaviorCwd ? stepCwd : instructionCwd;
|
|
671
674
|
let behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(a, buildStepOverrides(s), chainSkills), s.task, originalTask);
|
|
672
675
|
const inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === undefined && typeof behavior.output === "string" && !path.isAbsolute(behavior.output);
|
|
673
676
|
if (inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex !== undefined) {
|
|
@@ -698,7 +701,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
|
|
|
698
701
|
}
|
|
699
702
|
systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: stepCwd, agentName: a.name });
|
|
700
703
|
|
|
701
|
-
const readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false);
|
|
704
|
+
const readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false, undefined, readExistenceCwd);
|
|
702
705
|
const isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;
|
|
703
706
|
if (behavior.progress) progressInstructionCreated = true;
|
|
704
707
|
const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);
|
|
@@ -776,6 +779,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
|
|
|
776
779
|
outputMode: behavior.outputMode,
|
|
777
780
|
sessionFile,
|
|
778
781
|
maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, a.maxSubagentDepth),
|
|
782
|
+
timeoutMs: a.defaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS,
|
|
779
783
|
waitToolEnabled: params.waitToolEnabled,
|
|
780
784
|
effectiveAcceptance: resolveEffectiveAcceptance({
|
|
781
785
|
explicit: s.acceptance,
|
|
@@ -1197,6 +1201,10 @@ export function executeAsyncChain(
|
|
|
1197
1201
|
/**
|
|
1198
1202
|
* Execute a single agent asynchronously
|
|
1199
1203
|
*/
|
|
1204
|
+
export function workflowAwaitedAsyncResultPath(asyncDir: string): string {
|
|
1205
|
+
return path.join(asyncDir, "workflow-result.json");
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1200
1208
|
export function executeAsyncSingle(
|
|
1201
1209
|
id: string,
|
|
1202
1210
|
params: AsyncSingleParams,
|
|
@@ -1292,8 +1300,9 @@ export function executeAsyncSingle(
|
|
|
1292
1300
|
// Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
|
|
1293
1301
|
// absolute paths pass through; relative paths resolve against the child cwd.
|
|
1294
1302
|
const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
|
|
1295
|
-
const
|
|
1296
|
-
|
|
1303
|
+
const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, runnerCwd) : [];
|
|
1304
|
+
const readsInstruction = readPaths.length > 0
|
|
1305
|
+
? `[Read from: ${readPaths.join(", ")}]\n\n`
|
|
1297
1306
|
: "";
|
|
1298
1307
|
const taskText = readsInstruction + taskWithOutputInstruction;
|
|
1299
1308
|
const primaryModel = externalRunner ? undefined : resolveSubagentModelOverride(
|
|
@@ -1395,7 +1404,7 @@ export function executeAsyncSingle(
|
|
|
1395
1404
|
...(params.acceptance !== undefined ? { acceptance: params.acceptance } : {}),
|
|
1396
1405
|
...(controlConfig ? { controlConfig } : {}),
|
|
1397
1406
|
...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
|
|
1398
|
-
...(initialTurnBudget ? { initialTurnBudget } : {}),
|
|
1407
|
+
...(initialTurnBudget ? { initialTurnBudget: { maxTurns: initialTurnBudget.maxTurns, graceTurns: initialTurnBudget.graceTurns } } : {}),
|
|
1399
1408
|
...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
|
|
1400
1409
|
maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
|
|
1401
1410
|
...(maxOutput ? { maxOutput } : {}),
|
|
@@ -1456,7 +1465,9 @@ export function executeAsyncSingle(
|
|
|
1456
1465
|
...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
|
|
1457
1466
|
},
|
|
1458
1467
|
],
|
|
1459
|
-
resultPath:
|
|
1468
|
+
resultPath: params.parentWorkflowRunId !== undefined && params.revivalLease !== undefined
|
|
1469
|
+
? workflowAwaitedAsyncResultPath(asyncDir)
|
|
1470
|
+
: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(DIRS.results, `${id}.json`),
|
|
1460
1471
|
cwd: runnerCwd,
|
|
1461
1472
|
placeholder: "{previous}",
|
|
1462
1473
|
maxOutput,
|