@xzzpig/pi-subagents 0.20.0 → 0.21.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 +154 -0
- package/README.md +1 -1
- package/agents/oracle.md +8 -19
- package/agents/researcher.md +0 -3
- package/agents/reviewer.md +17 -61
- package/agents/scout.md +1 -4
- package/agents/worker.md +8 -25
- package/docs/agents.md +72 -7
- package/docs/configuration.md +58 -7
- package/docs/extension-api.md +36 -11
- package/docs/fork-extensions.md +1 -0
- package/docs/missions.md +34 -17
- package/docs/models.md +1 -1
- package/docs/observability.md +10 -5
- package/docs/tool-reference.md +117 -84
- package/docs/watchdog.md +8 -6
- package/docs/workflows.md +16 -7
- package/index.ts +5 -0
- package/package.json +5 -3
- package/prompts/council.md +1 -1
- package/skills/pi-subagents/SKILL.md +1 -1
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +16 -16
- package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
- package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +9 -1
- package/src/agents/agent-management.ts +4 -0
- package/src/agents/agent-memory.ts +3 -3
- package/src/agents/agent-scope.ts +4 -0
- package/src/agents/agent-serializer.ts +8 -1
- package/src/agents/agents.ts +191 -145
- package/src/api/preflight.ts +8 -4
- package/src/extension/config.ts +21 -2
- package/src/extension/context-injection.ts +6 -1
- package/src/extension/control-notices.ts +1 -9
- package/src/extension/declaration-pinning.ts +164 -0
- package/src/extension/doctor.ts +7 -10
- package/src/extension/fanout-child.ts +7 -8
- package/src/extension/index.ts +114 -132
- package/src/extension/reply-workflow-script.ts +20 -11
- package/src/extension/rpc.ts +11 -6
- package/src/extension/schemas.ts +34 -30
- package/src/extension/subagent-guide.ts +86 -6
- package/src/extension/subagent-options.ts +47 -0
- package/src/extension/tool-activation.ts +3 -2
- package/src/extension/tool-description.ts +51 -68
- package/src/inspectors/actions.ts +37 -11
- package/src/inspectors/plugins.ts +3 -2
- package/src/inspectors/tmux/actions.ts +204 -0
- package/src/inspectors/tmux/client.ts +85 -0
- package/src/inspectors/tmux/plugin.ts +21 -0
- package/src/integrations/herdr-status.ts +18 -49
- package/src/integrations/program-status.ts +215 -0
- package/src/intercom/native-supervisor-channel.ts +77 -4
- package/src/intercom/result-intercom.ts +3 -2
- package/src/intercom/supervisor-ui.ts +2 -174
- package/src/missions/store.ts +25 -5
- package/src/profiles/profiles.ts +24 -21
- package/src/runs/background/active-async-capacity.ts +58 -8
- package/src/runs/background/async-execution.ts +143 -38
- package/src/runs/background/async-job-tracker.ts +11 -4
- package/src/runs/background/async-resume.ts +5 -2
- package/src/runs/background/await-async-run.ts +14 -9
- package/src/runs/background/binary-bootstrap.ts +2 -1
- package/src/runs/background/calendar-schedule.ts +90 -0
- package/src/runs/background/chain-root-attachment.ts +9 -5
- package/src/runs/background/fleet-view.ts +5 -5
- package/src/runs/background/notify.ts +185 -12
- package/src/runs/background/result-files.ts +116 -5
- package/src/runs/background/result-watcher.ts +99 -66
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/run-child-session.ts +16 -2
- package/src/runs/background/run-id-resolver.ts +8 -5
- package/src/runs/background/run-status.ts +21 -16
- package/src/runs/background/runner-child-launch.ts +1 -0
- package/src/runs/background/runner-http-dispatcher.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +256 -61
- package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
- package/src/runs/background/subagent-runner.ts +32 -12
- package/src/runs/background/subagent-wait.ts +38 -19
- package/src/runs/background/terminal-run-index.ts +46 -1
- package/src/runs/background/wait-completions.ts +1 -0
- package/src/runs/background/wait-tool.ts +33 -23
- package/src/runs/background/workflow-terminal-proof.ts +39 -22
- package/src/runs/foreground/async-stop-action.ts +48 -22
- package/src/runs/foreground/execution.ts +94 -52
- package/src/runs/foreground/foreground-history.ts +1 -0
- package/src/runs/foreground/subagent-executor.ts +207 -77
- package/src/runs/shared/child-commands.ts +2 -1
- package/src/runs/shared/child-hooks.ts +4 -3
- package/src/runs/shared/child-launch.ts +3 -0
- package/src/runs/shared/child-session.ts +41 -24
- package/src/runs/shared/child-tool-plan.ts +13 -26
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/fork-command-result.ts +10 -0
- package/src/runs/shared/herdr-placed-run.ts +5 -4
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
- package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
- package/src/runs/shared/model-resolution.ts +30 -1
- package/src/runs/shared/nested-events.ts +5 -0
- package/src/runs/shared/parallel-handoff.ts +56 -8
- package/src/runs/shared/parallel-utils.ts +2 -0
- package/src/runs/shared/partial-output.ts +48 -0
- package/src/runs/shared/runner-launcher.ts +25 -0
- package/src/runs/shared/single-output.ts +53 -0
- package/src/runs/shared/structured-output.ts +14 -7
- package/src/runs/shared/subagent-control.ts +3 -3
- package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
- package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
- package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
- package/src/runs/shared/worktree-lock.ts +29 -0
- package/src/runs/shared/worktree.ts +12 -1
- package/src/shared/atomic-json.ts +4 -2
- package/src/shared/edit-distance.ts +33 -0
- package/src/shared/file-lease.ts +74 -0
- package/src/shared/formatters.ts +1 -5
- package/src/shared/model-info.ts +22 -0
- package/src/shared/package-version.ts +17 -0
- package/src/shared/parent-wake.ts +79 -0
- package/src/shared/pruned-fork.ts +7 -1
- package/src/shared/runtime-module-path.ts +19 -0
- package/src/shared/settings-file-lease.ts +36 -0
- package/src/shared/types.ts +36 -2
- package/src/shared/utils.ts +8 -6
- package/src/slash/slash-commands.ts +3 -3
- package/src/slash/subagents-admin.ts +2 -1
- package/src/tui/fleet-native-transcript.ts +2 -0
- package/src/tui/fleet-transcript.ts +12 -3
- package/src/tui/fleet.ts +11 -8
- package/src/tui/render.ts +27 -19
- package/src/tui/subagent-messages.ts +305 -0
- package/src/watchdog/diff-tool.ts +2 -2
- package/src/watchdog/register-main.ts +2 -22
- package/src/watchdog/render.ts +2 -24
- package/src/watchdog/runtime.ts +6 -4
- package/src/watchdog/settings.ts +18 -13
- package/src/watchdog/tool-actions.ts +2 -2
- package/src/workflows/scripted-workflow.ts +20 -6
- package/src/workflows/workflow-resources.ts +11 -0
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
|
+
import * as os from "node:os";
|
|
4
5
|
import * as path from "node:path";
|
|
5
6
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
6
7
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
8
|
import { getProjectSubagentsDir } from "../../shared/artifacts.ts";
|
|
8
9
|
import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
|
|
10
|
+
import { withFileLease } from "../../shared/file-lease.ts";
|
|
9
11
|
import { shortenPath } from "../../shared/formatters.ts";
|
|
10
12
|
import type { AsyncStatus, Details, ExtensionConfig } from "../../shared/types.ts";
|
|
11
13
|
import type { SubagentParamsLike } from "../foreground/subagent-executor.ts";
|
|
@@ -18,6 +20,9 @@ import { normalizeWorktreeBaseRef } from "../shared/worktree.ts";
|
|
|
18
20
|
import { deepFreezeWorkflowArgs, normalizeWorkflowArgs } from "../../workflows/workflow-resources.ts";
|
|
19
21
|
import { readMission, resolveMissionStoreLocation, validateMissionId } from "../../missions/store.ts";
|
|
20
22
|
|
|
23
|
+
import { calendarDateAfter, latestCalendarOccurrence, nextCalendarOccurrence, normalizeCalendarRule, restoreCalendarTrigger, type CalendarTrigger } from "./calendar-schedule.ts";
|
|
24
|
+
import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
|
|
25
|
+
|
|
21
26
|
export const SCHEDULED_RUN_ACTIONS = [
|
|
22
27
|
"schedule.create",
|
|
23
28
|
"schedule.list",
|
|
@@ -41,7 +46,8 @@ export type ScheduledRunAction = typeof SCHEDULED_RUN_ACTIONS[number];
|
|
|
41
46
|
export type ScheduleRunState = "running" | "skipped" | "missed" | "completed" | "failed_launch" | "failed_run";
|
|
42
47
|
export type ScheduleTrigger =
|
|
43
48
|
| { kind: "once"; at: string; nextRunAt?: string }
|
|
44
|
-
| { kind: "interval"; every: string; everyMs: number; anchorAt: string; nextRunAt: string }
|
|
49
|
+
| { kind: "interval"; every: string; everyMs: number; anchorAt: string; nextRunAt: string }
|
|
50
|
+
| CalendarTrigger;
|
|
45
51
|
export type ScheduleTarget = { workflowScript: string; args: Record<string, unknown>; baseRef?: string; missionId?: string };
|
|
46
52
|
|
|
47
53
|
export interface ScheduleRecord {
|
|
@@ -88,6 +94,7 @@ type ScheduledRunManagerDeps = {
|
|
|
88
94
|
randomId?: () => string;
|
|
89
95
|
resolveCapabilityCeiling?: (sessionId: string) => ResolvedSubagentCapabilityCeiling | undefined;
|
|
90
96
|
timers?: ScheduledRunTimers;
|
|
97
|
+
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
91
98
|
};
|
|
92
99
|
|
|
93
100
|
export function isScheduledRunAction(action: unknown): action is ScheduledRunAction {
|
|
@@ -230,6 +237,18 @@ function resolveSharedGitConfigRoot(projectCwd: string): string | undefined {
|
|
|
230
237
|
return undefined;
|
|
231
238
|
}
|
|
232
239
|
|
|
240
|
+
// In the home directory the project config dir is the user's own Pi config dir,
|
|
241
|
+
// which may be a symlink to another disk.
|
|
242
|
+
function resolveHomeConfigRoot(projectPath: string): string | undefined {
|
|
243
|
+
const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
|
|
244
|
+
try {
|
|
245
|
+
if (!samePath(fs.realpathSync.native(home), projectPath)) return undefined;
|
|
246
|
+
return fs.realpathSync.native(path.join(home, getConfigDirName()));
|
|
247
|
+
} catch {
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
233
252
|
function assertScheduleRoot(root: string, projectCwd: string | undefined, create: boolean): void {
|
|
234
253
|
if (!projectCwd) {
|
|
235
254
|
if (create) fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
@@ -249,9 +268,12 @@ function assertScheduleRoot(root: string, projectCwd: string | undefined, create
|
|
|
249
268
|
existing = parent;
|
|
250
269
|
}
|
|
251
270
|
const existingPath = fs.realpathSync.native(existing);
|
|
252
|
-
const
|
|
271
|
+
const withinProject = pathWithin(projectPath, existingPath);
|
|
272
|
+
const sharedGitConfigRoot = withinProject ? undefined : resolveSharedGitConfigRoot(projectCwd);
|
|
273
|
+
const homeConfigRoot = withinProject ? undefined : resolveHomeConfigRoot(projectPath);
|
|
253
274
|
const isTrustedPath = (candidate: string): boolean => pathWithin(projectPath, candidate)
|
|
254
|
-
|| (sharedGitConfigRoot !== undefined && pathWithin(sharedGitConfigRoot, candidate))
|
|
275
|
+
|| (sharedGitConfigRoot !== undefined && pathWithin(sharedGitConfigRoot, candidate))
|
|
276
|
+
|| (homeConfigRoot !== undefined && pathWithin(homeConfigRoot, candidate));
|
|
255
277
|
if (!isTrustedPath(existingPath)) throw new Error(`Project schedule root '${root}' resolves outside the real project.`);
|
|
256
278
|
if (!create) return;
|
|
257
279
|
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
@@ -318,6 +340,8 @@ function parseSchedule(value: unknown, file: string): ScheduleRecord {
|
|
|
318
340
|
if (typeof record.trigger.at !== "string" || (record.trigger.nextRunAt !== undefined && typeof record.trigger.nextRunAt !== "string")) throw new Error(`Schedule record '${file}' has an invalid one-shot trigger.`);
|
|
319
341
|
} else if (record.trigger.kind === "interval") {
|
|
320
342
|
if (typeof record.trigger.every !== "string" || typeof record.trigger.everyMs !== "number" || typeof record.trigger.anchorAt !== "string" || typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid interval trigger.`);
|
|
343
|
+
} else if (record.trigger.kind === "calendar") {
|
|
344
|
+
restoreCalendarTrigger(record.trigger); // Validate without rewriting during read-only list/show.
|
|
321
345
|
} else throw new Error(`Schedule record '${file}' has an unsupported trigger.`);
|
|
322
346
|
if (record.sessionOnly !== undefined && typeof record.sessionOnly !== "boolean") throw new Error(`Schedule record '${file}' has invalid sessionOnly.`);
|
|
323
347
|
if (record.quiet !== undefined && typeof record.quiet !== "boolean") throw new Error(`Schedule record '${file}' has invalid quiet.`);
|
|
@@ -381,13 +405,28 @@ class ScheduleStore {
|
|
|
381
405
|
return value.runs as ScheduleRunRecord[];
|
|
382
406
|
}
|
|
383
407
|
|
|
408
|
+
/** The run's own receipt; it is written before history.json and is never trimmed. */
|
|
409
|
+
getRun(id: string, runId: string): ScheduleRunRecord | undefined {
|
|
410
|
+
if (!SCHEDULE_ID.test(runId)) throw new Error(`Invalid schedule run id '${runId}'.`);
|
|
411
|
+
const file = path.join(scheduleDir(this.root, id, false, this.projectCwd), "runs", `${runId}.json`);
|
|
412
|
+
if (!fs.existsSync(file)) return undefined;
|
|
413
|
+
const run = readJson(file, "schedule run") as ScheduleRunRecord;
|
|
414
|
+
if (run?.id !== runId || run.scheduleId !== id) throw new Error(`Schedule run '${file}' has invalid fields.`);
|
|
415
|
+
return run;
|
|
416
|
+
}
|
|
417
|
+
|
|
384
418
|
writeRun(schedule: ScheduleRecord, run: ScheduleRunRecord, event: string): void {
|
|
385
419
|
const dir = scheduleDir(this.root, schedule.id, true, this.projectCwd);
|
|
386
420
|
writePrivateAtomicJson(path.join(dir, "runs", `${run.id}.json`), run);
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
421
|
+
// Sessions sharing this project update history.json from their own snapshots.
|
|
422
|
+
withFileLease(path.join(dir, "history.json"), () => {
|
|
423
|
+
// An earlier update may have timed out; a run's own receipt is newer than a "running" entry.
|
|
424
|
+
const earlier = this.history(schedule.id).filter((item) => item.id !== run.id)
|
|
425
|
+
.map((item) => item.state === "running" ? this.getRun(schedule.id, item.id) ?? item : item);
|
|
426
|
+
const runs = [run, ...earlier].slice(0, MAX_HISTORY);
|
|
427
|
+
writePrivateAtomicJson(path.join(dir, "history.json"), { schemaVersion: 1, runs });
|
|
428
|
+
fs.appendFileSync(path.join(dir, "events.jsonl"), `${JSON.stringify({ schemaVersion: 1, timestamp: new Date().toISOString(), event, scheduleId: schedule.id, runId: run.id, state: run.state })}\n`, { encoding: "utf-8", mode: 0o600 });
|
|
429
|
+
});
|
|
391
430
|
}
|
|
392
431
|
|
|
393
432
|
appendEvent(schedule: ScheduleRecord, event: string): void {
|
|
@@ -406,11 +445,14 @@ function hasPendingScheduleWork(schedule: ScheduleRecord): boolean {
|
|
|
406
445
|
return schedule.activeRunId !== undefined || schedule.trigger.nextRunAt !== undefined;
|
|
407
446
|
}
|
|
408
447
|
|
|
409
|
-
function nextAfter(trigger: ScheduleTrigger, plannedAt: number, now: number):
|
|
410
|
-
if (trigger.kind === "once") return undefined;
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
448
|
+
function nextAfter(trigger: ScheduleTrigger, plannedAt: number, now: number): ScheduleTrigger {
|
|
449
|
+
if (trigger.kind === "once") return { ...trigger, nextRunAt: undefined };
|
|
450
|
+
if (trigger.kind === "calendar") return {
|
|
451
|
+
...trigger,
|
|
452
|
+
...nextCalendarOccurrence(trigger, Math.max(plannedAt, now), calendarDateAfter(trigger, plannedAt, trigger.nextLocalDate)),
|
|
453
|
+
};
|
|
454
|
+
const next = plannedAt + (Math.floor(Math.max(0, now - plannedAt) / trigger.everyMs) + 1) * trigger.everyMs;
|
|
455
|
+
return { ...trigger, nextRunAt: timestamp(next) };
|
|
414
456
|
}
|
|
415
457
|
|
|
416
458
|
function nextRunAt(schedule: ScheduleRecord): number | undefined {
|
|
@@ -423,8 +465,15 @@ function nextRunAt(schedule: ScheduleRecord): number | undefined {
|
|
|
423
465
|
|
|
424
466
|
function duePlannedAt(schedule: ScheduleRecord, now: number): number | undefined {
|
|
425
467
|
const next = nextRunAt(schedule);
|
|
426
|
-
if (next === undefined || next > now || schedule.catchUp !== "latest"
|
|
427
|
-
|
|
468
|
+
if (next === undefined || next > now || schedule.catchUp !== "latest") return next;
|
|
469
|
+
if (schedule.trigger.kind === "calendar") return Date.parse(latestCalendarOccurrence(schedule.trigger, now, schedule.trigger.nextLocalDate)!.nextRunAt);
|
|
470
|
+
if (schedule.trigger.kind === "interval") return next + Math.floor((now - next) / schedule.trigger.everyMs) * schedule.trigger.everyMs;
|
|
471
|
+
return next;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function triggerLabel(trigger: ScheduleTrigger): string {
|
|
475
|
+
if (trigger.kind === "calendar") return `every ${trigger.every}${trigger.on ? ` (${trigger.on.join(", ")})` : ""} at ${trigger.at} ${trigger.timezone}`;
|
|
476
|
+
return trigger.kind === "once" ? `at ${trigger.at}` : `every ${trigger.every}`;
|
|
428
477
|
}
|
|
429
478
|
|
|
430
479
|
function textResult(text: string, schedules?: ScheduleRecord[], runs?: ScheduleRunRecord[], isError = false): AgentToolResult<Details> {
|
|
@@ -609,8 +658,10 @@ export class ScheduledRunManager {
|
|
|
609
658
|
for (const id of ids) {
|
|
610
659
|
try {
|
|
611
660
|
const schedule = store.get(id);
|
|
612
|
-
const
|
|
613
|
-
|
|
661
|
+
const listed: ScheduleRunRecord | undefined = store.history(id).find((item) => item.asyncId === asyncId) ?? this.activeRun(store, schedule);
|
|
662
|
+
// history.json can lag the run's receipt when its update timed out.
|
|
663
|
+
const run: ScheduleRunRecord | undefined = listed && (store.getRun(id, listed.id) ?? listed);
|
|
664
|
+
if (run?.asyncId !== asyncId || run.state !== "running") continue;
|
|
614
665
|
this.finishRun(store, schedule, run, data.success === true, typeof data.summary === "string" ? data.summary : undefined);
|
|
615
666
|
return;
|
|
616
667
|
} catch (error) {
|
|
@@ -626,13 +677,14 @@ export class ScheduledRunManager {
|
|
|
626
677
|
if (target.error) return textResult(target.error, undefined, undefined, true);
|
|
627
678
|
const at = params.at?.trim();
|
|
628
679
|
const every = params.every?.trim();
|
|
629
|
-
|
|
680
|
+
const calendar = every === "day" || every === "week";
|
|
681
|
+
if (!calendar && Boolean(at) === Boolean(every)) return textResult("schedule.create requires exactly one trigger: at or every.", undefined, undefined, true);
|
|
630
682
|
if (params.overlap !== undefined && params.overlap !== "skip") return textResult("This first recurring slice supports overlap='skip' only.", undefined, undefined, true);
|
|
631
683
|
if (params.catchUp !== undefined && params.catchUp !== "none" && params.catchUp !== "latest") return textResult("catchUp must be 'none' or 'latest'.", undefined, undefined, true);
|
|
632
684
|
if (params.mission !== undefined || params.missionUpdate !== undefined || params.missionStatus !== undefined || params.missionScope !== undefined) return textResult("Schedules accept only an existing missionId; mission creation and updates are unsupported.", undefined, undefined, true);
|
|
633
|
-
if (params.on !== undefined || params.timezone !== undefined
|
|
685
|
+
if (!calendar && (params.on !== undefined || params.timezone !== undefined)) return textResult("on and timezone require every:'day' or every:'week'.", undefined, undefined, true);
|
|
634
686
|
if (params.quiet !== undefined && typeof params.quiet !== "boolean") return textResult("quiet must be a boolean.", undefined, undefined, true);
|
|
635
|
-
if (at && params.quiet === true) return textResult("quiet is only supported for recurring schedules.", undefined, undefined, true);
|
|
687
|
+
if (!calendar && at && params.quiet === true) return textResult("quiet is only supported for recurring schedules.", undefined, undefined, true);
|
|
636
688
|
const sessionOnly = params.sessionOnly === true;
|
|
637
689
|
if (sessionOnly && params.cwd !== undefined && !samePath(params.cwd, ctx.cwd)) return textResult("sessionOnly schedules cannot use an explicit cross-project cwd.", undefined, undefined, true);
|
|
638
690
|
const ownerSessionFile = sessionOnly ? ctx.sessionManager.getSessionFile() : undefined;
|
|
@@ -649,7 +701,10 @@ export class ScheduledRunManager {
|
|
|
649
701
|
if (store.ids().includes(id)) return textResult(`Schedule '${id}' already exists.`, undefined, undefined, true);
|
|
650
702
|
const now = this.now();
|
|
651
703
|
let trigger: ScheduleTrigger;
|
|
652
|
-
if (
|
|
704
|
+
if (calendar) {
|
|
705
|
+
const rule = normalizeCalendarRule({ every, at, on: params.on, timezone: params.timezone });
|
|
706
|
+
trigger = { kind: "calendar", ...rule, ...nextCalendarOccurrence(rule, now) };
|
|
707
|
+
} else if (at) {
|
|
653
708
|
const planned = parseScheduledRunTime(at, now);
|
|
654
709
|
trigger = { kind: "once", at, nextRunAt: timestamp(planned) };
|
|
655
710
|
} else {
|
|
@@ -669,14 +724,14 @@ export class ScheduledRunManager {
|
|
|
669
724
|
...(params.timeoutMs === undefined ? {} : { timeoutMs: params.timeoutMs }),
|
|
670
725
|
paused: false,
|
|
671
726
|
...(sessionOnly ? { sessionOnly: true, ownerSessionFile: path.resolve(ownerSessionFile!) } : {}),
|
|
672
|
-
...(trigger.kind
|
|
727
|
+
...(trigger.kind !== "once" && params.quiet === true ? { quiet: true } : {}),
|
|
673
728
|
createdAt: timestamp(now),
|
|
674
729
|
updatedAt: timestamp(now),
|
|
675
730
|
};
|
|
676
731
|
store.write(schedule);
|
|
677
732
|
store.appendEvent(schedule, "schedule.created");
|
|
678
733
|
this.arm(schedule, store);
|
|
679
|
-
return textResult(`Created schedule ${id}.\nName: ${schedule.name}\nTrigger: ${
|
|
734
|
+
return textResult(`Created schedule ${id}.\nName: ${schedule.name}\nTrigger: ${triggerLabel(trigger)}\nSession only: ${schedule.sessionOnly === true ? "yes" : "no"}\nQuiet: ${schedule.quiet === true ? "yes" : "no"}\nNext: ${schedule.trigger.nextRunAt}\nTarget: ${targetLabel(schedule.target)}${schedule.target.missionId === undefined ? "" : `\nMission: ${schedule.target.missionId}`}`, [schedule]);
|
|
680
735
|
}
|
|
681
736
|
|
|
682
737
|
private list(): AgentToolResult<Details> {
|
|
@@ -687,7 +742,7 @@ export class ScheduledRunManager {
|
|
|
687
742
|
|
|
688
743
|
private show(params: SubagentParamsLike): AgentToolResult<Details> {
|
|
689
744
|
const schedule = this.resolve(params);
|
|
690
|
-
return textResult([`Schedule: ${schedule.id}`, `Name: ${schedule.name}`, `State: ${schedule.paused ? "paused" : schedule.activeRunId ? "running" : "scheduled"}`, `Session only: ${schedule.sessionOnly === true ? "yes" : "no"}`, `Quiet: ${schedule.quiet === true ? "yes" : "no"}`, `Target: ${targetLabel(schedule.target)}`, schedule.target.missionId === undefined ? undefined : `Mission: ${schedule.target.missionId}`, `CWD: ${shortenPath(schedule.cwd)}`, `Next: ${schedule.trigger.nextRunAt ?? "none"}`, `Catch up: ${schedule.catchUp}`, schedule.activeRunId ? `Active run: ${schedule.activeRunId}` : undefined].filter(Boolean).join("\n"), [schedule]);
|
|
745
|
+
return textResult([`Schedule: ${schedule.id}`, `Name: ${schedule.name}`, `State: ${schedule.paused ? "paused" : schedule.activeRunId ? "running" : "scheduled"}`, `Session only: ${schedule.sessionOnly === true ? "yes" : "no"}`, `Quiet: ${schedule.quiet === true ? "yes" : "no"}`, `Target: ${targetLabel(schedule.target)}`, schedule.target.missionId === undefined ? undefined : `Mission: ${schedule.target.missionId}`, `CWD: ${shortenPath(schedule.cwd)}`, `Trigger: ${triggerLabel(schedule.trigger)}`, `Next: ${schedule.trigger.nextRunAt ?? "none"}`, `Catch up: ${schedule.catchUp}`, schedule.activeRunId ? `Active run: ${schedule.activeRunId}` : undefined].filter(Boolean).join("\n"), [schedule]);
|
|
691
746
|
}
|
|
692
747
|
|
|
693
748
|
private history(params: SubagentParamsLike): AgentToolResult<Details> {
|
|
@@ -716,11 +771,17 @@ export class ScheduledRunManager {
|
|
|
716
771
|
return textResult(`Skipped schedule ${schedule.id}: current session is not its owner.`, [schedule]);
|
|
717
772
|
}
|
|
718
773
|
if (params.quiet !== undefined && typeof params.quiet !== "boolean") return textResult("quiet must be a boolean.", undefined, undefined, true);
|
|
774
|
+
const manualTrigger = schedule.trigger;
|
|
719
775
|
const run = await this.launch(store, schedule, this.now(), "manual", false, params.quiet === true);
|
|
720
776
|
const updated = store.get(schedule.id);
|
|
721
777
|
if (run.state === "running") {
|
|
722
778
|
const now = this.now();
|
|
723
|
-
if (updated.trigger.kind === "
|
|
779
|
+
if (updated.trigger.kind === "calendar") {
|
|
780
|
+
if (manualTrigger.kind !== "calendar") throw new Error("Schedule trigger changed during manual launch.");
|
|
781
|
+
const consumed = latestCalendarOccurrence(manualTrigger, now, manualTrigger.nextLocalDate)?.nextRunAt ?? manualTrigger.nextRunAt;
|
|
782
|
+
const advanced = nextAfter(manualTrigger, Date.parse(consumed), now) as CalendarTrigger;
|
|
783
|
+
if (advanced.nextLocalDate > updated.trigger.nextLocalDate) updated.trigger = advanced;
|
|
784
|
+
} else if (updated.trigger.kind === "interval") updated.trigger.nextRunAt = timestamp(now + updated.trigger.everyMs);
|
|
724
785
|
else updated.trigger.nextRunAt = undefined;
|
|
725
786
|
updated.updatedAt = timestamp(now);
|
|
726
787
|
store.write(updated);
|
|
@@ -747,7 +808,7 @@ export class ScheduledRunManager {
|
|
|
747
808
|
const schedule = this.resolve(params);
|
|
748
809
|
const store = this.requireStore();
|
|
749
810
|
if (schedule.activeRunId) {
|
|
750
|
-
const run =
|
|
811
|
+
const run = this.activeRun(store, schedule);
|
|
751
812
|
let terminal = false;
|
|
752
813
|
if (run?.scheduleId === schedule.id && run.state === "running" && run.asyncId && run.asyncDir) {
|
|
753
814
|
const status = readJson(path.join(run.asyncDir, "status.json"), "async status") as Partial<AsyncStatus>;
|
|
@@ -767,17 +828,40 @@ export class ScheduledRunManager {
|
|
|
767
828
|
|
|
768
829
|
private restoreOne(store: ScheduleStore, schedule: ScheduleRecord, notBefore?: number, rearm = true): void {
|
|
769
830
|
if (!scheduleBelongsToSession(schedule, this.requireContext(store))) return;
|
|
831
|
+
if (schedule.trigger.kind === "calendar") {
|
|
832
|
+
const refreshed = restoreCalendarTrigger(schedule.trigger);
|
|
833
|
+
if (JSON.stringify(refreshed) !== JSON.stringify(schedule.trigger)) {
|
|
834
|
+
schedule.trigger = refreshed;
|
|
835
|
+
schedule.updatedAt = timestamp(this.now());
|
|
836
|
+
store.write(schedule);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
770
839
|
if (schedule.activeRunId) {
|
|
771
|
-
const run =
|
|
840
|
+
const run = this.activeRun(store, schedule);
|
|
772
841
|
if (run?.state === "running" && run.asyncId) this.observedAsyncIds.add(run.asyncId);
|
|
773
842
|
const startedAt = run?.startedAt ? Date.parse(run.startedAt) : Number.NaN;
|
|
774
|
-
|
|
843
|
+
const outcome = this.terminalAsyncOutcome(run);
|
|
844
|
+
if (run && outcome) {
|
|
845
|
+
// Restore releases a dead or terminal claim at most once and never re-enters itself. On success it continues
|
|
846
|
+
// to the existing policy code below with the latest record. On failure it arms the schedule from disk, so the
|
|
847
|
+
// next fire retries the release, and the original error propagates unchanged.
|
|
848
|
+
let latest: ScheduleRecord | undefined;
|
|
775
849
|
try {
|
|
776
|
-
|
|
777
|
-
if (["complete", "failed", "stopped", "rejected"].includes(String(status.state))) this.finishRun(store, schedule, run, status.state === "complete", typeof status.error === "string" ? status.error : undefined);
|
|
850
|
+
latest = this.finishRun(store, schedule, run, outcome.success, outcome.error, true) ?? store.find(schedule.id);
|
|
778
851
|
} catch (error) {
|
|
779
|
-
if (
|
|
852
|
+
if (rearm) {
|
|
853
|
+
try {
|
|
854
|
+
const current = store.find(schedule.id);
|
|
855
|
+
if (current) this.arm(current, store, notBefore);
|
|
856
|
+
} catch { /* Keep the release error. */ }
|
|
857
|
+
}
|
|
858
|
+
throw error;
|
|
780
859
|
}
|
|
860
|
+
if (!latest) {
|
|
861
|
+
this.clearTimer(store, schedule.id);
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
schedule = latest;
|
|
781
865
|
}
|
|
782
866
|
if (schedule.activeRunId && (!run || run.state !== "running" || (!run.asyncId && Number.isFinite(startedAt) && startedAt + STALE_LAUNCH_CLAIM_MS <= this.now()))) {
|
|
783
867
|
if (run?.state === "running") {
|
|
@@ -829,9 +913,9 @@ export class ScheduledRunManager {
|
|
|
829
913
|
const schedule = store.find(id);
|
|
830
914
|
if (!schedule) return;
|
|
831
915
|
const now = this.now();
|
|
832
|
-
const planned = schedule.trigger.kind
|
|
833
|
-
const notBefore = planned !== undefined && planned <= now ? Date.parse(nextAfter(schedule.trigger, planned, now)!) : undefined;
|
|
834
|
-
this.restoreOne(store, schedule, notBefore, schedule.trigger.kind
|
|
916
|
+
const planned = schedule.trigger.kind !== "once" ? duePlannedAt(schedule, now) : undefined;
|
|
917
|
+
const notBefore = planned !== undefined && planned <= now ? Date.parse(nextAfter(schedule.trigger, planned, now).nextRunAt!) : undefined;
|
|
918
|
+
this.restoreOne(store, schedule, notBefore, schedule.trigger.kind !== "once");
|
|
835
919
|
} catch (error) {
|
|
836
920
|
console.warn(`[pi-subagents] Scheduled run '${id}' could not be restored after fire failure: ${error instanceof Error ? error.message : String(error)}`);
|
|
837
921
|
}
|
|
@@ -855,12 +939,30 @@ export class ScheduledRunManager {
|
|
|
855
939
|
private async launch(store: ScheduleStore, schedule: ScheduleRecord, planned: number, dueReason: ScheduleRunRecord["dueReason"], advance: boolean, quiet?: boolean): Promise<ScheduleRunRecord> {
|
|
856
940
|
const now = this.now();
|
|
857
941
|
const nextRunAtBeforeClaim = schedule.trigger.nextRunAt;
|
|
942
|
+
const nextLocalDateBeforeClaim = schedule.trigger.kind === "calendar" ? schedule.trigger.nextLocalDate : undefined;
|
|
858
943
|
const run: ScheduleRunRecord = { schemaVersion: 1, id: this.randomId(), scheduleId: schedule.id, plannedAt: timestamp(planned), dueReason, state: "running", startedAt: timestamp(now) };
|
|
944
|
+
if (schedule.activeRunId) {
|
|
945
|
+
let active: ScheduleRunRecord | undefined;
|
|
946
|
+
let outcome: { success: boolean; error?: string } | undefined;
|
|
947
|
+
try {
|
|
948
|
+
active = this.activeRun(store, schedule);
|
|
949
|
+
outcome = this.terminalAsyncOutcome(active);
|
|
950
|
+
} catch (error) {
|
|
951
|
+
console.warn(`[pi-subagents] Could not reconcile active run '${schedule.activeRunId}' of schedule '${schedule.id}': ${error instanceof Error ? error.message : String(error)}`);
|
|
952
|
+
}
|
|
953
|
+
// A dead runner's completion never reaches this schedule, so its claim would skip every later fire.
|
|
954
|
+
if (active && outcome) {
|
|
955
|
+
const released = this.finishRun(store, schedule, active, outcome.success, outcome.error, true);
|
|
956
|
+
// Another session already released or re-claimed that run for this occurrence.
|
|
957
|
+
if (!released) return this.skipLostClaim(store, schedule.id, run, planned, now);
|
|
958
|
+
schedule = released;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
859
961
|
if (schedule.activeRunId) {
|
|
860
962
|
run.state = "skipped";
|
|
861
963
|
run.completedAt = timestamp(now);
|
|
862
964
|
if (advance) {
|
|
863
|
-
schedule.trigger
|
|
965
|
+
schedule.trigger = nextAfter(schedule.trigger, planned, now);
|
|
864
966
|
schedule.updatedAt = timestamp(now);
|
|
865
967
|
store.write(schedule);
|
|
866
968
|
}
|
|
@@ -870,30 +972,50 @@ export class ScheduledRunManager {
|
|
|
870
972
|
}
|
|
871
973
|
const lockPath = path.join(store.directory(schedule.id, true), "active.lock");
|
|
872
974
|
fs.mkdirSync(path.dirname(lockPath), { recursive: true, mode: 0o700 });
|
|
873
|
-
let lock: number;
|
|
975
|
+
let lock: number | undefined;
|
|
874
976
|
try {
|
|
875
977
|
lock = fs.openSync(lockPath, "wx", 0o600);
|
|
876
978
|
fs.writeFileSync(lock, run.id, "utf-8");
|
|
877
979
|
fs.closeSync(lock);
|
|
878
980
|
} catch (error) {
|
|
879
|
-
if (
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
981
|
+
if (lock !== undefined) {
|
|
982
|
+
// An empty or partial claim would make every later launch skip. Keep the
|
|
983
|
+
// descriptor open until the inode check so a replacement owner's lock survives.
|
|
984
|
+
try {
|
|
985
|
+
// Bigint stats: Windows file ids exceed 2^53, so number inodes of nearby files can compare equal.
|
|
986
|
+
const owned = fs.fstatSync(lock, { bigint: true });
|
|
987
|
+
const current = fs.lstatSync(lockPath, { bigint: true });
|
|
988
|
+
if (owned.ino !== 0n && owned.dev === current.dev && owned.ino === current.ino) fs.rmSync(lockPath);
|
|
989
|
+
} catch { /* Preserve the original error. */ }
|
|
990
|
+
try { fs.closeSync(lock); } catch { /* Preserve the original error. */ }
|
|
991
|
+
throw error;
|
|
886
992
|
}
|
|
887
|
-
|
|
888
|
-
this.
|
|
889
|
-
return run;
|
|
993
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
994
|
+
return this.skipLostClaim(store, schedule.id, run, planned, now);
|
|
890
995
|
}
|
|
891
996
|
schedule.activeRunId = run.id;
|
|
892
997
|
schedule.lastRunId = run.id;
|
|
893
|
-
if (advance) schedule.trigger
|
|
998
|
+
if (advance) schedule.trigger = nextAfter(schedule.trigger, planned, now);
|
|
894
999
|
schedule.updatedAt = timestamp(now);
|
|
895
|
-
|
|
896
|
-
|
|
1000
|
+
try {
|
|
1001
|
+
store.write(schedule);
|
|
1002
|
+
store.writeRun(schedule, run, "schedule.run.started");
|
|
1003
|
+
} catch (error) {
|
|
1004
|
+
// No child has launched: release this run's claim, then report the original error.
|
|
1005
|
+
// Another session may already have recovered the claim and launched its own run.
|
|
1006
|
+
try {
|
|
1007
|
+
const latest = store.find(schedule.id);
|
|
1008
|
+
if (latest?.activeRunId === run.id) {
|
|
1009
|
+
latest.activeRunId = undefined;
|
|
1010
|
+
latest.updatedAt = timestamp(this.now());
|
|
1011
|
+
store.write(latest);
|
|
1012
|
+
}
|
|
1013
|
+
if (fs.readFileSync(lockPath, "utf-8") === run.id) fs.rmSync(lockPath);
|
|
1014
|
+
} catch (cleanupError) {
|
|
1015
|
+
console.warn(`[pi-subagents] Could not release schedule claim '${run.id}': ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
|
|
1016
|
+
}
|
|
1017
|
+
throw error;
|
|
1018
|
+
}
|
|
897
1019
|
try {
|
|
898
1020
|
const result = await this.deps.launch(executionParams(schedule, dueReason === "manual" ? quiet === true : schedule.quiet === true), this.requireContext(store), new AbortController().signal);
|
|
899
1021
|
const asyncId = result.details?.asyncId ?? result.details?.runId;
|
|
@@ -905,27 +1027,53 @@ export class ScheduledRunManager {
|
|
|
905
1027
|
this.arm(schedule, store);
|
|
906
1028
|
return run;
|
|
907
1029
|
} catch (error) {
|
|
1030
|
+
// The child is running, so its claim stays until completion.
|
|
1031
|
+
if (run.asyncId) throw new Error(`Scheduled run '${run.id}' attached to async run '${run.asyncId}', but recording it failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
908
1032
|
run.state = "failed_launch";
|
|
909
1033
|
run.completedAt = timestamp(this.now());
|
|
910
1034
|
run.error = error instanceof Error ? error.message : String(error);
|
|
911
1035
|
const latest = store.get(schedule.id);
|
|
912
1036
|
latest.activeRunId = undefined;
|
|
913
|
-
if (!advance && nextRunAtBeforeClaim)
|
|
1037
|
+
if (!advance && nextRunAtBeforeClaim) {
|
|
1038
|
+
if (latest.trigger.kind === "calendar") {
|
|
1039
|
+
// An overlapping timer may have advanced both cursor fields while
|
|
1040
|
+
// this manual attachment was pending. Failure satisfies neither.
|
|
1041
|
+
if (nextLocalDateBeforeClaim !== undefined) {
|
|
1042
|
+
latest.trigger.nextLocalDate = nextLocalDateBeforeClaim;
|
|
1043
|
+
latest.trigger.nextRunAt = nextRunAtBeforeClaim;
|
|
1044
|
+
}
|
|
1045
|
+
} else latest.trigger.nextRunAt = nextRunAtBeforeClaim;
|
|
1046
|
+
}
|
|
914
1047
|
latest.updatedAt = timestamp(this.now());
|
|
915
1048
|
store.write(latest);
|
|
916
|
-
store.writeRun(latest, run, "schedule.run.failed");
|
|
917
1049
|
fs.rmSync(lockPath, { force: true });
|
|
918
|
-
|
|
1050
|
+
try {
|
|
1051
|
+
store.writeRun(latest, run, "schedule.run.failed");
|
|
1052
|
+
} finally {
|
|
1053
|
+
this.arm(latest, store);
|
|
1054
|
+
}
|
|
919
1055
|
return run;
|
|
920
1056
|
}
|
|
921
1057
|
}
|
|
922
1058
|
|
|
923
|
-
|
|
1059
|
+
/**
|
|
1060
|
+
* `releaseOnly` releases a dead run's claim and leaves the pending occurrence to the caller: it neither skips nor re-arms it.
|
|
1061
|
+
* It acts only while the schedule on disk still names that run, and returns the record it wrote, or undefined when another
|
|
1062
|
+
* session already released or re-claimed it.
|
|
1063
|
+
*/
|
|
1064
|
+
private finishRun(store: ScheduleStore, schedule: ScheduleRecord, run: ScheduleRunRecord, success: boolean, error?: string, releaseOnly = false): ScheduleRecord | undefined {
|
|
924
1065
|
const now = this.now();
|
|
1066
|
+
if (run.asyncId) this.observedAsyncIds.delete(run.asyncId);
|
|
1067
|
+
if (releaseOnly) {
|
|
1068
|
+
const latest = store.find(schedule.id);
|
|
1069
|
+
if (latest?.activeRunId !== run.id) return undefined;
|
|
1070
|
+
schedule = latest;
|
|
1071
|
+
}
|
|
925
1072
|
const next = nextRunAt(schedule);
|
|
926
|
-
|
|
1073
|
+
let skipped: ScheduleRunRecord | undefined;
|
|
1074
|
+
if (!releaseOnly && next !== undefined && next <= now) {
|
|
927
1075
|
const planned = duePlannedAt(schedule, now)!;
|
|
928
|
-
|
|
1076
|
+
skipped = {
|
|
929
1077
|
schemaVersion: 1,
|
|
930
1078
|
id: this.randomId(),
|
|
931
1079
|
scheduleId: schedule.id,
|
|
@@ -934,19 +1082,51 @@ export class ScheduledRunManager {
|
|
|
934
1082
|
state: "skipped",
|
|
935
1083
|
completedAt: timestamp(now),
|
|
936
1084
|
};
|
|
937
|
-
schedule.trigger
|
|
938
|
-
store.writeRun(schedule, skipped, "schedule.skipped_overlap");
|
|
1085
|
+
schedule.trigger = nextAfter(schedule.trigger, planned, now);
|
|
939
1086
|
}
|
|
940
|
-
if (run.asyncId) this.observedAsyncIds.delete(run.asyncId);
|
|
941
1087
|
run.state = success ? "completed" : "failed_run";
|
|
942
1088
|
run.completedAt = timestamp(now);
|
|
943
1089
|
if (!success && error) run.error = error;
|
|
944
1090
|
schedule.activeRunId = undefined;
|
|
945
1091
|
schedule.updatedAt = timestamp(now);
|
|
946
1092
|
store.write(schedule);
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
1093
|
+
const lockPath = path.join(store.directory(schedule.id), "active.lock");
|
|
1094
|
+
// A released dead run's lock may already belong to another session's newer claim.
|
|
1095
|
+
let holder: string | undefined;
|
|
1096
|
+
if (releaseOnly) try { holder = fs.readFileSync(lockPath, "utf-8"); } catch { /* No readable lock names this run. */ }
|
|
1097
|
+
if (!releaseOnly || holder === run.id) fs.rmSync(lockPath, { force: true });
|
|
1098
|
+
// The schedule is already released; a history.json timeout must not leave it unarmed.
|
|
1099
|
+
try {
|
|
1100
|
+
store.writeRun(schedule, run, success ? "schedule.run.completed" : "schedule.run.failed");
|
|
1101
|
+
if (skipped) store.writeRun(schedule, skipped, "schedule.skipped_overlap");
|
|
1102
|
+
} finally {
|
|
1103
|
+
if (!releaseOnly) this.arm(schedule, store);
|
|
1104
|
+
}
|
|
1105
|
+
return schedule;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
private skipLostClaim(store: ScheduleStore, scheduleId: string, run: ScheduleRunRecord, planned: number, now: number): ScheduleRunRecord {
|
|
1109
|
+
run.state = "skipped";
|
|
1110
|
+
run.completedAt = timestamp(now);
|
|
1111
|
+
// Losing the claim gives this snapshot no authority to change the owner.
|
|
1112
|
+
const latest = store.find(scheduleId);
|
|
1113
|
+
if (!latest) {
|
|
1114
|
+
this.clearTimer(store, scheduleId);
|
|
1115
|
+
return run;
|
|
1116
|
+
}
|
|
1117
|
+
store.writeRun(latest, run, "schedule.skipped_overlap");
|
|
1118
|
+
if (latest.trigger.kind === "once") {
|
|
1119
|
+
this.clearTimer(store, latest.id);
|
|
1120
|
+
} else {
|
|
1121
|
+
// The owner may hold the lock before persisting its cursor. Back off
|
|
1122
|
+
// locally without consuming that pending occurrence on disk.
|
|
1123
|
+
const next = nextRunAt(latest);
|
|
1124
|
+
const notBefore = next !== undefined && next <= now
|
|
1125
|
+
? Date.parse(nextAfter(latest.trigger, duePlannedAt(latest, now) ?? planned, now).nextRunAt!)
|
|
1126
|
+
: undefined;
|
|
1127
|
+
this.arm(latest, store, notBefore);
|
|
1128
|
+
}
|
|
1129
|
+
return run;
|
|
950
1130
|
}
|
|
951
1131
|
|
|
952
1132
|
private recordMissed(store: ScheduleStore, schedule: ScheduleRecord, planned: number, dueReason: ScheduleRunRecord["dueReason"]): ScheduleRunRecord {
|
|
@@ -959,7 +1139,7 @@ export class ScheduledRunManager {
|
|
|
959
1139
|
state: "missed",
|
|
960
1140
|
completedAt: timestamp(this.now()),
|
|
961
1141
|
};
|
|
962
|
-
schedule.trigger
|
|
1142
|
+
schedule.trigger = nextAfter(schedule.trigger, planned, this.now());
|
|
963
1143
|
schedule.updatedAt = timestamp(this.now());
|
|
964
1144
|
store.write(schedule);
|
|
965
1145
|
store.writeRun(schedule, run, "schedule.missed");
|
|
@@ -1004,6 +1184,21 @@ export class ScheduledRunManager {
|
|
|
1004
1184
|
return ctx;
|
|
1005
1185
|
}
|
|
1006
1186
|
|
|
1187
|
+
private activeRun(store: ScheduleStore, schedule: ScheduleRecord): ScheduleRunRecord | undefined {
|
|
1188
|
+
if (!schedule.activeRunId) return undefined;
|
|
1189
|
+
return store.getRun(schedule.id, schedule.activeRunId) ?? store.history(schedule.id).find((run) => run.id === schedule.activeRunId);
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/** Reconciles an attached running run (a dead runner PID becomes failed) and returns its outcome once terminal. */
|
|
1193
|
+
private terminalAsyncOutcome(run: ScheduleRunRecord | undefined): { success: boolean; error?: string } | undefined {
|
|
1194
|
+
if (run?.state !== "running" || !run.asyncDir) return undefined;
|
|
1195
|
+
const status = reconcileAsyncRun(run.asyncDir, { now: this.now, kill: this.deps.kill }).status;
|
|
1196
|
+
if (!status || !["complete", "failed", "stopped", "rejected"].includes(status.state)) return undefined;
|
|
1197
|
+
// Stale-run repair records its reason on the failed steps, not the root status.
|
|
1198
|
+
const error = [status.error, ...(status.steps ?? []).map((step) => step.error)].find((value): value is string => typeof value === "string");
|
|
1199
|
+
return { success: status.state === "complete", error };
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1007
1202
|
private timerKey(store: ScheduleStore, id: string): string {
|
|
1008
1203
|
return `${store.root}\0${id}`;
|
|
1009
1204
|
}
|
|
@@ -5,6 +5,7 @@ import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
|
5
5
|
import { acquireSessionLease } from "../shared/session-lease.ts";
|
|
6
6
|
import { readProcessTerminalCandidate, writeProcessTerminalCandidate, markProcessTerminalCandidateLeaseRelease } from "./process-terminal-candidate.ts";
|
|
7
7
|
import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
|
|
8
|
+
import { currentPidNamespaceScope } from "./pid-namespace.ts";
|
|
8
9
|
import type { DefaultChildSessionFactoryOptions } from "../shared/child-session.ts";
|
|
9
10
|
import type { SubagentRunConfig } from "./subagent-runner.ts";
|
|
10
11
|
|
|
@@ -129,6 +130,8 @@ export async function runConfiguredSubagent(rawConfig: unknown, options: RunnerB
|
|
|
129
130
|
process.once("exit", releaseOnExit);
|
|
130
131
|
try {
|
|
131
132
|
if (config.launchBarrierToken) {
|
|
133
|
+
// Behind a launcher the parent only knows the wrapper's pid; report this runner's own identity first.
|
|
134
|
+
if (config.launcher) writeAtomicJson(startupPath, { state: "identified", token: config.launchBarrierToken, pid: process.pid, pidNamespaceScope: currentPidNamespaceScope() });
|
|
132
135
|
await waitForStartupControl(startupProceedPath, config.launchBarrierToken, "proceed");
|
|
133
136
|
startupCommitted = true;
|
|
134
137
|
try {
|
|
@@ -139,7 +142,7 @@ export async function runConfiguredSubagent(rawConfig: unknown, options: RunnerB
|
|
|
139
142
|
} else if (config.revivalLease) {
|
|
140
143
|
lease = acquireSessionLease(config.revivalLease);
|
|
141
144
|
config.revivalLeaseToken = lease.owner.token;
|
|
142
|
-
writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner });
|
|
145
|
+
writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner, ...(config.launcher ? { pidNamespaceScope: currentPidNamespaceScope() } : {}) });
|
|
143
146
|
await waitForStartupControl(startupAckPath, lease.owner.token, "ack");
|
|
144
147
|
writeAtomicJson(startupPath, { state: "acknowledged", token: lease.owner.token, pid: process.pid });
|
|
145
148
|
await waitForStartupControl(startupConfirmPath, lease.owner.token, "confirm");
|