pi-link 0.1.12 → 0.1.14-beta.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 +21 -0
- package/README.md +13 -10
- package/bin/pi-link.mjs +424 -414
- package/index.ts +52 -8
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,27 @@ This changelog is based on the git history from `2026-03-21` (initial commit) th
|
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
9
|
+
## 0.1.14-beta.0 — 2026-05-04
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **`--link-name <name>` flag for link-only startup naming.** Run `pi --link-name worker` to join the link as `worker` while leaving Pi's normal session selection/resume behavior untouched. This restores link-name startup naming in a cleaner form than the previous session-coupled implementation: it sets only the pi-link identity, with hub collision handling unchanged. Use `pi-link <name>` when you want the combined session-by-name + link-name workflow. Empty or whitespace-only `--link-name` values are rejected with a clear error. The `pi-link` wrapper itself does not accept `--link-name` — its rejection message now points to either `pi-link <name>` (combined) or `pi --link-name <name>` (direct, link-only).
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- **`link-name` session entries no longer accumulate on no-op restarts.** Both `pi-link <name>` and `pi --link-name <name>` skip the append when the saved name already matches. Sessions opened and exited without any persisted activity will no longer bump `pi-link list` recency from the same-name startup alone; recency still updates on messages, tool calls, edits, and real link-name changes.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 0.1.13 — 2026-05-03
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- **`pi-link resolve <name>` now rejects whitespace-only names.** Previously a name that normalized to empty (e.g. `pi-link resolve " "`) fell through to session lookup and silently reported no match. The empty-name check that already covered `pi-link <name>` now also runs in `resolve`, printing usage and exiting non-zero.
|
|
26
|
+
- **README wording: session-dir lookup phrasing tightened** to say "matches Pi's lookup order" instead of "mirrors Pi's".
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
9
30
|
## 0.1.12 — 2026-05-03
|
|
10
31
|
|
|
11
32
|
### Changed
|
package/README.md
CHANGED
|
@@ -133,16 +133,19 @@ Every other terminal sees:
|
|
|
133
133
|
|
|
134
134
|
## Configuration
|
|
135
135
|
|
|
136
|
-
Link is **off by default**. Without `--link
|
|
136
|
+
Link is **off by default**. Without `--link`, `--link-name`, or `pi-link`, the extension is completely silent — no status bar, no connections, no warnings.
|
|
137
137
|
|
|
138
|
-
| Method
|
|
139
|
-
|
|
|
140
|
-
| `pi-link <name>`
|
|
141
|
-
| `pi --link
|
|
142
|
-
|
|
|
143
|
-
| `/link-
|
|
138
|
+
| Method | When | Auto-reconnect? |
|
|
139
|
+
| ----------------------- | ---------------------------------------------------------------- | -------------------------------- |
|
|
140
|
+
| `pi-link <name>` | Resume/create named session | Yes |
|
|
141
|
+
| `pi --link-name <name>` | Connect with a specific link name; Pi session behavior unchanged | Yes |
|
|
142
|
+
| `pi --link` | Connect on startup (random name) | Yes |
|
|
143
|
+
| `/link-connect` | Opt-in mid-session (no flag needed) | Yes |
|
|
144
|
+
| `/link-disconnect` | Opt-out mid-session | Suppressed until `/link-connect` |
|
|
144
145
|
|
|
145
|
-
|
|
146
|
+
`pi --link-name <name>` sets only the pi-link terminal name; Pi's session selection/resume runs as normal. Use this when you want a stable link identity without coupling it to a same-named session. Use `pi-link <name>` when you want the combined session-by-name + link-name workflow. The `pi-link` wrapper itself does not accept `--link-name`.
|
|
147
|
+
|
|
148
|
+
**Name precedence:** `pi --link-name` > `pi-link <name>` > saved `/link-name` > Pi session name > random `t-xxxx`.
|
|
146
149
|
|
|
147
150
|
`/link-connect` and `/link-disconnect` save their intent to the session — resume later and the connection state is restored without needing the flag. Explicit user intent takes precedence over `--link`.
|
|
148
151
|
|
|
@@ -157,7 +160,7 @@ pi-link worker-1 # resume or create session "worker-1"
|
|
|
157
160
|
pi-link worker-1 --model sonnet # with extra Pi flags
|
|
158
161
|
```
|
|
159
162
|
|
|
160
|
-
How it works: `pi-link worker-1` scans Pi's session directory, finds the session named "worker-1", and spawns `pi --session <path> --link`. Session-dir resolution
|
|
163
|
+
How it works: `pi-link worker-1` scans Pi's session directory, finds the session named "worker-1", and spawns `pi --session <path> --link`. Session-dir resolution matches Pi's lookup order: `PI_CODING_AGENT_SESSION_DIR` env > `<cwd>/.pi/settings.json` `sessionDir` > `<agentDir>/settings.json` `sessionDir` > default `<agentDir>/sessions/`. `<agentDir>` follows `PI_CODING_AGENT_DIR` and defaults to `~/.pi/agent/`.
|
|
161
164
|
|
|
162
165
|
Lookup is **scoped to the current cwd by default**; pass `--global` (`-g`) to consider sessions in any cwd.
|
|
163
166
|
|
|
@@ -168,7 +171,7 @@ Lookup is **scoped to the current cwd by default**; pass `--global` (`-g`) to co
|
|
|
168
171
|
|
|
169
172
|
### Discovering sessions
|
|
170
173
|
|
|
171
|
-
`pi-link list` shows pi-link sessions in the current cwd; `pi-link list --global` (or `-g`) lists them across all directories. Sorted by last activity.
|
|
174
|
+
`pi-link list` shows pi-link sessions in the current cwd; `pi-link list --global` (or `-g`) lists them across all directories. Sorted by last activity — starting a session with the same name it already has does not bump recency; only real activity (messages, tool calls, edits, name changes) does.
|
|
172
175
|
|
|
173
176
|
```
|
|
174
177
|
$ pi-link list
|
package/bin/pi-link.mjs
CHANGED
|
@@ -1,414 +1,424 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// pi-link CLI — launch Pi with session resume by name
|
|
4
|
-
//
|
|
5
|
-
// Usage:
|
|
6
|
-
// pi-link <name> [--global|-g] [flags...]
|
|
7
|
-
// Resume or create a named session, connected to link.
|
|
8
|
-
// pi-link list [--global|-g] List pi-link sessions in current cwd (or everywhere).
|
|
9
|
-
// pi-link resolve <name> [--global|-g]
|
|
10
|
-
// Print just the session path (machine-readable).
|
|
11
|
-
|
|
12
|
-
import { readdir, stat } from "fs/promises";
|
|
13
|
-
import { createReadStream, existsSync, readFileSync } from "fs";
|
|
14
|
-
import { createInterface } from "readline";
|
|
15
|
-
import { join } from "path";
|
|
16
|
-
import { homedir } from "os";
|
|
17
|
-
import { spawn } from "child_process";
|
|
18
|
-
|
|
19
|
-
// ── Pi config resolution ───────────────────────────────────────────────────
|
|
20
|
-
// Match Pi's session-dir lookup order so list/resolve/<name> see what Pi sees.
|
|
21
|
-
// Custom sessionDir → flat layout; default → <agentDir>/sessions/<encoded-cwd>.
|
|
22
|
-
|
|
23
|
-
// Match Pi's expandTildePath: only `~` and `~/...`.
|
|
24
|
-
function expandTilde(p) {
|
|
25
|
-
if (p === "~") return homedir();
|
|
26
|
-
if (p.startsWith("~/")) return join(homedir(), p.slice(2));
|
|
27
|
-
return p;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function readSessionDirFromSettings(settingsPath) {
|
|
31
|
-
if (!existsSync(settingsPath)) return undefined;
|
|
32
|
-
let parsed;
|
|
33
|
-
try {
|
|
34
|
-
parsed = JSON.parse(readFileSync(settingsPath, "utf-8"));
|
|
35
|
-
} catch (err) {
|
|
36
|
-
console.error(`pi-link: ignored ${settingsPath}: ${err.message}`);
|
|
37
|
-
return undefined;
|
|
38
|
-
}
|
|
39
|
-
const value = parsed?.sessionDir;
|
|
40
|
-
if (typeof value !== "string" || value.trim() === "") return undefined;
|
|
41
|
-
return value;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// PI_CODING_AGENT_DIR also relocates global settings.json to <agentDir>/settings.json.
|
|
45
|
-
function resolveAgentDir() {
|
|
46
|
-
const env = process.env.PI_CODING_AGENT_DIR;
|
|
47
|
-
if (env) return expandTilde(env);
|
|
48
|
-
return join(homedir(), ".pi", "agent");
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// Returns { dir, isCustom }. isCustom drives layout in scanSessions:
|
|
52
|
-
// true → flat <dir>/*.jsonl, false → <dir>/<encoded-cwd>/*.jsonl.
|
|
53
|
-
function resolveSessionDir(cwd, agentDir) {
|
|
54
|
-
const env = process.env.PI_CODING_AGENT_SESSION_DIR;
|
|
55
|
-
if (env) return { dir: expandTilde(env), isCustom: true };
|
|
56
|
-
|
|
57
|
-
const projectDir = readSessionDirFromSettings(join(cwd, ".pi", "settings.json"));
|
|
58
|
-
if (projectDir) return { dir: expandTilde(projectDir), isCustom: true };
|
|
59
|
-
|
|
60
|
-
const globalDir = readSessionDirFromSettings(join(agentDir, "settings.json"));
|
|
61
|
-
if (globalDir) return { dir: expandTilde(globalDir), isCustom: true };
|
|
62
|
-
|
|
63
|
-
return { dir: join(agentDir, "sessions"), isCustom: false };
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Reads a session JSONL file and returns its display name, cwd, id, link
|
|
67
|
-
// status, and message count.
|
|
68
|
-
//
|
|
69
|
-
// Name precedence: latest valid `link-name` custom entry wins as the
|
|
70
|
-
// authoritative pi-link name. `session_info.name` is only a fallback for
|
|
71
|
-
// sessions that never set a link-name. Historical link-names are not aliases.
|
|
72
|
-
async function getSessionMeta(filePath) {
|
|
73
|
-
let linkName;
|
|
74
|
-
let sessionName;
|
|
75
|
-
let cwd;
|
|
76
|
-
let id;
|
|
77
|
-
let hasLinkName = false;
|
|
78
|
-
let messages = 0;
|
|
79
|
-
const rl = createInterface({ input: createReadStream(filePath, "utf-8"), crlfDelay: Infinity });
|
|
80
|
-
for await (const line of rl) {
|
|
81
|
-
if (!line) continue;
|
|
82
|
-
try {
|
|
83
|
-
const entry = JSON.parse(line);
|
|
84
|
-
if (entry.type === "session") {
|
|
85
|
-
if (typeof entry.cwd === "string") cwd = entry.cwd;
|
|
86
|
-
if (typeof entry.id === "string") id = entry.id;
|
|
87
|
-
} else if (entry.type === "session_info" && typeof entry.name === "string") {
|
|
88
|
-
sessionName = entry.name.trim().replace(/\s+/g, " ") || undefined;
|
|
89
|
-
} else if (entry.type === "custom" && entry.customType === "link-name") {
|
|
90
|
-
hasLinkName = true;
|
|
91
|
-
if (entry.data && typeof entry.data.name === "string") {
|
|
92
|
-
const n = entry.data.name.trim().replace(/\s+/g, " ");
|
|
93
|
-
if (n) linkName = n;
|
|
94
|
-
}
|
|
95
|
-
} else if (entry.type === "message" || entry.type === "user" || entry.type === "assistant") {
|
|
96
|
-
messages++;
|
|
97
|
-
}
|
|
98
|
-
} catch {
|
|
99
|
-
// skip malformed lines (incl. partial last line of active sessions)
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
return { name: linkName ?? sessionName, cwd, id, hasLinkName, messages };
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function normalizePath(p) {
|
|
106
|
-
let s = p.replace(/[/\\]+/g, "/").replace(/\/+$/, "");
|
|
107
|
-
if (process.platform === "win32") s = s.toLowerCase();
|
|
108
|
-
return s;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// Replace $HOME with ~ in display paths. Comparison is normalized
|
|
112
|
-
// (case-insensitive on Windows) but display preserves original casing.
|
|
113
|
-
function displayPath(p) {
|
|
114
|
-
if (!p) return p;
|
|
115
|
-
const home = homedir();
|
|
116
|
-
const normP = normalizePath(p);
|
|
117
|
-
const normHome = normalizePath(home);
|
|
118
|
-
if (normP === normHome) return "~";
|
|
119
|
-
if (normP.startsWith(normHome + "/")) return "~" + p.slice(home.length).replace(/\\/g, "/");
|
|
120
|
-
return p;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const useAnsi =
|
|
124
|
-
!!process.stdout.isTTY &&
|
|
125
|
-
process.env.NO_COLOR === undefined &&
|
|
126
|
-
process.env.TERM !== "dumb";
|
|
127
|
-
const bold = (s) => (useAnsi ? `\x1b[1m${s}\x1b[22m` : s);
|
|
128
|
-
const dim = (s) => (useAnsi ? `\x1b[2m${s}\x1b[22m` : s);
|
|
129
|
-
|
|
130
|
-
function relTime(d) {
|
|
131
|
-
const sec = Math.max(0, Math.floor((Date.now() - d.getTime()) / 1000));
|
|
132
|
-
if (sec < 60) return `${sec}s ago`;
|
|
133
|
-
const min = Math.floor(sec / 60);
|
|
134
|
-
if (min < 60) return `${min}m ago`;
|
|
135
|
-
const hr = Math.floor(min / 60);
|
|
136
|
-
if (hr < 24) return `${hr}h ago`;
|
|
137
|
-
const day = Math.floor(hr / 24);
|
|
138
|
-
if (day < 30) return `${day}d ago`;
|
|
139
|
-
return d.toISOString().slice(0, 10);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
async function loadSessionRecord(filePath) {
|
|
143
|
-
try {
|
|
144
|
-
const meta = await getSessionMeta(filePath);
|
|
145
|
-
const stats = await stat(filePath);
|
|
146
|
-
return { ...meta, modified: stats.mtime, path: filePath };
|
|
147
|
-
} catch {
|
|
148
|
-
return null;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// Returns meta + mtime + path for every readable session in `dir`. Custom
|
|
153
|
-
// layout is flat (<dir>/*.jsonl); default layout has one subdir level per
|
|
154
|
-
// encoded cwd (<dir>/<sub>/*.jsonl). Errors on individual files/dirs are
|
|
155
|
-
// silently skipped — active or partially-written sessions are tolerated.
|
|
156
|
-
async function scanSessions(dir, isCustom) {
|
|
157
|
-
let entries;
|
|
158
|
-
try {
|
|
159
|
-
entries = await readdir(dir, { withFileTypes: true });
|
|
160
|
-
} catch {
|
|
161
|
-
return [];
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
const tasks = [];
|
|
165
|
-
if (isCustom) {
|
|
166
|
-
for (const entry of entries) {
|
|
167
|
-
if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
|
|
168
|
-
tasks.push(loadSessionRecord(join(dir, entry.name)));
|
|
169
|
-
}
|
|
170
|
-
} else {
|
|
171
|
-
for (const sub of entries) {
|
|
172
|
-
if (!sub.isDirectory()) continue;
|
|
173
|
-
const subPath = join(dir, sub.name);
|
|
174
|
-
let files;
|
|
175
|
-
try { files = await readdir(subPath); } catch { continue; }
|
|
176
|
-
for (const file of files) {
|
|
177
|
-
if (!file.endsWith(".jsonl")) continue;
|
|
178
|
-
tasks.push(loadSessionRecord(join(subPath, file)));
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
return (await Promise.all(tasks)).filter((s) => s !== null);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Find sessions whose current display name matches `targetName`. Returns both
|
|
187
|
-
// local-cwd matches and all matches (cross-cwd) so the caller can default to
|
|
188
|
-
// local while still surfacing a hint when non-local matches exist. Falls back
|
|
189
|
-
// to `session_info.name` for sessions without a link-name (so `pi-link <name>`
|
|
190
|
-
// can attach link to a previously-unlinked named session).
|
|
191
|
-
async function findSessionsByName(targetName, dir, isCustom) {
|
|
192
|
-
const localCwd = normalizePath(process.cwd());
|
|
193
|
-
const all = (await scanSessions(dir, isCustom))
|
|
194
|
-
.filter((s) => s.name === targetName)
|
|
195
|
-
.map((s) => ({ path: s.path, cwd: s.cwd || "?", modified: s.modified }))
|
|
196
|
-
.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
|
197
|
-
const local = all.filter((s) => normalizePath(s.cwd) === localCwd);
|
|
198
|
-
return { local, all };
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// List pi-link sessions (those with at least one link-name entry). Default
|
|
202
|
-
// scope is current cwd; `all` widens to every directory.
|
|
203
|
-
async function listSessions({ all, dir, isCustom }) {
|
|
204
|
-
const localCwd = normalizePath(process.cwd());
|
|
205
|
-
return (await scanSessions(dir, isCustom))
|
|
206
|
-
.filter((s) => s.hasLinkName)
|
|
207
|
-
.filter((s) => all || (s.cwd && normalizePath(s.cwd) === localCwd))
|
|
208
|
-
.map((s) => ({
|
|
209
|
-
name: s.name || "(unnamed)",
|
|
210
|
-
cwd: s.cwd || "?",
|
|
211
|
-
id: s.id ? s.id.slice(0, 8) : "?",
|
|
212
|
-
messages: s.messages,
|
|
213
|
-
modified: s.modified,
|
|
214
|
-
path: s.path,
|
|
215
|
-
}))
|
|
216
|
-
.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// Renders a plain-text table. Widths are computed from unstyled cells; ANSI
|
|
220
|
-
// styles are applied after padding so column alignment is preserved when piped
|
|
221
|
-
// or styled. Mark a column with `dim: true` to render its cells dim.
|
|
222
|
-
function renderTable(rows, columns) {
|
|
223
|
-
const widths = columns.map((c) => Math.max(c.header.length, ...rows.map((r) => String(c.get(r)).length)));
|
|
224
|
-
const padCell = (text, i) => (i === columns.length - 1 ? text : text.padEnd(widths[i]));
|
|
225
|
-
const styleBody = (text, i) => (columns[i].dim ? dim(text) : text);
|
|
226
|
-
const headerLine = columns.map((c, i) => bold(padCell(c.header, i))).join(" ");
|
|
227
|
-
const bodyLines = rows.map((r) =>
|
|
228
|
-
columns.map((c, i) => styleBody(padCell(String(c.get(r)), i), i)).join(" "),
|
|
229
|
-
);
|
|
230
|
-
return [headerLine, ...bodyLines].join("\n");
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// ── CLI ────────────────────────────────────────────────────────────────────
|
|
234
|
-
|
|
235
|
-
const [command, ...args] = process.argv.slice(2);
|
|
236
|
-
|
|
237
|
-
// Reject pi-link flags renamed in 0.1.12 with a clear pointer to the new name.
|
|
238
|
-
// Same intent as `rejectManagedFlag` (specific message > generic "Unknown argument")
|
|
239
|
-
// but for our own renames, not Pi-managed flags.
|
|
240
|
-
function rejectRenamedFlag(token) {
|
|
241
|
-
if (token === "--all" || token === "-a") {
|
|
242
|
-
const replacement = token === "-a" ? "-g" : "--global";
|
|
243
|
-
console.error(`Error: ${token} was renamed to ${replacement}.`);
|
|
244
|
-
process.exit(1);
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// Reject Pi flags that pi-link manages, plus
|
|
249
|
-
//
|
|
250
|
-
//
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
291
|
-
const
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
{ header: "
|
|
301
|
-
{ header: "MODIFIED", get: (s) => relTime(s.modified), dim: true },
|
|
302
|
-
{ header: "MESSAGES", get: (s) => s.messages, dim: true },
|
|
303
|
-
{ header: "ID", get: (s) => s.id, dim: true },
|
|
304
|
-
]
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// pi-link CLI — launch Pi with session resume by name
|
|
4
|
+
//
|
|
5
|
+
// Usage:
|
|
6
|
+
// pi-link <name> [--global|-g] [flags...]
|
|
7
|
+
// Resume or create a named session, connected to link.
|
|
8
|
+
// pi-link list [--global|-g] List pi-link sessions in current cwd (or everywhere).
|
|
9
|
+
// pi-link resolve <name> [--global|-g]
|
|
10
|
+
// Print just the session path (machine-readable).
|
|
11
|
+
|
|
12
|
+
import { readdir, stat } from "fs/promises";
|
|
13
|
+
import { createReadStream, existsSync, readFileSync } from "fs";
|
|
14
|
+
import { createInterface } from "readline";
|
|
15
|
+
import { join } from "path";
|
|
16
|
+
import { homedir } from "os";
|
|
17
|
+
import { spawn } from "child_process";
|
|
18
|
+
|
|
19
|
+
// ── Pi config resolution ───────────────────────────────────────────────────
|
|
20
|
+
// Match Pi's session-dir lookup order so list/resolve/<name> see what Pi sees.
|
|
21
|
+
// Custom sessionDir → flat layout; default → <agentDir>/sessions/<encoded-cwd>.
|
|
22
|
+
|
|
23
|
+
// Match Pi's expandTildePath: only `~` and `~/...`.
|
|
24
|
+
function expandTilde(p) {
|
|
25
|
+
if (p === "~") return homedir();
|
|
26
|
+
if (p.startsWith("~/")) return join(homedir(), p.slice(2));
|
|
27
|
+
return p;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function readSessionDirFromSettings(settingsPath) {
|
|
31
|
+
if (!existsSync(settingsPath)) return undefined;
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = JSON.parse(readFileSync(settingsPath, "utf-8"));
|
|
35
|
+
} catch (err) {
|
|
36
|
+
console.error(`pi-link: ignored ${settingsPath}: ${err.message}`);
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
const value = parsed?.sessionDir;
|
|
40
|
+
if (typeof value !== "string" || value.trim() === "") return undefined;
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// PI_CODING_AGENT_DIR also relocates global settings.json to <agentDir>/settings.json.
|
|
45
|
+
function resolveAgentDir() {
|
|
46
|
+
const env = process.env.PI_CODING_AGENT_DIR;
|
|
47
|
+
if (env) return expandTilde(env);
|
|
48
|
+
return join(homedir(), ".pi", "agent");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Returns { dir, isCustom }. isCustom drives layout in scanSessions:
|
|
52
|
+
// true → flat <dir>/*.jsonl, false → <dir>/<encoded-cwd>/*.jsonl.
|
|
53
|
+
function resolveSessionDir(cwd, agentDir) {
|
|
54
|
+
const env = process.env.PI_CODING_AGENT_SESSION_DIR;
|
|
55
|
+
if (env) return { dir: expandTilde(env), isCustom: true };
|
|
56
|
+
|
|
57
|
+
const projectDir = readSessionDirFromSettings(join(cwd, ".pi", "settings.json"));
|
|
58
|
+
if (projectDir) return { dir: expandTilde(projectDir), isCustom: true };
|
|
59
|
+
|
|
60
|
+
const globalDir = readSessionDirFromSettings(join(agentDir, "settings.json"));
|
|
61
|
+
if (globalDir) return { dir: expandTilde(globalDir), isCustom: true };
|
|
62
|
+
|
|
63
|
+
return { dir: join(agentDir, "sessions"), isCustom: false };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Reads a session JSONL file and returns its display name, cwd, id, link
|
|
67
|
+
// status, and message count.
|
|
68
|
+
//
|
|
69
|
+
// Name precedence: latest valid `link-name` custom entry wins as the
|
|
70
|
+
// authoritative pi-link name. `session_info.name` is only a fallback for
|
|
71
|
+
// sessions that never set a link-name. Historical link-names are not aliases.
|
|
72
|
+
async function getSessionMeta(filePath) {
|
|
73
|
+
let linkName;
|
|
74
|
+
let sessionName;
|
|
75
|
+
let cwd;
|
|
76
|
+
let id;
|
|
77
|
+
let hasLinkName = false;
|
|
78
|
+
let messages = 0;
|
|
79
|
+
const rl = createInterface({ input: createReadStream(filePath, "utf-8"), crlfDelay: Infinity });
|
|
80
|
+
for await (const line of rl) {
|
|
81
|
+
if (!line) continue;
|
|
82
|
+
try {
|
|
83
|
+
const entry = JSON.parse(line);
|
|
84
|
+
if (entry.type === "session") {
|
|
85
|
+
if (typeof entry.cwd === "string") cwd = entry.cwd;
|
|
86
|
+
if (typeof entry.id === "string") id = entry.id;
|
|
87
|
+
} else if (entry.type === "session_info" && typeof entry.name === "string") {
|
|
88
|
+
sessionName = entry.name.trim().replace(/\s+/g, " ") || undefined;
|
|
89
|
+
} else if (entry.type === "custom" && entry.customType === "link-name") {
|
|
90
|
+
hasLinkName = true;
|
|
91
|
+
if (entry.data && typeof entry.data.name === "string") {
|
|
92
|
+
const n = entry.data.name.trim().replace(/\s+/g, " ");
|
|
93
|
+
if (n) linkName = n;
|
|
94
|
+
}
|
|
95
|
+
} else if (entry.type === "message" || entry.type === "user" || entry.type === "assistant") {
|
|
96
|
+
messages++;
|
|
97
|
+
}
|
|
98
|
+
} catch {
|
|
99
|
+
// skip malformed lines (incl. partial last line of active sessions)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return { name: linkName ?? sessionName, cwd, id, hasLinkName, messages };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function normalizePath(p) {
|
|
106
|
+
let s = p.replace(/[/\\]+/g, "/").replace(/\/+$/, "");
|
|
107
|
+
if (process.platform === "win32") s = s.toLowerCase();
|
|
108
|
+
return s;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Replace $HOME with ~ in display paths. Comparison is normalized
|
|
112
|
+
// (case-insensitive on Windows) but display preserves original casing.
|
|
113
|
+
function displayPath(p) {
|
|
114
|
+
if (!p) return p;
|
|
115
|
+
const home = homedir();
|
|
116
|
+
const normP = normalizePath(p);
|
|
117
|
+
const normHome = normalizePath(home);
|
|
118
|
+
if (normP === normHome) return "~";
|
|
119
|
+
if (normP.startsWith(normHome + "/")) return "~" + p.slice(home.length).replace(/\\/g, "/");
|
|
120
|
+
return p;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const useAnsi =
|
|
124
|
+
!!process.stdout.isTTY &&
|
|
125
|
+
process.env.NO_COLOR === undefined &&
|
|
126
|
+
process.env.TERM !== "dumb";
|
|
127
|
+
const bold = (s) => (useAnsi ? `\x1b[1m${s}\x1b[22m` : s);
|
|
128
|
+
const dim = (s) => (useAnsi ? `\x1b[2m${s}\x1b[22m` : s);
|
|
129
|
+
|
|
130
|
+
function relTime(d) {
|
|
131
|
+
const sec = Math.max(0, Math.floor((Date.now() - d.getTime()) / 1000));
|
|
132
|
+
if (sec < 60) return `${sec}s ago`;
|
|
133
|
+
const min = Math.floor(sec / 60);
|
|
134
|
+
if (min < 60) return `${min}m ago`;
|
|
135
|
+
const hr = Math.floor(min / 60);
|
|
136
|
+
if (hr < 24) return `${hr}h ago`;
|
|
137
|
+
const day = Math.floor(hr / 24);
|
|
138
|
+
if (day < 30) return `${day}d ago`;
|
|
139
|
+
return d.toISOString().slice(0, 10);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function loadSessionRecord(filePath) {
|
|
143
|
+
try {
|
|
144
|
+
const meta = await getSessionMeta(filePath);
|
|
145
|
+
const stats = await stat(filePath);
|
|
146
|
+
return { ...meta, modified: stats.mtime, path: filePath };
|
|
147
|
+
} catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Returns meta + mtime + path for every readable session in `dir`. Custom
|
|
153
|
+
// layout is flat (<dir>/*.jsonl); default layout has one subdir level per
|
|
154
|
+
// encoded cwd (<dir>/<sub>/*.jsonl). Errors on individual files/dirs are
|
|
155
|
+
// silently skipped — active or partially-written sessions are tolerated.
|
|
156
|
+
async function scanSessions(dir, isCustom) {
|
|
157
|
+
let entries;
|
|
158
|
+
try {
|
|
159
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
160
|
+
} catch {
|
|
161
|
+
return [];
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const tasks = [];
|
|
165
|
+
if (isCustom) {
|
|
166
|
+
for (const entry of entries) {
|
|
167
|
+
if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
|
|
168
|
+
tasks.push(loadSessionRecord(join(dir, entry.name)));
|
|
169
|
+
}
|
|
170
|
+
} else {
|
|
171
|
+
for (const sub of entries) {
|
|
172
|
+
if (!sub.isDirectory()) continue;
|
|
173
|
+
const subPath = join(dir, sub.name);
|
|
174
|
+
let files;
|
|
175
|
+
try { files = await readdir(subPath); } catch { continue; }
|
|
176
|
+
for (const file of files) {
|
|
177
|
+
if (!file.endsWith(".jsonl")) continue;
|
|
178
|
+
tasks.push(loadSessionRecord(join(subPath, file)));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return (await Promise.all(tasks)).filter((s) => s !== null);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Find sessions whose current display name matches `targetName`. Returns both
|
|
187
|
+
// local-cwd matches and all matches (cross-cwd) so the caller can default to
|
|
188
|
+
// local while still surfacing a hint when non-local matches exist. Falls back
|
|
189
|
+
// to `session_info.name` for sessions without a link-name (so `pi-link <name>`
|
|
190
|
+
// can attach link to a previously-unlinked named session).
|
|
191
|
+
async function findSessionsByName(targetName, dir, isCustom) {
|
|
192
|
+
const localCwd = normalizePath(process.cwd());
|
|
193
|
+
const all = (await scanSessions(dir, isCustom))
|
|
194
|
+
.filter((s) => s.name === targetName)
|
|
195
|
+
.map((s) => ({ path: s.path, cwd: s.cwd || "?", modified: s.modified }))
|
|
196
|
+
.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
|
197
|
+
const local = all.filter((s) => normalizePath(s.cwd) === localCwd);
|
|
198
|
+
return { local, all };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// List pi-link sessions (those with at least one link-name entry). Default
|
|
202
|
+
// scope is current cwd; `all` widens to every directory.
|
|
203
|
+
async function listSessions({ all, dir, isCustom }) {
|
|
204
|
+
const localCwd = normalizePath(process.cwd());
|
|
205
|
+
return (await scanSessions(dir, isCustom))
|
|
206
|
+
.filter((s) => s.hasLinkName)
|
|
207
|
+
.filter((s) => all || (s.cwd && normalizePath(s.cwd) === localCwd))
|
|
208
|
+
.map((s) => ({
|
|
209
|
+
name: s.name || "(unnamed)",
|
|
210
|
+
cwd: s.cwd || "?",
|
|
211
|
+
id: s.id ? s.id.slice(0, 8) : "?",
|
|
212
|
+
messages: s.messages,
|
|
213
|
+
modified: s.modified,
|
|
214
|
+
path: s.path,
|
|
215
|
+
}))
|
|
216
|
+
.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Renders a plain-text table. Widths are computed from unstyled cells; ANSI
|
|
220
|
+
// styles are applied after padding so column alignment is preserved when piped
|
|
221
|
+
// or styled. Mark a column with `dim: true` to render its cells dim.
|
|
222
|
+
function renderTable(rows, columns) {
|
|
223
|
+
const widths = columns.map((c) => Math.max(c.header.length, ...rows.map((r) => String(c.get(r)).length)));
|
|
224
|
+
const padCell = (text, i) => (i === columns.length - 1 ? text : text.padEnd(widths[i]));
|
|
225
|
+
const styleBody = (text, i) => (columns[i].dim ? dim(text) : text);
|
|
226
|
+
const headerLine = columns.map((c, i) => bold(padCell(c.header, i))).join(" ");
|
|
227
|
+
const bodyLines = rows.map((r) =>
|
|
228
|
+
columns.map((c, i) => styleBody(padCell(String(c.get(r)), i), i)).join(" "),
|
|
229
|
+
);
|
|
230
|
+
return [headerLine, ...bodyLines].join("\n");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ── CLI ────────────────────────────────────────────────────────────────────
|
|
234
|
+
|
|
235
|
+
const [command, ...args] = process.argv.slice(2);
|
|
236
|
+
|
|
237
|
+
// Reject pi-link flags renamed in 0.1.12 with a clear pointer to the new name.
|
|
238
|
+
// Same intent as `rejectManagedFlag` (specific message > generic "Unknown argument")
|
|
239
|
+
// but for our own renames, not Pi-managed flags.
|
|
240
|
+
function rejectRenamedFlag(token) {
|
|
241
|
+
if (token === "--all" || token === "-a") {
|
|
242
|
+
const replacement = token === "-a" ? "-g" : "--global";
|
|
243
|
+
console.error(`Error: ${token} was renamed to ${replacement}.`);
|
|
244
|
+
process.exit(1);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Reject Pi flags that pi-link manages, plus --link-name (which exists at the
|
|
249
|
+
// `pi` level for link-only naming, but the wrapper's combined-mode contract
|
|
250
|
+
// conflicts with it).
|
|
251
|
+
// Runs on both the first token (so `pi-link --session foo` errors clearly) and on each
|
|
252
|
+
// flag in args (so `pi-link foo --session bar` does too).
|
|
253
|
+
function rejectManagedFlag(token) {
|
|
254
|
+
const key = token.split("=")[0];
|
|
255
|
+
if (key === "--link-name") {
|
|
256
|
+
console.error(
|
|
257
|
+
"Error: --link-name is not accepted by the pi-link wrapper.\n" +
|
|
258
|
+
" Use 'pi-link <name>' for combined link+session,\n" +
|
|
259
|
+
" or run 'pi --link-name <name>' directly to set link name without session resolution.",
|
|
260
|
+
);
|
|
261
|
+
process.exit(1);
|
|
262
|
+
}
|
|
263
|
+
if (["--session", "--continue", "-c", "--resume", "-r", "--fork", "--no-session", "--session-dir"].includes(key)) {
|
|
264
|
+
console.error(`Error: ${key} is managed by pi-link. Remove it.`);
|
|
265
|
+
process.exit(1);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function printCandidates(name, matches) {
|
|
270
|
+
console.error(`Multiple sessions named "${name}":\n`);
|
|
271
|
+
for (const m of matches) {
|
|
272
|
+
console.error(` ${m.modified.toISOString().slice(0, 19)} cwd: ${m.cwd}`);
|
|
273
|
+
console.error(` ${m.path}\n`);
|
|
274
|
+
}
|
|
275
|
+
console.error(`Use: pi --session <path> --link`);
|
|
276
|
+
process.exit(1);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (command === "list") {
|
|
280
|
+
let global = false;
|
|
281
|
+
for (const a of args) {
|
|
282
|
+
rejectRenamedFlag(a);
|
|
283
|
+
if (a === "--global" || a === "-g") global = true;
|
|
284
|
+
else {
|
|
285
|
+
console.error(`Unknown argument: ${a}`);
|
|
286
|
+
console.error("Usage: pi-link list [--global|-g]");
|
|
287
|
+
process.exit(1);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const { dir, isCustom } = resolveSessionDir(process.cwd(), resolveAgentDir());
|
|
291
|
+
const sessions = await listSessions({ all: global, dir, isCustom });
|
|
292
|
+
if (sessions.length === 0) {
|
|
293
|
+
console.log(global ? "No pi-link sessions found." : "No pi-link sessions found in this cwd.");
|
|
294
|
+
console.log("Start one: pi-link <name>");
|
|
295
|
+
process.exit(0);
|
|
296
|
+
}
|
|
297
|
+
const columns = global
|
|
298
|
+
? [
|
|
299
|
+
{ header: "NAME", get: (s) => s.name },
|
|
300
|
+
{ header: "CWD", get: (s) => displayPath(s.cwd) },
|
|
301
|
+
{ header: "MODIFIED", get: (s) => relTime(s.modified), dim: true },
|
|
302
|
+
{ header: "MESSAGES", get: (s) => s.messages, dim: true },
|
|
303
|
+
{ header: "ID", get: (s) => s.id, dim: true },
|
|
304
|
+
]
|
|
305
|
+
: [
|
|
306
|
+
{ header: "NAME", get: (s) => s.name },
|
|
307
|
+
{ header: "MODIFIED", get: (s) => relTime(s.modified), dim: true },
|
|
308
|
+
{ header: "MESSAGES", get: (s) => s.messages, dim: true },
|
|
309
|
+
{ header: "ID", get: (s) => s.id, dim: true },
|
|
310
|
+
];
|
|
311
|
+
console.log(renderTable(sessions, columns));
|
|
312
|
+
if (process.stdout.isTTY) {
|
|
313
|
+
console.log("");
|
|
314
|
+
console.log(dim("Resume: pi-link <name>"));
|
|
315
|
+
}
|
|
316
|
+
} else if (command === "resolve") {
|
|
317
|
+
let global = false;
|
|
318
|
+
const positional = [];
|
|
319
|
+
for (const a of args) {
|
|
320
|
+
rejectRenamedFlag(a);
|
|
321
|
+
if (a === "--global" || a === "-g") global = true;
|
|
322
|
+
else if (a.startsWith("-")) {
|
|
323
|
+
console.error(`Unknown argument: ${a}`);
|
|
324
|
+
console.error("Usage: pi-link resolve <name> [--global|-g]");
|
|
325
|
+
process.exit(1);
|
|
326
|
+
} else positional.push(a);
|
|
327
|
+
}
|
|
328
|
+
if (positional.length !== 1) {
|
|
329
|
+
console.error("Usage: pi-link resolve <name> [--global|-g]");
|
|
330
|
+
process.exit(1);
|
|
331
|
+
}
|
|
332
|
+
const name = positional[0].trim().replace(/\s+/g, " ");
|
|
333
|
+
if (!name) {
|
|
334
|
+
console.error("Usage: pi-link resolve <name> [--global|-g]");
|
|
335
|
+
process.exit(1);
|
|
336
|
+
}
|
|
337
|
+
const { dir, isCustom } = resolveSessionDir(process.cwd(), resolveAgentDir());
|
|
338
|
+
const { local, all } = await findSessionsByName(name, dir, isCustom);
|
|
339
|
+
const matches = global ? all : local;
|
|
340
|
+
if (matches.length === 1) {
|
|
341
|
+
process.stdout.write(matches[0].path);
|
|
342
|
+
} else if (matches.length > 1) {
|
|
343
|
+
printCandidates(name, matches);
|
|
344
|
+
}
|
|
345
|
+
} else if (command && command !== "--help" && command !== "-h") {
|
|
346
|
+
// pi-link [--global|-g] <name> [pi flags...] — resolve and launch Pi.
|
|
347
|
+
// Walk every token in one pass: pull out --global wherever it appears, treat
|
|
348
|
+
// the first non-flag token as the name, reject managed flags, forward the rest.
|
|
349
|
+
let global = false;
|
|
350
|
+
let name = null;
|
|
351
|
+
const piPassthrough = [];
|
|
352
|
+
for (const token of [command, ...args]) {
|
|
353
|
+
rejectRenamedFlag(token);
|
|
354
|
+
if (token === "--global" || token === "-g") { global = true; continue; }
|
|
355
|
+
rejectManagedFlag(token);
|
|
356
|
+
if (name === null) {
|
|
357
|
+
// Before the name is set, an unknown leading flag is almost certainly a
|
|
358
|
+
// user mistake (`pi-link --model gpt-4 foo`) — don't silently treat it
|
|
359
|
+
// as a session name. After the name is set, anything goes (forwarded to Pi).
|
|
360
|
+
if (token.startsWith("-")) {
|
|
361
|
+
console.error(`Unknown argument before name: ${token}`);
|
|
362
|
+
console.error("Usage: pi-link <name> [--global|-g] [pi flags...]");
|
|
363
|
+
process.exit(1);
|
|
364
|
+
}
|
|
365
|
+
name = token;
|
|
366
|
+
} else piPassthrough.push(token);
|
|
367
|
+
}
|
|
368
|
+
if (!name) {
|
|
369
|
+
console.error("Usage: pi-link <name> [--global|-g] [pi flags...]");
|
|
370
|
+
process.exit(1);
|
|
371
|
+
}
|
|
372
|
+
name = name.trim().replace(/\s+/g, " ");
|
|
373
|
+
if (!name) {
|
|
374
|
+
console.error("Usage: pi-link <name> [--global|-g] [pi flags...]");
|
|
375
|
+
process.exit(1);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const { dir, isCustom } = resolveSessionDir(process.cwd(), resolveAgentDir());
|
|
379
|
+
const { local, all } = await findSessionsByName(name, dir, isCustom);
|
|
380
|
+
const matches = global ? all : local;
|
|
381
|
+
if (matches.length > 1) {
|
|
382
|
+
printCandidates(name, matches);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const piArgs = [];
|
|
386
|
+
if (matches.length === 1) {
|
|
387
|
+
console.error(`Resuming session: ${matches[0].path}`);
|
|
388
|
+
piArgs.push("--session", matches[0].path);
|
|
389
|
+
} else {
|
|
390
|
+
if (!global && all.length > local.length) {
|
|
391
|
+
const elsewhere = all.length - local.length;
|
|
392
|
+
console.error(`No "${name}" in this cwd. (${elsewhere} match${elsewhere === 1 ? "" : "es"} in other cwds — use --global to consider ${elsewhere === 1 ? "it" : "them"}.)`);
|
|
393
|
+
}
|
|
394
|
+
console.error("Starting new session.");
|
|
395
|
+
}
|
|
396
|
+
piArgs.push("--link", ...piPassthrough);
|
|
397
|
+
|
|
398
|
+
const isWin = process.platform === "win32";
|
|
399
|
+
const cmd = isWin ? "cmd.exe" : "pi";
|
|
400
|
+
const cmdArgs = isWin ? ["/d", "/c", "pi", ...piArgs] : piArgs;
|
|
401
|
+
|
|
402
|
+
// PI_LINK_NAME is the internal handoff to the pi-link extension on the Pi side.
|
|
403
|
+
// The extension consumes and deletes it on startup; never expose this as a public API.
|
|
404
|
+
const child = spawn(cmd, cmdArgs, {
|
|
405
|
+
stdio: "inherit",
|
|
406
|
+
env: { ...process.env, PI_LINK_NAME: name },
|
|
407
|
+
});
|
|
408
|
+
child.once("exit", (code, signal) => {
|
|
409
|
+
if (code !== null) process.exit(code);
|
|
410
|
+
process.exit(signal === "SIGINT" ? 130 : 1);
|
|
411
|
+
});
|
|
412
|
+
child.once("error", (err) => {
|
|
413
|
+
console.error(`Failed to start pi: ${err.message}`);
|
|
414
|
+
process.exit(1);
|
|
415
|
+
});
|
|
416
|
+
} else {
|
|
417
|
+
console.error("Usage: pi-link <name> [--global|-g] [pi flags...]");
|
|
418
|
+
console.error(" pi-link list [--global|-g]");
|
|
419
|
+
console.error(" pi-link resolve <name> [--global|-g]");
|
|
420
|
+
console.error("");
|
|
421
|
+
console.error("By default, name lookup is scoped to the current cwd.");
|
|
422
|
+
console.error("--global / -g widens the search to sessions in any cwd.");
|
|
423
|
+
process.exit(0);
|
|
424
|
+
}
|
package/index.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Pi Link — WebSocket-based inter-terminal communication
|
|
3
3
|
*
|
|
4
4
|
* Connects multiple Pi terminals over a local WebSocket link.
|
|
5
|
-
* Opt-in via --link flag, pi-link CLI, or /link-connect command.
|
|
5
|
+
* Opt-in via --link flag, --link-name flag, pi-link CLI, or /link-connect command.
|
|
6
6
|
* First terminal to connect becomes the hub; others join as clients.
|
|
7
7
|
* Hub loss triggers automatic promotion of a surviving client.
|
|
8
8
|
*
|
|
@@ -115,6 +115,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
115
115
|
default: false,
|
|
116
116
|
});
|
|
117
117
|
|
|
118
|
+
pi.registerFlag("link-name", {
|
|
119
|
+
description:
|
|
120
|
+
"Set the pi-link terminal name on startup (link identity only; does not affect session)",
|
|
121
|
+
type: "string",
|
|
122
|
+
});
|
|
123
|
+
|
|
118
124
|
// ── State ────────────────────────────────────────────────────────────────
|
|
119
125
|
|
|
120
126
|
let role: "hub" | "client" | "disconnected" = "disconnected";
|
|
@@ -927,18 +933,56 @@ export default function (pi: ExtensionAPI) {
|
|
|
927
933
|
ctx = _ctx;
|
|
928
934
|
currentCwd = _ctx.cwd;
|
|
929
935
|
|
|
930
|
-
// Resolve terminal name:
|
|
931
|
-
// PI_LINK_NAME
|
|
932
|
-
//
|
|
933
|
-
|
|
936
|
+
// Resolve terminal name. Precedence:
|
|
937
|
+
// --link-name flag > PI_LINK_NAME env > saved link-name > session name > random
|
|
938
|
+
//
|
|
939
|
+
// --link-name is the public CLI surface (link identity only, never touches session name).
|
|
940
|
+
// PI_LINK_NAME is the internal handoff from the `pi-link` wrapper, which DOES
|
|
941
|
+
// seed session name when absent (the wrapper's combined-mode contract).
|
|
942
|
+
// PI_LINK_NAME is consumed once and removed from process.env so spawned children don't inherit it.
|
|
943
|
+
const cliRaw = pi.getFlag("link-name");
|
|
944
|
+
let cliFlagName: string | undefined;
|
|
945
|
+
if (typeof cliRaw === "string") {
|
|
946
|
+
cliFlagName = cliRaw.trim().replace(/\s+/g, " ");
|
|
947
|
+
if (!cliFlagName) {
|
|
948
|
+
console.error("Error: --link-name requires a non-empty value.");
|
|
949
|
+
process.exit(1);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
const envRaw = process.env.PI_LINK_NAME;
|
|
934
954
|
delete process.env.PI_LINK_NAME;
|
|
935
|
-
const
|
|
955
|
+
const envFlagName = envRaw?.trim().replace(/\s+/g, " ") || undefined;
|
|
956
|
+
|
|
957
|
+
const flagName = cliFlagName ?? envFlagName;
|
|
958
|
+
const fromEnv = !cliFlagName && !!envFlagName;
|
|
936
959
|
|
|
937
960
|
if (flagName) {
|
|
938
961
|
preferredName = flagName;
|
|
939
962
|
terminalName = flagName;
|
|
940
|
-
|
|
941
|
-
if
|
|
963
|
+
|
|
964
|
+
// Skip append if the saved name already matches; persistence is needed
|
|
965
|
+
// only for first-time set or actual change. Reduces session-file growth
|
|
966
|
+
// on repeated startups (common in automation).
|
|
967
|
+
let latestSaved: string | undefined;
|
|
968
|
+
const entries = _ctx.sessionManager.getEntries();
|
|
969
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
970
|
+
const e = entries[i] as {
|
|
971
|
+
type: string;
|
|
972
|
+
customType?: string;
|
|
973
|
+
data?: { name?: unknown };
|
|
974
|
+
};
|
|
975
|
+
if (e.type !== "custom" || e.customType !== "link-name") continue;
|
|
976
|
+
if (typeof e.data?.name === "string") latestSaved = e.data.name;
|
|
977
|
+
break;
|
|
978
|
+
}
|
|
979
|
+
if (latestSaved?.trim().replace(/\s+/g, " ") !== flagName) {
|
|
980
|
+
pi.appendEntry("link-name", { name: flagName });
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
// Critical: only the env path (wrapper combined mode) seeds session name.
|
|
984
|
+
// Public --link-name is link-only.
|
|
985
|
+
if (fromEnv && !pi.getSessionName()) pi.setSessionName(flagName);
|
|
942
986
|
} else {
|
|
943
987
|
const saved = _ctx.sessionManager
|
|
944
988
|
.getEntries()
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-link",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14-beta.0",
|
|
4
4
|
"description": "WebSocket-based inter-terminal communication for Pi. Connect multiple Pi terminals over a local link network.",
|
|
5
5
|
"author": "alvivar",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"bin": {
|
|
8
|
-
"pi-link": "
|
|
8
|
+
"pi-link": "bin/pi-link.mjs"
|
|
9
9
|
},
|
|
10
10
|
"repository": {
|
|
11
11
|
"type": "git",
|