@xevy/cli 0.1.28 → 0.1.30

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
@@ -159,7 +159,8 @@ xevy dev xevy/xevyai # start or reuse your Dev Session and op
159
159
  xevy dev # same, from a folder already set up by xevy dev
160
160
  xevy dev xevy/xevyai --new-conversation # keep the Dev Session, start a fresh conversation
161
161
  xevy dev xevy/xevyai --dir ~/work/shop # work from another folder
162
- xevy dev xevy/xevyai --new # start another Dev Session
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
163
164
  xevy dev xevy/xevyai -- --verbose # pass options to pi after --
164
165
  ```
165
166
 
@@ -172,7 +173,12 @@ 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
173
174
  `.xevy` folder is created there, readable by you alone. It holds the link to the
174
175
  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
+ 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
176
182
  run finishes it without creating a second Dev Session. A folder that already
177
183
  holds a local copy of the project is left untouched.
178
184
 
@@ -223,11 +223,23 @@ function extractApiError(payload, fallback) {
223
223
  return fallback;
224
224
  }
225
225
 
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
+
226
235
  export class DevSessionApiError extends Error {
227
- constructor(status, message, payload) {
236
+ constructor(status, message, payload, retryAfterMs = null) {
228
237
  super(message);
229
238
  this.name = "DevSessionApiError";
230
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);
231
243
  this.code = payload && typeof payload === "object"
232
244
  ? payload.code || payload.error?.code || null
233
245
  : null;
@@ -282,7 +294,7 @@ export function createApiClient({ base, token, fetchImpl, registerController, se
282
294
  }
283
295
  const fallback = `Xevy request failed (HTTP ${response.status}).`;
284
296
  const message = redactSensitive(extractApiError(payload, fallback), secrets);
285
- throw new DevSessionApiError(response.status, message, payload);
297
+ throw new DevSessionApiError(response.status, message, payload, parseRetryAfterMs(response.headers?.get?.("retry-after")));
286
298
  } catch (error) {
287
299
  if (error instanceof DevSessionApiError) throw error;
288
300
  if (controller.signal.aborted) {
@@ -313,7 +325,7 @@ function formatTask(task) {
313
325
  return `${code}${task.title} (${task.workspaceIdentifier}/${task.projectIdentifier})`;
314
326
  }
315
327
 
316
- export async function selectOne({ items, label, describe, interactive, ask, writeLine }) {
328
+ export async function selectOne({ items, label, choose, describe, interactive, ask, writeLine }) {
317
329
  if (items.length === 0) return null;
318
330
  if (items.length === 1) return items[0];
319
331
  writeLine(`Multiple ${label} match:`);
@@ -322,7 +334,7 @@ export async function selectOne({ items, label, describe, interactive, ask, writ
322
334
  throw new Error(`Multiple ${label} match; rerun interactively and choose one.`);
323
335
  }
324
336
  while (true) {
325
- const answer = await ask(`Choose ${label.slice(0, -1)} [1-${items.length}]: `);
337
+ const answer = await ask(`Choose ${choose ?? label} [1-${items.length}]: `);
326
338
  const index = Number.parseInt(answer, 10) - 1;
327
339
  if (Number.isInteger(index) && index >= 0 && index < items.length) return items[index];
328
340
  writeLine(`Enter a number from 1 to ${items.length}.`);
@@ -341,6 +353,7 @@ export async function selectDevSessionBranchTargets({ repositories, interactive,
341
353
  const selected = await selectOne({
342
354
  items: [...ordered, { id: "", label: "Repository default", branch: repository.defaultBranch || "remote default" }],
343
355
  label: `branch targets for ${repository.displayName || repository.role || repository.id}`,
356
+ choose: `a branch target for ${repository.displayName || repository.role || repository.id}`,
344
357
  describe: target => `${target.label} · ${target.branch}`,
345
358
  interactive, ask, writeLine,
346
359
  });
@@ -1104,6 +1117,7 @@ export async function runDevSession(options) {
1104
1117
  const repository = await selectOne({
1105
1118
  items: repositories,
1106
1119
  label: "repositories",
1120
+ choose: "a repository",
1107
1121
  describe: (item) => `${item.displayName || item.role}${item.defaultBranch ? ` · ${item.defaultBranch}` : ""}`,
1108
1122
  interactive,
1109
1123
  ask,
@@ -1144,7 +1158,7 @@ export async function runDevSession(options) {
1144
1158
  );
1145
1159
  const running = candidates?.personal?.existingSessions?.length ? candidates.personal.existingSessions
1146
1160
  : candidates?.personal?.existingSessionId ? [{ id: candidates.personal.existingSessionId, title: "Running workspace" }] : [];
1147
- 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 });
1148
1162
  const existingSessionId = choice?.id || null;
1149
1163
  if (existingSessionId) {
1150
1164
  sessionPath = `/api/agent/dev-sessions/${encodeURIComponent(existingSessionId)}`;
@@ -1160,6 +1174,7 @@ export async function runDevSession(options) {
1160
1174
  const repository = await selectOne({
1161
1175
  items: repositories,
1162
1176
  label: "repositories",
1177
+ choose: "a repository",
1163
1178
  describe: (item) => `${item.displayName || item.role}${item.defaultBranch ? ` · ${item.defaultBranch}` : ""}`,
1164
1179
  interactive,
1165
1180
  ask,
@@ -2,11 +2,13 @@
2
2
  * `xevy dev` — run the AI on this computer while its files and commands live
3
3
  * in a remote Dev Session.
4
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.
5
+ * The CLI resolves the local folder, reconnects to the folder's Dev Session
6
+ * when one is still running, downloads the remote-tools extension and
7
+ * launches pi. Without a running session pi opens straight away: the AI
8
+ * starts or links one itself, using the project or task named on the command
9
+ * line as hints. The extension (loaded with an explicit `-e`) owns heartbeats,
10
+ * the events stream and edit uploads for as long as pi runs. Nothing but
11
+ * `<folder>/.xevy/*` is ever written into the project folder.
10
12
  */
11
13
  import { randomUUID } from "node:crypto";
12
14
  import fs from "node:fs";
@@ -17,8 +19,6 @@ import {
17
19
  DevSessionApiError,
18
20
  parseDevTarget,
19
21
  redactSensitive,
20
- selectDevSessionBranchTargets,
21
- selectOne,
22
22
  waitForReady,
23
23
  } from "./dev-session.mjs";
24
24
 
@@ -32,8 +32,10 @@ const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{
32
32
  const MAX_SESSION_MOVES = 5;
33
33
  const RECONNECT_POLL_MS = 3_000;
34
34
  const RECONNECT_MAX_WAIT_MS = 10 * 60_000;
35
+ const RECONNECT_MAX_BACKOFF_MS = 15_000;
35
36
  const EXTENSION_DOWNLOAD_TIMEOUT_MS = 10_000;
36
37
  const SUMMARY_TIMEOUT_MS = 5_000;
38
+ const SUMMARY_ATTEMPTS = 4;
37
39
  const ACTIVE_AGENT_STATES = new Set(["working", "waiting"]);
38
40
 
39
41
  export class RemoteDevError extends Error {
@@ -44,12 +46,12 @@ export class RemoteDevError extends Error {
44
46
  }
45
47
  }
46
48
 
47
- const DEV_USAGE_LINE = "Usage: xevy dev [<workspace>/<project>] [--dir <path>] [--new] [--new-conversation] [--base <url>] [-- <pi options>]";
49
+ const DEV_USAGE_LINE = "Usage: xevy dev [<workspace>/<project> | task/<task-id-or-code>] [--dir <path>] [--new] [--new-conversation | --keep-conversation] [--base <url>] [-- <pi options>]";
48
50
 
49
51
  /** Parses `xevy dev` arguments. Everything after `--` is passed to pi. */
50
52
  export function parseRemoteDevArgs(argv) {
51
53
  const args = [...argv];
52
- const result = { help: false, target: null, dir: null, newSession: false, newConversation: false, base: null, piArgs: [] };
54
+ const result = { help: false, target: null, task: null, dir: null, newSession: false, newConversation: false, keepConversation: false, base: null, piArgs: [] };
53
55
  const branchTargets = {};
54
56
  let targetReference = "";
55
57
  while (args.length > 0) {
@@ -58,6 +60,7 @@ export function parseRemoteDevArgs(argv) {
58
60
  if (argument === "-h" || argument === "--help") return { ...result, help: true };
59
61
  if (argument === "--new") { result.newSession = true; continue; }
60
62
  if (argument === "--new-conversation") { result.newConversation = true; continue; }
63
+ if (argument === "--keep-conversation") { result.keepConversation = true; continue; }
61
64
  if (argument === "--dir" || argument === "--base" || argument === "--request-key") {
62
65
  const value = args.shift();
63
66
  if (!value) throw new RemoteDevError(`Missing value for ${argument}`);
@@ -78,9 +81,10 @@ export function parseRemoteDevArgs(argv) {
78
81
  continue;
79
82
  }
80
83
  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.");
84
+ if (targetReference) throw new RemoteDevError("`xevy dev` accepts one project or task.");
82
85
  targetReference = argument;
83
86
  }
87
+ if (result.newConversation && result.keepConversation) throw new RemoteDevError("Use either --new-conversation or --keep-conversation, not both.");
84
88
  if (result.piArgs.some((arg) => /^(?:--model|--provider|--thinking|-m)(?:=|$)/.test(arg))) {
85
89
  throw new RemoteDevError("Xevy selects models and reasoning automatically. Remove model/provider/thinking options and try again.");
86
90
  }
@@ -91,10 +95,11 @@ export function parseRemoteDevArgs(argv) {
91
95
  } catch (error) {
92
96
  throw new RemoteDevError(error instanceof Error ? error.message : String(error));
93
97
  }
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}\`.`);
98
+ if (target.kind === "session") {
99
+ throw new RemoteDevError(`\`xevy dev\` works on a project or task: use \`xevy dev <workspace>/<project>\` or \`xevy dev task/<task-id-or-code>\`. To open this Dev Session in your terminal instead, run \`xevy connect ${targetReference}\`.`);
96
100
  }
97
- result.target = target;
101
+ if (target.kind === "task") result.task = target.taskReference;
102
+ else result.target = target;
98
103
  }
99
104
  if (Object.keys(branchTargets).length) {
100
105
  if (!result.newSession) throw new RemoteDevError("--branch-target applies when starting a new Dev Session; add --new.");
@@ -167,6 +172,24 @@ export function resolveLocalFolder({ dir, cwd, homeDir, target, writeLine }) {
167
172
  return { folder, linked };
168
173
  }
169
174
 
175
+ /**
176
+ * The folder for a run without a project: `--dir`, else the current folder.
177
+ * A folder holding a local checkout linked to Xevy stays untouched; its
178
+ * project's folder is used instead and the project becomes the hint.
179
+ */
180
+ export function chooseFolder({ dir, cwd, homeDir, target, writeLine }) {
181
+ if (target) return { ...resolveLocalFolder({ dir, cwd, homeDir, target, writeLine }), project: target };
182
+ const folder = dir ? expandHome(dir, homeDir, cwd) : cwd;
183
+ const linked = readLinkedProject(folder);
184
+ if (linked?.mode === "remote") return { folder, linked, project: { kind: "personal", workspaceIdentifier: linked.workspaceIdentifier, projectIdentifier: linked.projectIdentifier } };
185
+ if (linked && dir) throw new RemoteDevError(`${folder} holds a local copy of a project linked to Xevy. Choose an empty folder for --dir.`);
186
+ if (linked) {
187
+ const project = { kind: "personal", workspaceIdentifier: linked.workspaceIdentifier, projectIdentifier: linked.projectIdentifier };
188
+ return { ...resolveLocalFolder({ dir: null, cwd, homeDir, target: project, writeLine }), project };
189
+ }
190
+ return { folder, linked: null, project: null };
191
+ }
192
+
170
193
  /** Creates the folder and its `.xevy/` tree with owner-only permissions. */
171
194
  export function prepareLocalFolder(folder) {
172
195
  fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
@@ -188,22 +211,45 @@ function writeJson(file, value) {
188
211
  writeFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`);
189
212
  }
190
213
 
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);
214
+ /** Writes project.json: the project link, the conversation id and the Dev Session that conversation belongs to. */
215
+ export function writeProjectFile(folder, { linked, workspace, project, piSessionId, conversationSessionId = null, now = new Date() }) {
194
216
  const value = {
195
217
  workspaceIdentifier: workspace.identifier,
196
218
  projectIdentifier: project.identifier,
197
- workspaceId: workspace.id,
198
- projectId: project.id,
219
+ workspaceId: workspace.id ?? null,
220
+ projectId: project.id ?? null,
199
221
  mode: "remote",
200
- piSessionId: keepConversation ? linked.piSessionId : randomUUID(),
222
+ piSessionId,
223
+ conversationSessionId,
201
224
  createdAt: typeof linked?.createdAt === "string" ? linked.createdAt : now.toISOString(),
202
225
  };
203
226
  writeJson(path.join(xevyDir(folder), "project.json"), value);
204
227
  return value;
205
228
  }
206
229
 
230
+ function savedConversationId(linked) {
231
+ return typeof linked?.piSessionId === "string" && UUID_PATTERN.test(linked.piSessionId) ? linked.piSessionId : null;
232
+ }
233
+
234
+ /**
235
+ * Keeps the saved conversation only for the Dev Session it belongs to. A moved
236
+ * session is the same work: `requestedId` is the id the session was loaded by,
237
+ * before following any move. Folders set up before the owner was recorded
238
+ * treat the session saved in session.json as the owner.
239
+ * Returns the conversation id and why: first, asked, kept, same or changed.
240
+ */
241
+ export function chooseConversation({ linked, savedSessionId, sessionId, requestedId, newConversation, keepConversation }) {
242
+ const saved = savedConversationId(linked);
243
+ if (!saved) return { piSessionId: randomUUID(), reason: "first" };
244
+ if (newConversation) return { piSessionId: randomUUID(), reason: "asked" };
245
+ if (keepConversation) return { piSessionId: saved, reason: "kept" };
246
+ const owner = typeof linked.conversationSessionId === "string" && linked.conversationSessionId ? linked.conversationSessionId : savedSessionId;
247
+ // A conversation that never had a Dev Session continues until it gets one.
248
+ if (!owner) return { piSessionId: saved, reason: "same" };
249
+ if (owner === sessionId || owner === requestedId) return { piSessionId: saved, reason: "same" };
250
+ return { piSessionId: randomUUID(), reason: "changed" };
251
+ }
252
+
207
253
  function emptySessionState(baseUrl) {
208
254
  return { version: 1, baseUrl, sessionId: null, pendingRequestKey: null, repositories: [], hostname: null, branch: null, updatedAt: null };
209
255
  }
@@ -325,20 +371,38 @@ function movedTargetOf(session) {
325
371
  return next && next !== session.id ? next : null;
326
372
  }
327
373
 
328
- /** Retries worker-bound calls while the worker reconnects instead of failing the run. */
374
+ /** A worker reconnecting, the session server restarting, or a gateway answering in its place. 4xx is never retried. */
375
+ function retryKind(error) {
376
+ if (!(error instanceof DevSessionApiError)) return null;
377
+ if (isApiError(error, 503, "LIVE_WORKER_RECONNECTING")) return "worker";
378
+ if (isApiError(error, 503, "LIVE_SERVER_RESTARTING")) return "server";
379
+ if ([502, 503, 504].includes(error.status) && !error.code) return "server";
380
+ return null;
381
+ }
382
+
383
+ /** Retries calls while the worker reconnects or the server restarts instead of failing the run. */
329
384
  export function withWorkerReconnect(api, { writeLine, sleep, maxWaitMs = RECONNECT_MAX_WAIT_MS }) {
385
+ // The restart line is said once per run; the worker line once per waiting call, as before.
386
+ let serverAnnounced = false;
330
387
  return {
331
388
  async request(requestPath, options) {
332
389
  const deadline = Date.now() + maxWaitMs;
333
- let announced = false;
390
+ let workerAnnounced = false;
391
+ let backoffMs = RECONNECT_POLL_MS;
334
392
  while (true) {
335
393
  try {
336
394
  return await api.request(requestPath, options);
337
395
  } 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);
396
+ const kind = retryKind(error);
397
+ if (!kind || Date.now() >= deadline) throw error;
398
+ if (kind === "worker" && !workerAnnounced) writeLine("Reconnecting to the Dev Session…");
399
+ if (kind === "server" && !serverAnnounced) writeLine("The Dev Session server is restarting. Waiting…");
400
+ if (kind === "worker") workerAnnounced = true;
401
+ else serverAnnounced = true;
402
+ const hinted = Number.isFinite(error.retryAfterMs) ? error.retryAfterMs : null;
403
+ const waitMs = Math.min(hinted ?? backoffMs, Math.max(0, deadline - Date.now()));
404
+ if (hinted === null) backoffMs = Math.min(backoffMs * 2, RECONNECT_MAX_BACKOFF_MS);
405
+ await sleep(waitMs);
342
406
  }
343
407
  }
344
408
  },
@@ -412,81 +476,15 @@ async function readySession(api, session, { writeLine, sleep }) {
412
476
  }
413
477
 
414
478
  /**
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.
479
+ * Reconnects to the Dev Session this folder last worked with, following a
480
+ * move to another worker. Null when it has ended; the AI then starts a new one.
418
481
  */
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));
482
+ export async function reconnectSession({ api, folder, state, project, writeLine, sleep }) {
483
+ const loaded = await loadSession(api, state.sessionId);
484
+ if (!isReusable(loaded, project)) return null;
485
+ writeLine("Reusing your Dev Session…");
486
+ const session = await readySession(api, loaded, { writeLine, sleep });
487
+ const nextState = writeSessionState(folder, sessionStateFrom(state, session));
490
488
 
491
489
  if (ACTIVE_AGENT_STATES.has(session.agentState)) {
492
490
  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.");
@@ -495,7 +493,7 @@ export async function resolveOrStartSession({ api, folder, state, project, optio
495
493
  if (!REQUIRED_WORKER_FEATURES.every((feature) => features.includes(feature))) {
496
494
  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
495
  }
498
- return { session, state: sessionState };
496
+ return { session, state: nextState, requestedId: state.sessionId };
499
497
  }
500
498
 
501
499
  // ── Extension download ──────────────────────────────────────────────────────
@@ -543,11 +541,18 @@ export function buildRemotePiArgs({ extensionFiles, remoteExtension, folder, piS
543
541
  return args;
544
542
  }
545
543
 
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) };
544
+ /**
545
+ * Environment for pi. `XEVY_REMOTE_DEV_SESSION` means "running on the worker"
546
+ * and is never passed. The hints tell the AI what was asked for; it decides
547
+ * whether and how to start a Dev Session.
548
+ */
549
+ export function buildRemotePiEnv({ env, folder, base, explicitBase, hints = null, piSessionId = null }) {
550
+ const next = { ...env, XEVY_REMOTE_PROJECT_DIR: path.resolve(folder), XEVY_REMOTE_BASE: base };
549
551
  delete next.XEVY_REMOTE_DEV_SESSION;
552
+ delete next.XEVY_REMOTE_DEV_HINTS;
550
553
  if (explicitBase) next.XEVY_BASE = base;
554
+ if (hints) next.XEVY_REMOTE_DEV_HINTS = JSON.stringify(hints);
555
+ if (piSessionId) next.XEVY_REMOTE_PI_SESSION_ID = piSessionId;
551
556
  return next;
552
557
  }
553
558
 
@@ -555,9 +560,14 @@ function shellQuote(value) {
555
560
  return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
556
561
  }
557
562
 
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(" ");
563
+ /**
564
+ * The one line printed after pi exits. `session` is null when it ended,
565
+ * undefined when it could not be checked; `started` is false when the AI never
566
+ * started or linked one.
567
+ */
568
+ export function formatExitSummary({ target, session, pending, dirArgument, started = true }) {
569
+ const resume = ["xevy", "dev", ...(target ? [`${target.workspaceIdentifier}/${target.projectIdentifier}`] : []), ...(dirArgument ? ["--dir", dirArgument] : [])].map(shellQuote).join(" ");
570
+ if (!started) return `No Dev Session was started · Run again: ${resume}`;
561
571
  const uploads = pending > 0 ? ` · ${pending} ${pending === 1 ? "edit" : "edits"} not uploaded yet (sent on your next run)` : "";
562
572
  if (session === null) return `The Dev Session has ended · Start a new one: ${resume}${uploads}`;
563
573
  const parts = [session === undefined ? "Could not check the Dev Session" : "Dev Session still running", `Resume: ${resume}`];
@@ -567,69 +577,129 @@ export function formatExitSummary({ target, session, pending, dirArgument }) {
567
577
  }
568
578
 
569
579
  /**
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.
580
+ * Reads the session for the exit summary. pi ran under spawnSync, so the event
581
+ * loop never saw the server close the keep-alive connections opened before
582
+ * launch; the first request can land on one and fail with "other side closed".
583
+ * A few more attempts reach a fresh connection. API errors are answers, not retried.
584
+ */
585
+ async function loadSummarySession(api, sessionId, log) {
586
+ // Each failed attempt discards one dead pooled connection; the pool can hold several.
587
+ for (let attempt = 1; ; attempt += 1) {
588
+ try {
589
+ return await loadSession(api, sessionId, { timeoutMs: SUMMARY_TIMEOUT_MS });
590
+ } catch (error) {
591
+ if (error instanceof DevSessionApiError || attempt >= SUMMARY_ATTEMPTS) throw error;
592
+ log({ op: "summary", status: "retry", attempt, error: error instanceof Error ? error.message : String(error) });
593
+ }
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Runs `xevy dev` end to end and returns pi's exit code. A folder whose Dev
599
+ * Session is still running reconnects first; otherwise pi opens without any
600
+ * request to Xevy. All side effects are injected so tests can drive it with a
601
+ * fake fetch and a fake pi.
572
602
  */
573
603
  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;
604
+ const { base, token, fetchImpl = globalThis.fetch, homeDir, cwd, writeLine, warn = writeLine, extensionFiles, spawnPi, beforeLaunch = () => {}, sleep = defaultSleep, env = process.env, correlationId = randomUUID() } = options;
575
605
  const secrets = [token];
576
606
  const say = (value = "") => writeLine(redactSensitive(value, secrets, null));
577
607
 
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 });
608
+ const { folder, linked, project: target } = chooseFolder({ dir: options.dir, cwd, homeDir, target: options.target || null, writeLine: say });
586
609
  const logged = createLoggedFetch(fetchImpl, correlationId);
587
610
  const baseApi = createApiClient({ base, token, fetchImpl: logged.fetch, registerController: () => () => {}, secrets });
588
611
  const api = withWorkerReconnect(baseApi, { writeLine: say, sleep });
589
612
 
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
613
  prepareLocalFolder(folder);
601
614
  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
615
  say(`Working from ${folder}`);
616
+ const state = readSessionState(folder, base);
606
617
 
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,
618
+ // Reconnect only to this folder's own running session; anything else is the AI's choice.
619
+ let reconnected = null;
620
+ let workspace = linked ? { id: linked.workspaceId ?? null, identifier: linked.workspaceIdentifier } : null;
621
+ let project = linked ? { id: linked.projectId ?? null, identifier: linked.projectIdentifier } : null;
622
+ if (linked?.mode === "remote" && state.sessionId && !options.newSession && !options.task) {
623
+ try {
624
+ await api.request("/api/profile");
625
+ } catch (error) {
626
+ if (error instanceof DevSessionApiError && (error.status === 401 || error.status === 403)) {
627
+ throw new RemoteDevError("Xevy did not accept your API key. Run `xevy setup --credentials` to store a new one.");
628
+ }
629
+ throw error;
630
+ }
631
+ ({ workspace, project } = await resolveProject(api, target));
632
+ reconnected = await reconnectSession({ api, folder, state, project, writeLine: say, sleep });
633
+ if (!reconnected) {
634
+ writeSessionState(folder, { ...state, sessionId: null });
635
+ say("Your last Dev Session has ended. The AI starts a new one when it needs it.");
636
+ }
637
+ }
638
+
639
+ const conversation = chooseConversation({
640
+ linked,
641
+ savedSessionId: state.sessionId,
642
+ sessionId: reconnected?.session.id ?? null,
643
+ requestedId: reconnected?.requestedId ?? null,
644
+ newConversation: options.newConversation,
645
+ keepConversation: options.keepConversation,
611
646
  });
612
- if (session.hostname) say(`Preview: https://${session.hostname}`);
647
+ const piSessionId = conversation.piSessionId;
648
+ if (target) {
649
+ writeProjectFile(folder, {
650
+ linked,
651
+ workspace: workspace ?? { id: null, identifier: target.workspaceIdentifier },
652
+ project: project ?? { id: null, identifier: target.projectIdentifier },
653
+ piSessionId,
654
+ conversationSessionId: reconnected?.session.id ?? null,
655
+ });
656
+ }
657
+ logged.log({ op: "conversation", status: conversation.reason, sessionId: reconnected?.session.id ?? null });
658
+ if (conversation.reason === "asked" || (conversation.reason === "changed" && !reconnected)) say("Starting a new conversation.");
659
+ if (conversation.reason === "changed" && reconnected) say("Starting a new conversation for this Dev Session.");
660
+ if (reconnected?.session.hostname) say(`Preview: https://${reconnected.session.hostname}`);
613
661
 
614
662
  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 });
663
+ const piArgs = buildRemotePiArgs({ extensionFiles, remoteExtension, folder, piSessionId, piArgs: options.piArgs });
664
+ const hints = {
665
+ project: target ? { workspaceIdentifier: target.workspaceIdentifier, projectIdentifier: target.projectIdentifier } : null,
666
+ task: options.task || null,
667
+ branchTargets: options.branchTargets || null,
668
+ requestKey: options.requestKey || null,
669
+ };
670
+ logged.log({ op: "launch", sessionId: reconnected?.session.id ?? null, linked: Boolean(reconnected) });
617
671
  beforeLaunch();
618
- const result = spawnPi(piArgs, { cwd: folder, env: buildRemotePiEnv({ env, folder, base, explicitBase: options.explicitBase }) });
672
+ const result = spawnPi(piArgs, { cwd: folder, env: buildRemotePiEnv({ env, folder, base, explicitBase: options.explicitBase, hints, piSessionId }) });
619
673
  if (result.error) throw new RemoteDevError(result.error.message);
620
674
  const exitCode = result.status ?? (result.signal ? 1 : 0);
621
675
  logged.log({ op: "exit", status: exitCode });
622
676
 
623
- // The extension may have moved the session while pi ran.
677
+ // The AI may have started or linked a session, and the extension may have moved it; the conversation goes with it.
624
678
  const finalState = readSessionState(folder, base);
679
+ const finalProject = readLinkedProject(folder);
680
+ const finalTarget = finalProject ? { workspaceIdentifier: finalProject.workspaceIdentifier, projectIdentifier: finalProject.projectIdentifier } : null;
681
+ if (!finalState.sessionId || !finalProject) {
682
+ say(formatExitSummary({ target: finalTarget, session: null, pending: countPendingUploads(folder), dirArgument: options.dir || null, started: false }));
683
+ return exitCode;
684
+ }
685
+ if (finalProject.conversationSessionId !== finalState.sessionId || finalProject.piSessionId !== piSessionId) {
686
+ writeProjectFile(folder, {
687
+ linked: finalProject,
688
+ workspace: { id: finalProject.workspaceId, identifier: finalProject.workspaceIdentifier },
689
+ project: { id: finalProject.projectId, identifier: finalProject.projectIdentifier },
690
+ piSessionId,
691
+ conversationSessionId: finalState.sessionId,
692
+ });
693
+ logged.log({ op: "conversation", status: reconnected && finalState.sessionId !== reconnected.session.id ? "moved" : "linked", sessionId: finalState.sessionId });
694
+ }
625
695
  let finalSession;
626
696
  try {
627
- finalSession = finalState.sessionId ? await loadSession(baseApi, finalState.sessionId, { timeoutMs: SUMMARY_TIMEOUT_MS }) : null;
628
- if (finalSession && !isReusable(finalSession, project)) finalSession = null;
697
+ finalSession = await loadSummarySession(baseApi, finalState.sessionId, logged.log);
698
+ if (finalSession && !isReusable(finalSession, { id: finalProject.projectId })) finalSession = null;
629
699
  } catch (error) {
630
700
  logged.log({ op: "summary", status: "error", error: error instanceof Error ? error.message : String(error) });
631
701
  finalSession = undefined;
632
702
  }
633
- say(formatExitSummary({ target, session: finalSession, pending: countPendingUploads(folder), dirArgument: options.dir || null }));
703
+ say(formatExitSummary({ target: finalTarget, session: finalSession, pending: countPendingUploads(folder), dirArgument: options.dir || null }));
634
704
  return exitCode;
635
705
  }
package/bin/xevy.mjs CHANGED
@@ -102,7 +102,7 @@ function usage() {
102
102
  xevy setup [options] Choose credentials, pi, skills, and MCP setup
103
103
  xevy update [--base u] Refresh the pi extensions + coding-agent skills/MCP
104
104
  xevy check [--base u] Report skill updates or missing coding-agent targets
105
- xevy dev [<ws>/<proj>] The AI runs on your computer and works on the Dev Session's files
105
+ xevy dev [<target>] Open the AI here; it starts or links a Dev Session and works on its files
106
106
  xevy connect <target> Attach your terminal to the AI running in the Dev Session
107
107
 
108
108
  Options:
@@ -125,6 +125,7 @@ Examples:
125
125
  npx @xevy/cli setup --credentials --mcp -a codex
126
126
  npx @xevy/cli setup --all -y
127
127
  npx @xevy/cli update
128
+ npx @xevy/cli dev
128
129
  npx @xevy/cli dev xevy/xevyai
129
130
  npx @xevy/cli connect task/VI22-07
130
131
  npx @xevy/cli connect xevy/xevyai
@@ -141,22 +142,29 @@ function remoteDevUsage() {
141
142
 
142
143
  ${devUsageLine().replace(/^Usage: /, "")}
143
144
 
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.
145
+ Opens the AI straight away. When your request needs code, the AI starts a Dev
146
+ Session or links one that is already running, picks the branch each
147
+ repository starts from, and tells you where its pull requests will go. A
148
+ project or task given here is a hint for the AI; nothing is asked before it
149
+ opens. Every file it reads or edits and every command it runs stays in the
150
+ Dev Session; this computer keeps the conversation and a short record of the
151
+ AI's recent edits until they are saved.
152
+
153
+ The AI works from the current folder, from ~/xevy/<project> when a project is
154
+ given, or from the folder given with --dir. Only a .xevy folder is created
155
+ there. Running \`xevy dev\` again in that folder reconnects to its Dev Session
156
+ while it runs. A different Dev Session (a --new start, or the saved one has
157
+ ended) starts a new conversation; a session that moved to another worker
158
+ keeps it.
152
159
 
153
160
  Options:
154
- --dir <path> Folder to work from instead of ~/xevy/<project>
155
- --new Start another Dev Session instead of reusing one
161
+ --dir <path> Folder to work from
162
+ --new Do not reconnect; let the AI start another Dev Session
156
163
  --request-key <uuid> Retry an interrupted start without creating a second session
157
164
  --branch-target <repositoryUUID>=<targetId>
158
- With --new: choose a configured branch target
165
+ With --new: the branch target the AI starts from
159
166
  --new-conversation Start a fresh conversation with the AI
167
+ --keep-conversation Keep the saved conversation, even in another Dev Session
160
168
  --base <url> Xevy host
161
169
  -- <pi options> Pass the remaining options to pi
162
170
 
@@ -838,8 +846,6 @@ async function remoteDev(opts) {
838
846
  cwd: process.cwd(),
839
847
  writeLine: (line) => console.log(line),
840
848
  warn: (line) => console.warn(line),
841
- ask: promptLine,
842
- interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
843
849
  // pi needs the terminal to itself.
844
850
  beforeLaunch: closePrompts,
845
851
  spawnPi: (args, { cwd, env }) => spawnSync(PI_BIN, args, { stdio: "inherit", shell: isWindows, cwd, env }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xevy/cli",
3
- "version": "0.1.28",
3
+ "version": "0.1.30",
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": [