Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(daemon): call pi's own getDefaultSessionDir instead of copying its rule

Gus8f25c4755fac
diff --git a/src/daemon/src/drivers/pi.ts b/src/daemon/src/drivers/pi.ts
index 41cdb80ab..8315bad8a 100644
--- a/src/daemon/src/drivers/pi.ts
+++ b/src/daemon/src/drivers/pi.ts
@@ -136,14 +136,24 @@ export function findPiSessionFile(sessionDir: string, sessionId: string): string
/**
* Resolve the Pi SDK's session directory for `cwd`.
*
- * Prefers the SDK's own `getDefaultSessionDir` when the loaded module actually
- * exposes it. It is NOT part of the vendor package's top-level exports (the
- * barrel re-exports only `SessionManager` from `core/session-manager.js`), so
+ * Prefers the SDK's own `getDefaultSessionDir`. That function is NOT on the
+ * vendor barrel (it enumerates re-exports by name and omits this one), so
* calling it unconditionally throws `sdk.getDefaultSessionDir is not a
- * function` and takes down every Pi resume. When it's absent we reproduce the
- * SDK's own rule (`core/session-manager.js`): `<agentDir>/sessions/--<cwd with
- * the leading separator stripped and remaining separators/colons turned into
- * dashes>--`, rooted at the exported `getAgentDir()` (or `~/.pi/agent`).
+ * function` and takes down every Pi resume — `withSessionDirHelper` in
+ * `piSdkDeps.ts` grafts it on from the deep `core/session-manager.js` module,
+ * which is why it's usually present here despite the barrel gap.
+ *
+ * The fallback reproduces the SDK's rule (`core/session-manager.js`):
+ * `<agentDir>/sessions/--<cwd with the leading separator stripped and
+ * remaining separators/colons turned into dashes>--`, rooted at the exported
+ * `getAgentDir()` (or `~/.pi/agent`). `getAgentDir` is the very function
+ * `session-manager.js` itself imports as `getDefaultAgentDir`, so the two
+ * paths agree today. This copy is the layer that can rot if the vendor
+ * changes its encoding — see the drift note in the plan.
+ *
+ * Unlike the SDK helper this does not create the directory. That's fine:
+ * `SessionManager` mkdirs on its first write, and `findPiSessionFile` treats
+ * a missing dir as "no match" rather than an error.
*/
export function resolvePiSessionDir(
sdk: { getDefaultSessionDir?: (cwd: string) => string; getAgentDir?: () => string },
diff --git a/src/daemon/src/drivers/piSdkDeps.test.ts b/src/daemon/src/drivers/piSdkDeps.test.ts
index 82e590add..d00ee044a 100644
--- a/src/daemon/src/drivers/piSdkDeps.test.ts
+++ b/src/daemon/src/drivers/piSdkDeps.test.ts
@@ -315,3 +315,76 @@ describe("loadPiSdkModule — global-install fallback", () => {
vi.resetModules();
});
});
+
+describe("loadPiSdkModule — grafting the vendor's getDefaultSessionDir", () => {
+ /**
+ * Build a package whose barrel mirrors the real vendor shape: it re-exports
+ * `SessionManager` from `core/session-manager.js` but NOT the sibling
+ * `getDefaultSessionDir` in that same file. This is the layout that made
+ * every Pi resume throw `sdk.getDefaultSessionDir is not a function`.
+ */
+ function writeVendorLikePackage(opts: { withDeepHelper: boolean }): string {
+ const pkgDir = path.join(mkTmp(), "lib", "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(path.join(pkgDir, "dist", "core"), { recursive: true });
+ fs.writeFileSync(
+ path.join(pkgDir, "package.json"),
+ JSON.stringify({ name: "@earendil-works/pi-coding-agent", main: "./dist/index.js" }),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, "dist", "core", "session-manager.js"),
+ [
+ "export const SessionManager = { create: () => 'sm' };",
+ ...(opts.withDeepHelper
+ ? ["export function getDefaultSessionDir(cwd) { return '/vendor-resolved/' + cwd; }"]
+ : []),
+ ].join("\n") + "\n",
+ );
+ // The barrel names its re-exports explicitly and omits the helper.
+ fs.writeFileSync(
+ path.join(pkgDir, "dist", "index.js"),
+ "export { SessionManager } from './core/session-manager.js';\n",
+ );
+ return pkgDir;
+ }
+
+ async function loadFrom(pkgDir: string) {
+ vi.resetModules();
+ vi.doMock("./pi.js", () => ({ resolvePiSdkPackageDir: () => pkgDir }));
+ const fresh = await import("./piSdkDeps.js");
+ const sdk = await fresh.loadPiSdkModule();
+ vi.doUnmock("./pi.js");
+ vi.resetModules();
+ return sdk;
+ }
+
+ it("grafts getDefaultSessionDir from the deep module when the barrel omits it", async () => {
+ const sdk = await loadFrom(writeVendorLikePackage({ withDeepHelper: true }));
+
+ expect(typeof sdk.getDefaultSessionDir).toBe("function");
+ // Came from the vendor's own function, not a reimplementation.
+ expect(sdk.getDefaultSessionDir!("/work/repo")).toBe("/vendor-resolved//work/repo");
+ });
+
+ it("loads without throwing when the deep module has no helper either (leaves the fallback to resolvePiSessionDir)", async () => {
+ const sdk = await loadFrom(writeVendorLikePackage({ withDeepHelper: false }));
+
+ expect(sdk.getDefaultSessionDir).toBeUndefined();
+ // Still a usable SDK — a missing helper must never fail the load.
+ expect(sdk.SessionManager).toBeDefined();
+ });
+
+ it("loads without throwing when core/session-manager.js doesn't exist at all", async () => {
+ const pkgDir = path.join(mkTmp(), "lib", "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(path.join(pkgDir, "dist"), { recursive: true });
+ fs.writeFileSync(
+ path.join(pkgDir, "package.json"),
+ JSON.stringify({ name: "@earendil-works/pi-coding-agent", main: "./dist/index.js" }),
+ );
+ fs.writeFileSync(path.join(pkgDir, "dist", "index.js"), "export const SessionManager = { create: () => 'sm' };\n");
+
+ const sdk = await loadFrom(pkgDir);
+
+ expect(sdk.getDefaultSessionDir).toBeUndefined();
+ expect(sdk.SessionManager).toBeDefined();
+ });
+});
diff --git a/src/daemon/src/drivers/piSdkDeps.ts b/src/daemon/src/drivers/piSdkDeps.ts
index f4a461c87..ba85f87b0 100644
--- a/src/daemon/src/drivers/piSdkDeps.ts
+++ b/src/daemon/src/drivers/piSdkDeps.ts
@@ -24,12 +24,12 @@ export interface PiSdkModule {
continueRecent(cwd: string, sessionDir?: string): unknown;
};
/**
- * The SDK's own path-substitution rule for `<sessionDir>` — mirrors
- * `--${cwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--` in
- * `session-manager.js`. Preferred when present, but NOT part of the vendor
- * package's top-level exports (it lives in `core/session-manager.js`, which
- * the barrel re-exports only `SessionManager` from) — hence optional, with
- * `resolvePiSessionDir` falling back to `getAgentDir` + the same rule.
+ * The SDK's own `<sessionDir>` resolver. Declared in
+ * `core/session-manager.d.ts` and defined in the matching `.js`, but NOT
+ * re-exported by the package barrel (which lists its exports by name and
+ * omits this one) — so it is absent on a plain top-level import. Optional
+ * for that reason. `withSessionDirHelper` grafts it on from the deep module
+ * when it can; `resolvePiSessionDir` reproduces the rule when it can't.
*/
getDefaultSessionDir?(cwd: string, agentDir?: string): string;
/** Root of the SDK's own config dir (`~/.pi/agent`) — this one IS exported. */
@@ -70,7 +70,44 @@ async function importPiSdkFromGlobalInstall(): Promise<PiSdkModule> {
};
const entry = pkg.exports?.["."]?.import ?? pkg.main ?? "./dist/index.js";
const entryPath = path.join(dir, entry);
- return import(pathToFileURL(entryPath).href) as Promise<PiSdkModule>;
+ const barrel = (await import(pathToFileURL(entryPath).href)) as PiSdkModule;
+ return withSessionDirHelper(barrel, entryPath);
+}
+
+/**
+ * Graft the vendor's own `getDefaultSessionDir` onto the barrel module.
+ *
+ * The function is declared in `core/session-manager.d.ts` and defined in the
+ * matching `.js`, but the package's top-level barrel enumerates its re-exports
+ * by name and omits it — so `sdk.getDefaultSessionDir` is undefined on the
+ * module we load. Its body encodes a path-substitution rule (see
+ * `resolvePiSessionDir`) that we'd rather call than reimplement: a duplicated
+ * copy rots silently into a wrong-but-plausible directory, turning a resume
+ * into a fresh session with no error.
+ *
+ * The package's `exports` map only exposes `.` and `./rpc-entry`, so a bare
+ * deep specifier is blocked — but we already load by file URL (global installs
+ * aren't resolvable by name from the daemon), and a file URL bypasses the map.
+ *
+ * Best-effort by design: on any failure (vendor relayout, the file genuinely
+ * moving) we return the barrel untouched and `resolvePiSessionDir` falls back
+ * to reproducing the rule. Never throws — a missing helper must not be the
+ * reason a Pi launch fails.
+ */
+async function withSessionDirHelper(barrel: PiSdkModule, entryPath: string): Promise<PiSdkModule> {
+ if (typeof barrel.getDefaultSessionDir === "function") return barrel;
+ try {
+ const deepPath = path.join(path.dirname(entryPath), "core", "session-manager.js");
+ const deep = (await import(pathToFileURL(deepPath).href)) as {
+ getDefaultSessionDir?: (cwd: string, agentDir?: string) => string;
+ };
+ if (typeof deep.getDefaultSessionDir !== "function") return barrel;
+ // The barrel is a live module namespace object (frozen, read-only) — copy
+ // onto a fresh object rather than mutating it.
+ return { ...barrel, getDefaultSessionDir: deep.getDefaultSessionDir };
+ } catch {
+ return barrel;
+ }
}
/**