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.
package/package.json CHANGED
@@ -1,7 +1,59 @@
1
1
  {
2
2
  "name": "pi-agent-swarm",
3
- "version": "0.0.0",
3
+ "version": "0.2.0",
4
4
  "description": "Window-manager-native agent swarm for the Pi Coding Agent — every agent runs as a real terminal window under a tiling window manager.",
5
+ "type": "module",
5
6
  "license": "MIT",
6
- "keywords": ["pi", "pi-coding-agent", "agents", "swarm", "window-manager", "tiling"]
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "pi",
12
+ "swarm",
13
+ "agents",
14
+ "window-manager",
15
+ "tiling",
16
+ "i3"
17
+ ],
18
+ "files": [
19
+ "src",
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "pi": {
25
+ "extensions": [
26
+ "./dist/index.ts"
27
+ ]
28
+ },
29
+ "scripts": {
30
+ "build": "node scripts/build-runtime.mjs",
31
+ "check": "npm run build && biome check . && npm run typecheck",
32
+ "format": "biome check --write .",
33
+ "typecheck": "tsc --noEmit",
34
+ "prepack": "npm run build"
35
+ },
36
+ "dependencies": {
37
+ "@narumitw/pi-tui-kit": "^0.59.0"
38
+ },
39
+ "peerDependencies": {
40
+ "@earendil-works/pi-ai": "*",
41
+ "@earendil-works/pi-coding-agent": "*",
42
+ "@earendil-works/pi-tui": "*",
43
+ "typebox": "*"
44
+ },
45
+ "devDependencies": {
46
+ "@earendil-works/pi-ai": "1.0.2",
47
+ "@earendil-works/pi-coding-agent": "1.0.2",
48
+ "@earendil-works/pi-tui": "1.0.2",
49
+ "@types/node": "26.6.4",
50
+ "esbuild": "0.28.2",
51
+ "typebox": "1.3.34",
52
+ "typescript": "7.0.2"
53
+ },
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "https://github.com/fishing-dev-sm/pi-agent-swarm",
57
+ "directory": "packages/pi-agent-swarm"
58
+ }
7
59
  }
package/src/color.ts ADDED
@@ -0,0 +1,129 @@
1
+ import { getTerminalColorMode, parseColor, styleText } from "@earendil-works/pi-tui";
2
+
3
+ export interface SwarmColor {
4
+ name: string;
5
+ hex: string;
6
+ }
7
+
8
+ export type SwarmColorPaletteName = "muted" | "bright";
9
+
10
+ /**
11
+ * Roster palettes derived from GitHub Linguist language colors (the language bar on
12
+ * github.com), one language per hue slot (see scripts/color-draft.mjs for the visual
13
+ * draft). `muted` is the default low-saturation set; its yellow deliberately matches
14
+ * the footer's ROLE badge (ROLE_BADGE_BACKGROUND) so a yellow session reads as one
15
+ * warm block. `bright` keeps the same slots at GitHub's original vivid tones. Both
16
+ * palettes share slot order, so a seed or stored name keeps its hue when the
17
+ * `colorPalette` setting switches.
18
+ */
19
+ export const SWARM_COLOR_PALETTES: Record<SwarmColorPaletteName, readonly SwarmColor[]> = {
20
+ muted: [
21
+ { name: "red", hex: "#c22d40" }, // Scala
22
+ { name: "orange", hex: "#b07219" }, // Java
23
+ { name: "yellow", hex: "#ffc85a" }, // matches ROLE_BADGE_BACKGROUND in footer.ts
24
+ { name: "green", hex: "#41b883" }, // Vue
25
+ { name: "cyan", hex: "#4298b8" }, // Groovy
26
+ { name: "blue", hex: "#3178c6" }, // TypeScript
27
+ { name: "magenta", hex: "#b83998" }, // Erlang
28
+ { name: "purple", hex: "#8847b9" }, // Elixir
29
+ ],
30
+ bright: [
31
+ { name: "red", hex: "#db5855" }, // Clojure
32
+ { name: "orange", hex: "#dea584" }, // Rust
33
+ { name: "yellow", hex: "#f1e05a" }, // JavaScript
34
+ { name: "green", hex: "#89e051" }, // Shell
35
+ { name: "cyan", hex: "#00add8" }, // Go
36
+ { name: "blue", hex: "#3572a5" }, // Python
37
+ { name: "magenta", hex: "#f34b7d" }, // C++
38
+ { name: "purple", hex: "#a97bff" }, // Kotlin
39
+ ],
40
+ };
41
+
42
+ /** Default roster palette: the muted GitHub-derived set. */
43
+ export const SWARM_COLORS: readonly SwarmColor[] = SWARM_COLOR_PALETTES.muted;
44
+
45
+ /**
46
+ * Pre-palette Tailwind colors. Kept only so hexes assigned by older versions still
47
+ * resolve to a palette name in labels; never used for new assignments.
48
+ */
49
+ const LEGACY_SWARM_COLORS: readonly SwarmColor[] = [
50
+ { name: "red", hex: "#ef4444" },
51
+ { name: "orange", hex: "#f97316" },
52
+ { name: "yellow", hex: "#eab308" },
53
+ { name: "green", hex: "#22c55e" },
54
+ { name: "cyan", hex: "#06b6d4" },
55
+ { name: "blue", hex: "#3b82f6" },
56
+ { name: "magenta", hex: "#d946ef" },
57
+ { name: "purple", hex: "#8b5cf6" },
58
+ ];
59
+
60
+ /** The palette behind a `colorPalette` setting value. */
61
+ export function swarmColorPalette(name: SwarmColorPaletteName): readonly SwarmColor[] {
62
+ return SWARM_COLOR_PALETTES[name];
63
+ }
64
+
65
+ const HEX_RE = /^#[0-9a-f]{6}$/u;
66
+ const HEX_TO_NAME = new Map<string, string>();
67
+ for (const palette of [SWARM_COLOR_PALETTES.muted, SWARM_COLOR_PALETTES.bright, LEGACY_SWARM_COLORS]) {
68
+ for (const color of palette) {
69
+ if (!HEX_TO_NAME.has(color.hex)) HEX_TO_NAME.set(color.hex, color.name);
70
+ }
71
+ }
72
+
73
+ /** Accept a palette name or a #rrggbb hex; return a normalized #rrggbb hex, or undefined. */
74
+ export function normalizeSwarmColor(value: unknown, palette: readonly SwarmColor[] = SWARM_COLORS): string | undefined {
75
+ if (typeof value !== "string") return undefined;
76
+ const trimmed = value.trim().toLowerCase();
77
+ const named = palette.find((color) => color.name === trimmed);
78
+ if (named) return named.hex;
79
+ if (HEX_RE.test(trimmed)) return trimmed;
80
+ return undefined;
81
+ }
82
+
83
+ /** Deterministic palette color from a seed string (stable, no coordination needed). */
84
+ export function pickSwarmColor(seed: string, palette: readonly SwarmColor[] = SWARM_COLORS): string {
85
+ let hash = 0;
86
+ for (let i = 0; i < seed.length; i += 1) hash = (hash * 31 + seed.charCodeAt(i)) >>> 0;
87
+ return palette[hash % palette.length].hex;
88
+ }
89
+
90
+ /** Palette name for a hex, or undefined when the hex is off-palette. */
91
+ export function swarmColorName(hex: string): string | undefined {
92
+ return HEX_TO_NAME.get(hex.toLowerCase());
93
+ }
94
+
95
+ /** Wrap text in a foreground color escape sequence (ANSI), best-effort. */
96
+ export function colorize(text: string, hex: string): string {
97
+ try {
98
+ return styleText(text, { fg: parseColor(hex) }, getTerminalColorMode());
99
+ } catch {
100
+ return text;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Pick black or white text for a filled badge on the given background, using WCAG
106
+ * relative luminance so the choice is measured rather than eyeballed.
107
+ */
108
+ export function contrastTextColor(bgHex: string): string {
109
+ const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/u.exec(bgHex.toLowerCase());
110
+ if (!match) return "#ffffff";
111
+ const [r, g, b] = match.slice(1).map((pair) => Number.parseInt(pair, 16));
112
+ const channel = (value: number): number => {
113
+ const s = value / 255;
114
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
115
+ };
116
+ const luminance = 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
117
+ const onBlack = (luminance + 0.05) / 0.05;
118
+ const onWhite = 1.05 / (luminance + 0.05);
119
+ return onBlack >= onWhite ? "#000000" : "#ffffff";
120
+ }
121
+
122
+ /** Wrap text in a filled badge (background with an explicit foreground), best-effort. */
123
+ export function badge(text: string, bgHex: string, fgHex: string): string {
124
+ try {
125
+ return styleText(text, { fg: parseColor(fgHex), bg: parseColor(bgHex) }, getTerminalColorMode());
126
+ } catch {
127
+ return text;
128
+ }
129
+ }
@@ -0,0 +1,150 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import type { I3WorkspacePinner } from "./i3-workspace.js";
5
+ import type { TerminalSplitDirection } from "./terminal.js";
6
+
7
+ /**
8
+ * swarm/external — launch a Pi session in a plain terminal window.
9
+ *
10
+ * The window manager (i3, Sway, or a desktop shell) decides where the new
11
+ * window goes, so there is no split direction and no multiplexer to talk to.
12
+ * The launch environment is embedded in the launcher script by the controller,
13
+ * exactly like the Zellij path, because a bare terminal emulator has no
14
+ * per-window `-e KEY=VAL` flags.
15
+ */
16
+ export class ExternalLaunchError extends Error {
17
+ constructor(
18
+ message: string,
19
+ readonly splitCreated = false,
20
+ readonly terminalId?: string,
21
+ ) {
22
+ super(message);
23
+ this.name = "ExternalLaunchError";
24
+ }
25
+ }
26
+
27
+ export interface SpawnExternalWindowOptions {
28
+ direction: TerminalSplitDirection;
29
+ cwd: string;
30
+ launcherCommand: string;
31
+ environment: Readonly<Record<string, string>>;
32
+ signal?: AbortSignal;
33
+ isCurrent(): boolean;
34
+ }
35
+
36
+ /** Split a settings value such as `"alacritty -e"` into `["alacritty", "-e"]`. */
37
+ export function parseExternalCommand(value: string): string[] {
38
+ return value.trim().split(/\s+/u).filter(Boolean);
39
+ }
40
+
41
+ export class ExternalTerminalAdapter {
42
+ constructor(
43
+ private readonly command: readonly string[],
44
+ private readonly i3Pinner?: I3WorkspacePinner,
45
+ ) {}
46
+
47
+ async assertAvailable(signal?: AbortSignal): Promise<string> {
48
+ throwIfAborted(signal, "external terminal availability check aborted");
49
+ const binary = this.command[0];
50
+ if (!binary) throw new ExternalLaunchError("Pi Agent Swarm external terminal command is empty");
51
+ if (!isOnPath(binary)) {
52
+ throw new ExternalLaunchError(`Pi Agent Swarm external terminal "${binary}" was not found on PATH`);
53
+ }
54
+ return binary;
55
+ }
56
+
57
+ async spawnSplit(options: SpawnExternalWindowOptions): Promise<{ terminalId: string; version: string }> {
58
+ throwIfAborted(options.signal, "external window creation aborted");
59
+ validateSpawnOptions(options);
60
+ const binary = await this.assertAvailable(options.signal);
61
+ if (!options.isCurrent()) {
62
+ throw new ExternalLaunchError("Pi Agent Swarm session became stale before window creation");
63
+ }
64
+ throwIfAborted(options.signal, "external window creation aborted");
65
+ // The lead workspace must be captured before the window exists so the diff
66
+ // below finds exactly the window this launch creates. A capture failure is
67
+ // non-fatal: the window manager then keeps its default placement.
68
+ let leadWorkspace: string | undefined;
69
+ if (this.i3Pinner) {
70
+ try {
71
+ leadWorkspace = await this.i3Pinner.captureLeadWorkspace(options.signal);
72
+ } catch {
73
+ leadWorkspace = undefined;
74
+ }
75
+ if (!options.isCurrent()) {
76
+ throw new ExternalLaunchError("Pi Agent Swarm session became stale before window creation");
77
+ }
78
+ throwIfAborted(options.signal, "external window creation aborted");
79
+ }
80
+ let pid: number | undefined;
81
+ try {
82
+ const child = spawn(binary, [...this.command.slice(1), options.launcherCommand], {
83
+ cwd: options.cwd,
84
+ detached: true,
85
+ stdio: "ignore",
86
+ });
87
+ pid = child.pid;
88
+ // The window outlives the extension. Failures surface indirectly: the
89
+ // child never announces itself and the controller's readiness wait fails.
90
+ child.on("error", () => undefined);
91
+ child.unref();
92
+ } catch (error) {
93
+ if (options.signal?.aborted) {
94
+ throw new ExternalLaunchError("external window creation was cancelled", true);
95
+ }
96
+ throw error;
97
+ }
98
+ // Placement is best-effort: the window is already open, so an i3 pin failure
99
+ // only leaves it where the window manager put it.
100
+ if (this.i3Pinner && leadWorkspace !== undefined) {
101
+ try {
102
+ await this.i3Pinner.pinNewWindowToLeadWorkspace(leadWorkspace, options.signal);
103
+ } catch {
104
+ // Intentionally ignored.
105
+ }
106
+ }
107
+ if (options.signal?.aborted) {
108
+ throw new ExternalLaunchError(
109
+ "external window was created after cancellation",
110
+ true,
111
+ pid ? String(pid) : undefined,
112
+ );
113
+ }
114
+ if (!options.isCurrent()) {
115
+ throw new ExternalLaunchError(
116
+ "Pi Agent Swarm session became stale after window creation",
117
+ true,
118
+ pid ? String(pid) : undefined,
119
+ );
120
+ }
121
+ return { terminalId: pid ? String(pid) : "unknown", version: binary };
122
+ }
123
+ }
124
+
125
+ function validateSpawnOptions(options: SpawnExternalWindowOptions): void {
126
+ for (const [label, value, maxBytes] of [
127
+ ["working directory", options.cwd, 4_096],
128
+ ["launcher command", options.launcherCommand, 4_096],
129
+ ] as const) {
130
+ if (!value || value.includes("\0") || Buffer.byteLength(value) > maxBytes) {
131
+ throw new ExternalLaunchError(`Pi Agent Swarm ${label} is invalid`);
132
+ }
133
+ }
134
+ }
135
+
136
+ function isOnPath(binary: string): boolean {
137
+ if (binary.includes("/")) return existsSync(binary);
138
+ const path = process.env.PATH ?? "";
139
+ for (const dir of path.split(":")) {
140
+ if (dir && existsSync(join(dir, binary))) return true;
141
+ }
142
+ return false;
143
+ }
144
+
145
+ function throwIfAborted(signal: AbortSignal | undefined, message: string): void {
146
+ if (!signal?.aborted) return;
147
+ const error = new Error(message);
148
+ error.name = "AbortError";
149
+ throw error;
150
+ }
package/src/footer.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { badge, contrastTextColor } from "./color.js";
3
+ import { safeTerminalLine } from "./text.js";
4
+
5
+ /** Uniform warning-cream background for the footer role badge (LEADER and WORKER alike). */
6
+ export const ROLE_BADGE_BACKGROUND = "#ffc85a";
7
+ /**
8
+ * Fraction of the terminal columns the roster badge may occupy. The built-in footer
9
+ * segments (cwd, git, model, context usage) take the rest; their width is not knowable
10
+ * from the extension API, so the budget scales with the window instead of a fixed reserve.
11
+ */
12
+ export const FOOTER_WIDTH_FRACTION = 0.55;
13
+ /** A short session id is the UUID prefix used by MANAGER-<id> naming and /lead matching. */
14
+ export const SHORT_ID_LENGTH = 8;
15
+ /** Column count assumed when the terminal does not report one (headless, piped output). */
16
+ export const DEFAULT_TERMINAL_COLUMNS = 80;
17
+ /** Below this a truncated name fragment carries no recognizable identity; drop to MINIMAL. */
18
+ const MIN_NAME_BUDGET = 8;
19
+ /** The ` ● ` prefix and trailing space around a non-empty name badge. */
20
+ const NAME_BADGE_OVERHEAD = 4;
21
+
22
+ export interface FooterBadgeInput {
23
+ name?: string;
24
+ sessionId: string;
25
+ color: string;
26
+ role: "LEADER" | "WORKER";
27
+ columns: number;
28
+ }
29
+
30
+ /**
31
+ * Build the roster footer badge, degrading through three width tiers:
32
+ * FULL (name + full id + role), COMPACT (name truncated with an ellipsis + 8-column
33
+ * short id + role), and MINIMAL (color dot + role). The role badge always survives:
34
+ * telling LEADER from WORKER at a glance is the badge's primary purpose. The short id
35
+ * is a first-class identifier (MANAGER-<prefix> naming and /lead prefix matching), so
36
+ * unlike a truncated name it carries no ellipsis.
37
+ */
38
+ export function buildRosterBadge(input: FooterBadgeInput): string {
39
+ const name = input.name ? safeTerminalLine(input.name) : "";
40
+ const sessionId = safeTerminalLine(input.sessionId);
41
+ const roleBadge = badge(` ${input.role} `, ROLE_BADGE_BACKGROUND, "#000000");
42
+ const nameBadge = (value: string) =>
43
+ badge(value ? ` ● ${value} ` : " ● ", input.color, contrastTextColor(input.color));
44
+ const available = Math.max(0, Math.floor(input.columns * FOOTER_WIDTH_FRACTION));
45
+
46
+ // FULL: the complete identifier set, unchanged from the original single-mode badge.
47
+ const full = `${nameBadge(name)}${badge(` ${sessionId} `, "#ffffff", "#000000")}${roleBadge}`;
48
+ if (visibleWidth(full) <= available) return full;
49
+
50
+ // COMPACT: shorten the id first (it is recoverable through /lead prefix matching),
51
+ // then give the name whatever budget remains.
52
+ const shortId = [...sessionId].slice(0, SHORT_ID_LENGTH).join("");
53
+ const shortIdBadge = badge(` ${shortId} `, "#ffffff", "#000000");
54
+ const nameBudget = available - visibleWidth(roleBadge) - visibleWidth(shortIdBadge) - NAME_BADGE_OVERHEAD;
55
+ if (nameBudget >= MIN_NAME_BUDGET) {
56
+ const truncated = visibleWidth(name) > nameBudget ? truncateToWidth(name, nameBudget, "…") : name;
57
+ return `${nameBadge(truncated)}${shortIdBadge}${roleBadge}`;
58
+ }
59
+
60
+ // MINIMAL: the swarm-colored dot is the identity; the full name and id stay
61
+ // available through the /swarm menu and message envelopes.
62
+ return `${nameBadge("")}${roleBadge}`;
63
+ }
@@ -0,0 +1,281 @@
1
+ /**
2
+ * swarm/i3-workspace — pin a newly spawned external window to the lead session's
3
+ * i3 workspace.
4
+ *
5
+ * The external terminal backend spawns a plain terminal window and normally lets
6
+ * the window manager decide where it goes. On i3 that means the currently focused
7
+ * workspace, which is not necessarily the workspace that hosts the lead (spawning)
8
+ * Pi session once focus-follows-mouse, a quick workspace switch, or a headless
9
+ * tool-triggered launch is involved.
10
+ *
11
+ * The lead workspace is located by walking the process tree from the current Pi
12
+ * process up to the terminal process that owns the X11 window (`_NET_WM_PID`), not
13
+ * by trusting the focused workspace. The pinner then snapshots the window tree,
14
+ * waits for the one new window id to appear, and moves that container onto the lead
15
+ * workspace. It talks to `i3-msg` and `xprop`, so it never depends on a specific
16
+ * terminal emulator or its command-line flags.
17
+ */
18
+
19
+ import { readFileSync } from "node:fs";
20
+
21
+ export interface I3CommandResult {
22
+ stdout: string;
23
+ stderr: string;
24
+ code: number;
25
+ killed?: boolean;
26
+ }
27
+
28
+ export type I3CommandExecutor = (
29
+ command: string,
30
+ args: string[],
31
+ options: { signal?: AbortSignal; timeoutMs: number },
32
+ ) => Promise<I3CommandResult>;
33
+
34
+ export interface I3WorkspacePinnerOptions {
35
+ execute: I3CommandExecutor;
36
+ readProcessId?: () => number;
37
+ readPpid?: (pid: number) => number | undefined;
38
+ sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
39
+ now?: () => number;
40
+ timeoutMs?: number;
41
+ pollIntervalMs?: number;
42
+ }
43
+
44
+ interface I3TreeNode {
45
+ id: number;
46
+ type?: string;
47
+ name?: string | null;
48
+ window?: number | null;
49
+ nodes?: I3TreeNode[];
50
+ floating_nodes?: I3TreeNode[];
51
+ }
52
+
53
+ const DEFAULT_TIMEOUT_MS = 3_000;
54
+ const DEFAULT_POLL_INTERVAL_MS = 100;
55
+ const MAX_ANCESTOR_DEPTH = 8;
56
+
57
+ /** Detect an i3 session from the standard `I3SOCK` and X11 `DISPLAY` variables. */
58
+ export function detectI3(environment: NodeJS.ProcessEnv): boolean {
59
+ return (
60
+ typeof environment.I3SOCK === "string" &&
61
+ environment.I3SOCK.length > 0 &&
62
+ typeof environment.DISPLAY === "string" &&
63
+ environment.DISPLAY.length > 0
64
+ );
65
+ }
66
+
67
+ export class I3WorkspacePinner {
68
+ private readonly execute: I3CommandExecutor;
69
+ private readonly readProcessId: () => number;
70
+ private readonly readPpid: (pid: number) => number | undefined;
71
+ private readonly sleep: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
72
+ private readonly now: () => number;
73
+ private readonly timeoutMs: number;
74
+ private readonly pollIntervalMs: number;
75
+ private beforeWindowIds: Set<number> | undefined;
76
+
77
+ constructor(options: I3WorkspacePinnerOptions) {
78
+ this.execute = options.execute;
79
+ this.readProcessId = options.readProcessId ?? (() => process.pid);
80
+ this.readPpid = options.readPpid ?? readProcPpid;
81
+ this.sleep = options.sleep ?? abortableSleep;
82
+ this.now = options.now ?? Date.now;
83
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
84
+ this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
85
+ }
86
+
87
+ /**
88
+ * Snapshot the tree before the new window is created and return the workspace
89
+ * that hosts this Pi session's terminal window, located by `_NET_WM_PID` and the
90
+ * process tree rather than by the currently focused workspace.
91
+ */
92
+ async captureLeadWorkspace(signal?: AbortSignal): Promise<string> {
93
+ const tree = await this.getTree(signal);
94
+ this.beforeWindowIds = collectWindowIds(tree);
95
+ const workspace = await this.findSelfWorkspace(tree, signal);
96
+ if (!workspace) throw new Error("Pi Agent Swarm could not locate the lead session's i3 workspace");
97
+ return workspace;
98
+ }
99
+
100
+ /**
101
+ * Wait for the one new window to appear and move it onto the captured lead
102
+ * workspace. Best-effort callers catch failures; the window is already open.
103
+ */
104
+ async pinNewWindowToLeadWorkspace(leadWorkspace: string, signal?: AbortSignal): Promise<void> {
105
+ const before = this.beforeWindowIds;
106
+ if (!before) throw new Error("Pi Agent Swarm must capture the lead workspace before pinning a window");
107
+ const deadline = this.now() + this.timeoutMs;
108
+ while (true) {
109
+ throwIfAborted(signal, "Pi Agent Swarm i3 workspace pin was aborted");
110
+ const tree = await this.getTree(signal);
111
+ const conId = findNewWindowId(tree, before);
112
+ if (conId !== undefined) {
113
+ await this.moveToWorkspace(conId, leadWorkspace, signal);
114
+ return;
115
+ }
116
+ if (this.now() >= deadline) {
117
+ throw new Error("Pi Agent Swarm timed out waiting for the new window to appear");
118
+ }
119
+ await this.sleep(this.pollIntervalMs, signal);
120
+ }
121
+ }
122
+
123
+ private async findSelfWorkspace(tree: I3TreeNode, signal?: AbortSignal): Promise<string | undefined> {
124
+ const ancestors = collectAncestors(this.readProcessId(), this.readPpid);
125
+ for (const node of windowNodes(tree)) {
126
+ const ownerPid = await this.xpropPid(node.window as number, signal);
127
+ if (ownerPid !== undefined && ancestors.includes(ownerPid)) {
128
+ return workspaceOf(tree, node.id);
129
+ }
130
+ }
131
+ return undefined;
132
+ }
133
+
134
+ private async xpropPid(windowId: number, signal?: AbortSignal): Promise<number | undefined> {
135
+ let result: I3CommandResult;
136
+ try {
137
+ result = await this.execute("xprop", ["-id", String(windowId), "_NET_WM_PID"], {
138
+ ...(signal ? { signal } : {}),
139
+ timeoutMs: this.timeoutMs,
140
+ });
141
+ } catch {
142
+ return undefined;
143
+ }
144
+ if (result.code !== 0 || result.killed) return undefined;
145
+ const match = /_NET_WM_PID[^=]*=\s*(\d+)/u.exec(result.stdout);
146
+ return match ? Number(match[1]) : undefined;
147
+ }
148
+
149
+ private async getTree(signal?: AbortSignal): Promise<I3TreeNode> {
150
+ const result = await this.execute("i3-msg", ["-t", "get_tree"], {
151
+ ...(signal ? { signal } : {}),
152
+ timeoutMs: this.timeoutMs,
153
+ });
154
+ if (result.code !== 0 || result.killed) {
155
+ throw new Error("Pi Agent Swarm could not query the i3 window tree");
156
+ }
157
+ try {
158
+ return JSON.parse(result.stdout) as I3TreeNode;
159
+ } catch {
160
+ throw new Error("Pi Agent Swarm received an invalid i3 window tree");
161
+ }
162
+ }
163
+
164
+ private async moveToWorkspace(conId: number, workspace: string, signal?: AbortSignal): Promise<void> {
165
+ const result = await this.execute(
166
+ "i3-msg",
167
+ [`[con_id=${conId}] move container to workspace ${quoteI3Value(workspace)}`],
168
+ {
169
+ ...(signal ? { signal } : {}),
170
+ timeoutMs: this.timeoutMs,
171
+ },
172
+ );
173
+ if (result.code !== 0 || result.killed) {
174
+ throw new Error("Pi Agent Swarm could not move the new window to the lead workspace");
175
+ }
176
+ }
177
+ }
178
+
179
+ function collectWindowIds(tree: I3TreeNode): Set<number> {
180
+ const ids = new Set<number>();
181
+ visit(tree, (node) => {
182
+ if (typeof node.window === "number") ids.add(node.window);
183
+ });
184
+ return ids;
185
+ }
186
+
187
+ function windowNodes(tree: I3TreeNode): I3TreeNode[] {
188
+ const nodes: I3TreeNode[] = [];
189
+ visit(tree, (node) => {
190
+ if (typeof node.window === "number") nodes.push(node);
191
+ });
192
+ return nodes;
193
+ }
194
+
195
+ function findNewWindowId(tree: I3TreeNode, before: Set<number>): number | undefined {
196
+ let found: number | undefined;
197
+ visit(tree, (node) => {
198
+ if (found !== undefined) return;
199
+ if (typeof node.window === "number" && !before.has(node.window)) {
200
+ found = node.id;
201
+ }
202
+ });
203
+ return found;
204
+ }
205
+
206
+ function workspaceOf(tree: I3TreeNode, conId: number): string | undefined {
207
+ let found: string | undefined;
208
+ visit(tree, (node, workspaceName) => {
209
+ if (found !== undefined) return;
210
+ const current = node.type === "workspace" && typeof node.name === "string" ? node.name : workspaceName;
211
+ if (node.id === conId) found = current;
212
+ });
213
+ return found;
214
+ }
215
+
216
+ function visit(node: I3TreeNode, callback: (node: I3TreeNode, workspaceName: string | undefined) => void): void {
217
+ const walk = (current: I3TreeNode, workspaceName: string | undefined): void => {
218
+ const nextWorkspace =
219
+ current.type === "workspace" && typeof current.name === "string" ? current.name : workspaceName;
220
+ callback(current, nextWorkspace);
221
+ for (const child of [...(current.nodes ?? []), ...(current.floating_nodes ?? [])]) {
222
+ walk(child, nextWorkspace);
223
+ }
224
+ };
225
+ walk(node, undefined);
226
+ }
227
+
228
+ function collectAncestors(pid: number, readPpid: (pid: number) => number | undefined): number[] {
229
+ const ancestors = [pid];
230
+ let current = pid;
231
+ for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth += 1) {
232
+ const parent = readPpid(current);
233
+ if (parent === undefined || parent <= 1) break;
234
+ ancestors.push(parent);
235
+ current = parent;
236
+ }
237
+ return ancestors;
238
+ }
239
+
240
+ function readProcPpid(pid: number): number | undefined {
241
+ try {
242
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
243
+ const close = stat.lastIndexOf(")");
244
+ if (close < 0) return undefined;
245
+ const fields = stat.slice(close + 2).split(" ");
246
+ const ppid = Number(fields[1]);
247
+ return Number.isInteger(ppid) && ppid > 0 ? ppid : undefined;
248
+ } catch {
249
+ return undefined;
250
+ }
251
+ }
252
+
253
+ function quoteI3Value(value: string): string {
254
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
255
+ }
256
+
257
+ async function abortableSleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
258
+ throwIfAborted(signal, "Pi Agent Swarm i3 workspace wait was aborted");
259
+ await new Promise<void>((resolve, reject) => {
260
+ const finish = (error?: Error) => {
261
+ clearTimeout(timer);
262
+ signal?.removeEventListener("abort", abort);
263
+ if (error) reject(error);
264
+ else resolve();
265
+ };
266
+ const timer = setTimeout(() => finish(), milliseconds);
267
+ const abort = () => finish(abortError("Pi Agent Swarm i3 workspace wait was aborted"));
268
+ signal?.addEventListener("abort", abort, { once: true });
269
+ if (signal?.aborted) abort();
270
+ });
271
+ }
272
+
273
+ function throwIfAborted(signal: AbortSignal | undefined, message: string): void {
274
+ if (signal?.aborted) throw abortError(message);
275
+ }
276
+
277
+ function abortError(message: string): Error {
278
+ const error = new Error(message);
279
+ error.name = "AbortError";
280
+ return error;
281
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./pi-agent-swarm.js";