@xzzpig/pi-subagents 0.18.0 → 0.19.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 +69 -0
- package/README.md +1 -1
- package/docs/agents.md +18 -12
- package/docs/configuration.md +66 -9
- package/docs/extension-api.md +5 -4
- package/docs/missions.md +13 -13
- package/docs/models.md +2 -2
- package/docs/observability.md +2 -2
- package/docs/standalone-background.md +1 -1
- package/docs/tool-reference.md +63 -86
- package/docs/workflows.md +170 -172
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +6 -6
- package/prompts/review-loop.md +1 -1
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +12 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
- package/skills/pi-subagents/references/execution-controls.md +68 -67
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-management.ts +2 -2
- package/src/agents/agents.ts +7 -0
- package/src/api/preflight.ts +67 -62
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +1 -0
- package/src/extension/fanout-child.ts +12 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +68 -159
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +29 -10
- package/src/extension/schemas.ts +36 -133
- package/src/extension/tool-activation.ts +57 -108
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/native-supervisor-channel.ts +4 -1
- package/src/runs/background/async-execution.ts +58 -53
- package/src/runs/background/async-job-tracker.ts +63 -22
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/notify.ts +5 -0
- package/src/runs/background/run-child-session.ts +4 -1
- package/src/runs/background/run-status.ts +6 -0
- package/src/runs/background/runner-aliases.ts +30 -2
- package/src/runs/background/runner-child-launch.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/subagent-runner.ts +15 -1
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +130 -125
- package/src/runs/foreground/subagent-executor.ts +487 -288
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/child-launch.ts +15 -2
- package/src/runs/shared/child-session.ts +92 -6
- package/src/runs/shared/child-tool-plan.ts +15 -3
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/mcp-config-sources.ts +2 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +103 -11
- package/src/runs/shared/model-resolution.ts +29 -9
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +55 -55
- package/src/runs/shared/parallel-utils.ts +2 -0
- package/src/runs/shared/pi-spawn.ts +7 -95
- package/src/runs/shared/subagent-prompt-runtime.ts +2 -0
- package/src/runs/shared/worktree.ts +1 -1
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/model-info.ts +9 -0
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +21 -0
- package/src/slash/prompt-template-bridge.ts +2 -2
- package/src/slash/slash-commands.ts +10 -5
- package/src/slash/subagents-admin.ts +24 -24
- package/src/tui/fleet-status.ts +14 -6
- package/src/tui/fleet.ts +14 -2
- package/src/tui/render.ts +113 -52
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +23 -9
- package/src/watchdog/register-child.ts +3 -3
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +2 -2
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +117 -37
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
|
@@ -51,6 +51,11 @@ const MAX_RECENT_FLEET_JOBS = 20;
|
|
|
51
51
|
const DEFAULT_LIVENESS_INTERVAL_MS = 5000;
|
|
52
52
|
const EVENT_REFRESH_DEBOUNCE_MS = 25;
|
|
53
53
|
const WATCH_ATTACHMENT_RETRY_MS = 100;
|
|
54
|
+
/** A native supervisor request is already its own parent turn; its attention notice only escalates an unanswered one. */
|
|
55
|
+
const SUPERVISOR_NOTICE_GRACE_MS = 60_000;
|
|
56
|
+
|
|
57
|
+
type ControlRecord = { event: ControlEvent; channels: string[]; childIntercomTarget?: string; noticeText?: string; intercom?: { to?: string; message?: string } };
|
|
58
|
+
type ControlPayload = { event: ControlEvent; source: "async"; asyncDir: string; childIntercomTarget?: string; noticeText: string };
|
|
54
59
|
|
|
55
60
|
const isTerminalJobStatus = (status: AsyncJobState["status"]): boolean =>
|
|
56
61
|
status === "complete" || status === "failed" || status === "partial" || status === "paused" || status === "rejected" || status === "stopped";
|
|
@@ -85,6 +90,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
85
90
|
// Early native failure is visible before its publisher finishes. Retain only
|
|
86
91
|
// that scoped observation, using the existing liveness sweep to renew delivery.
|
|
87
92
|
const terminalPublications = new Map<string, { instanceId: string; pending: true } | { pending: false }>();
|
|
93
|
+
const supervisorNoticeTimers = new Map<string, { asyncId: string; timer: ReturnType<typeof setTimeout> }>();
|
|
88
94
|
let rootWatcher: fs.FSWatcher | undefined;
|
|
89
95
|
let nextLivenessAt = Date.now() + livenessIntervalMs;
|
|
90
96
|
let nextWidgetAnimationAt = Date.now() + WIDGET_ANIMATION_INTERVAL_MS;
|
|
@@ -217,6 +223,46 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
217
223
|
}, completionRetentionMs);
|
|
218
224
|
state.cleanupTimers.set(asyncId, timer);
|
|
219
225
|
};
|
|
226
|
+
const deliverControlRecord = (record: ControlRecord, payload: ControlPayload) => {
|
|
227
|
+
if (record.channels.includes("event")) {
|
|
228
|
+
pi.events.emit(SUBAGENT_CONTROL_EVENT, payload);
|
|
229
|
+
}
|
|
230
|
+
if (record.event.type !== "active_long_running" && record.channels.includes("intercom") && record.intercom?.to && record.intercom.message) {
|
|
231
|
+
pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {
|
|
232
|
+
...payload,
|
|
233
|
+
to: record.intercom.to,
|
|
234
|
+
message: record.intercom.message,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
const readSupervisorRequestState = (event: ControlEvent, asyncDir: string): "pending" | "resolved" | "unknown" => {
|
|
239
|
+
try {
|
|
240
|
+
return options.supervisorRequestState?.(event) ?? "unknown";
|
|
241
|
+
} catch (error) {
|
|
242
|
+
console.error(`Failed to resolve supervisor request state for async control event in '${asyncDir}':`, error);
|
|
243
|
+
return "unknown";
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
const scheduleSupervisorNotice = (asyncId: string, record: ControlRecord, payload: ControlPayload) => {
|
|
247
|
+
const key = `${asyncId}:${record.event.index}:${record.event.toolCallId}`;
|
|
248
|
+
if (supervisorNoticeTimers.has(key)) return;
|
|
249
|
+
const timer = setTimeout(() => {
|
|
250
|
+
supervisorNoticeTimers.delete(key);
|
|
251
|
+
const job = state.asyncJobs.get(asyncId);
|
|
252
|
+
if (job?.status !== "running" && job?.status !== "queued") return;
|
|
253
|
+
if (readSupervisorRequestState(record.event, payload.asyncDir) === "resolved") return;
|
|
254
|
+
deliverControlRecord(record, payload);
|
|
255
|
+
}, SUPERVISOR_NOTICE_GRACE_MS);
|
|
256
|
+
timer.unref?.();
|
|
257
|
+
supervisorNoticeTimers.set(key, { asyncId, timer });
|
|
258
|
+
};
|
|
259
|
+
const clearSupervisorNotices = (asyncId?: string) => {
|
|
260
|
+
for (const [key, entry] of supervisorNoticeTimers) {
|
|
261
|
+
if (asyncId !== undefined && entry.asyncId !== asyncId) continue;
|
|
262
|
+
clearTimeout(entry.timer);
|
|
263
|
+
supervisorNoticeTimers.delete(key);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
220
266
|
const emitNewControlEvents = (job: AsyncJobState) => {
|
|
221
267
|
const eventsPath = path.join(job.asyncDir, "events.jsonl");
|
|
222
268
|
let fd: number;
|
|
@@ -292,34 +338,27 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
292
338
|
return;
|
|
293
339
|
}
|
|
294
340
|
if ((parsed as { type?: unknown }).type !== "subagent.control") return;
|
|
295
|
-
const
|
|
296
|
-
if (!
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
console.error(`Failed to resolve supervisor request state for async control event in '${job.asyncDir}':`, error);
|
|
303
|
-
}
|
|
304
|
-
if (requestState === "resolved") return;
|
|
305
|
-
}
|
|
306
|
-
const payload = {
|
|
341
|
+
const candidate = parsed as Partial<ControlRecord>;
|
|
342
|
+
if (!candidate.event || !Array.isArray(candidate.channels)) return;
|
|
343
|
+
// SAFETY: event is present and channels is an array; every other ControlRecord field is optional.
|
|
344
|
+
const record = candidate as ControlRecord;
|
|
345
|
+
const supervisorRequest = record.event.type === "needs_attention" && record.event.reason === "supervisor_request" && options.supervisorRequestState !== undefined;
|
|
346
|
+
if (supervisorRequest && readSupervisorRequestState(record.event, job.asyncDir) === "resolved") return;
|
|
347
|
+
const payload: ControlPayload = {
|
|
307
348
|
event: record.event,
|
|
308
|
-
source: "async"
|
|
349
|
+
source: "async",
|
|
309
350
|
asyncDir: job.asyncDir,
|
|
310
351
|
childIntercomTarget: record.childIntercomTarget,
|
|
311
352
|
noticeText: record.noticeText ?? formatControlNoticeMessage(record.event, record.childIntercomTarget),
|
|
312
353
|
};
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
to: record.intercom.to,
|
|
320
|
-
message: record.intercom.message,
|
|
321
|
-
});
|
|
354
|
+
// External intercom asks have no native lifecycle to re-check, so they keep the immediate notice.
|
|
355
|
+
if (supervisorRequest && record.event.currentTool !== "intercom") {
|
|
356
|
+
// Status and waits still react now; the parent notice and intercom copy wait for the grace period.
|
|
357
|
+
if (record.channels.includes("event")) pi.events.emit(SUBAGENT_CONTROL_EVENT, { ...payload, noticeDeferred: true });
|
|
358
|
+
scheduleSupervisorNotice(job.asyncId, record, payload);
|
|
359
|
+
return;
|
|
322
360
|
}
|
|
361
|
+
deliverControlRecord(record, payload);
|
|
323
362
|
};
|
|
324
363
|
let readCursor = cursor;
|
|
325
364
|
let lastCompleteCursor = cursor;
|
|
@@ -380,6 +419,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
380
419
|
runningJobIds.delete(asyncId);
|
|
381
420
|
externalJobBridgeRuns.delete(asyncId);
|
|
382
421
|
terminalPublications.delete(asyncId);
|
|
422
|
+
clearSupervisorNotices(asyncId);
|
|
383
423
|
};
|
|
384
424
|
|
|
385
425
|
const refreshJob = (job: AsyncJobState): boolean => {
|
|
@@ -773,6 +813,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
773
813
|
runningJobIds.clear();
|
|
774
814
|
externalJobBridgeRuns.clear();
|
|
775
815
|
terminalPublications.clear();
|
|
816
|
+
clearSupervisorNotices();
|
|
776
817
|
};
|
|
777
818
|
|
|
778
819
|
const resetJobs = (ctx?: ExtensionContext) => {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as path from "node:path";
|
|
@@ -6,7 +6,10 @@ import { randomUUID } from "node:crypto";
|
|
|
6
6
|
import { Worker } from "node:worker_threads";
|
|
7
7
|
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
8
8
|
import type { AsyncStatus } from "../../shared/types.ts";
|
|
9
|
-
import {
|
|
9
|
+
import { readMissionBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
|
|
10
|
+
import { MissionNotFoundError, readMission } from "../../missions/store.ts";
|
|
11
|
+
import type { MissionStatus } from "../../missions/types.ts";
|
|
12
|
+
import { REVIVAL_ORIGIN_FILE } from "../../workflows/workflow-revival.ts";
|
|
10
13
|
import { ACTIVE_RUN_INDEX_DIR } from "./active-run-index.ts";
|
|
11
14
|
import { encodeIndexSegment } from "./index-segment.ts";
|
|
12
15
|
import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
|
|
@@ -26,6 +29,8 @@ const RUN_TOMBSTONE_MARKERS_DIR = "async-retention-run-tombstones";
|
|
|
26
29
|
const LOCK_STALE_MS = 24 * 60 * 60 * 1000;
|
|
27
30
|
const RUN_MODES = new Set<AsyncStatus["mode"]>(["single", "parallel", "chain", "workflow"]);
|
|
28
31
|
const TERMINAL_STATES = new Set<AsyncStatus["state"]>(["complete", "failed", "stopped", "rejected"]);
|
|
32
|
+
// Mirrors TERMINAL_MISSION_STATUSES in src/missions/store.ts, which keeps it private.
|
|
33
|
+
const TERMINAL_MISSION_STATUSES = new Set<MissionStatus>(["completed", "failed", "cancelled"]);
|
|
29
34
|
const RESULT_TIMESTAMP_FIELDS = ["endedAt", "completedAt", "createdAt", "writtenAt", "expiresAt", "timestamp"] as const;
|
|
30
35
|
|
|
31
36
|
interface RetentionCursor {
|
|
@@ -93,7 +98,7 @@ export interface AsyncRetentionOptions {
|
|
|
93
98
|
hostname?: string;
|
|
94
99
|
processStartIdentity?: string;
|
|
95
100
|
isProcessAlive?: (pid: number) => boolean | undefined;
|
|
96
|
-
getProcessStartIdentity?: (pid: number) => string | undefined
|
|
101
|
+
getProcessStartIdentity?: (pid: number) => Promise<string | undefined>;
|
|
97
102
|
lstatSync?: typeof fs.lstatSync;
|
|
98
103
|
signal?: AbortSignal;
|
|
99
104
|
discoveryWorkerUrl?: URL;
|
|
@@ -212,6 +217,25 @@ function missionObserverIndexExists(resultsDir: string, runId: string): boolean
|
|
|
212
217
|
return fs.existsSync(path.join(resultsDir, "result-index", "observers", "mission", `${encodeIndexSegment(runId)}.json`));
|
|
213
218
|
}
|
|
214
219
|
|
|
220
|
+
// The retention window doubles as a terminal mission's grace period. Unreadable references and
|
|
221
|
+
// pending syncs are kept because the watcher needs the run's binding to retry.
|
|
222
|
+
function missionReferenceBlocksReclaim(runDir: string, resultsDir: string, runId: string): boolean {
|
|
223
|
+
if (missionObserverIndexExists(resultsDir, runId)) return true;
|
|
224
|
+
let binding: MissionLaunchBinding | undefined;
|
|
225
|
+
try {
|
|
226
|
+
binding = readMissionBinding(runDir);
|
|
227
|
+
} catch {
|
|
228
|
+
return true;
|
|
229
|
+
}
|
|
230
|
+
if (!binding) return false;
|
|
231
|
+
try {
|
|
232
|
+
const mission = readMission(binding.location, binding.missionId);
|
|
233
|
+
return !TERMINAL_MISSION_STATUSES.has(mission.status);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
return !(error instanceof MissionNotFoundError);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
215
239
|
function runTombstoneMarkerPath(maintenanceRoot: string, runId: string): string {
|
|
216
240
|
return path.join(maintenanceRoot, RUN_TOMBSTONE_MARKERS_DIR, `${encodeIndexSegment(runId)}.json`);
|
|
217
241
|
}
|
|
@@ -296,8 +320,10 @@ function runSkipReason(input: {
|
|
|
296
320
|
if (activeMarkerExists(input.asyncDirRoot, status.runId)) return "active-index";
|
|
297
321
|
if (!TERMINAL_STATES.has(status.state)) return "non-terminal";
|
|
298
322
|
if (status.mode === "workflow" || status.parentWorkflowRunId || status.workflowKey) return "workflow-reference";
|
|
323
|
+
// A revived workflow child is a link in its key's revival chain; deleting it would cut off later revivals.
|
|
324
|
+
if (fs.existsSync(path.join(runDir, REVIVAL_ORIGIN_FILE))) return "workflow-reference";
|
|
299
325
|
if (hasNestedReferences(status)) return "nested-reference";
|
|
300
|
-
if (
|
|
326
|
+
if (missionReferenceBlocksReclaim(runDir, input.resultsDir, status.runId)) return "mission-reference";
|
|
301
327
|
if (hasUnresolvedRunHandoff(runDir, status)) return "handoff-reference";
|
|
302
328
|
if (hasResumableContract(runDir, status)) return "resumable";
|
|
303
329
|
const timestamp = statusTimestamp(status, runDir);
|
|
@@ -324,16 +350,16 @@ function readCursor(root: string): RetentionCursor {
|
|
|
324
350
|
return value?.version === 1 ? value as unknown as RetentionCursor : { version: 1 };
|
|
325
351
|
}
|
|
326
352
|
|
|
327
|
-
let currentProcessStartIdentity: string | undefined |
|
|
353
|
+
let currentProcessStartIdentity: Promise<string | undefined> | undefined;
|
|
328
354
|
|
|
329
|
-
function processStartIdentity(pid: number): string | undefined {
|
|
355
|
+
function processStartIdentity(pid: number): Promise<string | undefined> {
|
|
330
356
|
// Foreign PIDs can be reused while this process lives, so resolve them afresh.
|
|
331
357
|
if (pid !== process.pid) return computeProcessStartIdentity(pid);
|
|
332
|
-
|
|
358
|
+
currentProcessStartIdentity ??= computeProcessStartIdentity(pid);
|
|
333
359
|
return currentProcessStartIdentity;
|
|
334
360
|
}
|
|
335
361
|
|
|
336
|
-
function computeProcessStartIdentity(pid: number): string | undefined {
|
|
362
|
+
async function computeProcessStartIdentity(pid: number): Promise<string | undefined> {
|
|
337
363
|
if (process.platform === "linux") {
|
|
338
364
|
try {
|
|
339
365
|
const stat = fs.readFileSync(`/proc/${pid}/stat`).toString("utf8");
|
|
@@ -346,8 +372,12 @@ function computeProcessStartIdentity(pid: number): string | undefined {
|
|
|
346
372
|
}
|
|
347
373
|
}
|
|
348
374
|
if (process.platform === "win32") {
|
|
349
|
-
|
|
350
|
-
const started =
|
|
375
|
+
// PowerShell takes ~0.5 s to start; a synchronous spawn would freeze the TUI.
|
|
376
|
+
const started = await new Promise<string>((resolve) => {
|
|
377
|
+
execFile("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CreationDate`], { encoding: "utf-8", windowsHide: true, timeout: 5_000 }, (error, stdout) => {
|
|
378
|
+
resolve(error ? "" : stdout.trim());
|
|
379
|
+
});
|
|
380
|
+
});
|
|
351
381
|
return started ? `win:${started}` : undefined;
|
|
352
382
|
}
|
|
353
383
|
return undefined;
|
|
@@ -381,7 +411,7 @@ function parseLockOwner(lockDir: string): RetentionLockOwner | undefined {
|
|
|
381
411
|
return owner as unknown as RetentionLockOwner;
|
|
382
412
|
}
|
|
383
413
|
|
|
384
|
-
function staleLock(lockDir: string, now: number, options: Required<Pick<AsyncRetentionOptions, "hostname" | "isProcessAlive" | "getProcessStartIdentity">>): { stale: boolean; token?: string } {
|
|
414
|
+
async function staleLock(lockDir: string, now: number, options: Required<Pick<AsyncRetentionOptions, "hostname" | "isProcessAlive" | "getProcessStartIdentity">>): Promise<{ stale: boolean; token?: string }> {
|
|
385
415
|
const owner = parseLockOwner(lockDir);
|
|
386
416
|
if (!owner) {
|
|
387
417
|
try {
|
|
@@ -394,7 +424,7 @@ function staleLock(lockDir: string, now: number, options: Required<Pick<AsyncRet
|
|
|
394
424
|
const alive = options.isProcessAlive(owner.pid);
|
|
395
425
|
if (alive === false) return { stale: true, token: owner.token };
|
|
396
426
|
if (alive === true && owner.processStartIdentity) {
|
|
397
|
-
const currentIdentity = options.getProcessStartIdentity(owner.pid);
|
|
427
|
+
const currentIdentity = await options.getProcessStartIdentity(owner.pid);
|
|
398
428
|
if (currentIdentity !== undefined && currentIdentity !== owner.processStartIdentity) return { stale: true, token: owner.token };
|
|
399
429
|
}
|
|
400
430
|
return { stale: now - owner.startedAt >= LOCK_STALE_MS, token: owner.token };
|
|
@@ -416,10 +446,10 @@ function createLockDirectory(lockDir: string, owner: RetentionLockOwner): boolea
|
|
|
416
446
|
}
|
|
417
447
|
}
|
|
418
448
|
|
|
419
|
-
function acquireRetentionLock(lockDir: string, owner: RetentionLockOwner, options: Required<Pick<AsyncRetentionOptions, "hostname" | "isProcessAlive" | "getProcessStartIdentity">>): boolean {
|
|
449
|
+
async function acquireRetentionLock(lockDir: string, owner: RetentionLockOwner, options: Required<Pick<AsyncRetentionOptions, "hostname" | "isProcessAlive" | "getProcessStartIdentity">>): Promise<boolean> {
|
|
420
450
|
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
421
451
|
if (createLockDirectory(lockDir, owner)) return true;
|
|
422
|
-
const stale = staleLock(lockDir, owner.startedAt, options);
|
|
452
|
+
const stale = await staleLock(lockDir, owner.startedAt, options);
|
|
423
453
|
if (!stale.stale) return false;
|
|
424
454
|
const staleKey = (stale.token ?? owner.token).replace(/[^A-Za-z0-9._-]/g, "-");
|
|
425
455
|
const tombstone = `${lockDir}.stale-${staleKey}`;
|
|
@@ -672,7 +702,7 @@ export async function cleanupAsyncRetention(options: AsyncRetentionOptions): Pro
|
|
|
672
702
|
const pid = options.pid ?? process.pid;
|
|
673
703
|
const hostname = options.hostname ?? os.hostname();
|
|
674
704
|
const getProcessStartIdentity = options.getProcessStartIdentity ?? processStartIdentity;
|
|
675
|
-
const currentProcessStartIdentity = options.processStartIdentity ?? getProcessStartIdentity(pid) ?? (pid === process.pid ? `runtime:${Math.round(Date.now() - process.uptime() * 1000)}` : undefined);
|
|
705
|
+
const currentProcessStartIdentity = options.processStartIdentity ?? await getProcessStartIdentity(pid) ?? (pid === process.pid ? `runtime:${Math.round(Date.now() - process.uptime() * 1000)}` : undefined);
|
|
676
706
|
const lockOwner: RetentionLockOwner = { version: 1, token: lockToken, pid, hostname, startedAt: currentTime, ...(currentProcessStartIdentity ? { processStartIdentity: currentProcessStartIdentity } : {}) };
|
|
677
707
|
const lockOptions = { hostname, isProcessAlive: options.isProcessAlive ?? processIsAlive, getProcessStartIdentity };
|
|
678
708
|
const result: AsyncRetentionResult = {
|
|
@@ -709,7 +739,7 @@ export async function cleanupAsyncRetention(options: AsyncRetentionOptions): Pro
|
|
|
709
739
|
return true;
|
|
710
740
|
};
|
|
711
741
|
fs.mkdirSync(maintenanceRoot, { recursive: true });
|
|
712
|
-
if (!acquireRetentionLock(lockDir, lockOwner, lockOptions)) {
|
|
742
|
+
if (!await acquireRetentionLock(lockDir, lockOwner, lockOptions)) {
|
|
713
743
|
increment(result.skipped, "lock-busy");
|
|
714
744
|
return finish();
|
|
715
745
|
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
3
|
+
import { workflowAwaitedAsyncResultPath } from "./async-execution.ts";
|
|
4
|
+
import { waitForImportedAsyncRoot, type ImportedAsyncRootResult } from "./chain-root-attachment.ts";
|
|
5
|
+
import { currentPidNamespaceScope } from "./pid-namespace.ts";
|
|
6
|
+
import { resultPayloadPathForSessionRun } from "./result-files.ts";
|
|
7
|
+
import { checkPidLiveness } from "./stale-run-reconciler.ts";
|
|
8
|
+
|
|
9
|
+
type ExistingAsyncRunOutcome =
|
|
10
|
+
| { status: "settled"; result: ImportedAsyncRootResult }
|
|
11
|
+
| { status: "unavailable"; reason: string };
|
|
12
|
+
|
|
13
|
+
function errorMessage(error: unknown): string {
|
|
14
|
+
return error instanceof Error ? error.message : String(error);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Read-only probe: the runner is gone while status still says it is active and no result was published. */
|
|
18
|
+
function runnerExitedWithoutResult(asyncDir: string, runId: string, resultPath: string): boolean {
|
|
19
|
+
const status = readStatus(asyncDir);
|
|
20
|
+
if (!status || (status.state !== "running" && status.state !== "queued") || typeof status.pid !== "number") return false;
|
|
21
|
+
if (status.pidNamespaceScope !== undefined && status.pidNamespaceScope !== currentPidNamespaceScope()) return false;
|
|
22
|
+
if (checkPidLiveness(status.pid) !== "dead") return false;
|
|
23
|
+
return !fs.existsSync(resultPath) && !(status.sessionId && resultPayloadPathForSessionRun(asyncDir, status.sessionId, runId));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Waits for an existing workflow-awaited async child, identified by its async
|
|
28
|
+
* directory and exact run id, and returns its published result without
|
|
29
|
+
* launching, consuming, or rewriting anything. Anything short of a published
|
|
30
|
+
* result file for that exact run is `unavailable`. Rejects with the signal's
|
|
31
|
+
* reason when aborted.
|
|
32
|
+
*/
|
|
33
|
+
export async function awaitExistingAsyncRun(asyncDir: string, runId: string, signal: AbortSignal): Promise<ExistingAsyncRunOutcome> {
|
|
34
|
+
signal.throwIfAborted();
|
|
35
|
+
let status: ReturnType<typeof readStatus>;
|
|
36
|
+
try {
|
|
37
|
+
status = readStatus(asyncDir);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
return { status: "unavailable", reason: `Async status for run '${runId}' is unreadable: ${errorMessage(error)}` };
|
|
40
|
+
}
|
|
41
|
+
if (!status) return { status: "unavailable", reason: `No async status exists for run '${runId}' at ${asyncDir}.` };
|
|
42
|
+
if (status.runId !== runId) return { status: "unavailable", reason: `Async status at ${asyncDir} belongs to run '${status.runId}', not '${runId}'.` };
|
|
43
|
+
// The launcher's initial status has no workflow identity until the runner starts, so only the
|
|
44
|
+
// mode is checked here; a run that does not publish to the workflow result path stays unavailable.
|
|
45
|
+
if (status.mode !== "single") return { status: "unavailable", reason: `Async run '${runId}' is not a single-agent run.` };
|
|
46
|
+
const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
|
|
47
|
+
let runnerExited = false;
|
|
48
|
+
let completed: ImportedAsyncRootResult;
|
|
49
|
+
try {
|
|
50
|
+
completed = await waitForImportedAsyncRoot({ runId, asyncDir, resultPath, index: 0 }, {
|
|
51
|
+
shouldAbort: () => signal.aborted || (runnerExited = runnerExitedWithoutResult(asyncDir, runId, resultPath)),
|
|
52
|
+
});
|
|
53
|
+
} catch (error) {
|
|
54
|
+
signal.throwIfAborted();
|
|
55
|
+
return { status: "unavailable", reason: `Could not await async run '${runId}': ${errorMessage(error)}` };
|
|
56
|
+
}
|
|
57
|
+
signal.throwIfAborted();
|
|
58
|
+
if (runnerExited) return { status: "unavailable", reason: `Async runner for run '${runId}' exited without publishing a result.` };
|
|
59
|
+
// Only a parsed result file carries importedPublication; status-derived fallbacks do not.
|
|
60
|
+
if (!completed.importedPublication) return { status: "unavailable", reason: `Async run '${runId}' ended without a result file at ${resultPath}.` };
|
|
61
|
+
return { status: "settled", result: completed };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Renames the published result to a file owned by `claimant`. Only one of several
|
|
66
|
+
* concurrent importers can win the rename; the others get undefined and launch fresh.
|
|
67
|
+
*/
|
|
68
|
+
export function claimWorkflowAwaitedResult(asyncDir: string, claimant: string): string | undefined {
|
|
69
|
+
const claimedPath = `${workflowAwaitedAsyncResultPath(asyncDir)}.${claimant}.claimed`;
|
|
70
|
+
try {
|
|
71
|
+
fs.renameSync(workflowAwaitedAsyncResultPath(asyncDir), claimedPath);
|
|
72
|
+
return claimedPath;
|
|
73
|
+
} catch {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -161,7 +161,7 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
|
|
|
161
161
|
};
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string): ImportedAsyncRootResult {
|
|
164
|
+
function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string, stopped = false): ImportedAsyncRootResult {
|
|
165
165
|
const step = selectedStatusStep(status, root.index);
|
|
166
166
|
return {
|
|
167
167
|
agent: step?.agent ?? status?.steps?.[root.index]?.agent ?? "subagent",
|
|
@@ -169,7 +169,7 @@ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null,
|
|
|
169
169
|
success: false,
|
|
170
170
|
exitCode: 1,
|
|
171
171
|
error: message,
|
|
172
|
-
timedOut: true,
|
|
172
|
+
...(stopped ? { stopped: true } : { timedOut: true }),
|
|
173
173
|
...(step?.sessionName ? { sessionName: step.sessionName } : {}),
|
|
174
174
|
...(step?.sessionFile ?? status?.sessionFile ? { sessionFile: step?.sessionFile ?? status?.sessionFile } : {}),
|
|
175
175
|
...(step?.model ? { model: step.model } : {}),
|
|
@@ -228,7 +228,7 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
|
|
|
228
228
|
|
|
229
229
|
export async function waitForImportedAsyncRoot(
|
|
230
230
|
root: ImportedAsyncRoot,
|
|
231
|
-
options: { pollIntervalMs?: number; terminalResultGraceMs?: number; now?: () => number; shouldAbort?: () => boolean; timeoutMessage?: string } = {},
|
|
231
|
+
options: { pollIntervalMs?: number; terminalResultGraceMs?: number; now?: () => number; shouldAbort?: () => boolean; timeoutMessage?: string; abortedAsStopped?: boolean } = {},
|
|
232
232
|
): Promise<ImportedAsyncRootResult> {
|
|
233
233
|
const pollIntervalMs = options.pollIntervalMs ?? 500;
|
|
234
234
|
const terminalResultGraceMs = options.terminalResultGraceMs ?? 1_000;
|
|
@@ -236,7 +236,7 @@ export async function waitForImportedAsyncRoot(
|
|
|
236
236
|
let terminalSince: number | undefined;
|
|
237
237
|
for (;;) {
|
|
238
238
|
const status = readStatus(root.asyncDir);
|
|
239
|
-
if (options.shouldAbort?.()) return outputFromTimeout(root, status, options.timeoutMessage ?? "Subagent timed out.");
|
|
239
|
+
if (options.shouldAbort?.()) return outputFromTimeout(root, status, options.timeoutMessage ?? "Subagent timed out.", options.abortedAsStopped === true);
|
|
240
240
|
const result = readImportedResultFile(root, status);
|
|
241
241
|
if (result) return buildImportedResult(root, status, result);
|
|
242
242
|
if (isTerminalStatus(status, root.index)) {
|
|
@@ -79,6 +79,8 @@ const STOP_REQUESTS_DIR = "stop-requests";
|
|
|
79
79
|
const REVIVAL_BRIEFS_DIR = "revival-briefs";
|
|
80
80
|
export const MAX_STEER_QUEUE_SIZE = 20;
|
|
81
81
|
const STEER_INBOX_CLOSED_FILE = "steer-inbox-closed.json";
|
|
82
|
+
const STOP_INBOX_CLOSED_FILE = "stop-inbox-closed.json";
|
|
83
|
+
const STOP_INBOX_CLOSED_MESSAGE = "Runner stop inbox is closed. Retry stop after runner shutdown is observed.";
|
|
82
84
|
const MAX_STEER_MESSAGE_BYTES = 128 * 1024;
|
|
83
85
|
const MAX_STEER_REQUEST_ID_LENGTH = 256;
|
|
84
86
|
|
|
@@ -116,6 +118,14 @@ export function steerInboxClosedPath(asyncDir: string): string {
|
|
|
116
118
|
return path.join(controlInboxDir(asyncDir), STEER_INBOX_CLOSED_FILE);
|
|
117
119
|
}
|
|
118
120
|
|
|
121
|
+
export function stopInboxClosedPath(asyncDir: string): string {
|
|
122
|
+
return path.join(controlInboxDir(asyncDir), STOP_INBOX_CLOSED_FILE);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function closeStopInbox(asyncDir: string): void {
|
|
126
|
+
writeAtomicJson(stopInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now() });
|
|
127
|
+
}
|
|
128
|
+
|
|
119
129
|
export function closeSteerInbox(asyncDir: string, state: string, write: (filePath: string, payload: object) => void = writeAtomicJson): void {
|
|
120
130
|
write(steerInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now(), state });
|
|
121
131
|
}
|
|
@@ -206,15 +216,21 @@ export function requestAsyncTimeout(
|
|
|
206
216
|
export function requestAsyncStop(
|
|
207
217
|
asyncDir: string,
|
|
208
218
|
payload: Omit<StopRequest, "type"> = {},
|
|
209
|
-
deps: { now?: () => number } = {},
|
|
219
|
+
deps: { now?: () => number; write?: typeof writeAtomicJson } = {},
|
|
210
220
|
): string {
|
|
211
221
|
if (payload.targetIndex !== undefined) assertChildIndex(payload.targetIndex);
|
|
212
222
|
if (payload.childId !== undefined && !validStopChildId(payload.childId)) {
|
|
213
223
|
throw new Error("stop childId must be a non-empty string without newlines and at most 256 characters.");
|
|
214
224
|
}
|
|
225
|
+
const closedPath = stopInboxClosedPath(asyncDir);
|
|
226
|
+
if (fs.existsSync(closedPath)) throw new Error(STOP_INBOX_CLOSED_MESSAGE);
|
|
215
227
|
const request: StopRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type: "stop" };
|
|
216
228
|
const requestPath = path.join(stopRequestsDir(asyncDir), stopRequestFileName(request));
|
|
217
|
-
writeAtomicJson(requestPath, request);
|
|
229
|
+
(deps.write ?? writeAtomicJson)(requestPath, request);
|
|
230
|
+
if (fs.existsSync(closedPath)) {
|
|
231
|
+
fs.rmSync(requestPath, { force: true });
|
|
232
|
+
throw new Error(STOP_INBOX_CLOSED_MESSAGE);
|
|
233
|
+
}
|
|
218
234
|
return requestPath;
|
|
219
235
|
}
|
|
220
236
|
|
|
@@ -27,6 +27,8 @@ export interface SubagentNotifyChildOutput {
|
|
|
27
27
|
runId?: string;
|
|
28
28
|
agent?: string;
|
|
29
29
|
status: string;
|
|
30
|
+
/** Latest detached revival of this failed child, e.g. `Revived → <run>: completed`. */
|
|
31
|
+
revival?: string;
|
|
30
32
|
savedOutputPath?: string;
|
|
31
33
|
outputArtifactPath?: string;
|
|
32
34
|
structuredOutputPath?: string;
|
|
@@ -93,6 +95,7 @@ export interface CompletionNotification {
|
|
|
93
95
|
agent?: string;
|
|
94
96
|
status?: string;
|
|
95
97
|
state?: string;
|
|
98
|
+
revival?: string;
|
|
96
99
|
success?: boolean;
|
|
97
100
|
output?: string;
|
|
98
101
|
structuredOutput?: unknown;
|
|
@@ -269,6 +272,7 @@ function formatChildOutputBlock(children: SubagentNotifyChildOutput[] | undefine
|
|
|
269
272
|
const runId = child.runId ? boundedSafeText(child.runId) : "unavailable";
|
|
270
273
|
const status = boundedSafeText(child.status) || "unavailable";
|
|
271
274
|
lines.push(`- key=${key} run=${runId} status=${status}`);
|
|
275
|
+
if (child.revival) lines.push(` ${boundedSafeText(child.revival)}`);
|
|
272
276
|
lines.push(` Saved output: ${child.savedOutputPath ? boundedSafeText(child.savedOutputPath) : "unavailable"}`);
|
|
273
277
|
if (child.outputArtifactPath) lines.push(` Output artifact (retention-managed): ${boundedSafeText(child.outputArtifactPath)}`);
|
|
274
278
|
if (child.structuredOutputPath) lines.push(` Structured output (retention-managed): ${boundedSafeText(child.structuredOutputPath)}`);
|
|
@@ -696,6 +700,7 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
|
|
|
696
700
|
...(runId ? { runId } : {}),
|
|
697
701
|
...(typeof child.agent === "string" ? { agent: child.agent } : {}),
|
|
698
702
|
status: childStatus(child, result.state),
|
|
703
|
+
...(typeof child.revival === "string" && child.revival ? { revival: child.revival } : {}),
|
|
699
704
|
...(savedOutputPath ? { savedOutputPath } : {}),
|
|
700
705
|
...(outputArtifact.status === "verified" ? { outputArtifactPath: outputArtifact.path } : {}),
|
|
701
706
|
...(structuredOutput.status === "verified" ? { structuredOutputPath: structuredOutput.path } : {}),
|
|
@@ -414,7 +414,10 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
414
414
|
const event = raw as ChildSessionEvent & ChildEvent;
|
|
415
415
|
appendChildEvent(projectChildSessionEventForJson(raw) as Record<string, unknown>);
|
|
416
416
|
input.transcriptWriter?.writeChildEvent(projectChildSessionEventForJson(raw) as ChildEvent);
|
|
417
|
-
if (event.type === "compaction_start")
|
|
417
|
+
if (event.type === "compaction_start") {
|
|
418
|
+
compactionStartedReceived = true;
|
|
419
|
+
if (agentSettledReceived) afterCompactionSettlement = true;
|
|
420
|
+
}
|
|
418
421
|
if (event.type === "compaction_end" && event.willRetry === true) {
|
|
419
422
|
compactionStartedReceived = false;
|
|
420
423
|
afterCompactionSettlement = false;
|
|
@@ -34,6 +34,7 @@ import { formatTimeoutRecoveryLines } from "../shared/mutation-evidence.ts";
|
|
|
34
34
|
import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
|
|
35
35
|
import { validHostStepNodes } from "../shared/host-step-status.ts";
|
|
36
36
|
import { workflowAsyncChildSteeringGuidance } from "../shared/workflow-async-child-guidance.ts";
|
|
37
|
+
import { formatWorkflowKeyRevival, projectWorkflowKeyRevival } from "../../workflows/workflow-revival.ts";
|
|
37
38
|
|
|
38
39
|
interface RunStatusParams {
|
|
39
40
|
action?: string;
|
|
@@ -595,6 +596,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
595
596
|
status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
|
|
596
597
|
status.mode === "workflow" && workflowReturnPreview !== undefined ? `Return: ${workflowReturnPreview}` : undefined,
|
|
597
598
|
status.mode === "workflow" && workflowEmitPreview !== undefined ? `Latest emit: ${workflowEmitPreview}` : undefined,
|
|
599
|
+
status.mode === "workflow" && (workflowReturnPreview?.endsWith("…") || workflowEmitPreview?.endsWith("…")) ? `Full return value and emits: ${path.join(asyncDir, "status.json")} (workflow.value, workflow.emits)` : undefined,
|
|
598
600
|
`Progress: ${progressLabel}`,
|
|
599
601
|
...(status.mode === "workflow" ? formatWorkflowChecklistText(projectWorkflowChecklist({
|
|
600
602
|
graph: status.workflowGraph,
|
|
@@ -634,6 +636,10 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
634
636
|
const phase = step.phase ? `[${step.phase}] ` : "";
|
|
635
637
|
lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText}`);
|
|
636
638
|
if (status.mode === "workflow" && step.runId) lines.push(` Child run: ${step.runId}`);
|
|
639
|
+
if (status.mode === "workflow" && step.runId && step.workflowKey && step.status === "failed") {
|
|
640
|
+
const revival = projectWorkflowKeyRevival(asyncDirRoot, status.runId, step.workflowKey, step.runId);
|
|
641
|
+
if (revival) lines.push(` ${formatWorkflowKeyRevival(revival)}`);
|
|
642
|
+
}
|
|
637
643
|
const structuredOutputPreview = step.structuredOutput === undefined ? undefined : formatWorkflowJsonPreview(step.structuredOutput, 4_000);
|
|
638
644
|
if (structuredOutputPreview !== undefined) lines.push(` Structured output: ${structuredOutputPreview}`);
|
|
639
645
|
if (step.structuredOutputPath) lines.push(` Structured output path: ${step.structuredOutputPath}`);
|
|
@@ -131,6 +131,26 @@ function findPeerPackageDir(piPackageRoot: string, pkg: string, hostName: unknow
|
|
|
131
131
|
return candidates.find((candidate) => readManifest(candidate)?.name === pkg);
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
+
/** Whether the package's `exports` map (or `main`) declares `subpath`, even if the target file is missing. */
|
|
135
|
+
function exportsDeclareSubpath(packageDir: string, subpath: string): boolean {
|
|
136
|
+
const manifest = readManifest(packageDir);
|
|
137
|
+
if (!manifest) return false;
|
|
138
|
+
const exportsField = manifest.exports;
|
|
139
|
+
if (exportsField === undefined || exportsField === null) return subpath === ".";
|
|
140
|
+
const map: Record<string, unknown> = typeof exportsField === "string" || Array.isArray(exportsField) || (exportsField && typeof exportsField === "object" && !Object.keys(exportsField as object).some((key) => key.startsWith(".")))
|
|
141
|
+
? { ".": exportsField }
|
|
142
|
+
: exportsField as Record<string, unknown>;
|
|
143
|
+
if (subpath in map) return true;
|
|
144
|
+
for (const pattern of Object.keys(map)) {
|
|
145
|
+
const star = pattern.indexOf("*");
|
|
146
|
+
if (star === -1) continue;
|
|
147
|
+
const prefix = pattern.slice(0, star);
|
|
148
|
+
const suffix = pattern.slice(star + 1);
|
|
149
|
+
if (subpath.startsWith(prefix) && subpath.endsWith(suffix) && subpath.length >= prefix.length + suffix.length) return true;
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
|
|
134
154
|
/** The alias map the runner needs, or the specifiers that could not be resolved. */
|
|
135
155
|
export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record<string, string>; missing: string[] } {
|
|
136
156
|
const aliases: Record<string, string> = {};
|
|
@@ -145,8 +165,16 @@ export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record
|
|
|
145
165
|
const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
|
|
146
166
|
const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : undefined;
|
|
147
167
|
// Native loaders short-circuit resolution, so aliases must retain the real package's dependency scope.
|
|
148
|
-
if (target && fs.existsSync(target))
|
|
149
|
-
|
|
168
|
+
if (target && fs.existsSync(target)) {
|
|
169
|
+
aliases[specifier] = fs.realpathSync(target);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
// Host API drift: the installed peer no longer exports the subpath at all
|
|
173
|
+
// (pi 1.0.0's pi-agent-core dropped ./node), so the runner cannot import
|
|
174
|
+
// it on this host either — the alias is best-effort. A subpath that is
|
|
175
|
+
// declared but missing on disk stays a broken install.
|
|
176
|
+
if (packageDir && subpath !== "." && !exportsDeclareSubpath(packageDir, subpath)) continue;
|
|
177
|
+
missing.push(specifier);
|
|
150
178
|
}
|
|
151
179
|
return { aliases, missing };
|
|
152
180
|
}
|
|
@@ -18,6 +18,7 @@ export interface RunnerChildLaunchContext {
|
|
|
18
18
|
runFanoutBudget?: BuildInProcessChildLaunchInput["runFanoutBudget"];
|
|
19
19
|
capabilityCeiling?: BuildInProcessChildLaunchInput["capabilityCeiling"];
|
|
20
20
|
inheritedChildRuntime?: InheritedChildRuntime;
|
|
21
|
+
projectTrusted?: boolean;
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChildLaunchContext, attempt: {
|
|
@@ -58,10 +59,12 @@ export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChil
|
|
|
58
59
|
systemPrompt: acceptancePrompt ? `${step.systemPrompt ?? ""}\n${acceptancePrompt}` : step.systemPrompt ?? "",
|
|
59
60
|
systemPromptMode: step.systemPromptMode,
|
|
60
61
|
mcpDirectTools: step.mcpDirectTools,
|
|
62
|
+
builtinMcpTools: step.builtinMcpTools,
|
|
61
63
|
extensionBindings: normalizeExtensionBindings(step.extensionBindings)?.value,
|
|
62
64
|
capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
|
|
63
65
|
cwd: step.cwd ?? ctx.cwd,
|
|
64
66
|
intercomSessionName: ctx.childIntercomTarget,
|
|
67
|
+
projectTrusted: ctx.projectTrusted,
|
|
65
68
|
sessionName: attempt.sessionName,
|
|
66
69
|
orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
|
|
67
70
|
runId: ctx.id,
|
|
@@ -296,7 +296,7 @@ function parseScheduleTarget(value: unknown, file: string): ScheduleTarget {
|
|
|
296
296
|
if ("error" in normalizedArgs) throw new Error(`Schedule record '${file}' has invalid args: ${normalizedArgs.error}`);
|
|
297
297
|
return { workflowScript: target.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }) };
|
|
298
298
|
}
|
|
299
|
-
if (target.agent !== undefined || target.task !== undefined) throw new Error(`Schedule record '${file}' uses a removed legacy agent target; recreate it with
|
|
299
|
+
if (target.agent !== undefined || target.task !== undefined) throw new Error(`Schedule record '${file}' uses a removed legacy agent target; recreate it with schedule.create and workflow: true or a workflow script path.`);
|
|
300
300
|
throw new Error(`Schedule record '${file}' requires a workflowScript target.`);
|
|
301
301
|
}
|
|
302
302
|
|
|
@@ -434,13 +434,13 @@ function publicScheduleRecord(schedule: ScheduleRecord): PublicScheduleRecord {
|
|
|
434
434
|
|
|
435
435
|
function targetLabel(target: ScheduleTarget): string {
|
|
436
436
|
const preview = previewSimpleWorkflowRun(target.workflowScript);
|
|
437
|
-
return preview?.agent ? `
|
|
437
|
+
return preview?.agent ? `workflow -> agent ${preview.agent}` : "workflow (dynamic)";
|
|
438
438
|
}
|
|
439
439
|
|
|
440
440
|
function sanitizeTarget(params: SubagentParamsLike): { target?: ScheduleTarget; error?: string } {
|
|
441
|
-
if (params.tasks || params.chain) return { error: "Recurring schedules require
|
|
442
|
-
if (params.agent !== undefined || params.task !== undefined) return { error: "schedule.create requires
|
|
443
|
-
if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) return { error: "schedule.create requires a
|
|
441
|
+
if (params.tasks || params.chain) return { error: "Recurring schedules require a workflow script; legacy tasks and chain inputs are unsupported." };
|
|
442
|
+
if (params.agent !== undefined || params.task !== undefined) return { error: "schedule.create requires workflow: true or a workflow script path, e.g. a ```js workflow block containing return runs.run('main', { agent, task })." };
|
|
443
|
+
if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) return { error: "schedule.create requires workflow: true or a workflow script path." };
|
|
444
444
|
if (params.context === "fork") return { error: "Scheduled runs require fresh context." };
|
|
445
445
|
if (params.async === false) return { error: "Scheduled runs are always async." };
|
|
446
446
|
let baseRef: string | undefined;
|