@hcflabs/pi-herdr-tools 0.0.0-stage → 1.6.7

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.
@@ -0,0 +1,228 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { stat, unlink, writeFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import {
5
+ CURRENT_SESSION_VERSION,
6
+ SessionManager,
7
+ type ExtensionAPI,
8
+ type ExtensionCommandContext,
9
+ type SessionHeader,
10
+ } from "@earendil-works/pi-coding-agent";
11
+ import {
12
+ createHerdrClient,
13
+ herdrCommandFailure,
14
+ withWorktreeLock,
15
+ type HerdrClient,
16
+ type HerdrExecResult,
17
+ } from "@hcflabs/pi-herdr";
18
+ import {
19
+ createWorktree,
20
+ errorMessage,
21
+ launchPiAgent,
22
+ parseCreatedTab,
23
+ prepareWorktreeLaunch,
24
+ requiredString,
25
+ resolveWorkspace,
26
+ worktreeParentWorkspace,
27
+ type HerdrWorkspace,
28
+ } from "./worktree.ts";
29
+
30
+ type SourceContext = HerdrWorkspace & {
31
+ sessionFile: string;
32
+ leafId: string;
33
+ /** False while Pi has not flushed the session yet (no conversation message on disk). */
34
+ persisted: boolean;
35
+ };
36
+
37
+ async function resolveSource(
38
+ commandName: string,
39
+ herdr: HerdrClient<{ cwd: string }>,
40
+ ctx: ExtensionCommandContext,
41
+ ): Promise<SourceContext> {
42
+ if (process.env.HERDR_ENV !== "1") {
43
+ throw new Error(`/${commandName} requires the current Pi session inside Herdr (HERDR_ENV=1).`);
44
+ }
45
+ const requestedPaneId = requiredString(process.env.HERDR_PANE_ID, "HERDR_PANE_ID");
46
+ const currentSessionFile = requiredString(
47
+ ctx.sessionManager.getSessionFile(),
48
+ "Persisted Pi session file",
49
+ );
50
+ const leafId = requiredString(ctx.sessionManager.getLeafId(), "Current Pi session leaf");
51
+ const sessionFile = resolve(currentSessionFile);
52
+ let persisted = true;
53
+ try {
54
+ if (!(await stat(sessionFile)).isFile()) throw new Error(`Persisted Pi session path is not a file: ${sessionFile}`);
55
+ } catch (error) {
56
+ // Pi defers all session-file writes until the first conversation message
57
+ // (user message since 0.99, first assistant reply before), so a fresh
58
+ // session can have live entries but no file on disk.
59
+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error;
60
+ persisted = false;
61
+ }
62
+
63
+ return { sessionFile, leafId, persisted, ...await resolveWorkspace(herdr, ctx.cwd, requestedPaneId) };
64
+ }
65
+
66
+ // Mirror of SessionManager.createBranchedSession for sessions Pi has not
67
+ // flushed to disk yet: serialize the live active path under a fresh header.
68
+ async function writeCloneFromLiveState(
69
+ ctx: ExtensionCommandContext,
70
+ source: SourceContext,
71
+ cwd: string,
72
+ ): Promise<string> {
73
+ const sessionId = randomUUID();
74
+ const timestamp = new Date().toISOString();
75
+ const header: SessionHeader = {
76
+ type: "session",
77
+ version: CURRENT_SESSION_VERSION,
78
+ id: sessionId,
79
+ timestamp,
80
+ cwd,
81
+ parentSession: source.sessionFile,
82
+ };
83
+ const entries = ctx.sessionManager.getBranch(source.leafId);
84
+ if (entries.length === 0) throw new Error("Pi session has no entries to clone.");
85
+ const cloneFile = join(
86
+ ctx.sessionManager.getSessionDir(),
87
+ `${timestamp.replace(/[:.]/g, "-")}_${sessionId}.jsonl`,
88
+ );
89
+ await writeFile(cloneFile, [JSON.stringify(header), ...entries.map((entry) => JSON.stringify(entry))].join("\n") + "\n");
90
+ return cloneFile;
91
+ }
92
+
93
+ async function createBranchedClone(
94
+ ctx: ExtensionCommandContext,
95
+ source: SourceContext,
96
+ cwd: string,
97
+ ): Promise<string> {
98
+ if (!source.persisted) return await writeCloneFromLiveState(ctx, source, cwd);
99
+ const session = SessionManager.open(source.sessionFile, ctx.sessionManager.getSessionDir(), cwd);
100
+ const createdClone = session.createBranchedSession(source.leafId);
101
+ if (!createdClone) throw new Error("Pi did not create a persisted clone session file.");
102
+ const cloneFile = resolve(createdClone);
103
+ try {
104
+ if ((await stat(cloneFile)).isFile()) return cloneFile;
105
+ } catch (error) {
106
+ throw new Error(`Pi clone session file was not created: ${cloneFile}`, { cause: error });
107
+ }
108
+ throw new Error(`Pi clone session path is not a file: ${cloneFile}`);
109
+ }
110
+
111
+ async function discardCloneOrAggregate(cloneFile: string, error: Error): Promise<never> {
112
+ try {
113
+ await unlink(cloneFile);
114
+ } catch (cleanupError) {
115
+ throw new AggregateError(
116
+ [error, cleanupError],
117
+ `${error.message} Clone cleanup also failed for ${cloneFile}: ${errorMessage(cleanupError)}`,
118
+ );
119
+ }
120
+ throw error;
121
+ }
122
+
123
+ const cloneAgentName = () => `clone-${randomUUID().replaceAll("-", "").slice(0, 24)}`;
124
+
125
+ export default function herdrCloneExtension(pi: ExtensionAPI): void {
126
+ const herdr = createHerdrClient<{ cwd: string }>(pi.exec.bind(pi));
127
+
128
+ pi.registerCommand("clone-tab", {
129
+ description: "Clone the current conversation path into a new Herdr tab",
130
+ handler: async (_args, ctx) => {
131
+ const source = await resolveSource("clone-tab", herdr, ctx);
132
+ const mutate = async (): Promise<{ createdTab: HerdrExecResult; cloneFile: string }> => {
133
+ const cloneFile = await createBranchedClone(ctx, source, ctx.cwd);
134
+ const tabCreateArgs = ["tab", "create", "--workspace", source.workspaceId, "--cwd", ctx.cwd, "--no-focus"] as const;
135
+ const createdTab = await herdr.exec(tabCreateArgs, { cwd: ctx.cwd });
136
+ if (createdTab.code !== 0 || createdTab.killed) {
137
+ await discardCloneOrAggregate(cloneFile, new Error(herdrCommandFailure(tabCreateArgs, createdTab)));
138
+ }
139
+ return { createdTab, cloneFile };
140
+ };
141
+ const { createdTab, cloneFile } = source.checkout ? await withWorktreeLock(source.checkout, mutate) : await mutate();
142
+ let tab: ReturnType<typeof parseCreatedTab>;
143
+ try {
144
+ tab = parseCreatedTab(createdTab, source.workspaceId);
145
+ } catch (error) {
146
+ throw new Error(
147
+ `Clone launch could not be confirmed after creating a Herdr tab; retained session ${cloneFile}: ${errorMessage(error)}`,
148
+ { cause: error },
149
+ );
150
+ }
151
+ const { tabId, rootPaneId } = tab;
152
+ const agentName = cloneAgentName();
153
+ await launchPiAgent(herdr, ctx.cwd, {
154
+ action: "Clone",
155
+ name: agentName,
156
+ pane: rootPaneId,
157
+ args: ["--session", cloneFile],
158
+ retained: () => `Herdr tab ${tabId}, root pane ${rootPaneId}, and session ${cloneFile}`,
159
+ });
160
+
161
+ try {
162
+ await herdr.run(["tab", "focus", tabId], { cwd: ctx.cwd });
163
+ } catch (error) {
164
+ ctx.ui.notify(
165
+ `Clone agent ${agentName} started in Herdr tab ${tabId} (root pane ${rootPaneId}), but focus failed: ${errorMessage(error)}`,
166
+ "warning",
167
+ );
168
+ return;
169
+ }
170
+ ctx.ui.notify(
171
+ `Cloned current conversation into Herdr tab ${tabId} (root pane ${rootPaneId}, agent ${agentName}).`,
172
+ "info",
173
+ );
174
+ },
175
+ });
176
+
177
+ pi.registerCommand("clone-worktree", {
178
+ description: "Clone the current conversation into Pi in a new Herdr Git worktree",
179
+ handler: async (_args, ctx) => {
180
+ const source = await resolveSource("clone-worktree", herdr, ctx);
181
+
182
+ // Create the worktree before the clone so the session header can be
183
+ // stamped with the fresh checkout cwd.
184
+ const worktreeCreateArgs = [
185
+ "worktree", "create", "--workspace", await worktreeParentWorkspace(herdr, ctx.cwd, source), "--no-focus",
186
+ ];
187
+ const worktree = await createWorktree(herdr, ctx.cwd, worktreeCreateArgs, "Clone");
188
+ const { workspaceId, tabId, checkoutPath } = worktree;
189
+ const { target, onPaneBusy } = await prepareWorktreeLaunch(herdr, ctx.cwd, worktree);
190
+
191
+ let cloneFile: string;
192
+ try {
193
+ cloneFile = source.checkout
194
+ ? await withWorktreeLock(source.checkout, () => createBranchedClone(ctx, source, checkoutPath))
195
+ : await createBranchedClone(ctx, source, checkoutPath);
196
+ } catch (error) {
197
+ throw new Error(
198
+ `Clone session could not be created for Herdr worktree workspace ${workspaceId} (tab ${tabId}, checkout ${checkoutPath}); retained worktree without a clone session: ${errorMessage(error)}`,
199
+ { cause: error },
200
+ );
201
+ }
202
+ const agentName = cloneAgentName();
203
+ await launchPiAgent(herdr, ctx.cwd, {
204
+ action: "Clone",
205
+ name: agentName,
206
+ pane: target.paneId,
207
+ args: ["--session", cloneFile],
208
+ retained: () => `Herdr workspace ${workspaceId}, tab ${target.tabId}, root pane ${target.paneId}, and session ${cloneFile}`,
209
+ onPaneBusy,
210
+ });
211
+ const targetTabId = target.tabId;
212
+
213
+ try {
214
+ await herdr.run(["tab", "focus", targetTabId], { cwd: ctx.cwd });
215
+ } catch (error) {
216
+ ctx.ui.notify(
217
+ `Clone agent ${agentName} started in Herdr worktree workspace ${workspaceId} (tab ${targetTabId}, checkout ${checkoutPath}), but focus failed: ${errorMessage(error)}`,
218
+ "warning",
219
+ );
220
+ return;
221
+ }
222
+ ctx.ui.notify(
223
+ `Cloned current conversation into Herdr worktree workspace ${workspaceId} (tab ${targetTabId}, checkout ${checkoutPath}, agent ${agentName}).`,
224
+ "info",
225
+ );
226
+ },
227
+ });
228
+ }
@@ -0,0 +1,67 @@
1
+ import { createConfigStore, field, parsers } from "@hcflabs/pi-config-store";
2
+
3
+ export const TOOL_MODES = ["inherit", "all", "read-only", "none"] as const;
4
+ export type BtwToolMode = (typeof TOOL_MODES)[number];
5
+ export type BtwSplit = "right" | "down";
6
+
7
+ export type BtwConfig = {
8
+ autoSubmit: boolean;
9
+ tools: BtwToolMode;
10
+ split: BtwSplit;
11
+ };
12
+
13
+ export const DEFAULT_CONFIG: Readonly<BtwConfig> = Object.freeze({
14
+ autoSubmit: false,
15
+ tools: "inherit",
16
+ split: "right",
17
+ });
18
+
19
+ export function formatConfig(config: BtwConfig): string {
20
+ return [
21
+ `auto-submit: ${config.autoSubmit ? "on" : "off"}`,
22
+ `tools: ${config.tools}`,
23
+ `split: ${config.split}`,
24
+ ].join(" · ");
25
+ }
26
+
27
+ export const CONFIG_COMMAND_USAGE =
28
+ "/btw config [auto-submit on|off | tools inherit|all|read-only|none | split right|down | reset]";
29
+
30
+ export function applyConfigCommand(current: BtwConfig, input: string): BtwConfig {
31
+ const [key, value, ...extra] = input.split(/\s+/);
32
+ if (!key || !value || extra.length > 0) throw new Error(CONFIG_COMMAND_USAGE);
33
+ const config = { ...current };
34
+
35
+ switch (key) {
36
+ case "auto-submit":
37
+ if (value !== "on" && value !== "off") throw new Error(CONFIG_COMMAND_USAGE);
38
+ config.autoSubmit = value === "on";
39
+ break;
40
+ case "tools":
41
+ if (!TOOL_MODES.includes(value as BtwToolMode)) {
42
+ throw new Error(CONFIG_COMMAND_USAGE);
43
+ }
44
+ config.tools = value as BtwToolMode;
45
+ break;
46
+ case "split":
47
+ if (value !== "right" && value !== "down") throw new Error(CONFIG_COMMAND_USAGE);
48
+ config.split = value;
49
+ break;
50
+ default:
51
+ throw new Error(CONFIG_COMMAND_USAGE);
52
+ }
53
+
54
+ return config;
55
+ }
56
+
57
+ export function createBtwConfigStore(agentDir?: string) {
58
+ return createConfigStore({
59
+ extensionId: "pi-herdr-btw",
60
+ agentDir,
61
+ fields: {
62
+ autoSubmit: field(parsers.boolean(), DEFAULT_CONFIG.autoSubmit),
63
+ tools: field(parsers.oneOf(TOOL_MODES), DEFAULT_CONFIG.tools),
64
+ split: field(parsers.oneOf(["right", "down"] as const), DEFAULT_CONFIG.split),
65
+ },
66
+ });
67
+ }
@@ -0,0 +1,282 @@
1
+ import {
2
+ chmod,
3
+ lstat,
4
+ mkdir,
5
+ mkdtemp,
6
+ readFile,
7
+ readdir,
8
+ realpath,
9
+ rename,
10
+ rm,
11
+ utimes,
12
+ writeFile,
13
+ } from "node:fs/promises";
14
+ import { tmpdir } from "node:os";
15
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
16
+ import { isBtwPayload, type BtwPayload } from "./core.ts";
17
+ import { MERGE_REQUEST_FILE, type MergeRequest } from "./merge.ts";
18
+
19
+ const PAYLOAD_FILE = "payload.json";
20
+ const LAUNCH_PREFIX = "launch-";
21
+ const MAX_MAILBOX_FILE_BYTES = 128 * 1024;
22
+ const MAX_PAYLOAD_FILE_BYTES = 64 * 1024 * 1024;
23
+
24
+ const STALE_CONTEXT_MS = 24 * 60 * 60 * 1000;
25
+
26
+ function currentUid(): number | undefined {
27
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
28
+ }
29
+
30
+ function assertOwnedByCurrentUser(uid: number, path: string): void {
31
+ const expectedUid = currentUid();
32
+ if (expectedUid !== undefined && uid !== expectedUid) {
33
+ throw new Error(`Refusing /btw context path not owned by the current user: ${path}`);
34
+ }
35
+ }
36
+
37
+ function assertPrivateMode(mode: number, path: string): void {
38
+ if (process.platform !== "win32" && (mode & 0o077) !== 0) {
39
+ throw new Error(`Refusing /btw context path with group or other permissions: ${path}`);
40
+ }
41
+ }
42
+
43
+ function isInside(root: string, candidate: string): boolean {
44
+ const child = relative(root, candidate);
45
+ return child !== "" && !child.startsWith("..") && !isAbsolute(child);
46
+ }
47
+
48
+ function isMissing(error: unknown): boolean {
49
+ return !!error && typeof error === "object" && (error as NodeJS.ErrnoException).code === "ENOENT";
50
+ }
51
+
52
+ function defaultContextRoot(): string {
53
+ const uid = currentUid();
54
+ return join(tmpdir(), uid === undefined ? "pi-herdr-btw" : `pi-herdr-btw-${uid}`);
55
+ }
56
+
57
+ export class ContextStore {
58
+ readonly root: string;
59
+ private canonicalRoot: string | undefined;
60
+
61
+ constructor(root = defaultContextRoot()) {
62
+ this.root = resolve(root);
63
+ }
64
+
65
+ async create(payload: BtwPayload): Promise<string> {
66
+ const root = await this.ensureRoot();
67
+ const serialized = `${JSON.stringify(payload)}\n`;
68
+ if (Buffer.byteLength(serialized, "utf8") > MAX_PAYLOAD_FILE_BYTES) {
69
+ throw new Error("Refusing oversized /btw context payload");
70
+ }
71
+ const launchDir = await mkdtemp(join(root, LAUNCH_PREFIX));
72
+ try {
73
+ await chmod(launchDir, 0o700);
74
+
75
+ const payloadPath = join(launchDir, PAYLOAD_FILE);
76
+ await writeFile(payloadPath, serialized, {
77
+ encoding: "utf8",
78
+ flag: "wx",
79
+ mode: 0o600,
80
+ });
81
+ return payloadPath;
82
+ } catch (error) {
83
+ await rm(launchDir, { recursive: true, force: true }).catch(() => undefined);
84
+ throw error;
85
+ }
86
+ }
87
+
88
+ async read(payloadPath: string): Promise<BtwPayload> {
89
+ const canonicalPath = await this.validateLaunchFile(payloadPath, PAYLOAD_FILE);
90
+ const parsed: unknown = JSON.parse(await readFile(canonicalPath, "utf8"));
91
+ if (!isBtwPayload(parsed)) {
92
+ throw new Error("Invalid or unsupported /btw context payload");
93
+ }
94
+ return parsed;
95
+ }
96
+
97
+ /** List payload paths for every launch directory currently in the private root. */
98
+ async listLaunchPayloadPaths(): Promise<string[]> {
99
+ const root = await this.ensureRoot();
100
+ const entries = await readdir(root, { withFileTypes: true });
101
+ return entries
102
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith(LAUNCH_PREFIX))
103
+ .map((entry) => join(root, entry.name, PAYLOAD_FILE));
104
+ }
105
+
106
+ async writeMergeRequest(payloadPath: string, request: MergeRequest): Promise<void> {
107
+ await this.writeLaunchFile(payloadPath, MERGE_REQUEST_FILE, request);
108
+ }
109
+
110
+ async readMergeRequest(payloadPath: string): Promise<unknown> {
111
+ return this.readLaunchFile(payloadPath, MERGE_REQUEST_FILE);
112
+ }
113
+
114
+ /** Keep a launch with a request until its parent consumes it. */
115
+ async removeIfNoPendingMerge(payloadPath: string): Promise<boolean> {
116
+ if ((await this.readMergeRequest(payloadPath)) !== undefined) return false;
117
+ await this.remove(payloadPath);
118
+ return true;
119
+ }
120
+
121
+ async remove(payloadPath: string): Promise<void> {
122
+ const launchDir = await this.validateLaunchDir(payloadPath, true);
123
+ if (launchDir) await rm(launchDir, { recursive: true, force: true });
124
+ }
125
+
126
+ /** Refresh launch liveness without modifying mailbox contents. */
127
+ async touch(payloadPath: string): Promise<void> {
128
+ const launchDir = await this.validateLaunchDir(payloadPath, true);
129
+ if (launchDir) {
130
+ const now = new Date();
131
+ await utimes(launchDir, now, now);
132
+ }
133
+ }
134
+
135
+ async removeStale(): Promise<void> {
136
+ const now = Date.now();
137
+ const root = await this.ensureRoot();
138
+ const entries = await readdir(root, { withFileTypes: true });
139
+ // One unsafe or foreign entry must not abort cleanup of the others.
140
+ await Promise.allSettled(
141
+ entries.map(async (entry) => {
142
+ if (!entry.name.startsWith(LAUNCH_PREFIX) || !entry.isDirectory()) return;
143
+ const launchDir = join(root, entry.name);
144
+ const info = await lstat(launchDir).catch(() => undefined);
145
+ if (!info?.isDirectory()) return;
146
+ assertOwnedByCurrentUser(info.uid, launchDir);
147
+ if (info.mtimeMs < now - STALE_CONTEXT_MS) {
148
+ // A heartbeat may have refreshed this launch after the first stat.
149
+ const current = await lstat(launchDir).catch(() => undefined);
150
+ if (
151
+ !current?.isDirectory() ||
152
+ current.dev !== info.dev ||
153
+ current.ino !== info.ino ||
154
+ current.ctimeMs !== info.ctimeMs ||
155
+ current.mtimeMs !== info.mtimeMs
156
+ ) {
157
+ return;
158
+ }
159
+ await rm(launchDir, { recursive: true, force: true });
160
+ }
161
+ }),
162
+ );
163
+ }
164
+
165
+ private async ensureRoot(): Promise<string> {
166
+ if (this.canonicalRoot) return this.canonicalRoot;
167
+
168
+ try {
169
+ await mkdir(this.root, { mode: 0o700 });
170
+ } catch (error) {
171
+ if (!error || typeof error !== "object" || (error as NodeJS.ErrnoException).code !== "EEXIST") {
172
+ throw error;
173
+ }
174
+ }
175
+
176
+ const info = await lstat(this.root);
177
+ if (!info.isDirectory()) {
178
+ throw new Error(`Refusing unsafe /btw context root: ${this.root}`);
179
+ }
180
+ assertOwnedByCurrentUser(info.uid, this.root);
181
+ await chmod(this.root, 0o700);
182
+ const canonicalRoot = await realpath(this.root);
183
+ const canonicalInfo = await lstat(canonicalRoot);
184
+ assertOwnedByCurrentUser(canonicalInfo.uid, canonicalRoot);
185
+ assertPrivateMode(canonicalInfo.mode, canonicalRoot);
186
+ this.canonicalRoot = canonicalRoot;
187
+ return canonicalRoot;
188
+ }
189
+
190
+ private async writeLaunchFile(payloadPath: string, fileName: string, data: unknown): Promise<void> {
191
+ const launchDir = await this.validateLaunchDir(payloadPath, false);
192
+ if (!launchDir) throw new Error(`Missing /btw launch directory: ${payloadPath}`);
193
+ const targetPath = join(launchDir, fileName);
194
+ const temporaryPath = join(launchDir, `.${fileName}.${process.pid}.${Date.now()}.tmp`);
195
+ try {
196
+ await writeFile(temporaryPath, `${JSON.stringify(data)}\n`, {
197
+ encoding: "utf8",
198
+ flag: "wx",
199
+ mode: 0o600,
200
+ });
201
+ await rename(temporaryPath, targetPath);
202
+ } catch (error) {
203
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
204
+ throw error;
205
+ }
206
+ }
207
+
208
+ private async readLaunchFile(payloadPath: string, fileName: string): Promise<unknown> {
209
+ const canonicalPath = await this.validateLaunchFile(payloadPath, fileName);
210
+ if (!canonicalPath) return undefined;
211
+ return JSON.parse(await readFile(canonicalPath, "utf8")) as unknown;
212
+ }
213
+
214
+ private validateLaunchFile(payloadPath: string, fileName: typeof PAYLOAD_FILE): Promise<string>;
215
+ private validateLaunchFile(payloadPath: string, fileName: string): Promise<string | undefined>;
216
+ private async validateLaunchFile(
217
+ payloadPath: string,
218
+ fileName: string,
219
+ ): Promise<string | undefined> {
220
+ const launchDir = await this.validateLaunchDir(payloadPath, false);
221
+ if (!launchDir) throw new Error(`Missing /btw context payload: ${payloadPath}`);
222
+
223
+ const candidate = join(launchDir, fileName);
224
+ let info;
225
+ try {
226
+ info = await lstat(candidate);
227
+ } catch (error) {
228
+ if (fileName !== PAYLOAD_FILE && isMissing(error)) return undefined;
229
+ throw error;
230
+ }
231
+ if (!info.isFile()) {
232
+ throw new Error(`Refusing unsafe /btw context payload: ${candidate}`);
233
+ }
234
+ assertOwnedByCurrentUser(info.uid, candidate);
235
+ assertPrivateMode(info.mode, candidate);
236
+ const maxBytes = fileName === PAYLOAD_FILE ? MAX_PAYLOAD_FILE_BYTES : MAX_MAILBOX_FILE_BYTES;
237
+ if (info.size > maxBytes) {
238
+ throw new Error(`Refusing oversized /btw mailbox file: ${candidate}`);
239
+ }
240
+
241
+ const canonicalPath = await realpath(candidate);
242
+ const root = await this.ensureRoot();
243
+ if (!isInside(root, canonicalPath)) {
244
+ throw new Error(`Refusing /btw context payload outside the private root: ${payloadPath}`);
245
+ }
246
+ return canonicalPath;
247
+ }
248
+
249
+ private async validateLaunchDir(
250
+ payloadPath: string,
251
+ allowMissing: boolean,
252
+ ): Promise<string | undefined> {
253
+ const root = await this.ensureRoot();
254
+ const absolutePayload = resolve(payloadPath);
255
+ const launchDir = dirname(absolutePayload);
256
+ if (basename(absolutePayload) !== PAYLOAD_FILE || !basename(launchDir).startsWith(LAUNCH_PREFIX)) {
257
+ throw new Error(`Refusing invalid /btw context payload path: ${payloadPath}`);
258
+ }
259
+ if (!isInside(root, launchDir)) {
260
+ throw new Error(`Refusing /btw context payload outside the private root: ${payloadPath}`);
261
+ }
262
+
263
+ let info;
264
+ try {
265
+ info = await lstat(launchDir);
266
+ } catch (error) {
267
+ if (allowMissing && isMissing(error)) return undefined;
268
+ throw error;
269
+ }
270
+ if (!info.isDirectory()) {
271
+ throw new Error(`Refusing unsafe /btw launch directory: ${launchDir}`);
272
+ }
273
+ assertOwnedByCurrentUser(info.uid, launchDir);
274
+ assertPrivateMode(info.mode, launchDir);
275
+
276
+ const canonicalLaunchDir = await realpath(launchDir);
277
+ if (!isInside(root, canonicalLaunchDir)) {
278
+ throw new Error(`Refusing /btw launch directory outside the private root: ${launchDir}`);
279
+ }
280
+ return canonicalLaunchDir;
281
+ }
282
+ }