pi-agent-swarm 0.0.0 → 0.2.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.
@@ -0,0 +1,124 @@
1
+ type SwarmThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
2
+
3
+ export const SWARM_LAUNCH_ENV_KEYS = [
4
+ "PI_SWARM_INVITE",
5
+ "PI_SWARM_PARENT_SESSION_ID",
6
+ "PI_SWARM_LAUNCH_ID",
7
+ "PI_SWARM_KICKOFF_CAPABILITY",
8
+ "PI_SWARM_CHILD_NAME",
9
+ "PI_SWARM_COLOR",
10
+ "PI_SWARM_ACCEPT_REQUESTS",
11
+ "PI_SWARM_MODEL_PROVIDER",
12
+ "PI_SWARM_MODEL_ID",
13
+ "PI_SWARM_THINKING",
14
+ ] as const;
15
+
16
+ export interface SwarmLaunchEnvelope {
17
+ invite: string;
18
+ parentSessionId: string;
19
+ launchId: string;
20
+ kickoffCapability: string;
21
+ childName?: string;
22
+ childColor?: string;
23
+ acceptsRequests: boolean;
24
+ model?: { provider: string; id: string; thinkingLevel?: SwarmThinkingLevel };
25
+ }
26
+
27
+ const THINKING_LEVELS = new Set<SwarmThinkingLevel>(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
28
+ const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
29
+
30
+ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.env): SwarmLaunchEnvelope | undefined {
31
+ const values = Object.fromEntries(SWARM_LAUNCH_ENV_KEYS.map((key) => [key, environment[key]]));
32
+ for (const key of SWARM_LAUNCH_ENV_KEYS) delete environment[key];
33
+ if (values.PI_SWARM_INVITE === undefined) {
34
+ if (Object.values(values).some((value) => value !== undefined)) {
35
+ throw new Error("Pi Agent Swarm launch envelope is incomplete");
36
+ }
37
+ return undefined;
38
+ }
39
+ const invite = bounded(values.PI_SWARM_INVITE, "invite", 256);
40
+ const parentSessionId = safeId(values.PI_SWARM_PARENT_SESSION_ID, "parent session id");
41
+ const launchId = safeId(values.PI_SWARM_LAUNCH_ID, "launch id");
42
+ const kickoffCapability = safeId(values.PI_SWARM_KICKOFF_CAPABILITY, "kickoff capability");
43
+ const childName = optionalBounded(values.PI_SWARM_CHILD_NAME, "child name", 200);
44
+ const childColor = optionalHexColor(values.PI_SWARM_COLOR);
45
+ const acceptsRequests = parseBoolean(values.PI_SWARM_ACCEPT_REQUESTS);
46
+ const provider = optionalBounded(values.PI_SWARM_MODEL_PROVIDER, "model provider", 200);
47
+ const id = optionalBounded(values.PI_SWARM_MODEL_ID, "model id", 500);
48
+ if ((provider === undefined) !== (id === undefined)) {
49
+ throw new Error("Pi Agent Swarm launch model identity is incomplete");
50
+ }
51
+ const thinking = values.PI_SWARM_THINKING;
52
+ if (thinking !== undefined && (!provider || !id)) {
53
+ throw new Error("Pi Agent Swarm launch model identity is incomplete");
54
+ }
55
+ if (thinking !== undefined && !THINKING_LEVELS.has(thinking as SwarmThinkingLevel)) {
56
+ throw new Error("Pi Agent Swarm launch thinking level is invalid");
57
+ }
58
+ return {
59
+ invite,
60
+ parentSessionId,
61
+ launchId,
62
+ kickoffCapability,
63
+ ...(childName ? { childName } : {}),
64
+ ...(childColor ? { childColor } : {}),
65
+ acceptsRequests,
66
+ ...(provider && id
67
+ ? {
68
+ model: {
69
+ provider,
70
+ id,
71
+ ...(thinking ? { thinkingLevel: thinking as SwarmThinkingLevel } : {}),
72
+ },
73
+ }
74
+ : {}),
75
+ };
76
+ }
77
+
78
+ export function launchEnvelopeEnvironment(envelope: SwarmLaunchEnvelope): Record<string, string> {
79
+ return {
80
+ PI_SWARM_INVITE: envelope.invite,
81
+ PI_SWARM_PARENT_SESSION_ID: envelope.parentSessionId,
82
+ PI_SWARM_LAUNCH_ID: envelope.launchId,
83
+ PI_SWARM_KICKOFF_CAPABILITY: envelope.kickoffCapability,
84
+ PI_SWARM_ACCEPT_REQUESTS: envelope.acceptsRequests ? "1" : "0",
85
+ ...(envelope.childName ? { PI_SWARM_CHILD_NAME: envelope.childName } : {}),
86
+ ...(envelope.childColor ? { PI_SWARM_COLOR: envelope.childColor } : {}),
87
+ ...(envelope.model
88
+ ? {
89
+ PI_SWARM_MODEL_PROVIDER: envelope.model.provider,
90
+ PI_SWARM_MODEL_ID: envelope.model.id,
91
+ ...(envelope.model.thinkingLevel ? { PI_SWARM_THINKING: envelope.model.thinkingLevel } : {}),
92
+ }
93
+ : {}),
94
+ };
95
+ }
96
+
97
+ function parseBoolean(value: string | undefined): boolean {
98
+ if (value === undefined || value === "0") return false;
99
+ if (value === "1") return true;
100
+ throw new Error("Pi Agent Swarm launch request policy is invalid");
101
+ }
102
+
103
+ function safeId(value: string | undefined, label: string): string {
104
+ if (!value || !SAFE_ID.test(value)) throw new Error(`Pi Agent Swarm launch ${label} is invalid`);
105
+ return value;
106
+ }
107
+
108
+ function bounded(value: string | undefined, label: string, maxBytes: number): string {
109
+ if (!value || value.includes("\0") || Buffer.byteLength(value) > maxBytes) {
110
+ throw new Error(`Pi Agent Swarm launch ${label} is invalid`);
111
+ }
112
+ return value;
113
+ }
114
+
115
+ function optionalBounded(value: string | undefined, label: string, maxBytes: number): string | undefined {
116
+ return value === undefined ? undefined : bounded(value, label, maxBytes);
117
+ }
118
+
119
+ function optionalHexColor(value: string | undefined): string | undefined {
120
+ if (value === undefined) return undefined;
121
+ const lower = value.toLowerCase();
122
+ if (!/^#[0-9a-f]{6}$/u.test(lower)) throw new Error("Pi Agent Swarm launch color is invalid");
123
+ return lower;
124
+ }
@@ -0,0 +1,93 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { lstat, open, rm } from "node:fs/promises";
3
+ import { join, relative, resolve } from "node:path";
4
+ import type { PiInvocation } from "./pi-invocation.js";
5
+
6
+ export interface PiLauncher {
7
+ path: string;
8
+ command: string;
9
+ cleanup(): Promise<void>;
10
+ }
11
+
12
+ export async function createPiLauncher(
13
+ invocation: PiInvocation,
14
+ directory: string,
15
+ embeddedEnvironment?: Readonly<Record<string, string>>,
16
+ ): Promise<PiLauncher> {
17
+ await assertPrivateDirectory(directory);
18
+ const launcherPath = join(directory, `launch-${randomBytes(8).toString("hex")}.sh`);
19
+ assertInside(directory, launcherPath);
20
+ const command = [invocation.command, ...invocation.args];
21
+ for (const value of command) {
22
+ if (value.includes("\0")) throw new Error("Pi Agent Swarm launcher argument contains a NUL byte");
23
+ }
24
+ const environment = validateEmbeddedEnvironment(embeddedEnvironment);
25
+ const setup = environment.length
26
+ ? [
27
+ `rm -f ${quoteShell(launcherPath)} || exit 1`,
28
+ ...environment.map(([key, value]) => `export ${key}=${quoteShell(value)}`),
29
+ ]
30
+ : [];
31
+ const source = ["#!/bin/sh", ...setup, `exec ${command.map(quoteShell).join(" ")}`, ""].join("\n");
32
+ const handle = await open(launcherPath, "wx", 0o700);
33
+ try {
34
+ await handle.writeFile(source, "utf8");
35
+ await handle.sync();
36
+ await handle.chmod(0o700);
37
+ await handle.close();
38
+ } catch (error) {
39
+ await handle.close().catch(() => undefined);
40
+ await rm(launcherPath, { force: true }).catch(() => undefined);
41
+ throw error;
42
+ }
43
+ let cleaned = false;
44
+ return {
45
+ path: launcherPath,
46
+ command: launcherPath,
47
+ async cleanup() {
48
+ if (cleaned) return;
49
+ cleaned = true;
50
+ assertInside(directory, launcherPath);
51
+ await rm(launcherPath, { force: true });
52
+ },
53
+ };
54
+ }
55
+
56
+ function validateEmbeddedEnvironment(
57
+ environment: Readonly<Record<string, string>> | undefined,
58
+ ): Array<readonly [string, string]> {
59
+ const entries = Object.entries(environment ?? {}).sort(([left], [right]) => left.localeCompare(right));
60
+ let bytes = 0;
61
+ for (const [key, value] of entries) {
62
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/u.test(key) || value.includes("\0")) {
63
+ throw new Error("Pi Agent Swarm launch environment is invalid");
64
+ }
65
+ bytes += Buffer.byteLength(key) + Buffer.byteLength(value) + 1;
66
+ }
67
+ if (bytes > 24 * 1024) throw new Error("Pi Agent Swarm launch environment is too large");
68
+ return entries;
69
+ }
70
+
71
+ function quoteShell(value: string): string {
72
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
73
+ }
74
+
75
+ async function assertPrivateDirectory(path: string): Promise<void> {
76
+ const info = await lstat(path);
77
+ if (info.isSymbolicLink() || !info.isDirectory()) {
78
+ throw new Error("Pi Agent Swarm launcher directory is invalid");
79
+ }
80
+ if (typeof process.getuid === "function" && info.uid !== process.getuid()) {
81
+ throw new Error("Pi Agent Swarm launcher directory has another owner");
82
+ }
83
+ if ((info.mode & 0o777) !== 0o700) {
84
+ throw new Error("Pi Agent Swarm launcher directory permissions are not private");
85
+ }
86
+ }
87
+
88
+ function assertInside(parent: string, candidate: string): void {
89
+ const rel = relative(resolve(parent), resolve(candidate));
90
+ if (!rel || rel === ".." || rel.startsWith("../")) {
91
+ throw new Error("Pi Agent Swarm launcher path escapes its runtime directory");
92
+ }
93
+ }
package/src/menu.ts ADDED
@@ -0,0 +1,131 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import type { MenuDefinition } from "@narumitw/pi-tui-kit";
3
+ import { SWARM_COLORS, type SwarmColorPaletteName } from "./color.js";
4
+ import type { SpawnSessionInput, SwarmSnapshot } from "./swarm-controller.js";
5
+ import { safeError } from "./text.js";
6
+
7
+ export interface SwarmMenuState extends SwarmSnapshot {}
8
+
9
+ export interface SwarmMenuSource {
10
+ snapshot(signal?: AbortSignal): Promise<SwarmMenuState>;
11
+ spawn(ctx: ExtensionCommandContext, input: SpawnSessionInput, signal?: AbortSignal): Promise<void>;
12
+ rename(ctx: ExtensionCommandContext, name: string, signal?: AbortSignal): Promise<void>;
13
+ setColor(ctx: ExtensionCommandContext, color: string, signal?: AbortSignal): Promise<void>;
14
+ setPalette(ctx: ExtensionCommandContext, palette: SwarmColorPaletteName, signal?: AbortSignal): Promise<void>;
15
+ }
16
+
17
+ type Screen = "main";
18
+ type Action = "spawn" | "rename" | "setColor" | "setTheme";
19
+
20
+ const DIRECTION_OPTIONS = ["Right", "Down", "Left", "Up"] as const;
21
+ const PALETTE_OPTIONS = [
22
+ { label: "muted (default, low-saturation GitHub colors)", value: "muted" },
23
+ { label: "bright (vivid GitHub colors)", value: "bright" },
24
+ ] as const satisfies readonly { label: string; value: SwarmColorPaletteName }[];
25
+
26
+ export function createSwarmMenu(source: SwarmMenuSource) {
27
+ const getState = ({ signal }: { signal?: AbortSignal } = {}) => source.snapshot(signal);
28
+ const menu: MenuDefinition<SwarmMenuState, Screen, Action> = {
29
+ start: "main",
30
+ screens: {
31
+ main: () => ({
32
+ kind: "actions",
33
+ title: "Pi Agent Swarm",
34
+ lines: ["Spawn workers and manage this session's badge."],
35
+ items: [
36
+ {
37
+ id: "spawn",
38
+ label: "Spawn",
39
+ action: "spawn",
40
+ },
41
+ {
42
+ id: "rename",
43
+ label: "Rename",
44
+ action: "rename",
45
+ },
46
+ {
47
+ id: "color",
48
+ label: "Set color",
49
+ action: "setColor",
50
+ },
51
+ {
52
+ id: "theme",
53
+ label: "Set theme",
54
+ action: "setTheme",
55
+ },
56
+ ],
57
+ hint: "close",
58
+ }),
59
+ },
60
+ actions: {
61
+ spawn: async ({ ctx, signal }) => {
62
+ const directionChoice = await ctx.ui.select("Terminal window direction", [...DIRECTION_OPTIONS], {
63
+ signal,
64
+ });
65
+ if (!directionChoice || signal.aborted) return { kind: "stay" };
66
+ const task = await ctx.ui.input("Optional first task", "Submit an empty value for an idle child session", {
67
+ signal,
68
+ });
69
+ if (task === undefined || signal.aborted) return { kind: "stay" };
70
+ await source.spawn(
71
+ ctx,
72
+ {
73
+ direction: directionChoice.toLowerCase() as SpawnSessionInput["direction"],
74
+ ...(task ? { task } : {}),
75
+ },
76
+ signal,
77
+ );
78
+ return { kind: "close" };
79
+ },
80
+ rename: async ({ ctx, signal, state }) => {
81
+ const name = await ctx.ui.input("Rename session", state.self?.name ?? "Enter a new session name", {
82
+ signal,
83
+ });
84
+ if (name === undefined || !name.trim() || signal.aborted) return { kind: "stay" };
85
+ await source.rename(ctx, name, signal);
86
+ return { kind: "stay" };
87
+ },
88
+ setColor: async ({ ctx, signal }) => {
89
+ const choice = await ctx.ui.select("Session color", [...SWARM_COLORS.map((color) => color.name)], {
90
+ signal,
91
+ });
92
+ if (!choice || signal.aborted) return { kind: "stay" };
93
+ await source.setColor(ctx, choice, signal);
94
+ return { kind: "stay" };
95
+ },
96
+ setTheme: async ({ ctx, signal }) => {
97
+ const choice = await ctx.ui.select(
98
+ "Roster theme (badge palette)",
99
+ PALETTE_OPTIONS.map((option) => option.label),
100
+ { signal },
101
+ );
102
+ if (!choice || signal.aborted) return { kind: "stay" };
103
+ const palette = PALETTE_OPTIONS.find((option) => option.label === choice)?.value;
104
+ if (!palette) return { kind: "stay" };
105
+ await source.setPalette(ctx, palette, signal);
106
+ return { kind: "stay" };
107
+ },
108
+ },
109
+ };
110
+ return { menu, getState };
111
+ }
112
+
113
+ export async function showSwarmMenu(
114
+ ctx: ExtensionCommandContext,
115
+ source: SwarmMenuSource,
116
+ ownership: { signal: AbortSignal; isCurrent(): boolean },
117
+ ): Promise<void> {
118
+ const { runMenu } = await import("@narumitw/pi-tui-kit");
119
+ if (ownership.signal.aborted || !ownership.isCurrent()) return;
120
+ const controller = createSwarmMenu(source);
121
+ await runMenu(ctx, controller.menu, {
122
+ getState: controller.getState,
123
+ signal: ownership.signal,
124
+ isCurrent: ownership.isCurrent,
125
+ onError: (_ctx, error) => {
126
+ if (ownership.isCurrent() && !ownership.signal.aborted) {
127
+ ctx.ui.notify(`Pi Agent Swarm failed: ${safeError(error)}`, "error");
128
+ }
129
+ },
130
+ });
131
+ }
@@ -0,0 +1,173 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import type { SwarmMenuSource } from "./menu.js";
3
+ import { parseInvite } from "./protocol.js";
4
+ import { renderSwarmMessage, SWARM_MESSAGE_TYPE } from "./renderer.js";
5
+ import { createSwarmSettingsRuntime, type SwarmSettingsRuntime } from "./settings.js";
6
+ import { SwarmController, type SwarmControllerDependencies } from "./swarm-controller.js";
7
+ import { safeTerminalLine } from "./text.js";
8
+ import { registerSwarmTools } from "./tools.js";
9
+
10
+ const USAGE = "Usage: /swarm, /swarm start, or /swarm <piagentswarm:v1:invite>";
11
+
12
+ type SwarmMenuModule = Pick<typeof import("./menu.js"), "showSwarmMenu">;
13
+
14
+ export interface PiSwarmDependencies {
15
+ controllerDependencies?: SwarmControllerDependencies;
16
+ settingsRuntime?: SwarmSettingsRuntime;
17
+ loadMenu?: () => Promise<SwarmMenuModule>;
18
+ }
19
+
20
+ export function createPiSwarmExtension(dependencies: PiSwarmDependencies = {}): (pi: ExtensionAPI) => void {
21
+ return function piSwarmExtension(pi: ExtensionAPI): void {
22
+ const settings = dependencies.settingsRuntime ?? createSwarmSettingsRuntime();
23
+ const controller = new SwarmController(pi, dependencies.controllerDependencies, settings);
24
+ const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./menu.js")));
25
+
26
+ pi.registerMessageRenderer(SWARM_MESSAGE_TYPE, renderSwarmMessage);
27
+ registerSwarmTools(pi, controller);
28
+
29
+ pi.on("session_start", async (event, ctx) => {
30
+ await controller.sessionStart(event, ctx);
31
+ });
32
+ pi.on("session_shutdown", async (event, ctx) => {
33
+ await controller.sessionShutdown(event, ctx);
34
+ });
35
+ pi.on("input", async (event, ctx) => {
36
+ if (event.source !== "interactive") return;
37
+ void controller.relaySteerInput(event.text, ctx);
38
+ });
39
+
40
+ pi.registerCommand("swarm", {
41
+ description: "Spawn a worker Pi session, or start/join a local group",
42
+ handler: async (rawArgs, ctx) => {
43
+ const args = rawArgs.trim();
44
+ if (ctx.mode !== "tui" && ctx.mode !== "rpc") {
45
+ throw new Error(`Pi Agent Swarm is unavailable in ${ctx.mode} mode. ${USAGE}`);
46
+ }
47
+ if (args === "start") {
48
+ await startGroupDirectly(controller, ctx);
49
+ return;
50
+ }
51
+ if (args) {
52
+ await joinDirectInvite(controller, args, ctx);
53
+ return;
54
+ }
55
+ const ownerSignal = controller.sessionSignal;
56
+ const menuModule = await loadMenu();
57
+ if (ownerSignal.aborted || !controller.isCurrent(ctx)) return;
58
+ await menuModule.showSwarmMenu(ctx, menuSource(controller), {
59
+ signal: ownerSignal,
60
+ isCurrent: () => controller.isCurrent(ctx) && !ownerSignal.aborted,
61
+ });
62
+ },
63
+ });
64
+
65
+ pi.registerCommand("lead", {
66
+ description: "Set the swarm lead (coordinator) by session name or id",
67
+ handler: async (rawArgs, ctx) => {
68
+ const target = rawArgs.trim();
69
+ if (!target) throw new Error("Usage: /lead <session name or id>");
70
+ const signal = controller.sessionSignal;
71
+ const peer = await controller.resolvePeer(target, signal);
72
+ if (!peer) throw new Error(`No live Pi Agent Swarm session matches "${target}"`);
73
+ await controller.setLead(ctx, peer, signal);
74
+ ctx.ui.notify(`Lead is now ${peer.name ?? peer.sessionId}.`, "info");
75
+ },
76
+ });
77
+
78
+ pi.registerCommand("color", {
79
+ description: "Set this session's color (palette name or #rrggbb)",
80
+ handler: async (rawArgs, ctx) => {
81
+ const color = controller.normalizeColor(rawArgs.trim());
82
+ if (!color) {
83
+ throw new Error("Usage: /color <red|orange|yellow|green|cyan|blue|magenta|purple|#rrggbb>");
84
+ }
85
+ await controller.setOwnColor(ctx, color);
86
+ ctx.ui.notify(`Color set to ${color}.`, "info");
87
+ },
88
+ });
89
+ };
90
+ }
91
+
92
+ async function joinDirectInvite(
93
+ controller: SwarmController,
94
+ invite: string,
95
+ ctx: ExtensionCommandContext,
96
+ ): Promise<void> {
97
+ try {
98
+ parseInvite(invite);
99
+ } catch {
100
+ throw new Error(USAGE);
101
+ }
102
+ const signal = controller.sessionSignal;
103
+ if (signal.aborted) return;
104
+ const confirmed = await ctx.ui.confirm(
105
+ "Join local Pi Agent Swarm group?",
106
+ "The bearer invite permits local peer messages. Incoming agent requests start blocked.",
107
+ { signal },
108
+ );
109
+ if (!confirmed || signal.aborted || !controller.isCurrent(ctx)) return;
110
+ await controller.joinInvite(ctx, invite, false, signal);
111
+ if (controller.isCurrent(ctx)) {
112
+ ctx.ui.notify("Joined the local Pi Agent Swarm group.", "info");
113
+ }
114
+ }
115
+
116
+ async function startGroupDirectly(controller: SwarmController, ctx: ExtensionCommandContext): Promise<void> {
117
+ const signal = controller.sessionSignal;
118
+ if (signal.aborted) return;
119
+ await controller.startNewGroup(ctx, false, signal);
120
+ if (controller.isCurrent(ctx)) {
121
+ ctx.ui.notify("Started a local Pi Agent Swarm group. You are its lead.", "info");
122
+ }
123
+ }
124
+
125
+ function menuSource(controller: SwarmController): SwarmMenuSource {
126
+ return {
127
+ snapshot: (signal) => controller.snapshot(signal),
128
+ spawn: async (commandContext, input, signal) => {
129
+ const result = await controller.spawn(commandContext, input, signal);
130
+ if (controller.isCurrent(commandContext)) {
131
+ commandContext.ui.notify(
132
+ `Pi session ${safeTerminalLine(result.name ?? result.sessionId)} is ready in an external window.`,
133
+ "info",
134
+ );
135
+ }
136
+ },
137
+ rename: async (commandContext, name, signal) => {
138
+ await controller.setOwnName(commandContext, name, signal);
139
+ if (controller.isCurrent(commandContext)) {
140
+ commandContext.ui.notify(`Session renamed to ${safeTerminalLine(name)}.`, "info");
141
+ }
142
+ },
143
+ setColor: async (commandContext, color, signal) => {
144
+ const normalized = controller.normalizeColor(color);
145
+ if (!normalized) throw new Error("Pi Agent Swarm color is invalid");
146
+ await controller.setOwnColor(commandContext, normalized, signal);
147
+ if (controller.isCurrent(commandContext)) {
148
+ commandContext.ui.notify(`Color set to ${normalized}.`, "info");
149
+ }
150
+ },
151
+ setPalette: async (commandContext, palette, signal) => {
152
+ await controller.setColorPalette(commandContext, palette, signal);
153
+ if (controller.isCurrent(commandContext)) {
154
+ commandContext.ui.notify(`Theme set to ${palette}.`, "info");
155
+ }
156
+ },
157
+ };
158
+ }
159
+
160
+ function cachedModuleLoader<T>(load: () => Promise<T>): () => Promise<T> {
161
+ let cached: Promise<T> | undefined;
162
+ return async () => {
163
+ if (!cached) {
164
+ cached = load().catch((error) => {
165
+ cached = undefined;
166
+ throw error;
167
+ });
168
+ }
169
+ return cached;
170
+ };
171
+ }
172
+
173
+ export default createPiSwarmExtension();
@@ -0,0 +1,144 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { getPackageDir } from "@earendil-works/pi-coding-agent";
4
+
5
+ const CORE_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
6
+ const MAX_DISPLAY_PATH_BYTES = 500;
7
+
8
+ export interface PiInvocation {
9
+ command: string;
10
+ args: string[];
11
+ }
12
+
13
+ export interface PiInvocationRuntime {
14
+ execPath: string;
15
+ packageDir: string;
16
+ runtimeKind: "node" | "bun" | "unsupported";
17
+ }
18
+
19
+ export class PiInvocationError extends Error {
20
+ constructor(message: string) {
21
+ super(message);
22
+ this.name = "PiInvocationError";
23
+ }
24
+ }
25
+
26
+ export function resolvePiInvocation(args: string[], runtime: PiInvocationRuntime = currentRuntime()): PiInvocation {
27
+ const packageDirectory = existingDirectory(runtime.packageDir);
28
+ const manifest = readManifest(packageDirectory);
29
+ const declaredBin = resolveDeclaredBin(packageDirectory, manifest);
30
+ const standalone = resolveStandaloneExecutable(packageDirectory, runtime);
31
+ if (standalone) return { command: standalone, args: [...args] };
32
+ if (runtime.runtimeKind !== "node" && runtime.runtimeKind !== "bun") {
33
+ throw resolutionError(packageDirectory, "the host does not provide Node or Bun");
34
+ }
35
+ return {
36
+ command: runtime.execPath,
37
+ args: [resolveExistingFile(packageDirectory, declaredBin, "the declared bin.pi target is unavailable"), ...args],
38
+ };
39
+ }
40
+
41
+ function currentRuntime(): PiInvocationRuntime {
42
+ let packageDir: string;
43
+ try {
44
+ packageDir = getPackageDir();
45
+ } catch {
46
+ throw resolutionError("<unavailable>", "Pi core did not provide its package directory");
47
+ }
48
+ return {
49
+ execPath: process.execPath,
50
+ packageDir,
51
+ runtimeKind: process.versions.bun
52
+ ? "bun"
53
+ : process.release.name === "node" && !process.versions.electron
54
+ ? "node"
55
+ : "unsupported",
56
+ };
57
+ }
58
+
59
+ function existingDirectory(value: string): string {
60
+ try {
61
+ const resolved = fs.realpathSync(value);
62
+ if (!fs.statSync(resolved).isDirectory()) throw new Error("not a directory");
63
+ return resolved;
64
+ } catch {
65
+ throw resolutionError(value, "the package directory is unavailable");
66
+ }
67
+ }
68
+
69
+ function readManifest(packageDirectory: string): Record<string, unknown> {
70
+ let value: unknown;
71
+ try {
72
+ value = JSON.parse(fs.readFileSync(path.join(packageDirectory, "package.json"), "utf8"));
73
+ } catch {
74
+ throw resolutionError(packageDirectory, "the package manifest is unavailable or invalid");
75
+ }
76
+ if (!isRecord(value) || value.name !== CORE_PACKAGE_NAME) {
77
+ throw resolutionError(packageDirectory, "the package manifest has an unexpected package name");
78
+ }
79
+ return value;
80
+ }
81
+
82
+ function resolveDeclaredBin(packageDirectory: string, manifest: Record<string, unknown>): string {
83
+ const bin = manifest.bin;
84
+ const piBin = isRecord(bin) ? bin.pi : undefined;
85
+ if (typeof piBin !== "string" || !piBin.trim()) {
86
+ throw resolutionError(packageDirectory, "package.json bin.pi must be a non-empty string");
87
+ }
88
+ const candidate = path.resolve(packageDirectory, piBin);
89
+ if (path.isAbsolute(piBin) || !isWithin(packageDirectory, candidate)) {
90
+ throw resolutionError(packageDirectory, "the declared bin.pi target escapes the package");
91
+ }
92
+ return candidate;
93
+ }
94
+
95
+ function resolveExistingFile(packageDirectory: string, candidate: string, reason: string): string {
96
+ try {
97
+ const resolved = fs.realpathSync(candidate);
98
+ if (!fs.statSync(resolved).isFile()) throw new Error("not a file");
99
+ if (!isWithin(packageDirectory, resolved)) {
100
+ throw resolutionError(packageDirectory, "the declared bin.pi target escapes the package");
101
+ }
102
+ return resolved;
103
+ } catch (error) {
104
+ if (error instanceof PiInvocationError) throw error;
105
+ throw resolutionError(packageDirectory, reason);
106
+ }
107
+ }
108
+
109
+ function resolveStandaloneExecutable(packageDirectory: string, runtime: PiInvocationRuntime): string | undefined {
110
+ if (runtime.runtimeKind !== "bun" || !/^pi(?:\.exe)?$/iu.test(path.basename(runtime.execPath))) {
111
+ return undefined;
112
+ }
113
+ let resolved: string;
114
+ let mode: number;
115
+ try {
116
+ resolved = fs.realpathSync(runtime.execPath);
117
+ const info = fs.statSync(resolved);
118
+ if (!info.isFile()) throw new Error("not a file");
119
+ mode = info.mode;
120
+ } catch {
121
+ throw resolutionError(packageDirectory, "the standalone Pi executable is unavailable");
122
+ }
123
+ if (path.dirname(resolved) !== packageDirectory) return undefined;
124
+ if (process.platform !== "win32" && (mode & 0o111) === 0) {
125
+ throw resolutionError(packageDirectory, "the standalone Pi executable is not executable");
126
+ }
127
+ return resolved;
128
+ }
129
+
130
+ function isWithin(parent: string, candidate: string): boolean {
131
+ const relative = path.relative(parent, candidate);
132
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
133
+ }
134
+
135
+ function resolutionError(packageDirectory: string, reason: string): PiInvocationError {
136
+ const displayed = Buffer.from(packageDirectory).subarray(0, MAX_DISPLAY_PATH_BYTES).toString();
137
+ return new PiInvocationError(
138
+ `Unable to resolve the Pi CLI from ${JSON.stringify(displayed)}: ${reason}. Reinstall the matching Pi core package before spawning a session.`,
139
+ );
140
+ }
141
+
142
+ function isRecord(value: unknown): value is Record<string, unknown> {
143
+ return typeof value === "object" && value !== null && !Array.isArray(value);
144
+ }