@xzzpig/pi-subagents 0.19.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 +214 -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 +86 -11
- package/docs/configuration.md +68 -7
- package/docs/extension-api.md +37 -12
- package/docs/fork-extensions.md +1 -0
- package/docs/missions.md +48 -17
- package/docs/models.md +7 -3
- package/docs/observability.md +18 -8
- package/docs/tool-reference.md +138 -80
- package/docs/watchdog.md +8 -6
- package/docs/workflows.md +18 -9
- 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 +224 -122
- package/src/api/preflight.ts +50 -5
- package/src/extension/config.ts +24 -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 +134 -145
- package/src/extension/public-execution.ts +3 -0
- package/src/extension/reply-workflow-script.ts +21 -12
- package/src/extension/rpc.ts +12 -7
- package/src/extension/schemas.ts +39 -33
- 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/goal-driver.ts +44 -31
- package/src/missions/store.ts +35 -6
- package/src/profiles/profiles.ts +29 -23
- package/src/runs/background/active-async-capacity.ts +58 -8
- package/src/runs/background/async-execution.ts +231 -44
- package/src/runs/background/async-job-tracker.ts +12 -4
- package/src/runs/background/async-resume.ts +5 -2
- package/src/runs/background/await-async-run.ts +18 -11
- 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/control-channel.ts +43 -0
- 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 +29 -8
- package/src/runs/background/run-id-resolver.ts +8 -5
- package/src/runs/background/run-status.ts +21 -16
- package/src/runs/background/runner-aliases.ts +7 -4
- 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 +282 -72
- package/src/runs/background/stale-run-reconciler.ts +13 -2
- package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
- package/src/runs/background/subagent-runner.ts +75 -16
- 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/command-action.ts +41 -0
- package/src/runs/foreground/execution.ts +109 -58
- package/src/runs/foreground/foreground-history.ts +1 -0
- package/src/runs/foreground/subagent-executor.ts +270 -89
- package/src/runs/shared/child-commands.ts +229 -0
- 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 +131 -40
- package/src/runs/shared/child-tool-plan.ts +14 -27
- package/src/runs/shared/claude-code-adapter.ts +157 -2
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/external-cli-preflight.ts +54 -6
- package/src/runs/shared/external-cli-runner.ts +5 -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 +8 -5
- package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
- package/src/runs/shared/model-resolution.ts +39 -2
- 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 +4 -0
- package/src/runs/shared/partial-output.ts +48 -0
- package/src/runs/shared/run-history.ts +87 -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 +33 -18
- package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
- 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/required-child-extensions.ts +39 -5
- package/src/shared/runtime-module-path.ts +19 -0
- package/src/shared/settings-file-lease.ts +36 -0
- package/src/shared/types.ts +42 -3
- package/src/shared/utils.ts +8 -6
- package/src/slash/slash-commands.ts +3 -3
- package/src/slash/subagent-cost.ts +9 -5
- 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 +28 -20
- 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-receipt.ts +2 -2
- package/src/workflows/workflow-resources.ts +18 -4
|
@@ -57,6 +57,8 @@ export interface WorktreeSetup {
|
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
export interface WorktreeInfo {
|
|
60
|
+
/** Canonical parent captured at allocation; never re-resolve this evidence later. */
|
|
61
|
+
recordedBaseDir?: string;
|
|
60
62
|
path: string;
|
|
61
63
|
agentCwd: string;
|
|
62
64
|
branch: string;
|
|
@@ -80,6 +82,7 @@ export interface WorktreeDiff {
|
|
|
80
82
|
}
|
|
81
83
|
|
|
82
84
|
export interface WorktreeCleanupTask {
|
|
85
|
+
recordedBaseDir?: string;
|
|
83
86
|
index: number;
|
|
84
87
|
path: string;
|
|
85
88
|
branch: string;
|
|
@@ -945,9 +948,11 @@ async function createNativeWorktree(
|
|
|
945
948
|
if (branch.status !== 1 || pathExists) throw new Error(`worktree path or branch already exists: ${worktreePath}, ${naming.requestedBranch}`);
|
|
946
949
|
tx.attempt(index, naming.requestedBranch, worktreePath);
|
|
947
950
|
ensureProjectWorktreeDir(dedicatedRoot, toplevel);
|
|
951
|
+
const recordedBaseDir = normalizeComparableCwd(path.dirname(worktreePath));
|
|
948
952
|
await tx.git(toplevel, ["worktree", "add", worktreePath, "-b", naming.requestedBranch, baseCommit]);
|
|
949
953
|
const worktree: WorktreeInfo = {
|
|
950
954
|
path: worktreePath,
|
|
955
|
+
recordedBaseDir,
|
|
951
956
|
agentCwd: worktreePath,
|
|
952
957
|
branch: naming.requestedBranch,
|
|
953
958
|
index,
|
|
@@ -1026,6 +1031,7 @@ async function createWorktrunkWorktree(
|
|
|
1026
1031
|
if (returnedHead !== baseCommit) throw new Error("Worktrunk provisioning returned a worktree at a different base commit");
|
|
1027
1032
|
const worktree: WorktreeInfo = {
|
|
1028
1033
|
path: worktreePath,
|
|
1034
|
+
recordedBaseDir: normalizeComparableCwd(path.dirname(worktreePath)),
|
|
1029
1035
|
agentCwd: cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath,
|
|
1030
1036
|
branch: naming.requestedBranch,
|
|
1031
1037
|
index,
|
|
@@ -1189,6 +1195,7 @@ function cleanupSingleWorktree(
|
|
|
1189
1195
|
branch: worktree.branch,
|
|
1190
1196
|
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1191
1197
|
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
1198
|
+
...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
|
|
1192
1199
|
worktreeRemoved: false,
|
|
1193
1200
|
branchRemoved: false,
|
|
1194
1201
|
preserved: true,
|
|
@@ -1213,6 +1220,7 @@ function cleanupSingleWorktree(
|
|
|
1213
1220
|
branch: worktree.branch,
|
|
1214
1221
|
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1215
1222
|
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
1223
|
+
...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
|
|
1216
1224
|
worktreeRemoved: false,
|
|
1217
1225
|
branchRemoved: false,
|
|
1218
1226
|
preserved: true,
|
|
@@ -1248,6 +1256,7 @@ function cleanupSingleWorktree(
|
|
|
1248
1256
|
branch: worktree.branch,
|
|
1249
1257
|
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1250
1258
|
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
1259
|
+
...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
|
|
1251
1260
|
worktreeRemoved: false,
|
|
1252
1261
|
branchRemoved: false,
|
|
1253
1262
|
preserved: true,
|
|
@@ -1269,6 +1278,7 @@ function cleanupSingleWorktree(
|
|
|
1269
1278
|
branch: worktree.branch,
|
|
1270
1279
|
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1271
1280
|
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
1281
|
+
...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
|
|
1272
1282
|
worktreeRemoved: false,
|
|
1273
1283
|
branchRemoved: false,
|
|
1274
1284
|
preserved: true,
|
|
@@ -1298,6 +1308,7 @@ function cleanupSingleWorktree(
|
|
|
1298
1308
|
branch: worktree.branch,
|
|
1299
1309
|
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1300
1310
|
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
1311
|
+
...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
|
|
1301
1312
|
worktreeRemoved,
|
|
1302
1313
|
branchRemoved,
|
|
1303
1314
|
...(errors.length ? { errors } : {}),
|
|
@@ -1337,7 +1348,7 @@ async function compensateSetup(tx: SetupTransaction): Promise<WorktreeCleanupRep
|
|
|
1337
1348
|
}
|
|
1338
1349
|
const known = setup.worktrees.find((worktree) => worktree.index === attempt.index);
|
|
1339
1350
|
const task: WorktreeCleanupTask = { index: attempt.index, path: attempt.path, branch: attempt.branch,
|
|
1340
|
-
provider: known?.provider ?? "native", naming: known?.naming, worktreeRemoved: false, branchRemoved: false };
|
|
1351
|
+
provider: known?.provider ?? "native", naming: known?.naming, recordedBaseDir: known?.recordedBaseDir, worktreeRemoved: false, branchRemoved: false };
|
|
1341
1352
|
report.tasks.push(task);
|
|
1342
1353
|
try {
|
|
1343
1354
|
if (normalizeComparableCwd(attempt.path) === normalizeComparableCwd(setup.cwd)) throw new Error("Refusing source-checkout removal");
|
|
@@ -39,7 +39,8 @@ function tempBaseName(filePath: string, pid: number, nowMs: number, randomId: st
|
|
|
39
39
|
return `.${createHash("sha256").update(path.basename(filePath)).digest("hex")}${suffix}`;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
/** `beforeRename` runs after the payload is written to its temporary file and before it appears at `filePath`. */
|
|
43
|
+
export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (filePath: string, payload: object, beforeRename?: () => void) => void {
|
|
43
44
|
const fsImpl = options.fs ?? fs;
|
|
44
45
|
const now = options.now ?? Date.now;
|
|
45
46
|
const pid = options.pid ?? process.pid;
|
|
@@ -52,7 +53,7 @@ export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (
|
|
|
52
53
|
const renameRetryDelaysMs = retryRenameErrors ? retryDelaysMs : [];
|
|
53
54
|
const directoryRetryDelaysMs = retryDirectoryErrors ? retryDelaysMs : [];
|
|
54
55
|
const wait = options.wait ?? waitForFileSystemRetry;
|
|
55
|
-
return (filePath: string, payload: object): void => {
|
|
56
|
+
return (filePath: string, payload: object, beforeRename?: () => void): void => {
|
|
56
57
|
runFileSystemOperationWithRetry(() => {
|
|
57
58
|
fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
58
59
|
}, { retryDelaysMs: directoryRetryDelaysMs, wait });
|
|
@@ -63,6 +64,7 @@ export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (
|
|
|
63
64
|
let writeError: unknown;
|
|
64
65
|
try {
|
|
65
66
|
fsImpl.writeFileSync(tempPath, JSON.stringify(payload, null, 2), mode === undefined ? "utf-8" : { encoding: "utf-8", mode });
|
|
67
|
+
beforeRename?.();
|
|
66
68
|
renameWithRetry(fsImpl, tempPath, filePath, renameRetryDelaysMs, wait);
|
|
67
69
|
} catch (error) {
|
|
68
70
|
writeError = error;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export function editDistance(left: string, right: string): number {
|
|
2
|
+
const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
3
|
+
for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
|
|
4
|
+
let diagonal = previous[0]!;
|
|
5
|
+
previous[0] = leftIndex;
|
|
6
|
+
for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
|
|
7
|
+
const above = previous[rightIndex]!;
|
|
8
|
+
previous[rightIndex] = left[leftIndex - 1] === right[rightIndex - 1]
|
|
9
|
+
? diagonal
|
|
10
|
+
: Math.min(diagonal, above, previous[rightIndex - 1]!) + 1;
|
|
11
|
+
diagonal = above;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return previous[right.length]!;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function hasSingleAdjacentTransposition(left: string, right: string): boolean {
|
|
18
|
+
if (left.length !== right.length) return false;
|
|
19
|
+
const mismatch = [...left].findIndex((character, index) => character !== right[index]);
|
|
20
|
+
return mismatch >= 0
|
|
21
|
+
&& left[mismatch] === right[mismatch + 1]
|
|
22
|
+
&& left[mismatch + 1] === right[mismatch]
|
|
23
|
+
&& left.slice(mismatch + 2) === right.slice(mismatch + 2);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The closest candidate that is a likely typo of `requested`, compared case-insensitively. */
|
|
27
|
+
export function closestMatch(requested: string, candidates: Iterable<string>): string | undefined {
|
|
28
|
+
const lower = requested.toLowerCase();
|
|
29
|
+
return [...candidates]
|
|
30
|
+
.map((candidate) => ({ candidate, distance: editDistance(lower, candidate.toLowerCase()) }))
|
|
31
|
+
.filter(({ candidate, distance }) => distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(lower, candidate.toLowerCase()))
|
|
32
|
+
.sort((left, right) => left.distance - right.distance || left.candidate.localeCompare(right.candidate))[0]?.candidate;
|
|
33
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { performance } from "node:perf_hooks";
|
|
6
|
+
import { waitForFileSystemRetry } from "./file-system-retry.ts";
|
|
7
|
+
|
|
8
|
+
type Owner = { token: string; pid: number; hostname: string; processStart?: string };
|
|
9
|
+
|
|
10
|
+
function startIdentity(pid: number): string | undefined {
|
|
11
|
+
if (process.platform !== "linux") return undefined;
|
|
12
|
+
try {
|
|
13
|
+
const raw = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
14
|
+
return raw.slice(raw.lastIndexOf(")") + 1).trim().split(/\s+/)[19];
|
|
15
|
+
} catch { return undefined; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function readOwner(lockPath: string): Owner | undefined {
|
|
19
|
+
try {
|
|
20
|
+
const owner = JSON.parse(fs.readFileSync(path.join(lockPath, "owner.json"), "utf-8"));
|
|
21
|
+
if ((typeof owner.token !== "string" || !/^[A-Za-z0-9-]{1,64}$/.test(owner.token)) || typeof owner.hostname !== "string" || !Number.isSafeInteger(owner.pid) || owner.pid <= 0) return undefined;
|
|
22
|
+
return owner;
|
|
23
|
+
} catch { return undefined; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function deadOwner(owner: Owner): boolean {
|
|
27
|
+
if (owner.hostname !== os.hostname()) return false;
|
|
28
|
+
try { process.kill(owner.pid, 0); }
|
|
29
|
+
catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
|
|
30
|
+
const current = startIdentity(owner.pid);
|
|
31
|
+
return owner.processStart !== undefined && current !== undefined && owner.processStart !== current;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Unknown owners and live processes are never evicted merely because a lock is old. */
|
|
35
|
+
export function tryLease(lockPath: string): (() => void) | undefined {
|
|
36
|
+
const owner: Owner = { token: randomUUID(), pid: process.pid, hostname: os.hostname(), processStart: startIdentity(process.pid) };
|
|
37
|
+
try { fs.mkdirSync(lockPath, { mode: 0o700 }); }
|
|
38
|
+
catch (error) {
|
|
39
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
40
|
+
const previous = readOwner(lockPath);
|
|
41
|
+
if (!previous || !deadOwner(previous)) return undefined;
|
|
42
|
+
// Retain the nonempty old directory as a fence: a delayed reclaimer of
|
|
43
|
+
// this token cannot rename a replacement lease over that destination.
|
|
44
|
+
const retired = `${lockPath}.retired-${previous.token}`;
|
|
45
|
+
try { fs.renameSync(lockPath, retired); }
|
|
46
|
+
catch (error) {
|
|
47
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT" || readOwner(retired)?.token === previous.token) return undefined;
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
if (readOwner(retired)?.token !== previous.token) throw new Error(`Retired lock owner changed during recovery: ${lockPath}`);
|
|
51
|
+
return tryLease(lockPath);
|
|
52
|
+
}
|
|
53
|
+
try { fs.writeFileSync(path.join(lockPath, "owner.json"), JSON.stringify(owner), { flag: "wx", mode: 0o600 }); }
|
|
54
|
+
catch (error) { fs.rmSync(lockPath, { recursive: true, force: true }); throw error; }
|
|
55
|
+
return () => {
|
|
56
|
+
if (readOwner(lockPath)?.token === owner.token) fs.rmSync(lockPath, { recursive: true });
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Hold a lease beside `filePath` for a short synchronous update, waiting at most `waitMs` for another owner. */
|
|
61
|
+
export function withFileLease<T>(filePath: string, action: () => T, waitMs = 200): T {
|
|
62
|
+
const requested = path.resolve(filePath);
|
|
63
|
+
const absolute = path.join(fs.realpathSync.native(path.dirname(requested)), path.basename(requested));
|
|
64
|
+
const lockPath = `${absolute}.write-lock`;
|
|
65
|
+
const deadline = performance.now() + waitMs;
|
|
66
|
+
let release = tryLease(lockPath);
|
|
67
|
+
while (!release) {
|
|
68
|
+
const remaining = deadline - performance.now();
|
|
69
|
+
if (remaining <= 0) throw new Error(`Timed out waiting for another process to finish updating ${absolute}.`);
|
|
70
|
+
waitForFileSystemRetry(Math.min(10, remaining));
|
|
71
|
+
release = tryLease(lockPath);
|
|
72
|
+
}
|
|
73
|
+
try { return action(); } finally { release(); }
|
|
74
|
+
}
|
package/src/shared/formatters.ts
CHANGED
|
@@ -34,13 +34,9 @@ export function formatContextUsage(usage: Pick<TokenUsage, "window" | "windowPea
|
|
|
34
34
|
|
|
35
35
|
export function formatModelThinking(model?: string, thinking?: string): string {
|
|
36
36
|
const parsed = model ? splitKnownThinkingSuffix(model) : undefined;
|
|
37
|
-
|
|
37
|
+
const displayModel = parsed?.baseModel ?? model;
|
|
38
38
|
const explicitThinking = THINKING_LEVELS.find((level) => level === thinking?.trim());
|
|
39
39
|
const displayThinking = parsed?.thinkingSuffix ? parsed.thinkingSuffix.slice(1) : explicitThinking;
|
|
40
|
-
if (displayModel) {
|
|
41
|
-
const slashIdx = displayModel.lastIndexOf("/");
|
|
42
|
-
if (slashIdx !== -1) displayModel = displayModel.slice(slashIdx + 1);
|
|
43
|
-
}
|
|
44
40
|
return [displayModel, displayThinking ? `thinking ${displayThinking}` : undefined].filter(Boolean).join(" · ");
|
|
45
41
|
}
|
|
46
42
|
|
package/src/shared/model-info.ts
CHANGED
|
@@ -80,6 +80,28 @@ export function splitKnownThinkingSuffix(model: string): { baseModel: string; th
|
|
|
80
80
|
};
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
/**
|
|
84
|
+
* Combine an observed model id with the provider that served it into `provider/id`.
|
|
85
|
+
* When the registry is available a known id resolves to its canonical `fullId`, so a
|
|
86
|
+
* provider-local id that repeats its provider (OpenRouter's `openrouter/auto-beta`,
|
|
87
|
+
* full id `openrouter/openrouter/auto-beta`) keeps that full form. Without the
|
|
88
|
+
* registry, an id already qualified for this provider is returned unchanged.
|
|
89
|
+
*/
|
|
90
|
+
export function qualifyModelWithProvider(
|
|
91
|
+
model: string | undefined,
|
|
92
|
+
provider: string | undefined,
|
|
93
|
+
availableModels?: ReadonlyArray<Pick<ModelInfo, "provider" | "id" | "fullId">>,
|
|
94
|
+
): string | undefined {
|
|
95
|
+
if (!model) return undefined;
|
|
96
|
+
if (!provider) return model;
|
|
97
|
+
const exactFullId = availableModels?.find((entry) => entry.provider === provider && entry.fullId === model);
|
|
98
|
+
if (exactFullId) return exactFullId.fullId;
|
|
99
|
+
const idMatch = availableModels?.find((entry) => entry.provider === provider && entry.id === model);
|
|
100
|
+
if (idMatch) return idMatch.fullId;
|
|
101
|
+
if (model.startsWith(`${provider}/`)) return model;
|
|
102
|
+
return `${provider}/${model}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
83
105
|
export function findModelInfo(model: string | undefined, availableModels: ModelInfo[] | undefined, preferredProvider?: string): ModelInfo | undefined {
|
|
84
106
|
if (!model || !availableModels || availableModels.length === 0) return undefined;
|
|
85
107
|
const { baseModel } = splitKnownThinkingSuffix(model);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
const packagePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json");
|
|
6
|
+
|
|
7
|
+
export function readInstalledPackageVersion(): string {
|
|
8
|
+
const parsed = JSON.parse(fs.readFileSync(packagePath, "utf-8")) as { version?: unknown };
|
|
9
|
+
if (typeof parsed.version !== "string" || !parsed.version.trim()) {
|
|
10
|
+
throw new Error(`Invalid package version in '${packagePath}'.`);
|
|
11
|
+
}
|
|
12
|
+
return parsed.version;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Node keeps an imported module for the life of the process, so this stays the
|
|
16
|
+
// version first loaded even after an in-place update and /reload.
|
|
17
|
+
export const loadedPackageVersion = readInstalledPackageVersion();
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
export const PARENT_WAKE_TEXT = "Inspect subagent updates above. Answer pending supervisor requests within your authority. For completed work, read saved results and resume the already-authorized parent task, or report completion. If approval is required, explicitly ask the user. Do not silently yield, rerun completed work, or infer new authorization.";
|
|
4
|
+
// A handled or failed wake prompt emits no agent_start. Past this deadline an idle parent's
|
|
5
|
+
// wake counts as abandoned: its notices are already in the session, only the turn is lost.
|
|
6
|
+
const WAKE_PENDING_MS = 10_000;
|
|
7
|
+
|
|
8
|
+
// Reload replaces extension instances, not Pi's session manager or a wake prompt in preflight.
|
|
9
|
+
// The key and shape are shared with pi-intercom's idle wake: Pi marks a run active only after the
|
|
10
|
+
// prompt's async preflight, so a second extension's wake sent in that gap throws in agent.prompt().
|
|
11
|
+
type WakeReservation = { sessionId: string; sentAt?: number };
|
|
12
|
+
const reservationsSymbol = Symbol.for("pi.idle-wake.v1");
|
|
13
|
+
const wakeGlobal = globalThis as typeof globalThis & { [reservationsSymbol]?: WeakMap<object, WakeReservation> };
|
|
14
|
+
const reservations = wakeGlobal[reservationsSymbol] ?? (wakeGlobal[reservationsSymbol] = new WeakMap<object, WakeReservation>());
|
|
15
|
+
|
|
16
|
+
export interface ParentWake {
|
|
17
|
+
/**
|
|
18
|
+
* pi.sendMessage, except that a turn-triggering message to an idle parent is appended and the
|
|
19
|
+
* turn is started with sendUserMessage. Pi starts a sendMessage-triggered run without
|
|
20
|
+
* before_agent_start (earendil-works/pi#5581), so that run drops every hook-set prompt section.
|
|
21
|
+
* Returns true when the message was appended that way: Pi emits no extension message_start for it.
|
|
22
|
+
*/
|
|
23
|
+
sendMessage(...args: Parameters<ExtensionAPI["sendMessage"]>): boolean;
|
|
24
|
+
/** True from an idle wake until its run starts or the session shuts down. Past the deadline it holds only while the parent is busy, which may still be the wake's preflight (for example compacting). */
|
|
25
|
+
isPending(): boolean;
|
|
26
|
+
bindSession(ctx: Pick<ExtensionContext, "isIdle" | "sessionManager">): void;
|
|
27
|
+
agentStarted(): void;
|
|
28
|
+
sessionShutdown(reason: string | undefined): void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createParentWake(pi: Pick<ExtensionAPI, "sendMessage" | "sendUserMessage">, now: () => number = Date.now): ParentWake {
|
|
32
|
+
let ctx!: Pick<ExtensionContext, "isIdle">;
|
|
33
|
+
// Captured at bind: Pi's ctx throws once stale, which it can be by session_shutdown.
|
|
34
|
+
let session: { manager: object; id: string } | undefined;
|
|
35
|
+
// Look the reservation up on every access: another extension may have created this session's entry.
|
|
36
|
+
const reservation = (): WakeReservation => {
|
|
37
|
+
// Pi can shut an extension down before session_start binds it; an unbound wake reserved nothing.
|
|
38
|
+
if (!session) return { sessionId: "" };
|
|
39
|
+
const current = reservations.get(session.manager);
|
|
40
|
+
if (current?.sessionId === session.id) return current;
|
|
41
|
+
const next = { sessionId: session.id };
|
|
42
|
+
reservations.set(session.manager, next);
|
|
43
|
+
return next;
|
|
44
|
+
};
|
|
45
|
+
const reserved = () => {
|
|
46
|
+
const { sentAt } = reservation();
|
|
47
|
+
return sentAt !== undefined && now() - sentAt < WAKE_PENDING_MS;
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
sendMessage(message, options) {
|
|
51
|
+
if (options?.triggerTurn !== true) {
|
|
52
|
+
pi.sendMessage(message, options);
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
if (!ctx.isIdle()) {
|
|
56
|
+
pi.sendMessage(message, options);
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
pi.sendMessage(message, { triggerTurn: false });
|
|
60
|
+
if (!reserved()) {
|
|
61
|
+
reservation().sentAt = now();
|
|
62
|
+
// Steer queues the wake if another prompt starts the run first.
|
|
63
|
+
pi.sendUserMessage(PARENT_WAKE_TEXT, { deliverAs: "steer" });
|
|
64
|
+
}
|
|
65
|
+
return true;
|
|
66
|
+
},
|
|
67
|
+
isPending: () => reservation().sentAt !== undefined && (reserved() || !ctx.isIdle()),
|
|
68
|
+
bindSession(context) {
|
|
69
|
+
ctx = context;
|
|
70
|
+
session = { manager: context.sessionManager, id: context.sessionManager.getSessionId() };
|
|
71
|
+
},
|
|
72
|
+
agentStarted() {
|
|
73
|
+
reservation().sentAt = undefined;
|
|
74
|
+
},
|
|
75
|
+
sessionShutdown(reason) {
|
|
76
|
+
if (reason !== "reload") reservation().sentAt = undefined;
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -6,6 +6,7 @@ import type { TextContent } from "@earendil-works/pi-ai";
|
|
|
6
6
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { resolveModelCandidate } from "../runs/shared/model-resolution.ts";
|
|
8
8
|
import { splitKnownThinkingSuffix, toModelInfo } from "./model-info.ts";
|
|
9
|
+
import { opencodeSessionHeaders } from "./opencode-session-headers.ts";
|
|
9
10
|
import type { ForkContextConfig } from "./types.ts";
|
|
10
11
|
|
|
11
12
|
const MAX_INHERITED_SESSION_BYTES = 64 * 1024;
|
|
@@ -421,7 +422,7 @@ function splitProviderModel(value: string): { provider: string; id: string } | u
|
|
|
421
422
|
}
|
|
422
423
|
|
|
423
424
|
export async function createPrunedForkSessionWriter(
|
|
424
|
-
ctx: Pick<ExtensionContext, "modelRegistry" | "model">,
|
|
425
|
+
ctx: Pick<ExtensionContext, "modelRegistry" | "model" | "sessionManager">,
|
|
425
426
|
config: ForkContextConfig | undefined,
|
|
426
427
|
signal?: AbortSignal,
|
|
427
428
|
): Promise<(sessionFile: string) => Promise<void>> {
|
|
@@ -435,6 +436,9 @@ export async function createPrunedForkSessionWriter(
|
|
|
435
436
|
if (!named) throw new Error(`Pruned fork model '${config.model}' must resolve to provider/model.`);
|
|
436
437
|
const model = ctx.modelRegistry.find(named.provider, named.id);
|
|
437
438
|
if (!model) throw new Error(`Pruned fork model '${config.model}' was not found as '${baseModel}'.`);
|
|
439
|
+
// OpenCode rejects requests without its session header (400 MissingSessionID).
|
|
440
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
441
|
+
const sessionHeaders = opencodeSessionHeaders(model, sessionId);
|
|
438
442
|
|
|
439
443
|
let sharedSummary: Promise<string> | undefined;
|
|
440
444
|
const summarize: SummaryFunction = async (payload) => {
|
|
@@ -445,6 +449,8 @@ export async function createPrunedForkSessionWriter(
|
|
|
445
449
|
}, {
|
|
446
450
|
maxTokens: Math.min(MAX_SUMMARY_TOKENS, typeof model.maxTokens === "number" && model.maxTokens > 0 ? model.maxTokens : MAX_SUMMARY_TOKENS),
|
|
447
451
|
signal,
|
|
452
|
+
sessionId,
|
|
453
|
+
...(sessionHeaders ? { headers: sessionHeaders } : {}),
|
|
448
454
|
}).result();
|
|
449
455
|
if (response.stopReason === "error" || response.stopReason === "aborted") {
|
|
450
456
|
throw new Error(`Pruned fork summarization stopped with ${response.stopReason}${response.errorMessage ? `: ${response.errorMessage}` : ""}`);
|
|
@@ -16,10 +16,13 @@ export interface RequiredChildExtension {
|
|
|
16
16
|
export interface RegisterRequiredChildExtensionsInput {
|
|
17
17
|
sessionId: string;
|
|
18
18
|
extensions: readonly RequiredChildExtension[];
|
|
19
|
+
/** Reject launches whose runner or machine placement cannot load these extensions, instead of dropping them. */
|
|
20
|
+
requireForAllRunners?: boolean;
|
|
19
21
|
}
|
|
20
22
|
|
|
21
23
|
export interface RequiredChildExtensionRegistration { dispose(): void }
|
|
22
|
-
|
|
24
|
+
/** Registration stamps `requireForAllRunners` on each entry so every carrier of the snapshot retains it. */
|
|
25
|
+
export type RequiredChildExtensionSnapshot = ReadonlyArray<Readonly<RequiredChildExtension & { requireForAllRunners?: true }>>;
|
|
23
26
|
|
|
24
27
|
/** Validate and freeze a snapshot; registration canonicalizes once, while retained launches preserve that identity. */
|
|
25
28
|
export function snapshotRequiredChildExtensions(value: unknown, label = "Required child extensions", canonicalizeFiles = false): RequiredChildExtensionSnapshot {
|
|
@@ -27,11 +30,14 @@ export function snapshotRequiredChildExtensions(value: unknown, label = "Require
|
|
|
27
30
|
const ids = new Set<string>();
|
|
28
31
|
const paths = new Set<string>();
|
|
29
32
|
return Object.freeze(value.map((entry, index) => {
|
|
30
|
-
|
|
33
|
+
// The flag comes from registration, so only serialized snapshots (not registration input) may carry it.
|
|
34
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((key) => key !== "id" && key !== "path" && (canonicalizeFiles || key !== "requireForAllRunners"))) throw new Error(`${label} entry ${index} requires only id and path.`);
|
|
31
35
|
const id = "id" in entry ? entry.id : undefined;
|
|
32
36
|
const rawPath = "path" in entry ? entry.path : undefined;
|
|
37
|
+
const requireForAllRunners = "requireForAllRunners" in entry ? entry.requireForAllRunners : undefined;
|
|
33
38
|
if (typeof id !== "string" || !ID_PATTERN.test(id)) throw new Error(`${label} entry ${index} requires a safe id of at most 128 characters.`);
|
|
34
39
|
if (ids.has(id)) throw new Error(`${label} id '${id}' is duplicated.`);
|
|
40
|
+
if (requireForAllRunners !== undefined && requireForAllRunners !== true) throw new Error(`${label} '${id}' requireForAllRunners must be true when present.`);
|
|
35
41
|
if (typeof rawPath !== "string" || !rawPath.trim() || rawPath.includes("\0") || Buffer.byteLength(rawPath, "utf8") > MAX_PATH_BYTES || (!canonicalizeFiles && !path.isAbsolute(rawPath))) throw new Error(`${label} '${id}' requires ${canonicalizeFiles ? "a" : "an absolute"} non-empty path of at most ${MAX_PATH_BYTES} bytes without NUL.`);
|
|
36
42
|
let extensionPath = rawPath;
|
|
37
43
|
if (canonicalizeFiles) {
|
|
@@ -45,7 +51,7 @@ export function snapshotRequiredChildExtensions(value: unknown, label = "Require
|
|
|
45
51
|
if (paths.has(extensionPath)) throw new Error(`${label} path '${extensionPath}' is duplicated.`);
|
|
46
52
|
ids.add(id);
|
|
47
53
|
paths.add(extensionPath);
|
|
48
|
-
return Object.freeze({ id, path: extensionPath });
|
|
54
|
+
return Object.freeze(requireForAllRunners ? { id, path: extensionPath, requireForAllRunners } : { id, path: extensionPath });
|
|
49
55
|
}));
|
|
50
56
|
}
|
|
51
57
|
|
|
@@ -66,9 +72,11 @@ function registry(): Registry {
|
|
|
66
72
|
|
|
67
73
|
/** Register one immutable host-required extension snapshot for a parent session. */
|
|
68
74
|
export function registerRequiredChildExtensions(input: RegisterRequiredChildExtensionsInput): RequiredChildExtensionRegistration {
|
|
69
|
-
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => key !== "sessionId" && key !== "extensions")) throw new Error("Required child extension registration
|
|
75
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => key !== "sessionId" && key !== "extensions" && key !== "requireForAllRunners")) throw new Error("Required child extension registration accepts only sessionId, extensions, and requireForAllRunners.");
|
|
70
76
|
if (typeof input.sessionId !== "string" || !input.sessionId || input.sessionId.trim() !== input.sessionId || input.sessionId.length > 256 || input.sessionId.includes("\0")) throw new Error("Required child extension registration requires a non-empty trimmed sessionId of at most 256 characters without NUL.");
|
|
71
|
-
|
|
77
|
+
if (input.requireForAllRunners !== undefined && typeof input.requireForAllRunners !== "boolean") throw new Error("Required child extension registration requireForAllRunners must be a boolean.");
|
|
78
|
+
const canonical = snapshotRequiredChildExtensions(input.extensions, "Required child extensions", true);
|
|
79
|
+
const frozen = input.requireForAllRunners ? Object.freeze(canonical.map((entry) => Object.freeze({ ...entry, requireForAllRunners: true as const }))) : canonical;
|
|
72
80
|
const store = registry();
|
|
73
81
|
if (store.bySession.has(input.sessionId)) throw new Error(`Required child extensions are already registered for session '${input.sessionId}'; dispose them first.`);
|
|
74
82
|
store.bySession.set(input.sessionId, frozen);
|
|
@@ -79,3 +87,29 @@ export function resolveRequiredChildExtensions(sessionId: string | undefined): R
|
|
|
79
87
|
if (!sessionId) return EMPTY_SNAPSHOT;
|
|
80
88
|
return registry().bySession.get(sessionId) ?? EMPTY_SNAPSHOT;
|
|
81
89
|
}
|
|
90
|
+
|
|
91
|
+
/** Reject a non-native runner or machine placement when any given snapshot has a `requireForAllRunners` entry. */
|
|
92
|
+
export function assertRequiredChildExtensionsAdmitted(snapshots: ReadonlyArray<RequiredChildExtensionSnapshot | undefined>, launch: { agent: string; runnerType?: string; machine?: string }): void {
|
|
93
|
+
const ids = [...new Set(snapshots.flatMap((snapshot) => snapshot ?? []).filter((entry) => entry.requireForAllRunners).map((entry) => entry.id))];
|
|
94
|
+
if (ids.length === 0) return;
|
|
95
|
+
const route = launch.machine ? `machine '${launch.machine}'` : launch.runnerType !== undefined && launch.runnerType !== "pi" ? `runner.type='${launch.runnerType}'` : undefined;
|
|
96
|
+
if (route) throw new Error(`Agent '${launch.agent}' cannot run on ${route}: the host requires child extensions (${ids.join(", ")}) for every runner, and only local native Pi children load them.`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function hasMandatoryRequiredChildExtensions(snapshot: RequiredChildExtensionSnapshot | undefined): snapshot is RequiredChildExtensionSnapshot {
|
|
100
|
+
return snapshot?.some((entry) => entry.requireForAllRunners) === true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const RETAINED_FILE = "required-child-extensions.json";
|
|
104
|
+
|
|
105
|
+
/** Persist a run's mandatory snapshot so append-step admits against it; writes nothing without a mandatory entry. */
|
|
106
|
+
export function writeRetainedRequiredChildExtensions(asyncDir: string, snapshot: RequiredChildExtensionSnapshot): void {
|
|
107
|
+
if (!hasMandatoryRequiredChildExtensions(snapshot)) return;
|
|
108
|
+
fs.writeFileSync(path.join(asyncDir, RETAINED_FILE), `${JSON.stringify(snapshot)}\n`, { mode: 0o600 });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function readRetainedRequiredChildExtensions(asyncDir: string): RequiredChildExtensionSnapshot | undefined {
|
|
112
|
+
const filePath = path.join(asyncDir, RETAINED_FILE);
|
|
113
|
+
if (!fs.existsSync(filePath)) return undefined;
|
|
114
|
+
return snapshotRequiredChildExtensions(JSON.parse(fs.readFileSync(filePath, "utf-8")), "Retained required child extensions");
|
|
115
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Every extension a sibling runtime module may be published with: compiled `.js` first, source `.ts`. */
|
|
5
|
+
export const RUNTIME_MODULE_EXTENSIONS = [".js", ".ts"] as const;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Which extension a sibling runtime module has on disk now. An in-place package
|
|
9
|
+
* update can swap the `.ts` source layout for the compiled `.js` layout under a
|
|
10
|
+
* running process, so the running module's own extension is not reliable.
|
|
11
|
+
*/
|
|
12
|
+
export function resolveRuntimeModuleExtension(dir: string, basename: string): string {
|
|
13
|
+
return RUNTIME_MODULE_EXTENSIONS.find((extension) => fs.existsSync(path.join(dir, `${basename}${extension}`))) ?? ".js";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Absolute, normalized path to a sibling runtime module that exists on disk. */
|
|
17
|
+
export function resolveRuntimeModulePath(dir: string, basename: string): string {
|
|
18
|
+
return path.normalize(path.join(dir, `${basename}${resolveRuntimeModuleExtension(dir, basename)}`));
|
|
19
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { withFileLease } from "./file-lease.ts";
|
|
4
|
+
|
|
5
|
+
/** Physical file a settings path writes to, following file and directory links (including a dangling file link). */
|
|
6
|
+
export function resolveSettingsWriteTarget(filePath: string): string {
|
|
7
|
+
let targetPath = filePath;
|
|
8
|
+
for (;;) {
|
|
9
|
+
try {
|
|
10
|
+
return fs.realpathSync.native(targetPath);
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
13
|
+
// A trailing separator requires a directory; it cannot name a new settings file.
|
|
14
|
+
if (targetPath.endsWith("/") || targetPath.endsWith(path.sep)) throw error;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// A missing target is allowed only when its physical parent already exists.
|
|
18
|
+
const parentPath = fs.realpathSync.native(path.dirname(targetPath));
|
|
19
|
+
const unresolvedPath = path.join(parentPath, path.basename(targetPath));
|
|
20
|
+
let linkText: string;
|
|
21
|
+
try {
|
|
22
|
+
linkText = fs.readlinkSync(unresolvedPath);
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
25
|
+
return unresolvedPath;
|
|
26
|
+
}
|
|
27
|
+
// Keep link text intact so the filesystem follows directory links before "..".
|
|
28
|
+
targetPath = path.isAbsolute(linkText) ? linkText : `${parentPath}${path.sep}${linkText}`;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Hold the physical settings file's lease for a whole read-modify-write. */
|
|
33
|
+
export function withSettingsFileLease<T>(filePath: string, action: () => T): T {
|
|
34
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
35
|
+
return withFileLease(resolveSettingsWriteTarget(filePath), action);
|
|
36
|
+
}
|