@xevy/cli 0.1.31 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ /**
2
+ * One pi per conversation: `xevy dev` claims the folder's conversation with a
3
+ * lock file before launching pi, so a second run in the same folder knows the
4
+ * first is still using it and starts its own conversation instead.
5
+ *
6
+ * The lock is `<folder>/.xevy/locks/<conversation id>.lock`, created
7
+ * exclusively and holding the CLI's pid and computer name. The CLI waits for
8
+ * pi to exit, so its pid is alive exactly as long as the conversation is in
9
+ * use. A lock whose process is gone (a crash, a closed terminal) is stale and
10
+ * taken over.
11
+ */
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+
16
+ /** A lock this young with no readable content may still be being written by its owner. */
17
+ const UNREADABLE_GRACE_MS = 5_000;
18
+
19
+ /** Whether a process id runs on this computer. EPERM means it runs under another user. Works on Windows too. */
20
+ export function isProcessAlive(pid) {
21
+ if (!Number.isInteger(pid) || pid <= 0) return false;
22
+ try {
23
+ process.kill(pid, 0);
24
+ return true;
25
+ } catch (error) {
26
+ return error?.code === "EPERM";
27
+ }
28
+ }
29
+
30
+ export function conversationLockPath(folder, piSessionId) {
31
+ return path.join(folder, ".xevy", "locks", `${piSessionId}.lock`);
32
+ }
33
+
34
+ function readLock(file) {
35
+ try {
36
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
37
+ return parsed && typeof parsed === "object" ? parsed : null;
38
+ } catch {
39
+ return null; // Missing, empty or half-written: the caller decides by its age.
40
+ }
41
+ }
42
+
43
+ function lockAgeMs(file, now) {
44
+ try {
45
+ return now - fs.statSync(file).mtimeMs;
46
+ } catch {
47
+ return Number.POSITIVE_INFINITY;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Whether the recorded holder still uses the conversation. A lock from another
53
+ * computer (a synced folder) cannot be checked from here and counts as held;
54
+ * the cost is only a new conversation.
55
+ */
56
+ function isHeld(holder, file, { pid, hostname, alive, now }) {
57
+ if (!holder) return lockAgeMs(file, now) < UNREADABLE_GRACE_MS;
58
+ if (holder.hostname && holder.hostname !== hostname) return true;
59
+ // Our own pid in an old lock means the pid was reused after the owner died.
60
+ if (holder.pid === pid) return false;
61
+ return alive(holder.pid);
62
+ }
63
+
64
+ /**
65
+ * Claims a conversation for this run. Returns `{ release, recovered }`, or
66
+ * null while another live `xevy dev` holds it. `recovered` is true when a
67
+ * stale lock was taken over.
68
+ */
69
+ export function claimConversation(folder, piSessionId, options = {}) {
70
+ const { pid = process.pid, hostname = os.hostname(), alive = isProcessAlive, now = () => Date.now(), log = () => {} } = options;
71
+ const file = conversationLockPath(folder, piSessionId);
72
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
73
+ let recovered = false;
74
+ for (let attempt = 0; attempt < 3; attempt += 1) {
75
+ try {
76
+ const fd = fs.openSync(file, "wx", 0o600);
77
+ try {
78
+ fs.writeSync(fd, JSON.stringify({ pid, hostname, startedAt: new Date(now()).toISOString() }));
79
+ } finally {
80
+ fs.closeSync(fd);
81
+ }
82
+ log({ op: "conversation-lock", status: recovered ? "recovered" : "claimed", piSessionId });
83
+ return {
84
+ recovered,
85
+ release() {
86
+ const holder = readLock(file);
87
+ if (holder?.pid !== pid || holder?.hostname !== hostname) return;
88
+ try {
89
+ fs.unlinkSync(file);
90
+ } catch (error) {
91
+ if (error?.code !== "ENOENT") log({ op: "conversation-lock", status: "release-failed", piSessionId, error: error instanceof Error ? error.message : String(error) });
92
+ }
93
+ },
94
+ };
95
+ } catch (error) {
96
+ if (error?.code !== "EEXIST") throw error;
97
+ }
98
+ const holder = readLock(file);
99
+ if (isHeld(holder, file, { pid, hostname, alive, now: now() })) {
100
+ log({ op: "conversation-lock", status: "busy", piSessionId, holderPid: holder?.pid ?? null });
101
+ return null;
102
+ }
103
+ try {
104
+ fs.unlinkSync(file);
105
+ } catch (error) {
106
+ if (error?.code !== "ENOENT") throw error;
107
+ }
108
+ recovered = true;
109
+ }
110
+ // Another run keeps re-creating the lock between our checks: it is in use.
111
+ log({ op: "conversation-lock", status: "busy", piSessionId, holderPid: null });
112
+ return null;
113
+ }
@@ -13,6 +13,7 @@
13
13
  import { randomUUID } from "node:crypto";
14
14
  import fs from "node:fs";
15
15
  import path from "node:path";
16
+ import { claimConversation } from "./conversation-lock.mjs";
16
17
  import {
17
18
  createApiClient,
18
19
  defaultSleep,
@@ -142,10 +143,23 @@ function expandHome(value, homeDir, cwd) {
142
143
  }
143
144
 
144
145
  /**
145
- * Chooses the folder the local AI works from. Order: `--dir`, then the current
146
- * folder when it is already linked to this project for remote work, then
147
- * `~/xevy/<project>`. A folder linked by repository setup holds a real checkout
148
- * and is never used.
146
+ * Whether a folder may become this project's remote folder without asking: it
147
+ * is linked to nothing, is neither the home folder nor the filesystem root,
148
+ * and holds no real checkout. This is the "make my own folder, add an
149
+ * AGENTS.md, run xevy dev there" workflow.
150
+ */
151
+ function isFreeFolder(folder, homeDir) {
152
+ const resolved = path.resolve(folder);
153
+ if (resolved === path.resolve(homeDir) || resolved === path.parse(resolved).root) return false;
154
+ return !fs.existsSync(path.join(resolved, ".git"));
155
+ }
156
+
157
+ /**
158
+ * Chooses the folder the local AI works from. Order: `--dir`; then the current
159
+ * folder when it is already linked to this project for remote work, or is a
160
+ * free folder (see isFreeFolder); then `~/xevy/<project>`. A folder linked by
161
+ * repository setup holds a real checkout and is never used; one linked to
162
+ * another project for remote work is refused.
149
163
  */
150
164
  export function resolveLocalFolder({ dir, cwd, homeDir, target, writeLine }) {
151
165
  if (dir) {
@@ -161,8 +175,12 @@ export function resolveLocalFolder({ dir, cwd, homeDir, target, writeLine }) {
161
175
  }
162
176
  const here = readLinkedProject(cwd);
163
177
  if (here?.mode === "remote" && sameProject(here, target)) return { folder: cwd, linked: here };
178
+ if (here?.mode === "remote") {
179
+ throw new RemoteDevError(`${cwd} is already used for ${here.workspaceIdentifier}/${here.projectIdentifier}. Run xevy dev from another folder, or choose one with --dir <path>.`);
180
+ }
181
+ if (!here && isFreeFolder(cwd, homeDir)) return { folder: cwd, linked: null };
164
182
  const folder = path.join(homeDir, "xevy", target.projectIdentifier);
165
- if (here && here.mode !== "remote") {
183
+ if (here) {
166
184
  writeLine(`This folder holds a local copy of the project, so it stays untouched. The AI works from ${folder}.`);
167
185
  }
168
186
  const linked = readLinkedProject(folder);
@@ -193,7 +211,7 @@ export function chooseFolder({ dir, cwd, homeDir, target, writeLine }) {
193
211
  /** Creates the folder and its `.xevy/` tree with owner-only permissions. */
194
212
  export function prepareLocalFolder(folder) {
195
213
  fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
196
- for (const directory of [xevyDir(folder), path.join(xevyDir(folder), "pi"), path.join(xevyDir(folder), "logs")]) {
214
+ for (const directory of [xevyDir(folder), path.join(xevyDir(folder), "pi"), path.join(xevyDir(folder), "logs"), path.join(xevyDir(folder), "locks")]) {
197
215
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
198
216
  fs.chmodSync(directory, 0o700);
199
217
  }
@@ -289,14 +307,23 @@ function sessionStateFrom(state, session) {
289
307
  };
290
308
  }
291
309
 
310
+ /**
311
+ * The edit journal of a conversation. The folder's own conversation keeps
312
+ * `journal.ndjson`; a second conversation running alongside it keeps its own,
313
+ * so two extensions never append to or compact the same file.
314
+ */
315
+ export function journalFileName(secondaryConversationId = null) {
316
+ return secondaryConversationId ? `journal-${secondaryConversationId}.ndjson` : "journal.ndjson";
317
+ }
318
+
292
319
  /**
293
320
  * Counts edits the extension recorded but has not uploaded yet. Journal lines
294
321
  * are either edit entries (carry `op`) or status records for an entry's `seq`;
295
322
  * an entry counts as settled once a record marks it uploaded, saved or in
296
323
  * conflict (conflicts are reported, never replayed).
297
324
  */
298
- export function countPendingUploads(folder) {
299
- const file = path.join(xevyDir(folder), "journal.ndjson");
325
+ export function countPendingUploads(folder, secondaryConversationId = null) {
326
+ const file = path.join(xevyDir(folder), journalFileName(secondaryConversationId));
300
327
  if (!fs.existsSync(file)) return 0;
301
328
  const pending = new Set();
302
329
  for (const line of fs.readFileSync(file, "utf8").split(/\r?\n/)) {
@@ -545,14 +572,27 @@ export function buildRemotePiArgs({ extensionFiles, remoteExtension, folder, piS
545
572
  * Environment for pi. `XEVY_REMOTE_DEV_SESSION` means "running on the worker"
546
573
  * and is never passed. The hints tell the AI what was asked for; it decides
547
574
  * whether and how to start a Dev Session.
575
+ *
576
+ * A second conversation in a folder whose own conversation is in use gets
577
+ * `XEVY_REMOTE_SECONDARY_CONVERSATION` instead of `XEVY_REMOTE_PI_SESSION_ID`:
578
+ * it keeps its own edit journal and never records itself as the folder's
579
+ * conversation.
580
+ *
581
+ * `XEVY_REMOTE_EXTENSION_PATH` names the remote-tools extension so the
582
+ * specialists pi dispatches load it too and work on the same Dev Session.
548
583
  */
549
- export function buildRemotePiEnv({ env, folder, base, explicitBase, hints = null, piSessionId = null }) {
584
+ export function buildRemotePiEnv({ env, folder, base, explicitBase, hints = null, piSessionId = null, secondary = false, remoteExtension = null }) {
550
585
  const next = { ...env, XEVY_REMOTE_PROJECT_DIR: path.resolve(folder), XEVY_REMOTE_BASE: base };
586
+ delete next.XEVY_REMOTE_EXTENSION_PATH;
587
+ if (remoteExtension) next.XEVY_REMOTE_EXTENSION_PATH = path.resolve(remoteExtension);
551
588
  delete next.XEVY_REMOTE_DEV_SESSION;
552
589
  delete next.XEVY_REMOTE_DEV_HINTS;
590
+ delete next.XEVY_REMOTE_PI_SESSION_ID;
591
+ delete next.XEVY_REMOTE_SECONDARY_CONVERSATION;
553
592
  if (explicitBase) next.XEVY_BASE = base;
554
593
  if (hints) next.XEVY_REMOTE_DEV_HINTS = JSON.stringify(hints);
555
- if (piSessionId) next.XEVY_REMOTE_PI_SESSION_ID = piSessionId;
594
+ if (piSessionId && secondary) next.XEVY_REMOTE_SECONDARY_CONVERSATION = piSessionId;
595
+ else if (piSessionId) next.XEVY_REMOTE_PI_SESSION_ID = piSessionId;
556
596
  return next;
557
597
  }
558
598
 
@@ -644,32 +684,57 @@ export async function runRemoteDev(options) {
644
684
  newConversation: options.newConversation,
645
685
  keepConversation: options.keepConversation,
646
686
  });
647
- const piSessionId = conversation.piSessionId;
648
- if (target) {
649
- writeProjectFile(folder, {
650
- linked,
651
- workspace: workspace ?? { id: null, identifier: target.workspaceIdentifier },
652
- project: project ?? { id: null, identifier: target.projectIdentifier },
653
- piSessionId,
654
- conversationSessionId: reconnected?.session.id ?? null,
655
- });
687
+ // Another `xevy dev` in this folder may be using its conversation: then this
688
+ // run starts its own conversation on the same Dev Session, and leaves the
689
+ // folder's saved conversation alone.
690
+ let piSessionId = conversation.piSessionId;
691
+ let claim = claimConversation(folder, piSessionId, { log: logged.log });
692
+ const secondary = !claim;
693
+ if (secondary) {
694
+ piSessionId = randomUUID();
695
+ claim = claimConversation(folder, piSessionId, { log: logged.log });
656
696
  }
657
- logged.log({ op: "conversation", status: conversation.reason, sessionId: reconnected?.session.id ?? null });
658
- if (conversation.reason === "asked" || (conversation.reason === "changed" && !reconnected)) say("Starting a new conversation.");
659
- if (conversation.reason === "changed" && reconnected) say("Starting a new conversation for this Dev Session.");
660
- if (reconnected?.session.hostname) say(`Preview: https://${reconnected.session.hostname}`);
697
+ try {
698
+ if (target && !secondary) {
699
+ writeProjectFile(folder, {
700
+ linked,
701
+ workspace: workspace ?? { id: null, identifier: target.workspaceIdentifier },
702
+ project: project ?? { id: null, identifier: target.projectIdentifier },
703
+ piSessionId,
704
+ conversationSessionId: reconnected?.session.id ?? null,
705
+ });
706
+ }
707
+ logged.log({ op: "conversation", status: secondary ? "busy" : conversation.reason, sessionId: reconnected?.session.id ?? null });
708
+ if (secondary) {
709
+ say(reconnected
710
+ ? "Another xevy dev is using this folder's conversation, so this one starts a new conversation in the same Dev Session."
711
+ : "Another xevy dev is using this folder's conversation, so this one starts a new conversation.");
712
+ } else {
713
+ if (conversation.reason === "asked" || (conversation.reason === "changed" && !reconnected)) say("Starting a new conversation.");
714
+ if (conversation.reason === "changed" && reconnected) say("Starting a new conversation for this Dev Session.");
715
+ }
716
+ if (reconnected?.session.hostname) say(`Preview: https://${reconnected.session.hostname}`);
717
+ return await launchAndSummarize({ ...options, base, fetchImpl, homeDir, say, warn, extensionFiles, spawnPi, beforeLaunch, env, folder, target, reconnected, piSessionId, secondary, logged, baseApi });
718
+ } finally {
719
+ claim?.release();
720
+ }
721
+ }
661
722
 
723
+ /** Launches pi for the chosen conversation and prints the one-line summary after it exits. */
724
+ async function launchAndSummarize(run) {
725
+ const { base, fetchImpl, homeDir, say, warn, extensionFiles, spawnPi, beforeLaunch, env, folder, target, reconnected, piSessionId, secondary, logged, baseApi } = run;
726
+ const journalOwner = secondary ? piSessionId : null;
662
727
  const remoteExtension = await ensureRemoteExtension({ base, fetchImpl, homeDir, writeLine: say, warn });
663
- const piArgs = buildRemotePiArgs({ extensionFiles, remoteExtension, folder, piSessionId, piArgs: options.piArgs });
728
+ const piArgs = buildRemotePiArgs({ extensionFiles, remoteExtension, folder, piSessionId, piArgs: run.piArgs });
664
729
  const hints = {
665
730
  project: target ? { workspaceIdentifier: target.workspaceIdentifier, projectIdentifier: target.projectIdentifier } : null,
666
- task: options.task || null,
667
- branchTargets: options.branchTargets || null,
668
- requestKey: options.requestKey || null,
731
+ task: run.task || null,
732
+ branchTargets: run.branchTargets || null,
733
+ requestKey: run.requestKey || null,
669
734
  };
670
- logged.log({ op: "launch", sessionId: reconnected?.session.id ?? null, linked: Boolean(reconnected) });
735
+ logged.log({ op: "launch", sessionId: reconnected?.session.id ?? null, linked: Boolean(reconnected), secondary });
671
736
  beforeLaunch();
672
- const result = spawnPi(piArgs, { cwd: folder, env: buildRemotePiEnv({ env, folder, base, explicitBase: options.explicitBase, hints, piSessionId }) });
737
+ const result = spawnPi(piArgs, { cwd: folder, env: buildRemotePiEnv({ env, folder, base, explicitBase: run.explicitBase, hints, piSessionId, secondary, remoteExtension }) });
673
738
  if (result.error) throw new RemoteDevError(result.error.message);
674
739
  const exitCode = result.status ?? (result.signal ? 1 : 0);
675
740
  logged.log({ op: "exit", status: exitCode });
@@ -679,10 +744,11 @@ export async function runRemoteDev(options) {
679
744
  const finalProject = readLinkedProject(folder);
680
745
  const finalTarget = finalProject ? { workspaceIdentifier: finalProject.workspaceIdentifier, projectIdentifier: finalProject.projectIdentifier } : null;
681
746
  if (!finalState.sessionId || !finalProject) {
682
- say(formatExitSummary({ target: finalTarget, session: null, pending: countPendingUploads(folder), dirArgument: options.dir || null, started: false }));
747
+ say(formatExitSummary({ target: finalTarget, session: null, pending: countPendingUploads(folder, journalOwner), dirArgument: run.dir || null, started: false }));
683
748
  return exitCode;
684
749
  }
685
- if (finalProject.conversationSessionId !== finalState.sessionId || finalProject.piSessionId !== piSessionId) {
750
+ // A second conversation never becomes the folder's conversation.
751
+ if (!secondary && (finalProject.conversationSessionId !== finalState.sessionId || finalProject.piSessionId !== piSessionId)) {
686
752
  writeProjectFile(folder, {
687
753
  linked: finalProject,
688
754
  workspace: { id: finalProject.workspaceId, identifier: finalProject.workspaceIdentifier },
@@ -700,6 +766,6 @@ export async function runRemoteDev(options) {
700
766
  logged.log({ op: "summary", status: "error", error: error instanceof Error ? error.message : String(error) });
701
767
  finalSession = undefined;
702
768
  }
703
- say(formatExitSummary({ target: finalTarget, session: finalSession, pending: countPendingUploads(folder), dirArgument: options.dir || null }));
769
+ say(formatExitSummary({ target: finalTarget, session: finalSession, pending: countPendingUploads(folder, journalOwner), dirArgument: run.dir || null }));
704
770
  return exitCode;
705
771
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xevy/cli",
3
- "version": "0.1.31",
3
+ "version": "0.1.33",
4
4
  "description": "Xevy CLI \u2014 connect to remote Dev Sessions, configure credentials, pi, coding-agent skills, and MCP, and keep integrations current.",
5
5
  "type": "module",
6
6
  "keywords": [