@xevy/cli 0.1.26 → 0.1.28

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/README.md CHANGED
@@ -57,11 +57,12 @@ OAuth.
57
57
  ```bash
58
58
  xevy # open an interactive pi session with Xevy loaded
59
59
  xevy "summarise this repo" # or send a one-off prompt
60
- xevy dev task/VI22-07 # attach to a task's remote Dev Session
61
- xevy dev xevy/xevyai # select a running project workspace
62
- xevy dev xevy/xevyai --new # create another workspace
63
- xevy dev session/<uuid> # open one exact session
64
- xevy dev session/<uuid> --rename "Checkout fix" # change its display name
60
+ xevy dev xevy/xevyai # the AI runs here and works on the Dev Session's files
61
+ xevy connect task/VI22-07 # attach to a task's remote Dev Session
62
+ xevy connect xevy/xevyai # select a running project workspace
63
+ xevy connect xevy/xevyai --new # create another workspace
64
+ xevy connect session/<uuid> # open one exact session
65
+ xevy connect session/<uuid> --rename "Checkout fix" # change its display name
65
66
  ```
66
67
 
67
68
  That's it — you're set up. The sections below are reference for when you need more detail.
@@ -151,15 +152,48 @@ xevy "summarise this repo" # forwards the prompt to pi
151
152
 
152
153
  ## `xevy dev`
153
154
 
155
+ The AI runs on your computer and works on the Dev Session's files:
156
+
157
+ ```bash
158
+ xevy dev xevy/xevyai # start or reuse your Dev Session and open the AI
159
+ xevy dev # same, from a folder already set up by xevy dev
160
+ xevy dev xevy/xevyai --new-conversation # keep the Dev Session, start a fresh conversation
161
+ xevy dev xevy/xevyai --dir ~/work/shop # work from another folder
162
+ xevy dev xevy/xevyai --new # start another Dev Session
163
+ xevy dev xevy/xevyai -- --verbose # pass options to pi after --
164
+ ```
165
+
166
+ `xevy dev` starts your Dev Session for the project, or reuses the one already
167
+ running, waits until it is ready and opens the AI in this terminal. Every file
168
+ the AI reads or edits and every command it runs stays in the Dev Session. This
169
+ computer keeps the conversation and a short record of the AI's recent edits,
170
+ cleared once they are saved in the Dev Session.
171
+
172
+ The AI works from `~/xevy/<project>`, or the folder given with `--dir`. Only a
173
+ `.xevy` folder is created there, readable by you alone. It holds the link to the
174
+ project and your conversation, so running the same command again picks up the
175
+ same Dev Session and the same conversation. If a start is interrupted, the next
176
+ run finishes it without creating a second Dev Session. A folder that already
177
+ holds a local copy of the project is left untouched.
178
+
179
+ When you leave the AI, the Dev Session keeps running and the CLI prints how to
180
+ come back, the preview address, and the `xevy connect` command for its terminal.
181
+ The Dev Session needs an up-to-date worker; if its worker cannot yet run
182
+ commands for a local AI, the CLI says so and suggests `xevy connect` instead.
183
+
184
+ ## `xevy connect`
185
+
186
+ Attach your terminal to the AI running in the Dev Session.
187
+
154
188
  Connect an interactive terminal to a task-linked or task-free remote Dev Session:
155
189
 
156
190
  ```bash
157
- xevy dev task/VI22-07
158
- xevy dev task/cb49c02e-66d8-4475-95a8-6f3930643ec8
159
- xevy dev xevy/xevyai --new
160
- xevy dev xevy/xevyai --request-key <uuid>
161
- xevy dev session/<uuid> --rename "Checkout fix"
162
- xevy dev xevy/xevyai --base https://xevy.example.com
191
+ xevy connect task/VI22-07
192
+ xevy connect task/cb49c02e-66d8-4475-95a8-6f3930643ec8
193
+ xevy connect xevy/xevyai --new
194
+ xevy connect xevy/xevyai --request-key <uuid>
195
+ xevy connect session/<uuid> --rename "Checkout fix"
196
+ xevy connect xevy/xevyai --base https://xevy.example.com
163
197
  ```
164
198
 
165
199
  The command stays attached across normal Pi exits and transient terminal
@@ -175,7 +209,7 @@ workspace: normal composer, thinking, tools, history, keyboard shortcuts, and
175
209
  session resume all behave like Pi on a local machine. A multi-repository project
176
210
  asks for its runtime repository only on first start.
177
211
 
178
- `xevy dev` is only a terminal transport. Pi, Git credentials, the repository,
212
+ `xevy connect` is only a terminal transport. Pi, Git credentials, the repository,
179
213
  and Docker remain on the server. Press `Ctrl+]` to detach without stopping Pi;
180
214
  run the same command again to reattach. Pi conversation history is stored in the
181
215
  bounded Dev Session volume. The controller periodically commits work and pushes
@@ -19,7 +19,7 @@ const TERMINAL_START_MAX_DELAY_MS = 5_000;
19
19
  const TERMINAL_SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
20
20
  const DEV_TARGET_SEGMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
21
21
 
22
- function parseDevTarget(value) {
22
+ export function parseDevTarget(value) {
23
23
  const reference = String(value || "").trim();
24
24
  const segments = reference.split("/");
25
25
  const usage = "Use `session/<session-id>`, `task/<task-id-or-code>` or `<workspace>/<project>`.";
@@ -84,10 +84,18 @@ export function parseDevCommandArgs(argv) {
84
84
  let newSession = false;
85
85
  let requestKey;
86
86
  let rename;
87
+ const branchTargets = {};
87
88
  while (args.length > 0) {
88
89
  const argument = args.shift();
89
90
  if (argument === "-h" || argument === "--help") return { help: true, target: null, base: null };
90
91
  if (argument === "--new") { newSession = true; continue; }
92
+ if (argument === "--branch-target") {
93
+ const value = args.shift() || "";
94
+ const match = value.match(/^([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})=(production|staging|development|custom-[a-z0-9-]+|)$/i);
95
+ if (!match) throw new Error("--branch-target needs repositoryUUID=targetId; use an empty targetId for the repository default.");
96
+ branchTargets[match[1]] = match[2];
97
+ continue;
98
+ }
91
99
  if (argument === "--request-key" || argument === "--rename") {
92
100
  const value = args.shift();
93
101
  if (!value) throw new Error(`Missing value for ${argument}`);
@@ -106,17 +114,19 @@ export function parseDevCommandArgs(argv) {
106
114
  base = value;
107
115
  continue;
108
116
  }
109
- if (argument.startsWith("-")) throw new Error(`Unknown option for \`xevy dev\`: ${argument}.`);
110
- if (targetReference) throw new Error("`xevy dev` accepts one Dev Session target.");
117
+ if (argument.startsWith("-")) throw new Error(`Unknown option for \`xevy connect\`: ${argument}.`);
118
+ if (targetReference) throw new Error("`xevy connect` accepts one Dev Session target.");
111
119
  targetReference = argument;
112
120
  }
113
121
  if (!targetReference) {
114
- throw new Error("Usage: xevy dev <task/<task-id-or-code>|workspace/project> [--base <url>]");
122
+ throw new Error("Usage: xevy connect <task/<task-id-or-code>|workspace/project> [--base <url>]");
115
123
  }
116
124
  const target = parseDevTarget(targetReference);
117
125
  if (newSession && target.kind !== "personal") throw new Error("--new and --request-key apply to workspace/project targets.");
126
+ if (Object.keys(branchTargets).length && target.kind === "personal" && !newSession) throw new Error("--branch-target requires --new for workspace/project targets; existing sessions keep saved targets.");
127
+ if (Object.keys(branchTargets).length && target.kind === "session") throw new Error("--branch-target applies when starting a new session; existing sessions keep saved targets.");
118
128
  if (rename && target.kind !== "session") throw new Error("--rename requires session/<session-id>.");
119
- return { help: false, target, base, ...(newSession ? { newSession } : {}), ...(requestKey ? { requestKey } : {}), ...(rename ? { rename } : {}) };
129
+ return { help: false, target, base, ...(newSession ? { newSession } : {}), ...(requestKey ? { requestKey } : {}), ...(rename ? { rename } : {}), ...(Object.keys(branchTargets).length ? { branchTargets } : {}) };
120
130
  }
121
131
 
122
132
  export function resolveDevConnection({
@@ -213,7 +223,7 @@ function extractApiError(payload, fallback) {
213
223
  return fallback;
214
224
  }
215
225
 
216
- class DevSessionApiError extends Error {
226
+ export class DevSessionApiError extends Error {
217
227
  constructor(status, message, payload) {
218
228
  super(message);
219
229
  this.name = "DevSessionApiError";
@@ -303,7 +313,7 @@ function formatTask(task) {
303
313
  return `${code}${task.title} (${task.workspaceIdentifier}/${task.projectIdentifier})`;
304
314
  }
305
315
 
306
- async function selectOne({ items, label, describe, interactive, ask, writeLine }) {
316
+ export async function selectOne({ items, label, describe, interactive, ask, writeLine }) {
307
317
  if (items.length === 0) return null;
308
318
  if (items.length === 1) return items[0];
309
319
  writeLine(`Multiple ${label} match:`);
@@ -319,6 +329,26 @@ async function selectOne({ items, label, describe, interactive, ask, writeLine }
319
329
  }
320
330
  }
321
331
 
332
+ /** Select configured branch targets for each linked repository on a fresh start. */
333
+ export async function selectDevSessionBranchTargets({ repositories, interactive, ask, writeLine, branchTargets }) {
334
+ const selections = { ...branchTargets };
335
+ if (!interactive) return Object.keys(selections).length ? selections : undefined;
336
+ for (const repository of repositories) {
337
+ if (Object.hasOwn(selections, repository.id)) continue;
338
+ const targets = repository.branchTargets || [];
339
+ if (!targets.length) continue;
340
+ const ordered = [...targets].sort((left, right) => Number(right.id === "development") - Number(left.id === "development"));
341
+ const selected = await selectOne({
342
+ items: [...ordered, { id: "", label: "Repository default", branch: repository.defaultBranch || "remote default" }],
343
+ label: `branch targets for ${repository.displayName || repository.role || repository.id}`,
344
+ describe: target => `${target.label} · ${target.branch}`,
345
+ interactive, ask, writeLine,
346
+ });
347
+ selections[repository.id] = selected.id;
348
+ }
349
+ return Object.keys(selections).length ? selections : undefined;
350
+ }
351
+
322
352
  function executionCreatedAt(execution) {
323
353
  const value = Date.parse(execution.createdAt || "");
324
354
  return Number.isFinite(value) ? value : 0;
@@ -521,7 +551,7 @@ async function followExecution({
521
551
  return execution;
522
552
  }
523
553
  if (reconnects >= EXECUTION_RECONNECT_LIMIT) {
524
- throw new Error("The agent is still running, but the activity stream could not be reattached. Rerun `xevy dev` to resume safely.");
554
+ throw new Error("The agent is still running, but the activity stream could not be reattached. Rerun `xevy connect` to resume safely.");
525
555
  }
526
556
  reconnects += 1;
527
557
  writeLine(streamError ? "Connection lost; reconnecting…" : "Agent still running; reconnecting…");
@@ -543,7 +573,7 @@ async function showHistory({ api, taskId, branch, state, writeLine }) {
543
573
  return result?.executions || [];
544
574
  }
545
575
 
546
- function defaultSleep(milliseconds, signal) {
576
+ export function defaultSleep(milliseconds, signal) {
547
577
  return new Promise((resolve, reject) => {
548
578
  if (signal?.aborted) return reject(new Error("Dev Session detached."));
549
579
  const cleanup = () => signal?.removeEventListener("abort", abort);
@@ -560,7 +590,7 @@ function defaultSleep(milliseconds, signal) {
560
590
  });
561
591
  }
562
592
 
563
- async function waitForReady({ api, sessionPath, initialSession, writeLine, sleep, signal }) {
593
+ export async function waitForReady({ api, sessionPath, initialSession, writeLine, sleep, signal }) {
564
594
  let session = initialSession;
565
595
  let lastStatus = null;
566
596
  const deadline = Date.now() + SESSION_START_TIMEOUT_MS;
@@ -576,7 +606,7 @@ async function waitForReady({ api, sessionPath, initialSession, writeLine, sleep
576
606
  throw new Error(`Unexpected Dev Session status: ${session.status}`);
577
607
  }
578
608
  if (Date.now() >= deadline) {
579
- throw new Error("Dev Session startup is taking longer than expected. It remains active; rerun `xevy dev` to attach later.");
609
+ throw new Error("Dev Session startup is taking longer than expected. It remains active; rerun `xevy connect` to attach later.");
580
610
  }
581
611
  await sleep(SESSION_POLL_INTERVAL_MS, signal);
582
612
  const result = await api.request(`${sessionPath}/`, { signal });
@@ -851,7 +881,7 @@ async function attachNativeTerminalOnce({
851
881
  if (error instanceof DevSessionApiError && ![409, 502, 503, 504].includes(error.status)) throw error;
852
882
  attempts += 1;
853
883
  if (attempts >= TERMINAL_START_ATTEMPT_LIMIT) {
854
- throw new Error("The remote Xevy terminal never became ready. The Dev Session remains active; check its logs and rerun `xevy dev` after correcting the startup error.");
884
+ throw new Error("The remote Xevy terminal never became ready. The Dev Session remains active; check its logs and rerun `xevy connect` after correcting the startup error.");
855
885
  }
856
886
  status.update("Terminal is not ready yet · retrying…");
857
887
  await sleep(Math.min(500 * 2 ** (attempts - 1), TERMINAL_START_MAX_DELAY_MS), signal);
@@ -956,7 +986,7 @@ export async function runDevSession(options) {
956
986
  }
957
987
  const target = options.target;
958
988
  if (!target || !["task", "personal", "session"].includes(target.kind)) {
959
- throw new Error("Usage: xevy dev <task/<task-id-or-code>|workspace/project> [--base <url>]");
989
+ throw new Error("Usage: xevy connect <task/<task-id-or-code>|workspace/project> [--base <url>]");
960
990
  }
961
991
 
962
992
  const fetchImpl = options.fetchImpl || globalThis.fetch;
@@ -1079,16 +1109,24 @@ export async function runDevSession(options) {
1079
1109
  ask,
1080
1110
  writeLine,
1081
1111
  });
1112
+ const branchTargets = repositoryResult.branchTargetLocked && !options.branchTargets
1113
+ ? undefined : await selectDevSessionBranchTargets({ repositories, interactive, ask, writeLine, branchTargets: options.branchTargets });
1082
1114
  writeLine(`Starting Dev Session with ${repository.displayName || repository.role}…`);
1083
1115
  const started = await api.request(`${sessionPath}/`, {
1084
1116
  method: "POST",
1085
- body: { runtimeRepositoryId: repository.id },
1117
+ body: { runtimeRepositoryId: repository.id, ...(branchTargets ? { branchTargets } : {}) },
1086
1118
  signal: detachController.signal,
1087
1119
  timeoutMs: 60_000,
1088
1120
  });
1089
1121
  session = started?.session;
1090
1122
  if (!session) throw new Error("Xevy accepted the request but returned no Dev Session.");
1091
1123
  } else {
1124
+ if (options.branchTargets) {
1125
+ for (const [repositoryId, targetId] of Object.entries(options.branchTargets)) {
1126
+ const saved = session.config?.repos?.find(repository => repository.id === repositoryId);
1127
+ if (!saved || (saved.branchTarget?.id || "") !== targetId) throw new Error("The existing session has a different branch target. Resume its saved target or start a new task session.");
1128
+ }
1129
+ }
1092
1130
  writeLine("Attaching to the existing Dev Session…");
1093
1131
  }
1094
1132
  } else {
@@ -1127,6 +1165,7 @@ export async function runDevSession(options) {
1127
1165
  ask,
1128
1166
  writeLine,
1129
1167
  });
1168
+ const branchTargets = await selectDevSessionBranchTargets({ repositories, interactive, ask, writeLine, branchTargets: options.branchTargets });
1130
1169
  writeLine(`Starting new Dev Session with ${repository.displayName || repository.role}…`);
1131
1170
  const requestKey = options.requestKey || randomUUID();
1132
1171
  writeLine(`New request ${requestKey} · retry safely with --request-key ${requestKey}`);
@@ -1137,6 +1176,7 @@ export async function runDevSession(options) {
1137
1176
  kind: "personal",
1138
1177
  requestKey,
1139
1178
  projectId: project.id,
1179
+ ...(branchTargets ? { branchTargets } : {}),
1140
1180
  runtimeRepositoryId: repository.id,
1141
1181
  },
1142
1182
  },
@@ -1188,7 +1228,7 @@ export async function runDevSession(options) {
1188
1228
  api,
1189
1229
  base,
1190
1230
  sessionPath,
1191
- reattachHint: `Reattach with: xevy dev ${reattachTarget}`,
1231
+ reattachHint: `Reattach with: xevy connect ${reattachTarget}`,
1192
1232
  input,
1193
1233
  output,
1194
1234
  signal: detachController.signal,
@@ -0,0 +1,635 @@
1
+ /**
2
+ * `xevy dev` — run the AI on this computer while its files and commands live
3
+ * in a remote Dev Session.
4
+ *
5
+ * The CLI only resolves the local folder, starts or reuses one Dev Session,
6
+ * waits for it, downloads the remote-tools extension and launches pi. The
7
+ * extension (loaded with an explicit `-e`) owns heartbeats, the events stream
8
+ * and edit uploads for as long as pi runs. Nothing but `<folder>/.xevy/*` is
9
+ * ever written into the project folder.
10
+ */
11
+ import { randomUUID } from "node:crypto";
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import {
15
+ createApiClient,
16
+ defaultSleep,
17
+ DevSessionApiError,
18
+ parseDevTarget,
19
+ redactSensitive,
20
+ selectDevSessionBranchTargets,
21
+ selectOne,
22
+ waitForReady,
23
+ } from "./dev-session.mjs";
24
+
25
+ export const REQUIRED_WORKER_FEATURES = ["files_v1", "exec_v1"];
26
+ export const REMOTE_EXTENSION_FILE = "xevy-remote.ts";
27
+ export const REMOTE_EXTENSION_MARKERS = ["xevyRemoteExtension", "REMOTE_EXTENSION_VERSION"];
28
+ const EXCLUDED_LOCAL_TOOLS = "powershell,codemode";
29
+ const SESSION_READY_STATUSES = new Set(["ready", "busy"]);
30
+ const SESSION_PENDING_STATUSES = new Set(["provisioning", "installing", "starting"]);
31
+ const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
32
+ const MAX_SESSION_MOVES = 5;
33
+ const RECONNECT_POLL_MS = 3_000;
34
+ const RECONNECT_MAX_WAIT_MS = 10 * 60_000;
35
+ const EXTENSION_DOWNLOAD_TIMEOUT_MS = 10_000;
36
+ const SUMMARY_TIMEOUT_MS = 5_000;
37
+ const ACTIVE_AGENT_STATES = new Set(["working", "waiting"]);
38
+
39
+ export class RemoteDevError extends Error {
40
+ constructor(message, exitCode = 1) {
41
+ super(message);
42
+ this.name = "RemoteDevError";
43
+ this.exitCode = exitCode;
44
+ }
45
+ }
46
+
47
+ const DEV_USAGE_LINE = "Usage: xevy dev [<workspace>/<project>] [--dir <path>] [--new] [--new-conversation] [--base <url>] [-- <pi options>]";
48
+
49
+ /** Parses `xevy dev` arguments. Everything after `--` is passed to pi. */
50
+ export function parseRemoteDevArgs(argv) {
51
+ const args = [...argv];
52
+ const result = { help: false, target: null, dir: null, newSession: false, newConversation: false, base: null, piArgs: [] };
53
+ const branchTargets = {};
54
+ let targetReference = "";
55
+ while (args.length > 0) {
56
+ const argument = args.shift();
57
+ if (argument === "--") { result.piArgs = args.splice(0); break; }
58
+ if (argument === "-h" || argument === "--help") return { ...result, help: true };
59
+ if (argument === "--new") { result.newSession = true; continue; }
60
+ if (argument === "--new-conversation") { result.newConversation = true; continue; }
61
+ if (argument === "--dir" || argument === "--base" || argument === "--request-key") {
62
+ const value = args.shift();
63
+ if (!value) throw new RemoteDevError(`Missing value for ${argument}`);
64
+ if (argument === "--dir") result.dir = value;
65
+ else if (argument === "--base") result.base = value;
66
+ else {
67
+ if (!UUID_PATTERN.test(value)) throw new RemoteDevError("--request-key must be a UUID.");
68
+ result.requestKey = value;
69
+ result.newSession = true;
70
+ }
71
+ continue;
72
+ }
73
+ if (argument === "--branch-target") {
74
+ const value = args.shift() || "";
75
+ const match = value.match(/^([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})=(production|staging|development|custom-[a-z0-9-]+|)$/i);
76
+ if (!match) throw new RemoteDevError("--branch-target needs repositoryUUID=targetId; use an empty targetId for the repository default.");
77
+ branchTargets[match[1]] = match[2];
78
+ continue;
79
+ }
80
+ if (argument.startsWith("-")) throw new RemoteDevError(`Unknown option for \`xevy dev\`: ${argument}. Put pi options after \`--\`.`);
81
+ if (targetReference) throw new RemoteDevError("`xevy dev` accepts one project.");
82
+ targetReference = argument;
83
+ }
84
+ if (result.piArgs.some((arg) => /^(?:--model|--provider|--thinking|-m)(?:=|$)/.test(arg))) {
85
+ throw new RemoteDevError("Xevy selects models and reasoning automatically. Remove model/provider/thinking options and try again.");
86
+ }
87
+ if (targetReference) {
88
+ let target;
89
+ try {
90
+ target = parseDevTarget(targetReference);
91
+ } catch (error) {
92
+ throw new RemoteDevError(error instanceof Error ? error.message : String(error));
93
+ }
94
+ if (target.kind !== "personal") {
95
+ throw new RemoteDevError(`\`xevy dev\` works on a project: use \`xevy dev <workspace>/<project>\`. To open this Dev Session in your terminal instead, run \`xevy connect ${targetReference}\`.`);
96
+ }
97
+ result.target = target;
98
+ }
99
+ if (Object.keys(branchTargets).length) {
100
+ if (!result.newSession) throw new RemoteDevError("--branch-target applies when starting a new Dev Session; add --new.");
101
+ result.branchTargets = branchTargets;
102
+ }
103
+ return result;
104
+ }
105
+
106
+ export function devUsageLine() {
107
+ return DEV_USAGE_LINE;
108
+ }
109
+
110
+ // ── Local files ─────────────────────────────────────────────────────────────
111
+
112
+ function xevyDir(folder) {
113
+ return path.join(folder, ".xevy");
114
+ }
115
+
116
+ /** Reads `<folder>/.xevy/project.json`; null when absent or unreadable. */
117
+ export function readLinkedProject(folder) {
118
+ const file = path.join(xevyDir(folder), "project.json");
119
+ if (!fs.existsSync(file)) return null;
120
+ try {
121
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
122
+ if (!parsed || typeof parsed !== "object" || !parsed.workspaceIdentifier || !parsed.projectIdentifier) return null;
123
+ return parsed;
124
+ } catch (error) {
125
+ throw new RemoteDevError(`Could not read ${file}: ${error instanceof Error ? error.message : String(error)}`);
126
+ }
127
+ }
128
+
129
+ function sameProject(linked, target) {
130
+ return linked.workspaceIdentifier === target.workspaceIdentifier && linked.projectIdentifier === target.projectIdentifier;
131
+ }
132
+
133
+ function expandHome(value, homeDir, cwd) {
134
+ if (value === "~") return homeDir;
135
+ if (value.startsWith("~/")) return path.join(homeDir, value.slice(2));
136
+ return path.resolve(cwd, value);
137
+ }
138
+
139
+ /**
140
+ * Chooses the folder the local AI works from. Order: `--dir`, then the current
141
+ * folder when it is already linked to this project for remote work, then
142
+ * `~/xevy/<project>`. A folder linked by repository setup holds a real checkout
143
+ * and is never used.
144
+ */
145
+ export function resolveLocalFolder({ dir, cwd, homeDir, target, writeLine }) {
146
+ if (dir) {
147
+ const folder = expandHome(dir, homeDir, cwd);
148
+ const linked = readLinkedProject(folder);
149
+ if (linked && linked.mode !== "remote") {
150
+ throw new RemoteDevError(`${folder} holds a local copy of a project linked to Xevy. Choose an empty folder for --dir.`);
151
+ }
152
+ if (linked && !sameProject(linked, target)) {
153
+ throw new RemoteDevError(`${folder} is already used for ${linked.workspaceIdentifier}/${linked.projectIdentifier}. Choose another folder for --dir.`);
154
+ }
155
+ return { folder, linked };
156
+ }
157
+ const here = readLinkedProject(cwd);
158
+ if (here?.mode === "remote" && sameProject(here, target)) return { folder: cwd, linked: here };
159
+ const folder = path.join(homeDir, "xevy", target.projectIdentifier);
160
+ if (here && here.mode !== "remote") {
161
+ writeLine(`This folder holds a local copy of the project, so it stays untouched. The AI works from ${folder}.`);
162
+ }
163
+ const linked = readLinkedProject(folder);
164
+ if (linked && (linked.mode !== "remote" || !sameProject(linked, target))) {
165
+ throw new RemoteDevError(`${folder} is already used for ${linked.workspaceIdentifier}/${linked.projectIdentifier}. Choose another folder with --dir <path>.`);
166
+ }
167
+ return { folder, linked };
168
+ }
169
+
170
+ /** Creates the folder and its `.xevy/` tree with owner-only permissions. */
171
+ export function prepareLocalFolder(folder) {
172
+ fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
173
+ for (const directory of [xevyDir(folder), path.join(xevyDir(folder), "pi"), path.join(xevyDir(folder), "logs")]) {
174
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
175
+ fs.chmodSync(directory, 0o700);
176
+ }
177
+ }
178
+
179
+ /** Writes a file with mode 0600 via a temporary file and rename, so readers never see half a file. */
180
+ export function writeFileAtomic(file, content) {
181
+ const temporary = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
182
+ fs.writeFileSync(temporary, content, { mode: 0o600 });
183
+ fs.chmodSync(temporary, 0o600);
184
+ fs.renameSync(temporary, file);
185
+ }
186
+
187
+ function writeJson(file, value) {
188
+ writeFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`);
189
+ }
190
+
191
+ /** Writes project.json, keeping the conversation id unless a new one is asked for. */
192
+ export function writeProjectFile(folder, { linked, workspace, project, newConversation, now = new Date() }) {
193
+ const keepConversation = !newConversation && typeof linked?.piSessionId === "string" && UUID_PATTERN.test(linked.piSessionId);
194
+ const value = {
195
+ workspaceIdentifier: workspace.identifier,
196
+ projectIdentifier: project.identifier,
197
+ workspaceId: workspace.id,
198
+ projectId: project.id,
199
+ mode: "remote",
200
+ piSessionId: keepConversation ? linked.piSessionId : randomUUID(),
201
+ createdAt: typeof linked?.createdAt === "string" ? linked.createdAt : now.toISOString(),
202
+ };
203
+ writeJson(path.join(xevyDir(folder), "project.json"), value);
204
+ return value;
205
+ }
206
+
207
+ function emptySessionState(baseUrl) {
208
+ return { version: 1, baseUrl, sessionId: null, pendingRequestKey: null, repositories: [], hostname: null, branch: null, updatedAt: null };
209
+ }
210
+
211
+ /** Reads session.json. A file written for another Xevy host starts fresh. */
212
+ export function readSessionState(folder, baseUrl) {
213
+ const file = path.join(xevyDir(folder), "session.json");
214
+ if (!fs.existsSync(file)) return emptySessionState(baseUrl);
215
+ let parsed;
216
+ try {
217
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
218
+ } catch (error) {
219
+ throw new RemoteDevError(`Could not read ${file}: ${error instanceof Error ? error.message : String(error)}`);
220
+ }
221
+ if (!parsed || typeof parsed !== "object" || (baseUrl && parsed.baseUrl !== baseUrl)) return emptySessionState(baseUrl);
222
+ return { ...emptySessionState(baseUrl), ...parsed, version: 1, baseUrl };
223
+ }
224
+
225
+ export function writeSessionState(folder, state, now = new Date()) {
226
+ const value = { ...state, version: 1, updatedAt: now.toISOString() };
227
+ writeJson(path.join(xevyDir(folder), "session.json"), value);
228
+ return value;
229
+ }
230
+
231
+ function sessionStateFrom(state, session) {
232
+ return {
233
+ ...state,
234
+ sessionId: session.id,
235
+ pendingRequestKey: null,
236
+ repositories: (session.config?.repos || []).map((repository) => ({
237
+ id: repository.id,
238
+ dir: repository.slug,
239
+ displayName: repository.displayName || repository.slug,
240
+ })),
241
+ hostname: session.hostname || null,
242
+ branch: session.branch || session.config?.branch || null,
243
+ };
244
+ }
245
+
246
+ /**
247
+ * Counts edits the extension recorded but has not uploaded yet. Journal lines
248
+ * are either edit entries (carry `op`) or status records for an entry's `seq`;
249
+ * an entry counts as settled once a record marks it uploaded, saved or in
250
+ * conflict (conflicts are reported, never replayed).
251
+ */
252
+ export function countPendingUploads(folder) {
253
+ const file = path.join(xevyDir(folder), "journal.ndjson");
254
+ if (!fs.existsSync(file)) return 0;
255
+ const pending = new Set();
256
+ for (const line of fs.readFileSync(file, "utf8").split(/\r?\n/)) {
257
+ if (!line.trim()) continue;
258
+ let entry;
259
+ try {
260
+ entry = JSON.parse(line);
261
+ } catch {
262
+ continue; // A torn final line from a crash; the extension repairs the journal on its next run.
263
+ }
264
+ if (!entry || typeof entry !== "object" || entry.seq === undefined) continue;
265
+ if (entry.op) pending.add(entry.seq);
266
+ if (entry.uploaded || entry.saved || entry.conflict || ["uploaded", "saved", "conflict"].includes(entry.status)) pending.delete(entry.seq);
267
+ }
268
+ return pending.size;
269
+ }
270
+
271
+ // ── Boundary logging ────────────────────────────────────────────────────────
272
+
273
+ /**
274
+ * Wraps fetch so every CLI request carries one correlation id and is logged to
275
+ * `.xevy/logs/remote.log` (method, path, status, milliseconds; never bodies).
276
+ * Lines are buffered until the folder exists.
277
+ */
278
+ export function createLoggedFetch(fetchImpl, correlationId) {
279
+ let logFile = null;
280
+ const buffered = [];
281
+ const append = (record) => {
282
+ const line = `${JSON.stringify({ ts: new Date().toISOString(), correlationId, source: "cli", ...record })}\n`;
283
+ if (!logFile) { buffered.push(line); return; }
284
+ fs.appendFileSync(logFile, line, { mode: 0o600 });
285
+ };
286
+ const loggedFetch = async (input, init = {}) => {
287
+ const url = new URL(String(input));
288
+ const started = Date.now();
289
+ const method = init.method || "GET";
290
+ try {
291
+ const response = await fetchImpl(input, { ...init, headers: { ...(init.headers || {}), "X-Correlation-Id": correlationId } });
292
+ append({ op: "request", method, path: url.pathname, status: response.status, ms: Date.now() - started, requestId: response.headers?.get?.("x-request-id") || null });
293
+ return response;
294
+ } catch (error) {
295
+ append({ op: "request", method, path: url.pathname, status: "error", ms: Date.now() - started, error: error instanceof Error ? error.message : String(error) });
296
+ throw error;
297
+ }
298
+ };
299
+ return {
300
+ fetch: loggedFetch,
301
+ log: append,
302
+ attach(folder) {
303
+ logFile = path.join(xevyDir(folder), "logs", "remote.log");
304
+ fs.appendFileSync(logFile, buffered.splice(0).join(""), { mode: 0o600 });
305
+ },
306
+ };
307
+ }
308
+
309
+ // ── Session resolution ──────────────────────────────────────────────────────
310
+
311
+ function sessionPathFor(sessionId) {
312
+ return `/api/agent/dev-sessions/${encodeURIComponent(sessionId)}`;
313
+ }
314
+
315
+ function isApiError(error, status, code) {
316
+ return error instanceof DevSessionApiError && error.status === status && (!code || error.code === code);
317
+ }
318
+
319
+ function isGone(error) {
320
+ return error instanceof DevSessionApiError && [403, 404, 410].includes(error.status);
321
+ }
322
+
323
+ function movedTargetOf(session) {
324
+ const next = session?.movedTo || session?.successorSessionId || null;
325
+ return next && next !== session.id ? next : null;
326
+ }
327
+
328
+ /** Retries worker-bound calls while the worker reconnects instead of failing the run. */
329
+ export function withWorkerReconnect(api, { writeLine, sleep, maxWaitMs = RECONNECT_MAX_WAIT_MS }) {
330
+ return {
331
+ async request(requestPath, options) {
332
+ const deadline = Date.now() + maxWaitMs;
333
+ let announced = false;
334
+ while (true) {
335
+ try {
336
+ return await api.request(requestPath, options);
337
+ } catch (error) {
338
+ if (!isApiError(error, 503, "LIVE_WORKER_RECONNECTING") || Date.now() >= deadline) throw error;
339
+ if (!announced) writeLine("Reconnecting to the Dev Session…");
340
+ announced = true;
341
+ await sleep(RECONNECT_POLL_MS);
342
+ }
343
+ }
344
+ },
345
+ };
346
+ }
347
+
348
+ /** Loads a session and follows it to wherever it moved. Null when it no longer exists. */
349
+ async function loadSession(api, sessionId, options = {}) {
350
+ let currentId = sessionId;
351
+ for (let hop = 0; hop <= MAX_SESSION_MOVES; hop += 1) {
352
+ let session;
353
+ try {
354
+ session = (await api.request(sessionPathFor(currentId), options))?.session || null;
355
+ } catch (error) {
356
+ if (isGone(error)) return null;
357
+ if (!isApiError(error, 409, "LIVE_SESSION_MOVED")) throw error;
358
+ const health = await api.request(`${sessionPathFor(currentId)}/health`, options);
359
+ if (!health?.movedTo) throw new RemoteDevError("This Dev Session moved to a new worker. Try again in a minute.");
360
+ currentId = health.movedTo;
361
+ continue;
362
+ }
363
+ if (!session) return null;
364
+ const next = movedTargetOf(session);
365
+ if (!next) return session;
366
+ currentId = next;
367
+ }
368
+ throw new RemoteDevError("This Dev Session is still moving to a new worker. Try again in a minute.");
369
+ }
370
+
371
+ function isReusable(session, project) {
372
+ if (!session) return false;
373
+ if (session.project?.id && session.project.id !== project.id) return false;
374
+ return SESSION_READY_STATUSES.has(session.status) || SESSION_PENDING_STATUSES.has(session.status);
375
+ }
376
+
377
+ async function resolveProject(api, target) {
378
+ const result = await api.request("/api/workspaces");
379
+ const workspace = (result?.workspaces || []).find((item) => item.identifier === target.workspaceIdentifier);
380
+ const project = workspace?.projects?.find((item) => item.identifier === target.projectIdentifier);
381
+ if (!workspace || !project) {
382
+ throw new RemoteDevError(`No accessible project matches '${target.workspaceIdentifier}/${target.projectIdentifier}'.`);
383
+ }
384
+ return { workspace, project };
385
+ }
386
+
387
+ /** Waits until ready, sends one heartbeat, and follows a move reported on the way. */
388
+ async function readySession(api, session, { writeLine, sleep }) {
389
+ let current = session;
390
+ for (let hop = 0; hop <= MAX_SESSION_MOVES; hop += 1) {
391
+ current = await waitForReady({ api, sessionPath: sessionPathFor(current.id), initialSession: current, writeLine, sleep });
392
+ let beat = null;
393
+ let movedByError = false;
394
+ try {
395
+ beat = (await api.request(`${sessionPathFor(current.id)}/heartbeat`, { method: "POST", body: {} }))?.session || null;
396
+ } catch (error) {
397
+ if (!isApiError(error, 409, "LIVE_SESSION_MOVED")) {
398
+ writeLine(`Could not reach the Dev Session's keep-alive (${error instanceof Error ? error.message : String(error)}). Continuing.`);
399
+ return current;
400
+ }
401
+ movedByError = true;
402
+ }
403
+ const moved = movedByError ? current.id : movedTargetOf(beat);
404
+ if (!moved) return beat && SESSION_READY_STATUSES.has(beat.status) ? beat : current;
405
+ // loadSession follows `movedTo` (summary) or the health record (409) to the successor.
406
+ const next = await loadSession(api, moved);
407
+ if (!next) throw new RemoteDevError("The Dev Session ended while moving to a new worker. Run the command again to start a new one.");
408
+ writeLine("The Dev Session moved to a new worker.");
409
+ current = next;
410
+ }
411
+ throw new RemoteDevError("This Dev Session is still moving to a new worker. Try again in a minute.");
412
+ }
413
+
414
+ /**
415
+ * Starts or reuses the one Dev Session this folder works with. The request key
416
+ * is written to session.json before the start request, so a rerun after a
417
+ * crash reuses it and the server returns the same session.
418
+ */
419
+ export async function resolveOrStartSession({ api, folder, state, project, options, interactive, ask, writeLine, sleep }) {
420
+ let session = null;
421
+ let sessionState = state;
422
+
423
+ if (sessionState.sessionId && !options.newSession) {
424
+ session = await loadSession(api, sessionState.sessionId);
425
+ if (isReusable(session, project)) writeLine("Reusing your Dev Session…");
426
+ else session = null;
427
+ }
428
+
429
+ if (!session && sessionState.pendingRequestKey) {
430
+ // A previous start may have reached Xevy before this computer saw the reply.
431
+ const pending = await loadSession(api, sessionState.pendingRequestKey);
432
+ if (isReusable(pending, project)) {
433
+ session = pending;
434
+ writeLine("Reusing the Dev Session started on your last run…");
435
+ }
436
+ }
437
+
438
+ let candidates = null;
439
+ if (!session && !options.newSession) {
440
+ candidates = await api.request(`/api/agent/dev-session-candidates?projectId=${encodeURIComponent(project.id)}`);
441
+ const running = candidates?.personal?.existingSessions?.length ? candidates.personal.existingSessions
442
+ : candidates?.personal?.existingSessionId ? [{ id: candidates.personal.existingSessionId, title: "Running Dev Session" }] : [];
443
+ const choice = await selectOne({ items: running, label: "sessions", describe: (item) => `${item.title} · ${item.id}`, interactive, ask, writeLine });
444
+ if (choice) {
445
+ const chosen = await loadSession(api, choice.id);
446
+ if (isReusable(chosen, project)) {
447
+ session = chosen;
448
+ writeLine("Opening your running Dev Session…");
449
+ }
450
+ }
451
+ }
452
+
453
+ if (!session) {
454
+ candidates ||= await api.request(`/api/agent/dev-session-candidates?projectId=${encodeURIComponent(project.id)}`);
455
+ const repositories = candidates?.repositories || [];
456
+ if (repositories.length === 0) {
457
+ throw new RemoteDevError(candidates?.personal?.blocker || "No linked repository is configured for this project.");
458
+ }
459
+ const repository = await selectOne({
460
+ items: repositories,
461
+ label: "repositories",
462
+ describe: (item) => `${item.displayName || item.role}${item.defaultBranch ? ` · ${item.defaultBranch}` : ""}`,
463
+ interactive, ask, writeLine,
464
+ });
465
+ const branchTargets = await selectDevSessionBranchTargets({ repositories, interactive, ask, writeLine, branchTargets: options.branchTargets });
466
+ const requestKey = options.requestKey || sessionState.pendingRequestKey || randomUUID();
467
+ sessionState = writeSessionState(folder, { ...sessionState, sessionId: null, pendingRequestKey: requestKey });
468
+ writeLine(`Starting a new Dev Session with ${repository.displayName || repository.role}…`);
469
+ const started = await api.request("/api/agent/dev-sessions", {
470
+ method: "POST",
471
+ body: {
472
+ target: {
473
+ kind: "personal",
474
+ requestKey,
475
+ projectId: project.id,
476
+ agentLocation: "local",
477
+ runtimeRepositoryId: repository.id,
478
+ ...(branchTargets ? { branchTargets } : {}),
479
+ },
480
+ },
481
+ timeoutMs: 60_000,
482
+ });
483
+ session = started?.session;
484
+ if (!session?.id) throw new RemoteDevError("Xevy accepted the request but returned no Dev Session. Run the command again to retry it safely.");
485
+ sessionState = writeSessionState(folder, { ...sessionState, sessionId: session.id, pendingRequestKey: null });
486
+ }
487
+
488
+ session = await readySession(api, session, { writeLine, sleep });
489
+ sessionState = writeSessionState(folder, sessionStateFrom(sessionState, session));
490
+
491
+ if (ACTIVE_AGENT_STATES.has(session.agentState)) {
492
+ writeLine("⚠ Another Xevy agent is active in this Dev Session. File edits cannot overwrite each other, but commands from both agents run side by side.");
493
+ }
494
+ const features = Array.isArray(session.workerFeatures) ? session.workerFeatures : [];
495
+ if (!REQUIRED_WORKER_FEATURES.every((feature) => features.includes(feature))) {
496
+ throw new RemoteDevError(`This Dev Session's worker needs an update before it can run commands for a local AI. Try again later, or work in the Dev Session's terminal with \`xevy connect session/${session.id}\`.`);
497
+ }
498
+ return { session, state: sessionState };
499
+ }
500
+
501
+ // ── Extension download ──────────────────────────────────────────────────────
502
+
503
+ /** Downloads the remote-tools extension; keeps the cached copy when the download fails. */
504
+ export async function ensureRemoteExtension({ base, fetchImpl, homeDir, writeLine, warn = writeLine, timeoutMs = EXTENSION_DOWNLOAD_TIMEOUT_MS }) {
505
+ const directory = path.join(homeDir, ".xevy", "remote");
506
+ const destination = path.join(directory, REMOTE_EXTENSION_FILE);
507
+ const url = `${base}/${REMOTE_EXTENSION_FILE}`;
508
+ let reason;
509
+ try {
510
+ const response = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
511
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
512
+ const source = await response.text();
513
+ if (!REMOTE_EXTENSION_MARKERS.every((marker) => source.includes(marker))) {
514
+ throw new Error("the download was not the expected file; check --base");
515
+ }
516
+ fs.mkdirSync(directory, { recursive: true });
517
+ writeFileAtomic(destination, source);
518
+ return destination;
519
+ } catch (error) {
520
+ reason = error instanceof Error ? error.message : String(error);
521
+ }
522
+ if (fs.existsSync(destination)) {
523
+ warn(`⚠ Could not refresh the Dev Session tools (${reason}). Using the copy from your last run.`);
524
+ return destination;
525
+ }
526
+ throw new RemoteDevError(`Could not download the Dev Session tools from ${url} (${reason}). Check your connection and try again.`);
527
+ }
528
+
529
+ // ── pi launch ───────────────────────────────────────────────────────────────
530
+
531
+ /** The exact pi argv for `xevy dev`. */
532
+ export function buildRemotePiArgs({ extensionFiles, remoteExtension, folder, piSessionId, piArgs = [] }) {
533
+ const args = [];
534
+ for (const file of extensionFiles) args.push("-e", file);
535
+ args.push(
536
+ "-e", remoteExtension,
537
+ "--session-dir", path.join(xevyDir(folder), "pi"),
538
+ "--session-id", piSessionId,
539
+ "--exclude-tools", EXCLUDED_LOCAL_TOOLS,
540
+ ...piArgs,
541
+ "--provider", "xevy", "--model", "auto",
542
+ );
543
+ return args;
544
+ }
545
+
546
+ /** Environment for pi. `XEVY_REMOTE_DEV_SESSION` means "running on the worker" and is never passed. */
547
+ export function buildRemotePiEnv({ env, folder, base, explicitBase }) {
548
+ const next = { ...env, XEVY_REMOTE_PROJECT_DIR: path.resolve(folder) };
549
+ delete next.XEVY_REMOTE_DEV_SESSION;
550
+ if (explicitBase) next.XEVY_BASE = base;
551
+ return next;
552
+ }
553
+
554
+ function shellQuote(value) {
555
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
556
+ }
557
+
558
+ /** The one line printed after pi exits. `session` is null when it ended, undefined when it could not be checked. */
559
+ export function formatExitSummary({ target, session, pending, dirArgument }) {
560
+ const resume = ["xevy", "dev", `${target.workspaceIdentifier}/${target.projectIdentifier}`, ...(dirArgument ? ["--dir", dirArgument] : [])].map(shellQuote).join(" ");
561
+ const uploads = pending > 0 ? ` · ${pending} ${pending === 1 ? "edit" : "edits"} not uploaded yet (sent on your next run)` : "";
562
+ if (session === null) return `The Dev Session has ended · Start a new one: ${resume}${uploads}`;
563
+ const parts = [session === undefined ? "Could not check the Dev Session" : "Dev Session still running", `Resume: ${resume}`];
564
+ if (session?.hostname) parts.push(`Preview: https://${session.hostname}`);
565
+ if (session?.id) parts.push(`Terminal: xevy connect session/${session.id}`);
566
+ return `${parts.join(" · ")}${uploads}`;
567
+ }
568
+
569
+ /**
570
+ * Runs `xevy dev` end to end and returns pi's exit code. All side effects are
571
+ * injected so tests can drive it with a fake fetch and a fake pi.
572
+ */
573
+ export async function runRemoteDev(options) {
574
+ const { base, token, fetchImpl = globalThis.fetch, homeDir, cwd, writeLine, warn = writeLine, ask, interactive = false, extensionFiles, spawnPi, beforeLaunch = () => {}, sleep = defaultSleep, env = process.env, correlationId = randomUUID() } = options;
575
+ const secrets = [token];
576
+ const say = (value = "") => writeLine(redactSensitive(value, secrets, null));
577
+
578
+ let target = options.target;
579
+ if (!target) {
580
+ const linked = readLinkedProject(cwd);
581
+ if (!linked) throw new RemoteDevError(`${DEV_USAGE_LINE}\nRun it with a project, or from a folder already set up by \`xevy dev\`.`);
582
+ target = { kind: "personal", workspaceIdentifier: linked.workspaceIdentifier, projectIdentifier: linked.projectIdentifier };
583
+ }
584
+
585
+ const { folder, linked } = resolveLocalFolder({ dir: options.dir, cwd, homeDir, target, writeLine: say });
586
+ const logged = createLoggedFetch(fetchImpl, correlationId);
587
+ const baseApi = createApiClient({ base, token, fetchImpl: logged.fetch, registerController: () => () => {}, secrets });
588
+ const api = withWorkerReconnect(baseApi, { writeLine: say, sleep });
589
+
590
+ try {
591
+ await api.request("/api/profile");
592
+ } catch (error) {
593
+ if (error instanceof DevSessionApiError && (error.status === 401 || error.status === 403)) {
594
+ throw new RemoteDevError("Xevy did not accept your API key. Run `xevy setup --credentials` to store a new one.");
595
+ }
596
+ throw error;
597
+ }
598
+ const { workspace, project } = await resolveProject(api, target);
599
+
600
+ prepareLocalFolder(folder);
601
+ logged.attach(folder);
602
+ const projectFile = writeProjectFile(folder, { linked, workspace, project, newConversation: options.newConversation });
603
+ if (options.newConversation) say("Starting a new conversation.");
604
+ const state = readSessionState(folder, base);
605
+ say(`Working from ${folder}`);
606
+
607
+ const { session } = await resolveOrStartSession({
608
+ api, folder, state, project,
609
+ options: { newSession: options.newSession, requestKey: options.requestKey, branchTargets: options.branchTargets },
610
+ interactive, ask, writeLine: say, sleep,
611
+ });
612
+ if (session.hostname) say(`Preview: https://${session.hostname}`);
613
+
614
+ const remoteExtension = await ensureRemoteExtension({ base, fetchImpl, homeDir, writeLine: say, warn });
615
+ const piArgs = buildRemotePiArgs({ extensionFiles, remoteExtension, folder, piSessionId: projectFile.piSessionId, piArgs: options.piArgs });
616
+ logged.log({ op: "launch", sessionId: session.id });
617
+ beforeLaunch();
618
+ const result = spawnPi(piArgs, { cwd: folder, env: buildRemotePiEnv({ env, folder, base, explicitBase: options.explicitBase }) });
619
+ if (result.error) throw new RemoteDevError(result.error.message);
620
+ const exitCode = result.status ?? (result.signal ? 1 : 0);
621
+ logged.log({ op: "exit", status: exitCode });
622
+
623
+ // The extension may have moved the session while pi ran.
624
+ const finalState = readSessionState(folder, base);
625
+ let finalSession;
626
+ try {
627
+ finalSession = finalState.sessionId ? await loadSession(baseApi, finalState.sessionId, { timeoutMs: SUMMARY_TIMEOUT_MS }) : null;
628
+ if (finalSession && !isReusable(finalSession, project)) finalSession = null;
629
+ } catch (error) {
630
+ logged.log({ op: "summary", status: "error", error: error instanceof Error ? error.message : String(error) });
631
+ finalSession = undefined;
632
+ }
633
+ say(formatExitSummary({ target, session: finalSession, pending: countPendingUploads(folder), dirArgument: options.dir || null }));
634
+ return exitCode;
635
+ }
package/bin/xevy.mjs CHANGED
@@ -6,6 +6,8 @@
6
6
  * and MCP integrations independently.
7
7
  * xevy update Refresh the pi extensions + coding-agent integration.
8
8
  * xevy check Report skill updates or missing coding-agent targets.
9
+ * xevy dev Run the AI on this computer, working on a Dev Session's files.
10
+ * xevy connect Attach this terminal to the AI running in a Dev Session.
9
11
  * xevy Open pi with the Xevy extensions.
10
12
  *
11
13
  * `xevy setup` fetches the extensions from the server and asks for an API key
@@ -24,6 +26,7 @@ import {
24
26
  resolveDevConnection,
25
27
  runDevSession,
26
28
  } from "./dev-session.mjs";
29
+ import { devUsageLine, parseRemoteDevArgs, RemoteDevError, runRemoteDev } from "./remote-dev.mjs";
27
30
 
28
31
  const here = path.dirname(fileURLToPath(import.meta.url));
29
32
  const pkgRoot = path.resolve(here, "..");
@@ -99,7 +102,8 @@ function usage() {
99
102
  xevy setup [options] Choose credentials, pi, skills, and MCP setup
100
103
  xevy update [--base u] Refresh the pi extensions + coding-agent skills/MCP
101
104
  xevy check [--base u] Report skill updates or missing coding-agent targets
102
- xevy dev <target> Attach to a remote task or task-free Dev Session
105
+ xevy dev [<ws>/<proj>] The AI runs on your computer and works on the Dev Session's files
106
+ xevy connect <target> Attach your terminal to the AI running in the Dev Session
103
107
 
104
108
  Options:
105
109
  --base <url> Xevy host (default: XEVY_BASE or ${DEFAULT_BASE})
@@ -121,8 +125,9 @@ Examples:
121
125
  npx @xevy/cli setup --credentials --mcp -a codex
122
126
  npx @xevy/cli setup --all -y
123
127
  npx @xevy/cli update
124
- npx @xevy/cli dev task/VI22-07
125
128
  npx @xevy/cli dev xevy/xevyai
129
+ npx @xevy/cli connect task/VI22-07
130
+ npx @xevy/cli connect xevy/xevyai
126
131
  npx @xevy/cli
127
132
 
128
133
  Install globally to drop the npx prefix:
@@ -131,16 +136,49 @@ Install globally to drop the npx prefix:
131
136
  xevy`);
132
137
  }
133
138
 
139
+ function remoteDevUsage() {
140
+ console.log(`Xevy dev — the AI runs on your computer and works on the Dev Session's files
141
+
142
+ ${devUsageLine().replace(/^Usage: /, "")}
143
+
144
+ Starts your Dev Session for the project, or reuses the one already running,
145
+ and opens the AI here. Every file it reads or edits and every command it runs
146
+ stays in the Dev Session; this computer keeps the conversation and a short
147
+ record of the AI's recent edits until they are saved.
148
+
149
+ The AI works from ~/xevy/<project> (or the folder given with --dir). Only a
150
+ .xevy folder is created there. Run the same command again to pick up where
151
+ you left off.
152
+
153
+ Options:
154
+ --dir <path> Folder to work from instead of ~/xevy/<project>
155
+ --new Start another Dev Session instead of reusing one
156
+ --request-key <uuid> Retry an interrupted start without creating a second session
157
+ --branch-target <repositoryUUID>=<targetId>
158
+ With --new: choose a configured branch target
159
+ --new-conversation Start a fresh conversation with the AI
160
+ --base <url> Xevy host
161
+ -- <pi options> Pass the remaining options to pi
162
+
163
+ To attach your terminal to the AI running inside the Dev Session instead,
164
+ use \`xevy connect\`.
165
+
166
+ Credentials:
167
+ XEVY_API_KEY takes precedence over ~/.config/xevy/credentials.
168
+ Host precedence: --base, XEVY_BASE, saved baseUrl, https://xevy.ai.`);
169
+ }
170
+
134
171
  function devUsage() {
135
- console.log(`Xevy Dev Session
172
+ console.log(`Xevy connect — attach your terminal to the AI running in the Dev Session
136
173
 
137
- xevy dev task/<task-id-or-code> [--base <url>]
138
- xevy dev <workspace>/<project> [--new] [--request-key <uuid>] [--base <url>]
139
- xevy dev session/<session-id> [--rename <name>] [--base <url>]
174
+ xevy connect task/<task-id-or-code> [--base <url>]
175
+ xevy connect <workspace>/<project> [--new] [--request-key <uuid>] [--branch-target <repositoryUUID>=<targetId>] [--base <url>]
176
+ xevy connect session/<session-id> [--rename <name>] [--base <url>]
140
177
 
141
178
  Connects this terminal to a remote Dev Session. The reserved task/ prefix
142
179
  selects task work; workspace/project selects a running workspace. Use --new
143
- for another session, and reuse --request-key after a failed create. A session/
180
+ for another session, and reuse --request-key after a failed create. Use repeated
181
+ --branch-target repositoryUUID=targetId to select configured branch targets. A session/
144
182
  target opens one exact workspace and --rename changes its display name. Xevy runs inside the isolated remote workspace.
145
183
 
146
184
  Terminal control:
@@ -164,7 +202,7 @@ function parseArgv(argv) {
164
202
  if (first === "dev") {
165
203
  args.shift();
166
204
  try {
167
- const parsed = parseDevCommandArgs(args);
205
+ const parsed = parseRemoteDevArgs(args);
168
206
  if (parsed.help) return { command: "dev-help" };
169
207
  return { command: "dev", ...parsed };
170
208
  } catch (error) {
@@ -172,6 +210,17 @@ function parseArgv(argv) {
172
210
  }
173
211
  }
174
212
 
213
+ if (first === "connect") {
214
+ args.shift();
215
+ try {
216
+ const parsed = parseDevCommandArgs(args);
217
+ if (parsed.help) return { command: "connect-help" };
218
+ return { command: "connect", ...parsed };
219
+ } catch (error) {
220
+ die(error instanceof Error ? error.message : String(error));
221
+ }
222
+ }
223
+
175
224
  if (first === "setup" || first === "update" || first === "check") {
176
225
  const command = args.shift();
177
226
  const opts = {
@@ -719,7 +768,8 @@ function check(opts) {
719
768
  process.exit(r.status ?? (r.error ? 1 : 0));
720
769
  }
721
770
 
722
- async function open(opts) {
771
+ /** The pi checks shared by `xevy` and `xevy dev`; returns the extensions to load. */
772
+ function requireXevyPi() {
723
773
  requirePiNode();
724
774
  if (!hasPi()) {
725
775
  die("pi is not installed. Run `xevy setup` first.");
@@ -735,6 +785,11 @@ async function open(opts) {
735
785
  if (files.length === 0) {
736
786
  die(`No Xevy extensions in ${XEVY_EXTENSIONS_DIR}. Run \`xevy setup\` first.`);
737
787
  }
788
+ return files;
789
+ }
790
+
791
+ async function open(opts) {
792
+ const files = requireXevyPi();
738
793
 
739
794
  const storedBase = readStoredCredentials().baseUrl;
740
795
  const updateBase = (
@@ -753,18 +808,51 @@ async function open(opts) {
753
808
  process.exitCode = r.status ?? 0;
754
809
  }
755
810
 
756
- async function dev(opts) {
811
+ function resolveCliConnection(explicitBase) {
757
812
  const stored = readStoredCredentials();
758
- const { base, token } = resolveDevConnection({
759
- explicitBase: opts.base,
813
+ const connection = resolveDevConnection({
814
+ explicitBase,
760
815
  environmentBase: process.env.XEVY_BASE,
761
816
  storedBase: stored.baseUrl,
762
817
  environmentToken: readEnvironmentToken(),
763
818
  storedToken: stored.token,
764
819
  });
765
- if (!token) {
820
+ if (!connection.token) {
766
821
  die("A Xevy API key is required. Run `xevy setup --credentials` first.");
767
822
  }
823
+ return connection;
824
+ }
825
+
826
+ // `xevy dev` — pi runs here; its file and command tools run in the Dev Session.
827
+ async function remoteDev(opts) {
828
+ const files = requireXevyPi();
829
+ const { base, token } = resolveCliConnection(opts.base);
830
+ try {
831
+ process.exitCode = await runRemoteDev({
832
+ ...opts,
833
+ base,
834
+ token,
835
+ explicitBase: Boolean(opts.base),
836
+ extensionFiles: files,
837
+ homeDir: os.homedir(),
838
+ cwd: process.cwd(),
839
+ writeLine: (line) => console.log(line),
840
+ warn: (line) => console.warn(line),
841
+ ask: promptLine,
842
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
843
+ // pi needs the terminal to itself.
844
+ beforeLaunch: closePrompts,
845
+ spawnPi: (args, { cwd, env }) => spawnSync(PI_BIN, args, { stdio: "inherit", shell: isWindows, cwd, env }),
846
+ });
847
+ } catch (error) {
848
+ closePrompts();
849
+ if (error instanceof RemoteDevError) die(error.message);
850
+ throw error;
851
+ }
852
+ }
853
+
854
+ async function connect(opts) {
855
+ const { base, token } = resolveCliConnection(opts.base);
768
856
  await runDevSession({
769
857
  base,
770
858
  token,
@@ -772,6 +860,7 @@ async function dev(opts) {
772
860
  newSession: opts.newSession,
773
861
  requestKey: opts.requestKey,
774
862
  rename: opts.rename,
863
+ branchTargets: opts.branchTargets,
775
864
  });
776
865
  }
777
866
 
@@ -779,12 +868,14 @@ async function main() {
779
868
  const opts = parseArgv(process.argv.slice(2));
780
869
 
781
870
  if (opts.command === "help") return usage();
782
- if (opts.command === "dev-help") return devUsage();
871
+ if (opts.command === "connect-help") return devUsage();
872
+ if (opts.command === "dev-help") return remoteDevUsage();
783
873
  if (opts.command === "version") return console.log(readCliVersion());
784
874
  if (opts.command === "setup") return setup(opts);
785
875
  if (opts.command === "update") return update(opts);
786
876
  if (opts.command === "check") return check(opts);
787
- if (opts.command === "dev") return dev(opts);
877
+ if (opts.command === "dev") return remoteDev(opts);
878
+ if (opts.command === "connect") return connect(opts);
788
879
  if (opts.command === "open") return open(opts);
789
880
  }
790
881
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xevy/cli",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
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": [