@xevy/cli 0.1.26 → 0.1.29

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