pi-spaces 0.16.2 → 0.18.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 CHANGED
@@ -6,6 +6,35 @@ commands and options and a patch version fixes.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.18.0
10
+
11
+ ### Changed
12
+
13
+ - `/space new` with a setup command creates only the space's folder, waiting for its setup (a `.pi-space-new` file holds
14
+ the declaration), so the setup command makes `agent/` itself: gentle-shell 4.8 leaves alone a `--home` that already
15
+ has content. `pi-space setup` adds the declaration once the setup succeeds.
16
+
17
+ - The README's gentle-shell profile sets `GENTLE_PI_CONFIG_HOME` to `{space}`: gentle-shell 4.8 adds `gentle-ai` to it,
18
+ so `{space}/gentle-ai` gave `<space>/gentle-ai/gentle-ai`.
19
+
20
+ ### Added
21
+
22
+ - `pi-spaces/spaces` exports `createSpaceRoot`, `markPending`, `finishPending` and `declareInHome`; `spaceHome` and
23
+ `isRooted` count a space waiting for its setup as rooted.
24
+
25
+ ## 0.17.0
26
+
27
+ ### Added
28
+
29
+ - `/space pin` pins the space this Pi runs in (`<profile>/<name>`, `<profile>/base` in base) to the
30
+ repository of the session's folder, the same marker as `pi-space pin`, so a bare `pi-space` there
31
+ starts it; `/space unpin` removes it. Only the current space.
32
+ - `pi-spaces/pin` exports the marker logic that `pi-space` and `/space` share.
33
+
34
+ ### Changed
35
+
36
+ - The skill tells that `pi-space pin` alone opens a picker and `pi-space pin --show` prints the pinned space.
37
+
9
38
  ## 0.16.2
10
39
 
11
40
  ### Changed
package/README.md CHANGED
@@ -98,7 +98,7 @@ pi-space remove pi/work # delete it, after asking; keeps a backu
98
98
  pi-space update --every # update the packages of base and of every space of every profile
99
99
  ```
100
100
 
101
- A new space is a folder with an `agent/` folder inside it, empty except for `agent/settings.json`, which declares this package so `/space` works inside it. Sign in and install packages there as you would in a fresh Pi. Spaces made by an older version have no `agent/` folder and keep working as they are; see [Moving an old space](#moving-an-old-space).
101
+ A new space is a folder with an `agent/` folder inside it, empty except for `agent/settings.json`, which declares this package so `/space` works inside it. When the profile has a setup command, `agent/` is left to that command, which makes it (a launcher such as gentle-shell only sets up a home it made itself), and the declaration joins the `settings.json` it wrote. Sign in and install packages there as you would in a fresh Pi. Spaces made by an older version have no `agent/` folder and keep working as they are; see [Moving an old space](#moving-an-old-space).
102
102
 
103
103
  ## Commands in Pi
104
104
 
@@ -106,11 +106,13 @@ A new space is a folder with an `agent/` folder inside it, empty except for `age
106
106
  | --- | --- |
107
107
  | `/space` | Opens a list of the other spaces and restarts Pi in the one you pick. Without the interactive terminal it lists them instead. |
108
108
  | `/space list` | Lists `base` and every space, with `*` on the active one. |
109
- | `/space new <name>` | Creates an empty space (its folder, with `agent/` inside). When a setup command is set (the profile's `commands.setup`, or `PI_SPACES_SETUP`), it names `pi-space setup <profile>/<name>` to run from a shell, with this Pi's profile (`pi` when none matches). |
109
+ | `/space new <name>` | Creates an empty space (its folder, with `agent/` inside). When a setup command is set (the profile's `commands.setup`, or `PI_SPACES_SETUP`), it creates only the folder, waiting for its setup, and names `pi-space setup <profile>/<name>` to run from a shell, with this Pi's profile (`pi` when none matches): the setup makes `agent/`, then the declaration joins its `settings.json`. |
110
110
  | `/space switch <name>` | Restarts Pi in that space. `base` is the home Pi started with. |
111
111
  | `/space switch` | Same as `/space`. |
112
112
  | `/space rename <old> <new>` | Renames a space. The active space cannot be renamed. |
113
113
  | `/space remove <name> [--yes] [--no-backup]` | Deletes a space after asking, then asks whether to keep a backup in `<spaces folder>/.backups` (keeping one is first in the list; dismissing the question keeps the space). `--yes` skips the questions and keeps a backup; it is required without a dialog (print and JSON modes). `--no-backup` deletes without one. |
114
+ | `/space pin` | Pins the space this Pi runs in (`<profile>/<name>`, or `<profile>/base` in base) to the repository of the session's folder, so a bare `pi-space` there starts it (see [`pi-space pin`](cli/README.md#pinning-a-space-to-a-folder)). Only the current space; another one is pinned from a shell with `pi-space pin`. |
115
+ | `/space unpin` | Removes the space pinned to that repository, as `pi-space unpin` does. |
114
116
  | `pi --space <name>` | Starts Pi directly in a space, keeping the prompt and every other option. |
115
117
  | `pi --space <name> <command> [args...]` | Runs one of Pi's package commands (`install`, `remove`, `uninstall`, `update`, `list`) in a space, or in the base home with `base`: `pi --space work update --extensions`, `pi --space work install npm:<package>`. |
116
118
 
@@ -278,14 +280,14 @@ Keep the `spaceEnv` of the program's own config home: without it, a space's `--h
278
280
 
279
281
  ### Example: gentle-shell
280
282
 
281
- For whoever uses gentle-shell, this is a profile for it. The base runs `gentle-shell` as it is, and each space gets its own config folder, `gentle-ai`, next to its `agent/` folder through `spaceEnv`:
283
+ For whoever uses gentle-shell, this is a profile for it. The base runs `gentle-shell` as it is, and each space gets its own config folder, `gentle-ai`, next to its `agent/` folder through `spaceEnv` (gentle-shell 4.8 adds `gentle-ai` to `GENTLE_PI_CONFIG_HOME`, so it names the space's root; an older gentle-shell took `{space}/gentle-ai`):
282
284
 
283
285
  ```toml
284
286
  schema = "pi-spaces.config/v2"
285
287
 
286
288
  [profiles.gentle]
287
289
  home = "~/.gentle-shell/agent"
288
- spaceEnv = { GENTLE_PI_CONFIG_HOME = "{space}/gentle-ai" }
290
+ spaceEnv = { GENTLE_PI_CONFIG_HOME = "{space}" }
289
291
 
290
292
  [profiles.gentle.commands]
291
293
  base = "gentle-shell"
@@ -306,7 +308,7 @@ setup = "gentle-shell --home {home} setup"
306
308
  "space": "gentle-shell --home {home}",
307
309
  "setup": "gentle-shell --home {home} setup"
308
310
  },
309
- "spaceEnv": { "GENTLE_PI_CONFIG_HOME": "{space}/gentle-ai" }
311
+ "spaceEnv": { "GENTLE_PI_CONFIG_HOME": "{space}" }
310
312
  }
311
313
  }
312
314
  }
package/dist/command.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { join } from "node:path";
3
3
 
4
4
  import { profileCommand } from "./launch.js";
5
+ import { PinError, pinnedMessage, removePin, unpinnedMessage, writePin } from "./pin.js";
5
6
  import { parseSpaceFlag, relaunchEnv, resolveSwitch } from "./relaunch.js";
6
7
  import {
7
8
  activeSpace,
@@ -10,19 +11,21 @@ import {
10
11
  backupSpace,
11
12
  checkRemovable,
12
13
  createSpace,
14
+ createSpaceRoot,
13
15
 
14
16
  hasSetupCommand,
15
17
  listSpaces,
18
+ markPending,
16
19
 
17
20
  removeSpace,
18
21
  renameSpace,
19
22
  SpaceError,
20
23
  } from "./spaces.js";
21
24
 
22
- export const USAGE = "Usage: /space [list | new <name> | remove <name> [--yes] [--no-backup] | rename <old> <new> | switch [<name>]]";
25
+ export const USAGE = "Usage: /space [list | new <name> | remove <name> [--yes] [--no-backup] | rename <old> <new> | switch [<name>] | pin | unpin]";
23
26
  const KEEP_BACKUP = "Keep a backup";
24
27
  const NO_BACKUP = "Delete without a backup";
25
- const SUBCOMMANDS = ["list", "new", "remove", "rename", "switch"];
28
+ const SUBCOMMANDS = ["list", "new", "remove", "rename", "switch", "pin", "unpin"];
26
29
 
27
30
 
28
31
 
@@ -49,6 +52,10 @@ const SUBCOMMANDS = ["list", "new", "remove", "rename", "switch"];
49
52
 
50
53
 
51
54
 
55
+
56
+
57
+
58
+
52
59
 
53
60
 
54
61
  export async function runSpaceCommand(args , deps ) {
@@ -60,11 +67,20 @@ export async function runSpaceCommand(args , deps )
60
67
  if (sub === "list" && rest.length === 0) return list(deps);
61
68
  if (sub === "new" && rest.length === 1) {
62
69
  const [name] = rest;
63
- const path = createSpace(deps.dir, name, deps.declaration());
70
+ const withSetup = hasSetupCommand(deps.env) || Boolean(deps.profile?.setup);
71
+ // With a setup command the agent home is left to pi-space setup: a launcher such as gentle-shell only provisions
72
+ // a home it made, and the declaration joins its settings once the setup succeeds.
73
+ let path ;
74
+ if (withSetup) {
75
+ path = createSpaceRoot(deps.dir, name);
76
+ markPending(path, deps.declaration());
77
+ } else {
78
+ path = createSpace(deps.dir, name, deps.declaration());
79
+ }
64
80
  // pi-space names a space with its profile; without a matching profile this Pi is plain pi.
65
81
  const qualified = `${deps.profile?.name ?? "pi"}/${name}`;
66
82
  ctx.ui.notify(
67
- hasSetupCommand(deps.env) || Boolean(deps.profile?.setup)
83
+ withSetup
68
84
  ? `Created space "${name}" at ${path}. Prepare it from a shell with: pi-space setup ${qualified}. Then enter it with /space switch ${name}.`
69
85
  : `Created space "${name}" at ${path}. Enter it with /space switch ${name}.`,
70
86
  "info",
@@ -78,6 +94,8 @@ export async function runSpaceCommand(args , deps )
78
94
  ctx.ui.notify(`Renamed space "${rest[0]}" to "${rest[1]}".`, "info");
79
95
  return;
80
96
  }
97
+ if (sub === "pin" && rest.length === 0) return pin(deps);
98
+ if (sub === "unpin" && rest.length === 0) return unpin(deps);
81
99
  if (sub === "switch" && rest.length === 0) return await pickAndSwitch(deps);
82
100
  if (sub === "switch" && rest.length === 1) return switchTo(rest[0], deps);
83
101
  ctx.ui.notify(USAGE, "error");
@@ -139,6 +157,31 @@ async function remove({ name, yes, backup } , deps )
139
157
  ctx.ui.notify(`Removed space "${name}".`, "info");
140
158
  }
141
159
 
160
+ /**
161
+ * /space pin: pins this Pi's own space, as pi-space names it (`<profile>/<name>`, `<profile>/base` in base), to the
162
+ * repository of the session's folder; a bare pi-space there then starts it. Only the current space: another one is
163
+ * pinned from a shell with pi-space pin.
164
+ */
165
+ function pin(deps ) {
166
+ const space = activeSpace(deps.dir, deps.currentHome()) ?? BASE;
167
+ try {
168
+ deps.ctx.ui.notify(pinnedMessage(writePin(deps.cwd(), deps.userHome, `${deps.profile?.name ?? "pi"}/${space}`)), "info");
169
+ } catch (error) {
170
+ if (!(error instanceof PinError)) throw error;
171
+ deps.ctx.ui.notify(error.message, "error");
172
+ }
173
+ }
174
+
175
+ /** /space unpin: removes the marker that applies in the session's folder, as pi-space unpin does. */
176
+ function unpin(deps ) {
177
+ try {
178
+ deps.ctx.ui.notify(unpinnedMessage(removePin(deps.cwd(), deps.userHome)), "info");
179
+ } catch (error) {
180
+ if (!(error instanceof PinError)) throw error;
181
+ deps.ctx.ui.notify(error.message, "error");
182
+ }
183
+ }
184
+
142
185
  function protectedHomes(deps ) {
143
186
  return deps.env.PI_SPACES_BASE_HOME ? [deps.env.PI_SPACES_BASE_HOME] : [];
144
187
  }
package/dist/pin.js ADDED
@@ -0,0 +1,207 @@
1
+ // A space pinned to a folder, like .nvmrc: <folder>/.pi/pi-space/space holds one line, <profile>/<name>, next to a
2
+ // .gitignore that ignores the whole pi-space folder, itself included. .pi itself is Pi's project folder and is never
3
+ // touched. Shared by the pi-space command (pin, unpin, a bare pi-space) and /space pin and /space unpin.
4
+ // A marker may come with a cloned repository: nothing is written or removed through a symbolic link, and a marker
5
+ // whose line holds control or bidi characters names nothing (it is never echoed to a terminal).
6
+ import { spawnSync } from "node:child_process";
7
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
9
+ import { samePath } from "./spaces.js";
10
+
11
+ export const PIN_FOLDER = join(".pi", "pi-space");
12
+ export const PIN_FILE = "space";
13
+ export const PIN_IGNORE = ".gitignore";
14
+ export const PIN_IGNORE_TEXT = "# pi-space: this folder is local to this machine; this file ignores all of it, itself included.\n*\n";
15
+
16
+ /** Why a pin or unpin did not happen; `code` is the exit status pi-space gives it (2: the home folder, 1: anything else). */
17
+ export class PinError extends Error {
18
+ code ;
19
+ constructor(message , code ) {
20
+ super(message);
21
+ this.code = code;
22
+ }
23
+ }
24
+
25
+ /** Whether `path` is a file, following links; false for anything that cannot be read as one. */
26
+ function isFile(path ) {
27
+ try {
28
+ return statSync(path).isFile();
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ /** Whether `path` is a symbolic link itself (not followed); false when there is nothing there. */
35
+ function isLink(path ) {
36
+ try {
37
+ return lstatSync(path).isSymbolicLink();
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * The marker that applies in `from`: the first <folder>/.pi/pi-space/space file from it upwards. The home folder is
45
+ * skipped: its .pi is Pi's own folder, not a project.
46
+ */
47
+ export function findPin(from , home ) {
48
+ for (let folder = resolve(from); ; folder = dirname(folder)) {
49
+ const file = join(folder, PIN_FOLDER, PIN_FILE);
50
+ if (!samePath(folder, home) && isFile(file)) return file;
51
+ if (dirname(folder) === folder) return undefined;
52
+ }
53
+ }
54
+
55
+ /** Control characters (C0, DEL, C1) and the bidi controls that could rewrite what the terminal shows. */
56
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/;
57
+
58
+ /**
59
+ * What a marker names: `name` when it holds exactly one `<profile>/<name>` (blank lines and # comments left out),
60
+ * neither when it does not, and `error` when it cannot be read.
61
+ */
62
+ export function readPin(file ) {
63
+ let text ;
64
+ try {
65
+ text = readFileSync(file, "utf8");
66
+ } catch (error) {
67
+ return { error: (error ).message };
68
+ }
69
+ const lines = text
70
+ .split(/\r?\n/)
71
+ .map((line) => line.trim())
72
+ .filter((line) => line !== "" && !line.startsWith("#"));
73
+ if (lines.length !== 1 || UNSAFE.test(lines[0])) return {};
74
+ const slash = lines[0].indexOf("/");
75
+ return slash > 0 && slash < lines[0].length - 1 ? { name: lines[0] } : {};
76
+ }
77
+
78
+ /** The real path of a folder, links and Windows short names (RUNNER~1) resolved; the path itself when it cannot be read. */
79
+ function realFolder(path ) {
80
+ try {
81
+ return realpathSync.native(path);
82
+ } catch {
83
+ return resolve(path);
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Where pin and unpin work: the root of the git repository of `cwd`, else `cwd` (also when git is missing or hangs).
89
+ * The root is `cwd` or the folder above it that git names, spelled as `cwd` is: git gives the real path, which on
90
+ * Windows may be the long form of a short name, and on macOS /private/var for /var.
91
+ */
92
+ export function pinRoot(cwd ) {
93
+ const here = resolve(cwd);
94
+ const git = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: here, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000 });
95
+ const top = git.status === 0 ? git.stdout.trim() : "";
96
+ if (top === "") return here;
97
+ const real = realFolder(top);
98
+ for (let folder = here; ; folder = dirname(folder)) {
99
+ if (samePath(realFolder(folder), real)) return folder;
100
+ if (dirname(folder) === folder) return resolve(top);
101
+ }
102
+ }
103
+
104
+ /** The refusal of the home folder, whose .pi is Pi's own folder; undefined for any other root. */
105
+ export function homeRefusal(root , home ) {
106
+ return samePath(root, home) ? `${root} is your home folder, where .pi is Pi's own folder; pin a space in a project folder.` : undefined;
107
+ }
108
+
109
+ /** The first of .pi, .pi/pi-space and the given files in it that is a symbolic link. */
110
+ function linkIn(owner , files ) {
111
+ const folder = join(owner, PIN_FOLDER);
112
+ return [dirname(folder), folder, ...files.map((name) => join(folder, name))].find(isLink);
113
+ }
114
+
115
+ /** Whether `path` is `folder` or inside it. */
116
+ function isWithin(path , folder ) {
117
+ const rel = relative(folder, path);
118
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
119
+ }
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+ /**
129
+ * Pins `name` (`<profile>/<name>`, already known to exist) to the repository of `cwd`: writes the marker, and its
130
+ * .gitignore when there is none. The marker is written to a temporary file and renamed over the old one, so a failure
131
+ * leaves it as it was; a folder this call made is removed again. Throws a PinError for the home folder, a symbolic
132
+ * link, or a write that fails.
133
+ */
134
+ export function writePin(cwd , home , name ) {
135
+ const root = pinRoot(cwd);
136
+ const refusal = homeRefusal(root, home);
137
+ if (refusal !== undefined) throw new PinError(refusal, 2);
138
+ const link = linkIn(root, [PIN_FILE, PIN_IGNORE]);
139
+ if (link !== undefined) throw new PinError(`${link} is a symbolic link; pi-space does not write through it.`, 1);
140
+ const folder = join(root, PIN_FOLDER);
141
+ const file = join(folder, PIN_FILE);
142
+ const before = isFile(file) ? readPin(file).name : undefined;
143
+ const temporary = join(folder, `.${PIN_FILE}-${process.pid}.tmp`);
144
+ let made ;
145
+ try {
146
+ made = mkdirSync(folder, { recursive: true });
147
+ const ignore = join(folder, PIN_IGNORE);
148
+ if (!existsSync(ignore)) writeFileSync(ignore, PIN_IGNORE_TEXT, { flag: "wx" });
149
+ writeFileSync(temporary, `${name}\n`, { flag: "wx" });
150
+ renameSync(temporary, file);
151
+ } catch (error) {
152
+ // Cleaning up must not hide the reason: a path under a file (ENOTDIR) cannot be removed either.
153
+ try {
154
+ if (made !== undefined) rmSync(made, { recursive: true, force: true });
155
+ else rmSync(temporary, { force: true });
156
+ } catch {}
157
+ throw new PinError(`cannot write ${file}: ${(error ).message}`, 1);
158
+ }
159
+ return { name, file, ...(before !== undefined && before !== name ? { previous: before } : {}) };
160
+ }
161
+
162
+ /** The line that reports a pin. */
163
+ export function pinnedMessage({ name, file, previous } ) {
164
+ return `Pinned ${name} in ${file}${previous !== undefined ? ` (was ${previous})` : ""}.`;
165
+ }
166
+
167
+
168
+
169
+
170
+
171
+ /**
172
+ * Removes the marker that applies in `cwd` when it is inside the repository of `cwd` (else `cwd` itself), the
173
+ * .gitignore pin wrote, and the folder once empty (and .pi, when nothing else is in it). A marker of a folder above is
174
+ * reported as inherited and left. Throws a PinError for a symbolic link or a removal that fails.
175
+ */
176
+ export function removePin(cwd , home ) {
177
+ const root = pinRoot(cwd);
178
+ const here = findPin(cwd, home);
179
+ // <owner>/.pi/pi-space/space: the folder the marker belongs to.
180
+ const owner = here === undefined ? undefined : dirname(dirname(dirname(here)));
181
+ if (here === undefined || owner === undefined || !isWithin(owner, root)) return { kind: "none", root, ...(here !== undefined ? { inherited: here } : {}) };
182
+ const link = linkIn(owner, []);
183
+ if (link !== undefined) throw new PinError(`${link} is a symbolic link; pi-space does not remove through it.`, 1);
184
+ const folder = dirname(here);
185
+ const { name, error } = readPin(here);
186
+ const label = name ?? (error !== undefined ? "an unreadable marker" : "an invalid marker");
187
+ try {
188
+ rmSync(here);
189
+ const ignore = join(folder, PIN_IGNORE);
190
+ if (isFile(ignore) && !isLink(ignore) && readFileSync(ignore, "utf8") === PIN_IGNORE_TEXT) rmSync(ignore);
191
+ if (readdirSync(folder).length > 0) return { kind: "removed", label, file: here, folder, folderRemoved: false };
192
+ rmdirSync(folder);
193
+ // A .pi that pin made and that holds nothing else goes too; one with anything in it is Pi's and stays.
194
+ if (readdirSync(dirname(folder)).length === 0) rmdirSync(dirname(folder));
195
+ return { kind: "removed", label, file: here, folder, folderRemoved: true };
196
+ } catch (error) {
197
+ throw new PinError(`cannot remove ${here}: ${(error ).message}`, 1);
198
+ }
199
+ }
200
+
201
+ /** The line that reports an unpin. */
202
+ export function unpinnedMessage(result ) {
203
+ if (result.kind === "none") return `No space pinned in ${result.root}${result.inherited !== undefined ? `; the one here comes from ${result.inherited}` : ""}.`;
204
+ return result.folderRemoved
205
+ ? `Unpinned ${result.label} (removed ${result.folder}).`
206
+ : `Unpinned ${result.label} (removed ${result.file}; ${result.folder} holds other files and stays).`;
207
+ }
package/dist/spaces.js CHANGED
@@ -8,6 +8,11 @@ import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
8
8
  export const BASE = "base";
9
9
  /** The folder inside a space's root that is its agent home. */
10
10
  export const AGENT = "agent";
11
+ /**
12
+ * The file in a new space's root that waits for its setup command: the space is rooted, but its agent home is left to
13
+ * the setup, and the declaration it holds joins the settings.json the setup wrote once the setup succeeds.
14
+ */
15
+ export const PENDING = ".pi-space-new";
11
16
  const NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
12
17
 
13
18
  export class SpaceError extends Error {
@@ -84,17 +89,21 @@ export function listSpaces(dir ) {
84
89
 
85
90
  /**
86
91
  * The agent home of the space whose root is `root`: `<root>/agent` when that is a real folder (a symlink or a file named
87
- * agent does not count), else the root itself, an old space whose folder is the agent home. Pi's own agent home never has
88
- * a folder named agent, so the folder tells the two layouts apart.
92
+ * agent does not count) or when the space still waits for its setup (PENDING), else the root itself, an old space whose
93
+ * folder is the agent home. Pi's own agent home never has a folder named agent, so the folder tells the two layouts apart.
89
94
  */
90
95
  export function spaceHome(root ) {
91
- const home = join(root, AGENT);
92
- return isRealFolder(home) ? home : root;
96
+ return isRooted(root) ? join(root, AGENT) : root;
93
97
  }
94
98
 
95
- /** True when the space with this root keeps its agent home in `<root>/agent`. */
99
+ /** True when the space with this root keeps its agent home in `<root>/agent`, or will once its setup makes it. */
96
100
  export function isRooted(root ) {
97
- return isRealFolder(join(root, AGENT));
101
+ return isRealFolder(join(root, AGENT)) || isPending(root);
102
+ }
103
+
104
+ /** True when the space with this root waits for its setup command (its root holds PENDING). */
105
+ export function isPending(root ) {
106
+ return existsSync(join(root, PENDING));
98
107
  }
99
108
 
100
109
  /** The space whose agent home is the given one (`<root>/agent`, or the root of an old space), or undefined. */
@@ -122,16 +131,86 @@ function isInside(child , parent ) {
122
131
  * /space works inside it. Returns the root.
123
132
  */
124
133
  export function createSpace(dir , name , declaration ) {
134
+ const path = createSpaceRoot(dir, name);
135
+ declareInHome(join(path, AGENT), declaration);
136
+ return path;
137
+ }
138
+
139
+ /**
140
+ * Creates a space's root alone, without its agent home, so a setup command can make that home itself (a launcher such as
141
+ * gentle-shell only provisions a home it made). Returns the root.
142
+ */
143
+ export function createSpaceRoot(dir , name ) {
125
144
  assertName(name);
126
145
  const path = join(dir, name);
127
146
  if (existsSync(path) || isSymlink(path)) throw new SpaceError(`Space "${name}" already exists.`);
128
147
  mkdirSync(dir, { recursive: true });
129
148
  mkdirSync(path);
130
- mkdirSync(join(path, AGENT));
131
- writeFileSync(join(path, AGENT, "settings.json"), `${JSON.stringify({ packages: [declaration] }, null, 2)}\n`);
132
149
  return path;
133
150
  }
134
151
 
152
+ /**
153
+ * Marks a new space's root as waiting for its setup command, with the declaration to add once it succeeds (none for a
154
+ * space that does not declare this package).
155
+ */
156
+ export function markPending(root , declaration ) {
157
+ writeFileSync(join(root, PENDING), `${JSON.stringify(declaration === undefined ? {} : { declaration }, null, 2)}\n`);
158
+ }
159
+
160
+ /**
161
+ * Finishes a space whose setup succeeded: adds the declaration its PENDING file holds to the settings.json of its agent
162
+ * home (making both when the setup did not) and removes the file. False when the space was not waiting for a setup.
163
+ */
164
+ export function finishPending(root ) {
165
+ const file = join(root, PENDING);
166
+ if (!existsSync(file)) return false;
167
+ let pending ;
168
+ try {
169
+ pending = JSON.parse(readFileSync(file, "utf8"));
170
+ } catch {
171
+ throw new SpaceError(`${file} is not valid JSON; fix or delete it and run pi-space setup again.`);
172
+ }
173
+ declareInHome(join(root, AGENT), pending.declaration);
174
+ rmSync(file);
175
+ return true;
176
+ }
177
+
178
+ function sourceOf(entry ) {
179
+ const source = typeof entry === "string" ? entry : (entry )?.source;
180
+ return typeof source === "string" ? source : undefined;
181
+ }
182
+
183
+ /** Two package sources name the same package: npm sources by package name, whatever their version; others as written. */
184
+ function sameSource(a , b ) {
185
+ if (a === undefined || b === undefined) return false;
186
+ if (a.startsWith("npm:") && b.startsWith("npm:")) return npmName(a) === npmName(b);
187
+ return a === b;
188
+ }
189
+
190
+ /**
191
+ * Makes the agent home when it is missing and adds the declaration to its settings.json, keeping everything already
192
+ * there; a package with the same source is not declared twice. Without a declaration it only makes sure the file exists.
193
+ */
194
+ export function declareInHome(home , declaration ) {
195
+ mkdirSync(home, { recursive: true });
196
+ const file = join(home, "settings.json");
197
+ let settings = {};
198
+ if (existsSync(file)) {
199
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
200
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new SpaceError(`${file} is not a JSON object.`);
201
+ settings = parsed ;
202
+ if (!declaration) return;
203
+ }
204
+ if (declaration) {
205
+ if (settings.packages !== undefined && !Array.isArray(settings.packages)) throw new SpaceError(`${file} has "packages" that is not a list.`);
206
+ const packages = (settings.packages ) ?? [];
207
+ const wanted = sourceOf(declaration);
208
+ if (packages.some((entry) => sameSource(sourceOf(entry), wanted))) return;
209
+ settings.packages = [...packages, declaration];
210
+ }
211
+ writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
212
+ }
213
+
135
214
  function isSymlink(path ) {
136
215
  try {
137
216
  return lstatSync(path).isSymbolicLink();
@@ -267,6 +346,7 @@ export function migrateSpace(
267
346
  ) {
268
347
  assertName(name);
269
348
  const root = join(dir, name);
349
+ if (isPending(root)) throw new SpaceError(`Space "${name}" is waiting for its setup command, which makes its agent home; run pi-space setup.`);
270
350
  if (isRooted(root)) throw new SpaceError(`Space "${name}" already has its agent home in ${join(root, AGENT)}.`);
271
351
  checkRemovable(dir, name, agentHome, protect, userHome, "migrate");
272
352
  const home = join(root, AGENT);
@@ -83,7 +83,7 @@ export default function (pi: ExtensionAPI) {
83
83
  });
84
84
 
85
85
  pi.registerCommand("space", {
86
- description: "Pick a Pi space to switch to, or list, create, remove and rename spaces (separate agent homes)",
86
+ description: "Pick a Pi space to switch to, or list, create, remove and rename spaces (separate agent homes), or pin this one to the repository",
87
87
  getArgumentCompletions: (prefix) => completeSpaceArgs(prefix, dir),
88
88
  handler: async (args, ctx) => {
89
89
  // Without a UI (print and JSON modes) notifications go nowhere, so they go to stderr;
@@ -100,6 +100,8 @@ export default function (pi: ExtensionAPI) {
100
100
  declaration: () => findOwnDeclaration(getAgentDir(), packageName, packageRoot),
101
101
  command: () => relaunchCommand(),
102
102
  relaunch: scheduleRelaunch,
103
+ cwd: () => ctx.cwd,
104
+ userHome: homedir(),
103
105
  });
104
106
  },
105
107
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spaces",
3
- "version": "0.16.2",
3
+ "version": "0.18.0",
4
4
  "description": "Named spaces for Pi: keep several agent homes (sign-ins, packages, settings) and pick one by name.",
5
5
  "license": "MIT",
6
6
  "author": "jals1212",
@@ -21,6 +21,7 @@
21
21
  "exports": {
22
22
  "./spaces": "./dist/spaces.js",
23
23
  "./config": "./dist/config.js",
24
+ "./pin": "./dist/pin.js",
24
25
  "./package.json": "./package.json"
25
26
  },
26
27
  "pi": {
@@ -33,9 +33,9 @@ Use when a task depends on which Pi agent home this session uses (settings, sign
33
33
  | Spaces folder | `PI_SPACES_DIR`, else the `dir` of the profile whose `home` is the base home, else `spaces` next to the base home (`PI_SPACES_BASE_HOME`, else this home) |
34
34
  | Profiles, or why a variable differs per space | The config file (`PI_SPACES_CONFIG`, else `config.toml` or `config.json` in `~/.config/pi-spaces`, then in `~/.pi-spaces`): a profile's `spaceEnv` variables are set only inside spaces (`{home}` the agent home, `{space}` the space's root folder and `{name}` filled in) and removed in base; without `spaceEnv` whatever a program keeps outside its agent home is shared with base |
35
35
  | Pick a space from a shell | bare `pi-space` on a terminal opens a picker of every profile's spaces (`<profile>/<name>`, `base` included) and starts Pi in the one chosen |
36
- | Pin a space to a repository (like `.nvmrc`) | `pi-space pin <profile>/<name>` writes `.pi/pi-space/space` (one line `<profile>/<name>`) and a self-ignoring `.pi/pi-space/.gitignore` in the git root; a bare `pi-space` there or below then starts that space at once (a space named on the command line wins; `pi-space pick` opens the picker); `pi-space pin` shows it, `pi-space unpin` removes it. Only `pi-space` reads it, not Pi or `/space` |
36
+ | Pin a space to a repository (like `.nvmrc`) | `pi-space pin <profile>/<name>` writes `.pi/pi-space/space` (one line `<profile>/<name>`) and a self-ignoring `.pi/pi-space/.gitignore` in the git root; a bare `pi-space` there or below then starts that space at once (a space named on the command line wins; `pi-space pick` opens the picker); `pi-space pin` alone opens a picker to choose it on a terminal (the pinned space marked `⌂`), `pi-space pin --show` prints it, `pi-space unpin` removes it. From inside Pi, the user can pin this session's own space with `/space pin` and remove it with `/space unpin`. Only `pi-space` reads the marker; Pi and `/space switch` do not |
37
37
  | Rename a space | User request only: `pi-space rename <profile>/<old> <new>`; the new name alone or with the same profile (`<profile>/<new>`), a space never changes profile; refused for base and for the space you are in |
38
- | Create a space | `pi-space new <profile>/<name>`, or ask the user for `/space new <name>` (this Pi's profile); `pi-space new` also runs the profile's setup command when there is one (or `--setup <cmd>` for one call), and asks whether the space declares the extension: pass `--extension` or `--no-extension` when running it for the user, since there is no terminal to answer |
38
+ | Create a space | `pi-space new <profile>/<name>`, or ask the user for `/space new <name>` (this Pi's profile); `pi-space new` also runs the profile's setup command when there is one (or `--setup <cmd>` for one call), which makes `<space>/agent` itself (the declaration is added after it succeeds; `/space new` with a setup command leaves the space waiting until `pi-space setup` runs), and asks whether the space declares the extension: pass `--extension` or `--no-extension` when running it for the user, since there is no terminal to answer |
39
39
  | Prepare a space for the program that runs Pi | `pi-space setup <profile>/<name>` (or `<profile>/base`, `<profile>/--every` for base then its spaces, or `--every` for the base and spaces of every profile with a setup, which pi has not by default; the profile's `commands.setup`): runs the setup command (`{home}` becomes the space's agent home, `{space}` its root folder and `{name}` its name) with the agent home as `PI_CODING_AGENT_DIR`; in base `{home}` is the profile's home and `{name}` is `base` |
40
40
  | Work in another space | User runs `/space switch <name>` (with a v2 profile it runs `commands.space`, or `<commands.base> --space <name>`; `/space switch base` runs `commands.base`; otherwise Pi starts again), or `$PI_SPACES_COMMAND --space <name> "<prompt>"` (only when the command has no `{home}` or `{name}`), or `pi-space <profile>/<name>` from a shell |
41
41
  | Give an old space the `agent/` layout | User request only: `pi-space migrate <profile>/<name>` (or `<profile>/--every`, `--every`): copies the space to `.backups`, then moves its content into `<space>/agent/`; refuses base, the space you are in and a space that already has `agent/` |
package/src/command.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  import { join } from "node:path";
3
3
  import type { Profile } from "./config.ts";
4
4
  import { profileCommand } from "./launch.ts";
5
+ import { PinError, pinnedMessage, removePin, unpinnedMessage, writePin } from "./pin.ts";
5
6
  import { type Command, parseSpaceFlag, relaunchEnv, resolveSwitch } from "./relaunch.ts";
6
7
  import {
7
8
  activeSpace,
@@ -10,19 +11,21 @@ import {
10
11
  backupSpace,
11
12
  checkRemovable,
12
13
  createSpace,
14
+ createSpaceRoot,
13
15
  type Env,
14
16
  hasSetupCommand,
15
17
  listSpaces,
18
+ markPending,
16
19
  type PackageDeclaration,
17
20
  removeSpace,
18
21
  renameSpace,
19
22
  SpaceError,
20
23
  } from "./spaces.ts";
21
24
 
22
- export const USAGE = "Usage: /space [list | new <name> | remove <name> [--yes] [--no-backup] | rename <old> <new> | switch [<name>]]";
25
+ export const USAGE = "Usage: /space [list | new <name> | remove <name> [--yes] [--no-backup] | rename <old> <new> | switch [<name>] | pin | unpin]";
23
26
  const KEEP_BACKUP = "Keep a backup";
24
27
  const NO_BACKUP = "Delete without a backup";
25
- const SUBCOMMANDS = ["list", "new", "remove", "rename", "switch"];
28
+ const SUBCOMMANDS = ["list", "new", "remove", "rename", "switch", "pin", "unpin"];
26
29
 
27
30
  export interface SpaceCommandContext {
28
31
  mode: string;
@@ -49,6 +52,10 @@ export interface SpaceCommandDeps {
49
52
  /** The command that starts this Pi process again. */
50
53
  command(): Command;
51
54
  relaunch(command: Command, env: Env): void;
55
+ /** The session's folder: /space pin and /space unpin work in its repository. */
56
+ cwd(): string;
57
+ /** The user's home folder, whose .pi is Pi's own and is never pinned. */
58
+ userHome: string;
52
59
  }
53
60
 
54
61
  export async function runSpaceCommand(args: string, deps: SpaceCommandDeps): Promise<void> {
@@ -60,11 +67,20 @@ export async function runSpaceCommand(args: string, deps: SpaceCommandDeps): Pro
60
67
  if (sub === "list" && rest.length === 0) return list(deps);
61
68
  if (sub === "new" && rest.length === 1) {
62
69
  const [name] = rest;
63
- const path = createSpace(deps.dir, name, deps.declaration());
70
+ const withSetup = hasSetupCommand(deps.env) || Boolean(deps.profile?.setup);
71
+ // With a setup command the agent home is left to pi-space setup: a launcher such as gentle-shell only provisions
72
+ // a home it made, and the declaration joins its settings once the setup succeeds.
73
+ let path: string;
74
+ if (withSetup) {
75
+ path = createSpaceRoot(deps.dir, name);
76
+ markPending(path, deps.declaration());
77
+ } else {
78
+ path = createSpace(deps.dir, name, deps.declaration());
79
+ }
64
80
  // pi-space names a space with its profile; without a matching profile this Pi is plain pi.
65
81
  const qualified = `${deps.profile?.name ?? "pi"}/${name}`;
66
82
  ctx.ui.notify(
67
- hasSetupCommand(deps.env) || Boolean(deps.profile?.setup)
83
+ withSetup
68
84
  ? `Created space "${name}" at ${path}. Prepare it from a shell with: pi-space setup ${qualified}. Then enter it with /space switch ${name}.`
69
85
  : `Created space "${name}" at ${path}. Enter it with /space switch ${name}.`,
70
86
  "info",
@@ -78,6 +94,8 @@ export async function runSpaceCommand(args: string, deps: SpaceCommandDeps): Pro
78
94
  ctx.ui.notify(`Renamed space "${rest[0]}" to "${rest[1]}".`, "info");
79
95
  return;
80
96
  }
97
+ if (sub === "pin" && rest.length === 0) return pin(deps);
98
+ if (sub === "unpin" && rest.length === 0) return unpin(deps);
81
99
  if (sub === "switch" && rest.length === 0) return await pickAndSwitch(deps);
82
100
  if (sub === "switch" && rest.length === 1) return switchTo(rest[0], deps);
83
101
  ctx.ui.notify(USAGE, "error");
@@ -139,6 +157,31 @@ async function remove({ name, yes, backup }: Removal, deps: SpaceCommandDeps): P
139
157
  ctx.ui.notify(`Removed space "${name}".`, "info");
140
158
  }
141
159
 
160
+ /**
161
+ * /space pin: pins this Pi's own space, as pi-space names it (`<profile>/<name>`, `<profile>/base` in base), to the
162
+ * repository of the session's folder; a bare pi-space there then starts it. Only the current space: another one is
163
+ * pinned from a shell with pi-space pin.
164
+ */
165
+ function pin(deps: SpaceCommandDeps): void {
166
+ const space = activeSpace(deps.dir, deps.currentHome()) ?? BASE;
167
+ try {
168
+ deps.ctx.ui.notify(pinnedMessage(writePin(deps.cwd(), deps.userHome, `${deps.profile?.name ?? "pi"}/${space}`)), "info");
169
+ } catch (error) {
170
+ if (!(error instanceof PinError)) throw error;
171
+ deps.ctx.ui.notify(error.message, "error");
172
+ }
173
+ }
174
+
175
+ /** /space unpin: removes the marker that applies in the session's folder, as pi-space unpin does. */
176
+ function unpin(deps: SpaceCommandDeps): void {
177
+ try {
178
+ deps.ctx.ui.notify(unpinnedMessage(removePin(deps.cwd(), deps.userHome)), "info");
179
+ } catch (error) {
180
+ if (!(error instanceof PinError)) throw error;
181
+ deps.ctx.ui.notify(error.message, "error");
182
+ }
183
+ }
184
+
142
185
  function protectedHomes(deps: SpaceCommandDeps): string[] {
143
186
  return deps.env.PI_SPACES_BASE_HOME ? [deps.env.PI_SPACES_BASE_HOME] : [];
144
187
  }
package/src/pin.ts ADDED
@@ -0,0 +1,207 @@
1
+ // A space pinned to a folder, like .nvmrc: <folder>/.pi/pi-space/space holds one line, <profile>/<name>, next to a
2
+ // .gitignore that ignores the whole pi-space folder, itself included. .pi itself is Pi's project folder and is never
3
+ // touched. Shared by the pi-space command (pin, unpin, a bare pi-space) and /space pin and /space unpin.
4
+ // A marker may come with a cloned repository: nothing is written or removed through a symbolic link, and a marker
5
+ // whose line holds control or bidi characters names nothing (it is never echoed to a terminal).
6
+ import { spawnSync } from "node:child_process";
7
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
9
+ import { samePath } from "./spaces.ts";
10
+
11
+ export const PIN_FOLDER = join(".pi", "pi-space");
12
+ export const PIN_FILE = "space";
13
+ export const PIN_IGNORE = ".gitignore";
14
+ export const PIN_IGNORE_TEXT = "# pi-space: this folder is local to this machine; this file ignores all of it, itself included.\n*\n";
15
+
16
+ /** Why a pin or unpin did not happen; `code` is the exit status pi-space gives it (2: the home folder, 1: anything else). */
17
+ export class PinError extends Error {
18
+ readonly code: 1 | 2;
19
+ constructor(message: string, code: 1 | 2) {
20
+ super(message);
21
+ this.code = code;
22
+ }
23
+ }
24
+
25
+ /** Whether `path` is a file, following links; false for anything that cannot be read as one. */
26
+ function isFile(path: string): boolean {
27
+ try {
28
+ return statSync(path).isFile();
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ /** Whether `path` is a symbolic link itself (not followed); false when there is nothing there. */
35
+ function isLink(path: string): boolean {
36
+ try {
37
+ return lstatSync(path).isSymbolicLink();
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * The marker that applies in `from`: the first <folder>/.pi/pi-space/space file from it upwards. The home folder is
45
+ * skipped: its .pi is Pi's own folder, not a project.
46
+ */
47
+ export function findPin(from: string, home: string): string | undefined {
48
+ for (let folder = resolve(from); ; folder = dirname(folder)) {
49
+ const file = join(folder, PIN_FOLDER, PIN_FILE);
50
+ if (!samePath(folder, home) && isFile(file)) return file;
51
+ if (dirname(folder) === folder) return undefined;
52
+ }
53
+ }
54
+
55
+ /** Control characters (C0, DEL, C1) and the bidi controls that could rewrite what the terminal shows. */
56
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/;
57
+
58
+ /**
59
+ * What a marker names: `name` when it holds exactly one `<profile>/<name>` (blank lines and # comments left out),
60
+ * neither when it does not, and `error` when it cannot be read.
61
+ */
62
+ export function readPin(file: string): { name?: string; error?: string } {
63
+ let text: string;
64
+ try {
65
+ text = readFileSync(file, "utf8");
66
+ } catch (error) {
67
+ return { error: (error as Error).message };
68
+ }
69
+ const lines = text
70
+ .split(/\r?\n/)
71
+ .map((line) => line.trim())
72
+ .filter((line) => line !== "" && !line.startsWith("#"));
73
+ if (lines.length !== 1 || UNSAFE.test(lines[0])) return {};
74
+ const slash = lines[0].indexOf("/");
75
+ return slash > 0 && slash < lines[0].length - 1 ? { name: lines[0] } : {};
76
+ }
77
+
78
+ /** The real path of a folder, links and Windows short names (RUNNER~1) resolved; the path itself when it cannot be read. */
79
+ function realFolder(path: string): string {
80
+ try {
81
+ return realpathSync.native(path);
82
+ } catch {
83
+ return resolve(path);
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Where pin and unpin work: the root of the git repository of `cwd`, else `cwd` (also when git is missing or hangs).
89
+ * The root is `cwd` or the folder above it that git names, spelled as `cwd` is: git gives the real path, which on
90
+ * Windows may be the long form of a short name, and on macOS /private/var for /var.
91
+ */
92
+ export function pinRoot(cwd: string): string {
93
+ const here = resolve(cwd);
94
+ const git = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: here, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000 });
95
+ const top = git.status === 0 ? git.stdout.trim() : "";
96
+ if (top === "") return here;
97
+ const real = realFolder(top);
98
+ for (let folder = here; ; folder = dirname(folder)) {
99
+ if (samePath(realFolder(folder), real)) return folder;
100
+ if (dirname(folder) === folder) return resolve(top);
101
+ }
102
+ }
103
+
104
+ /** The refusal of the home folder, whose .pi is Pi's own folder; undefined for any other root. */
105
+ export function homeRefusal(root: string, home: string): string | undefined {
106
+ return samePath(root, home) ? `${root} is your home folder, where .pi is Pi's own folder; pin a space in a project folder.` : undefined;
107
+ }
108
+
109
+ /** The first of .pi, .pi/pi-space and the given files in it that is a symbolic link. */
110
+ function linkIn(owner: string, files: string[]): string | undefined {
111
+ const folder = join(owner, PIN_FOLDER);
112
+ return [dirname(folder), folder, ...files.map((name) => join(folder, name))].find(isLink);
113
+ }
114
+
115
+ /** Whether `path` is `folder` or inside it. */
116
+ function isWithin(path: string, folder: string): boolean {
117
+ const rel = relative(folder, path);
118
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
119
+ }
120
+
121
+ export interface Pinned {
122
+ name: string;
123
+ file: string;
124
+ /** The space the marker named before, when another. */
125
+ previous?: string;
126
+ }
127
+
128
+ /**
129
+ * Pins `name` (`<profile>/<name>`, already known to exist) to the repository of `cwd`: writes the marker, and its
130
+ * .gitignore when there is none. The marker is written to a temporary file and renamed over the old one, so a failure
131
+ * leaves it as it was; a folder this call made is removed again. Throws a PinError for the home folder, a symbolic
132
+ * link, or a write that fails.
133
+ */
134
+ export function writePin(cwd: string, home: string, name: string): Pinned {
135
+ const root = pinRoot(cwd);
136
+ const refusal = homeRefusal(root, home);
137
+ if (refusal !== undefined) throw new PinError(refusal, 2);
138
+ const link = linkIn(root, [PIN_FILE, PIN_IGNORE]);
139
+ if (link !== undefined) throw new PinError(`${link} is a symbolic link; pi-space does not write through it.`, 1);
140
+ const folder = join(root, PIN_FOLDER);
141
+ const file = join(folder, PIN_FILE);
142
+ const before = isFile(file) ? readPin(file).name : undefined;
143
+ const temporary = join(folder, `.${PIN_FILE}-${process.pid}.tmp`);
144
+ let made: string | undefined;
145
+ try {
146
+ made = mkdirSync(folder, { recursive: true });
147
+ const ignore = join(folder, PIN_IGNORE);
148
+ if (!existsSync(ignore)) writeFileSync(ignore, PIN_IGNORE_TEXT, { flag: "wx" });
149
+ writeFileSync(temporary, `${name}\n`, { flag: "wx" });
150
+ renameSync(temporary, file);
151
+ } catch (error) {
152
+ // Cleaning up must not hide the reason: a path under a file (ENOTDIR) cannot be removed either.
153
+ try {
154
+ if (made !== undefined) rmSync(made, { recursive: true, force: true });
155
+ else rmSync(temporary, { force: true });
156
+ } catch {}
157
+ throw new PinError(`cannot write ${file}: ${(error as Error).message}`, 1);
158
+ }
159
+ return { name, file, ...(before !== undefined && before !== name ? { previous: before } : {}) };
160
+ }
161
+
162
+ /** The line that reports a pin. */
163
+ export function pinnedMessage({ name, file, previous }: Pinned): string {
164
+ return `Pinned ${name} in ${file}${previous !== undefined ? ` (was ${previous})` : ""}.`;
165
+ }
166
+
167
+ export type Unpinned =
168
+ | { kind: "none"; root: string; inherited?: string }
169
+ | { kind: "removed"; label: string; file: string; folder: string; folderRemoved: boolean };
170
+
171
+ /**
172
+ * Removes the marker that applies in `cwd` when it is inside the repository of `cwd` (else `cwd` itself), the
173
+ * .gitignore pin wrote, and the folder once empty (and .pi, when nothing else is in it). A marker of a folder above is
174
+ * reported as inherited and left. Throws a PinError for a symbolic link or a removal that fails.
175
+ */
176
+ export function removePin(cwd: string, home: string): Unpinned {
177
+ const root = pinRoot(cwd);
178
+ const here = findPin(cwd, home);
179
+ // <owner>/.pi/pi-space/space: the folder the marker belongs to.
180
+ const owner = here === undefined ? undefined : dirname(dirname(dirname(here)));
181
+ if (here === undefined || owner === undefined || !isWithin(owner, root)) return { kind: "none", root, ...(here !== undefined ? { inherited: here } : {}) };
182
+ const link = linkIn(owner, []);
183
+ if (link !== undefined) throw new PinError(`${link} is a symbolic link; pi-space does not remove through it.`, 1);
184
+ const folder = dirname(here);
185
+ const { name, error } = readPin(here);
186
+ const label = name ?? (error !== undefined ? "an unreadable marker" : "an invalid marker");
187
+ try {
188
+ rmSync(here);
189
+ const ignore = join(folder, PIN_IGNORE);
190
+ if (isFile(ignore) && !isLink(ignore) && readFileSync(ignore, "utf8") === PIN_IGNORE_TEXT) rmSync(ignore);
191
+ if (readdirSync(folder).length > 0) return { kind: "removed", label, file: here, folder, folderRemoved: false };
192
+ rmdirSync(folder);
193
+ // A .pi that pin made and that holds nothing else goes too; one with anything in it is Pi's and stays.
194
+ if (readdirSync(dirname(folder)).length === 0) rmdirSync(dirname(folder));
195
+ return { kind: "removed", label, file: here, folder, folderRemoved: true };
196
+ } catch (error) {
197
+ throw new PinError(`cannot remove ${here}: ${(error as Error).message}`, 1);
198
+ }
199
+ }
200
+
201
+ /** The line that reports an unpin. */
202
+ export function unpinnedMessage(result: Unpinned): string {
203
+ if (result.kind === "none") return `No space pinned in ${result.root}${result.inherited !== undefined ? `; the one here comes from ${result.inherited}` : ""}.`;
204
+ return result.folderRemoved
205
+ ? `Unpinned ${result.label} (removed ${result.folder}).`
206
+ : `Unpinned ${result.label} (removed ${result.file}; ${result.folder} holds other files and stays).`;
207
+ }
package/src/spaces.ts CHANGED
@@ -8,6 +8,11 @@ import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
8
8
  export const BASE = "base";
9
9
  /** The folder inside a space's root that is its agent home. */
10
10
  export const AGENT = "agent";
11
+ /**
12
+ * The file in a new space's root that waits for its setup command: the space is rooted, but its agent home is left to
13
+ * the setup, and the declaration it holds joins the settings.json the setup wrote once the setup succeeds.
14
+ */
15
+ export const PENDING = ".pi-space-new";
11
16
  const NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
12
17
 
13
18
  export class SpaceError extends Error {
@@ -84,17 +89,21 @@ export function listSpaces(dir: string): string[] {
84
89
 
85
90
  /**
86
91
  * The agent home of the space whose root is `root`: `<root>/agent` when that is a real folder (a symlink or a file named
87
- * agent does not count), else the root itself, an old space whose folder is the agent home. Pi's own agent home never has
88
- * a folder named agent, so the folder tells the two layouts apart.
92
+ * agent does not count) or when the space still waits for its setup (PENDING), else the root itself, an old space whose
93
+ * folder is the agent home. Pi's own agent home never has a folder named agent, so the folder tells the two layouts apart.
89
94
  */
90
95
  export function spaceHome(root: string): string {
91
- const home = join(root, AGENT);
92
- return isRealFolder(home) ? home : root;
96
+ return isRooted(root) ? join(root, AGENT) : root;
93
97
  }
94
98
 
95
- /** True when the space with this root keeps its agent home in `<root>/agent`. */
99
+ /** True when the space with this root keeps its agent home in `<root>/agent`, or will once its setup makes it. */
96
100
  export function isRooted(root: string): boolean {
97
- return isRealFolder(join(root, AGENT));
101
+ return isRealFolder(join(root, AGENT)) || isPending(root);
102
+ }
103
+
104
+ /** True when the space with this root waits for its setup command (its root holds PENDING). */
105
+ export function isPending(root: string): boolean {
106
+ return existsSync(join(root, PENDING));
98
107
  }
99
108
 
100
109
  /** The space whose agent home is the given one (`<root>/agent`, or the root of an old space), or undefined. */
@@ -122,16 +131,86 @@ function isInside(child: string, parent: string): boolean {
122
131
  * /space works inside it. Returns the root.
123
132
  */
124
133
  export function createSpace(dir: string, name: string, declaration: PackageDeclaration): string {
134
+ const path = createSpaceRoot(dir, name);
135
+ declareInHome(join(path, AGENT), declaration);
136
+ return path;
137
+ }
138
+
139
+ /**
140
+ * Creates a space's root alone, without its agent home, so a setup command can make that home itself (a launcher such as
141
+ * gentle-shell only provisions a home it made). Returns the root.
142
+ */
143
+ export function createSpaceRoot(dir: string, name: string): string {
125
144
  assertName(name);
126
145
  const path = join(dir, name);
127
146
  if (existsSync(path) || isSymlink(path)) throw new SpaceError(`Space "${name}" already exists.`);
128
147
  mkdirSync(dir, { recursive: true });
129
148
  mkdirSync(path);
130
- mkdirSync(join(path, AGENT));
131
- writeFileSync(join(path, AGENT, "settings.json"), `${JSON.stringify({ packages: [declaration] }, null, 2)}\n`);
132
149
  return path;
133
150
  }
134
151
 
152
+ /**
153
+ * Marks a new space's root as waiting for its setup command, with the declaration to add once it succeeds (none for a
154
+ * space that does not declare this package).
155
+ */
156
+ export function markPending(root: string, declaration?: PackageDeclaration): void {
157
+ writeFileSync(join(root, PENDING), `${JSON.stringify(declaration === undefined ? {} : { declaration }, null, 2)}\n`);
158
+ }
159
+
160
+ /**
161
+ * Finishes a space whose setup succeeded: adds the declaration its PENDING file holds to the settings.json of its agent
162
+ * home (making both when the setup did not) and removes the file. False when the space was not waiting for a setup.
163
+ */
164
+ export function finishPending(root: string): boolean {
165
+ const file = join(root, PENDING);
166
+ if (!existsSync(file)) return false;
167
+ let pending: { declaration?: PackageDeclaration };
168
+ try {
169
+ pending = JSON.parse(readFileSync(file, "utf8"));
170
+ } catch {
171
+ throw new SpaceError(`${file} is not valid JSON; fix or delete it and run pi-space setup again.`);
172
+ }
173
+ declareInHome(join(root, AGENT), pending.declaration);
174
+ rmSync(file);
175
+ return true;
176
+ }
177
+
178
+ function sourceOf(entry: unknown): string | undefined {
179
+ const source = typeof entry === "string" ? entry : (entry as { source?: unknown } | null)?.source;
180
+ return typeof source === "string" ? source : undefined;
181
+ }
182
+
183
+ /** Two package sources name the same package: npm sources by package name, whatever their version; others as written. */
184
+ function sameSource(a: string | undefined, b: string | undefined): boolean {
185
+ if (a === undefined || b === undefined) return false;
186
+ if (a.startsWith("npm:") && b.startsWith("npm:")) return npmName(a) === npmName(b);
187
+ return a === b;
188
+ }
189
+
190
+ /**
191
+ * Makes the agent home when it is missing and adds the declaration to its settings.json, keeping everything already
192
+ * there; a package with the same source is not declared twice. Without a declaration it only makes sure the file exists.
193
+ */
194
+ export function declareInHome(home: string, declaration?: PackageDeclaration): void {
195
+ mkdirSync(home, { recursive: true });
196
+ const file = join(home, "settings.json");
197
+ let settings: Record<string, unknown> = {};
198
+ if (existsSync(file)) {
199
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
200
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new SpaceError(`${file} is not a JSON object.`);
201
+ settings = parsed as Record<string, unknown>;
202
+ if (!declaration) return;
203
+ }
204
+ if (declaration) {
205
+ if (settings.packages !== undefined && !Array.isArray(settings.packages)) throw new SpaceError(`${file} has "packages" that is not a list.`);
206
+ const packages = (settings.packages as unknown[] | undefined) ?? [];
207
+ const wanted = sourceOf(declaration);
208
+ if (packages.some((entry) => sameSource(sourceOf(entry), wanted))) return;
209
+ settings.packages = [...packages, declaration];
210
+ }
211
+ writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
212
+ }
213
+
135
214
  function isSymlink(path: string): boolean {
136
215
  try {
137
216
  return lstatSync(path).isSymbolicLink();
@@ -267,6 +346,7 @@ export function migrateSpace(
267
346
  ): Migration {
268
347
  assertName(name);
269
348
  const root = join(dir, name);
349
+ if (isPending(root)) throw new SpaceError(`Space "${name}" is waiting for its setup command, which makes its agent home; run pi-space setup.`);
270
350
  if (isRooted(root)) throw new SpaceError(`Space "${name}" already has its agent home in ${join(root, AGENT)}.`);
271
351
  checkRemovable(dir, name, agentHome, protect, userHome, "migrate");
272
352
  const home = join(root, AGENT);