@xevy/cli 0.1.13 → 0.1.15

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
@@ -150,30 +150,28 @@ xevy dev VI22-07 --base https://xevy.example.com
150
150
  ```
151
151
 
152
152
  The CLI resolves an exact task ID or task code, attaches to its existing Dev
153
- Session, or starts one from a linked repository. When several accessible tasks
154
- share a code, or a project has several linked repositories, it presents
155
- a numbered selector. It restores the recent conversation for the session branch
156
- and attaches to an already-running agent turn instead of submitting a duplicate.
153
+ Session, or starts one from a linked repository. It then renders Pi's native TUI
154
+ from the isolated remote workspace: normal composer, thinking, tools, history,
155
+ keyboard shortcuts, and session resume all behave like Pi on a local machine.
156
+ When several accessible tasks share a code, or a project has several linked
157
+ repositories, the CLI presents a numbered selector first.
157
158
 
158
- `xevy dev` is a remote client. It does **not** install or run local Pi, clone the
159
- repository, open a shell or PTY, use SSH, or invoke Docker. Ctrl+C, terminal EOF,
160
- and `/detach` only disconnect the local client; the server session and its pushed
161
- branch remain available for safe resume.
159
+ `xevy dev` is only a terminal transport. Pi, Git credentials, the repository,
160
+ and Docker remain on the server. Press `Ctrl+]` to detach without stopping Pi;
161
+ run the same command again to reattach. Pi conversation history is stored in the
162
+ bounded Dev Session volume. The controller periodically commits work and pushes
163
+ the resumable Dev Session branch; exiting Pi also commits and pushes any final
164
+ edits. You do not need to ask the agent to commit after every prompt.
162
165
 
163
- Available commands while attached:
166
+ Terminal control:
164
167
 
165
168
  ```text
166
- /status Refresh the lifecycle status and URL
167
- /logs Show the latest session logs
168
- /open Request a fresh one-use browser link and open it when supported
169
- /finish Merge into the task branch and stop
170
- /stop Stop without merging (the pushed session branch remains preserved)
171
- /detach Disconnect this terminal without stopping anything
172
- /help Show the command list
169
+ Ctrl+] Disconnect this terminal without stopping Pi or the Dev Session
173
170
  ```
174
171
 
175
- `/finish` and `/stop` always ask for confirmation. A heartbeat keeps the session
176
- active while the CLI is attached, within the server's hard expiry limit.
172
+ Use the task's Dev Session panel in Xevy to open the live site, stop the session,
173
+ or finish and redeploy after exiting Pi. A heartbeat keeps the session active
174
+ while the CLI is attached, within the server's hard expiry limit.
177
175
 
178
176
  Host precedence is `--base`, `XEVY_BASE`, the saved credentials `baseUrl`, then
179
177
  `https://xevy.ai`. API-key precedence is `XEVY_API_KEY`, then the saved key in
@@ -1,5 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import readline from "node:readline";
3
+ import WebSocket from "ws";
3
4
 
4
5
  const DEFAULT_BASE = "https://xevy.ai";
5
6
  const TERMINAL_EXECUTION_STATUSES = new Set(["succeeded", "failed", "cancelled"]);
@@ -80,17 +81,17 @@ export function resolveDevConnection({
80
81
  return { base, token };
81
82
  }
82
83
 
83
- export function redactSensitive(value, secrets = []) {
84
+ export function redactSensitive(value, secrets = [], maxLength = 2_000) {
84
85
  let text = String(value ?? "");
85
86
  for (const secret of secrets) {
86
87
  if (!secret) continue;
87
88
  text = text.split(String(secret)).join("[redacted]");
88
89
  }
89
- return text
90
+ text = text
90
91
  .replace(/xevy_pk_[A-Za-z0-9._~-]+/g, "xevy_pk_[redacted]")
91
92
  .replace(/(bearer\s+)[A-Za-z0-9._~+\/-]+/gi, "$1[redacted]")
92
- .replace(/([?&](?:access_token|token|ticket|capability|launch_ticket)=)[^&#\s]+/gi, "$1[redacted]")
93
- .slice(0, 2_000);
93
+ .replace(/([?&](?:access_token|token|ticket|capability|launch_ticket)=)[^&#\s]+/gi, "$1[redacted]");
94
+ return maxLength == null ? text : text.slice(0, maxLength);
94
95
  }
95
96
 
96
97
  export function createSseDecoder(onEvent) {
@@ -296,7 +297,14 @@ function messageText(message) {
296
297
  return typeof message?.content === "string" ? message.content.trim() : "";
297
298
  }
298
299
 
299
- function renderPersistedMessage(message, state, writeLine) {
300
+ function renderChatBlock(role, text, writeLine) {
301
+ writeLine("");
302
+ writeLine(role === "user" ? "you" : "xevy");
303
+ writeLine(text);
304
+ writeLine("");
305
+ }
306
+
307
+ function renderPersistedMessage(message, state, writeLine, { showUser = true } = {}) {
300
308
  if (!message || (message.id && state.messageIds.has(message.id))) return;
301
309
  if (message.id) state.messageIds.add(message.id);
302
310
  const text = messageText(message);
@@ -305,72 +313,53 @@ function renderPersistedMessage(message, state, writeLine) {
305
313
  state.currentExecutionAssistantSeen = true;
306
314
  state.pendingAssistantText = "";
307
315
  }
308
- if (message.role === "tool_call" || message.role === "tool_result") {
309
- const key = `${message.role}:${message.toolName || "tool"}`;
310
- const remaining = state.liveToolMessageBudget.get(key) || 0;
311
- if (remaining > 0) {
312
- if (remaining === 1) state.liveToolMessageBudget.delete(key);
313
- else state.liveToolMessageBudget.set(key, remaining - 1);
314
- return;
315
- }
316
- }
317
- if (message.role === "user") writeLine(`you> ${text}`);
318
- else if (message.role === "assistant") writeLine(`xevy> ${text}`);
319
- else if (message.role === "thinking") writeLine(`thinking> ${text}`);
320
- else if (message.role === "tool_call") {
321
- writeLine(`tool> ${message.toolName || "tool"}${text ? ` — ${text}` : ""}`);
322
- } else if (message.role === "tool_result") {
323
- writeLine(`tool result> ${message.toolName || "tool"}${text ? ` — ${text}` : ""}`);
324
- } else if (message.role === "system" && text) writeLine(`system> ${text}`);
316
+ if (message.role === "user" && showUser) renderChatBlock("user", text, writeLine);
317
+ else if (message.role === "assistant") renderChatBlock("assistant", text, writeLine);
325
318
  }
326
319
 
327
320
  function renderStreamEvent(eventName, payload, state, writeLine, secrets) {
328
321
  const event = payload && typeof payload === "object" ? payload : {};
329
322
  const type = event.type || eventName;
330
323
  if (type === "message" && event.message) {
331
- renderPersistedMessage(event.message, state, writeLine);
324
+ renderPersistedMessage(event.message, state, writeLine, { showUser: false });
332
325
  return;
333
326
  }
334
327
  // Persisted message events are the authoritative text. Ignoring deltas avoids
335
328
  // printing the same assistant answer again during post-stream reconciliation.
336
329
  if (type === "text_delta") {
337
- if (typeof event.text === "string") state.pendingAssistantText += event.text;
330
+ // Only final-answer deltas are eligible for the last-resort fallback. Pi's
331
+ // reasoning/thinking stream must never be rendered as user-facing chat.
332
+ if (event.kind === "assistant" && typeof event.text === "string") {
333
+ state.pendingAssistantText += event.text;
334
+ }
338
335
  return;
339
336
  }
340
337
  if (type === "usage" || type === "heartbeat" || type === "end") return;
341
338
  if (type === "tool_start") {
342
- const streamKey = `tool_start:${event.toolName || "tool"}:${event.summary || ""}`;
343
- if (state.lastToolStreamKey === streamKey) return;
344
- state.lastToolStreamKey = streamKey;
345
- const messageKey = `tool_call:${event.toolName || "tool"}`;
346
- state.liveToolMessageBudget.set(messageKey, (state.liveToolMessageBudget.get(messageKey) || 0) + 1);
347
- writeLine(`tool> ${event.toolName || "tool"}${event.summary ? ` — ${redactSensitive(event.summary, secrets)}` : ""}`);
339
+ const streamKey = `tool_start:${event.toolCallId || event.id || ""}:${event.toolName || "tool"}:${event.summary || ""}`;
340
+ if (state.toolStreamKeys.has(streamKey)) return;
341
+ state.toolStreamKeys.add(streamKey);
342
+ writeLine(` ↳ ${event.toolName || "tool"}${event.summary ? ` · ${redactSensitive(event.summary, secrets)}` : ""}`);
348
343
  return;
349
344
  }
350
345
  if (type === "tool_end") {
351
- const streamKey = `tool_end:${event.toolName || "tool"}:${event.summary || ""}:${event.ok !== false}`;
352
- if (state.lastToolStreamKey === streamKey) return;
353
- state.lastToolStreamKey = streamKey;
354
- const messageKey = `tool_result:${event.toolName || "tool"}`;
355
- state.liveToolMessageBudget.set(messageKey, (state.liveToolMessageBudget.get(messageKey) || 0) + 1);
356
- writeLine(`tool ${event.ok === false ? "failed" : "done"}> ${event.toolName || "tool"}${event.summary ? ` — ${redactSensitive(event.summary, secrets)}` : ""}`);
346
+ if (event.ok !== false) return;
347
+ const streamKey = `tool_end:${event.toolCallId || event.id || ""}:${event.toolName || "tool"}:${event.summary || ""}`;
348
+ if (state.toolStreamKeys.has(streamKey)) return;
349
+ state.toolStreamKeys.add(streamKey);
350
+ writeLine(` × ${event.toolName || "tool"} failed${event.summary ? ` · ${redactSensitive(event.summary, secrets)}` : ""}`);
357
351
  return;
358
352
  }
359
353
  if (type === "status" || eventName === "snapshot") {
360
354
  const status = event.status;
361
355
  if (status && status !== state.lastExecutionStatus) {
362
356
  state.lastExecutionStatus = status;
363
- writeLine(`execution> ${status}${event.errorMessage ? ` — ${redactSensitive(event.errorMessage, secrets)}` : ""}`);
357
+ if (status === "running") writeLine("Working…");
364
358
  }
365
359
  return;
366
360
  }
367
- if (type === "chunk" && typeof event.text === "string") {
368
- const safeLines = event.text
369
- .split(/\r?\n/)
370
- .map((line) => line.trim())
371
- .filter((line) => line.startsWith("[server]") || line.startsWith("[toolbox]"));
372
- for (const line of safeLines) writeLine(redactSensitive(line, secrets));
373
- }
361
+ // Raw server/toolbox chunks are operational logs, not chat. They remain
362
+ // available through /logs instead of interrupting the assistant response.
374
363
  }
375
364
 
376
365
  async function consumeExecutionStream({ api, taskId, executionId, state, writeLine, secrets, signal }) {
@@ -419,7 +408,7 @@ async function reconcileExecution({ api, taskId, executionId, state, writeLine }
419
408
  api.request(`/api/tasks/${encodeURIComponent(taskId)}/ai/executions/${encodeURIComponent(executionId)}/messages`),
420
409
  ]);
421
410
  for (const message of messageResult?.messages || []) {
422
- renderPersistedMessage(message, state, writeLine);
411
+ renderPersistedMessage(message, state, writeLine, { showUser: false });
423
412
  }
424
413
  return { execution, messageCount: (messageResult?.messages || []).length };
425
414
  }
@@ -436,8 +425,8 @@ async function followExecution({
436
425
  }) {
437
426
  state.pendingAssistantText = "";
438
427
  state.currentExecutionAssistantSeen = false;
439
- state.liveToolMessageBudget.clear();
440
- state.lastToolStreamKey = null;
428
+ state.lastExecutionStatus = null;
429
+ state.toolStreamKeys.clear();
441
430
  let reconnects = 0;
442
431
  while (true) {
443
432
  let streamError = null;
@@ -476,7 +465,7 @@ async function followExecution({
476
465
  }
477
466
  }
478
467
  if (!state.currentExecutionAssistantSeen && state.pendingAssistantText.trim()) {
479
- writeLine(`xevy> ${state.pendingAssistantText.trim()}`);
468
+ renderChatBlock("assistant", state.pendingAssistantText.trim(), writeLine);
480
469
  state.pendingAssistantText = "";
481
470
  state.currentExecutionAssistantSeen = true;
482
471
  }
@@ -495,7 +484,7 @@ async function showHistory({ api, taskId, branch, state, writeLine }) {
495
484
  const result = await api.request(`/api/tasks/${encodeURIComponent(taskId)}/ai/executions`);
496
485
  const executions = sessionExecutions(result?.executions || [], branch).slice(0, HISTORY_LIMIT).reverse();
497
486
  if (executions.length === 0) return result?.executions || [];
498
- writeLine("\nRecent Dev Session conversation:");
487
+ writeLine("\nRecent conversation");
499
488
  for (const execution of executions) {
500
489
  const messages = await api.request(
501
490
  `/api/tasks/${encodeURIComponent(taskId)}/ai/executions/${encodeURIComponent(execution.id)}/messages`,
@@ -528,7 +517,7 @@ async function waitForReady({ api, sessionPath, initialSession, writeLine, sleep
528
517
  const deadline = Date.now() + SESSION_START_TIMEOUT_MS;
529
518
  while (!SESSION_READY_STATUSES.has(session.status)) {
530
519
  if (session.status !== lastStatus) {
531
- writeLine(`session> ${session.status}`);
520
+ writeLine(`Preparing workspace · ${session.status}`);
532
521
  lastStatus = session.status;
533
522
  }
534
523
  if (SESSION_TERMINAL_STATUSES.has(session.status)) {
@@ -545,19 +534,111 @@ async function waitForReady({ api, sessionPath, initialSession, writeLine, sleep
545
534
  if (!result?.session) throw new Error("The Dev Session disappeared while starting.");
546
535
  session = result.session;
547
536
  }
548
- if (session.status !== lastStatus) writeLine(`session> ${session.status}`);
537
+ if (session.status !== lastStatus) writeLine("Dev Session ready");
549
538
  return session;
550
539
  }
551
540
 
552
541
  function sessionSummary(task, session, writeLine) {
553
542
  const url = canonicalSessionUrl(session.hostname);
554
- writeLine("\nDev Session attached");
555
- writeLine(`Task: ${formatTask(task)}`);
556
- writeLine(`Branch: ${session.config?.branch || "unknown"}`);
557
- writeLine(`Status: ${session.status}`);
558
- writeLine(`URL: ${url || "not available yet"}`);
559
- writeLine(`Expires: ${session.expiresAt || "server-managed"}`);
560
- writeLine("Use /open for a fresh browser link, or /help for commands.\n");
543
+ writeLine("\nDev Session");
544
+ writeLine(` Task ${formatTask(task)}`);
545
+ writeLine(` Site ${url || "not available yet"}`);
546
+ writeLine(` Branch ${session.config?.branch || "unknown"}`);
547
+ writeLine(` Status ${session.status}`);
548
+ writeLine(` Expires ${session.expiresAt || "server-managed"}`);
549
+ writeLine("\nNative Pi terminal · press Ctrl+] to detach and leave it running\n");
550
+ }
551
+
552
+ async function attachNativeTerminal({ api, base, sessionPath, input, output, signal, WebSocketImpl = WebSocket }) {
553
+ const ticket = await api.request(`${sessionPath}/terminal-ticket`, { method: "POST", body: {}, signal });
554
+ if (!ticket?.ticket || !ticket?.terminalPath) throw new Error("Xevy did not return a terminal ticket.");
555
+ const url = new URL(ticket.terminalPath, `${base}/`);
556
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
557
+
558
+ await new Promise((resolve, reject) => {
559
+ const socket = new WebSocketImpl(url, {
560
+ headers: { "X-Xevy-Terminal-Ticket": ticket.ticket },
561
+ maxPayload: 2 * 1024 * 1024,
562
+ });
563
+ let ready = false;
564
+ let settled = false;
565
+ let rawEnabled = false;
566
+ const onAbort = () => {
567
+ if (socket.readyState === WebSocketImpl.OPEN) socket.close(1000, "client_detach");
568
+ else socket.terminate?.();
569
+ finish(new Error("Detached."));
570
+ };
571
+ const finish = (error) => {
572
+ if (settled) return;
573
+ settled = true;
574
+ input.off("data", onInput);
575
+ process.off("SIGWINCH", onResize);
576
+ signal?.removeEventListener("abort", onAbort);
577
+ if (rawEnabled && typeof input.setRawMode === "function") input.setRawMode(false);
578
+ if (error) reject(error);
579
+ else resolve();
580
+ };
581
+ const sendResize = () => {
582
+ if (socket.readyState !== WebSocketImpl.OPEN) return;
583
+ socket.send(JSON.stringify({
584
+ type: "resize",
585
+ cols: Number(output.columns) || 80,
586
+ rows: Number(output.rows) || 24,
587
+ }));
588
+ };
589
+ const onResize = () => sendResize();
590
+ const onInput = (chunk) => {
591
+ const value = Buffer.from(chunk);
592
+ const detachAt = value.indexOf(0x1d);
593
+ if (detachAt >= 0) {
594
+ if (detachAt > 0 && socket.readyState === WebSocketImpl.OPEN) {
595
+ socket.send(value.subarray(0, detachAt), { binary: true });
596
+ }
597
+ output.write("\r\nDetached. Pi and the Dev Session are still running.\r\n");
598
+ socket.close(1000, "client_detach");
599
+ finish();
600
+ return;
601
+ }
602
+ if (socket.readyState === WebSocketImpl.OPEN) socket.send(value, { binary: true });
603
+ };
604
+
605
+ if (signal?.aborted) {
606
+ onAbort();
607
+ return;
608
+ }
609
+ signal?.addEventListener("abort", onAbort, { once: true });
610
+
611
+ socket.on("message", (data, isBinary) => {
612
+ if (isBinary) {
613
+ output.write(Buffer.from(data));
614
+ return;
615
+ }
616
+ let control;
617
+ try { control = JSON.parse(data.toString()); } catch { return; }
618
+ if (control.type === "ready" && !ready) {
619
+ ready = true;
620
+ if (typeof input.setRawMode === "function") {
621
+ input.setRawMode(true);
622
+ rawEnabled = true;
623
+ }
624
+ input.resume?.();
625
+ input.on("data", onInput);
626
+ process.on("SIGWINCH", onResize);
627
+ sendResize();
628
+ } else if (control.type === "error") {
629
+ finish(new Error(control.message || "Dev Session terminal failed."));
630
+ }
631
+ });
632
+ socket.once("unexpected-response", (_request, response) => {
633
+ finish(new Error(`Dev Session terminal refused the connection (HTTP ${response.statusCode || 500}).`));
634
+ });
635
+ socket.once("error", (error) => finish(new Error(`Dev Session terminal connection failed: ${error.message}`)));
636
+ socket.once("close", (code) => {
637
+ if (!ready && !settled) finish(new Error(`Dev Session terminal closed before it was ready (code ${code}).`));
638
+ else if (ready && code !== 1000 && !settled) finish(new Error("Dev Session terminal connection was lost. Rerun `xevy dev` to reattach."));
639
+ else finish();
640
+ });
641
+ });
561
642
  }
562
643
 
563
644
  function commandHelp(writeLine) {
@@ -622,7 +703,7 @@ export async function runDevSession(options) {
622
703
  const spawnImpl = options.spawnImpl || spawn;
623
704
  const sleep = options.sleep || defaultSleep;
624
705
  const secrets = [token];
625
- const writeLine = (value = "") => output.write(`${redactSensitive(value, secrets)}\n`);
706
+ const writeLine = (value = "") => output.write(`${redactSensitive(value, secrets, null)}\n`);
626
707
  const writeLaunchLine = (value) => output.write(`${String(value)}\n`);
627
708
 
628
709
  const controllers = new Set();
@@ -759,18 +840,33 @@ export async function runDevSession(options) {
759
840
  });
760
841
  sessionSummary(task, session, writeLine);
761
842
 
843
+ const nativeTerminal = options.nativeTerminal
844
+ ?? (input === process.stdin && output === process.stdout);
845
+ if (interactive && nativeTerminal) {
846
+ await attachNativeTerminal({
847
+ api,
848
+ base,
849
+ sessionPath,
850
+ input,
851
+ output,
852
+ signal: detachController.signal,
853
+ WebSocketImpl: options.webSocketImpl || WebSocket,
854
+ });
855
+ detached = true;
856
+ return { task, session, detached: true };
857
+ }
858
+
762
859
  const renderState = {
763
860
  messageIds: new Set(),
764
861
  lastExecutionStatus: null,
765
862
  pendingAssistantText: "",
766
863
  currentExecutionAssistantSeen: false,
767
- liveToolMessageBudget: new Map(),
768
- lastToolStreamKey: null,
864
+ toolStreamKeys: new Set(),
769
865
  };
770
866
  const executions = await showHistory({ api, taskId: task.id, branch: session.config.branch, state: renderState, writeLine });
771
867
  const active = activeExecutionForSession(executions, session.config.branch);
772
868
  if (active) {
773
- writeLine(`\nReattaching to active agent turn ${active.id}…`);
869
+ writeLine("\nResuming the active agent turn…");
774
870
  const completed = await followExecution({
775
871
  api,
776
872
  taskId: task.id,
@@ -791,7 +887,7 @@ export async function runDevSession(options) {
791
887
  }
792
888
 
793
889
  while (!detached) {
794
- const prompt = await ask("dev> ");
890
+ const prompt = await ask("you › ");
795
891
  if (detached) break;
796
892
  if (!prompt) continue;
797
893
  if (prompt === "/help") {
@@ -897,7 +993,7 @@ export async function runDevSession(options) {
897
993
  sleep,
898
994
  });
899
995
  if (completed.status === "succeeded") {
900
- writeLine(`Saved to Dev Session branch ${session.config.branch}.`);
996
+ if (!renderState.currentExecutionAssistantSeen) writeLine("Turn complete.");
901
997
  } else if (completed.status === "cancelled") {
902
998
  writeLine("Agent turn cancelled; the Dev Session remains attached.");
903
999
  } else {
package/bin/xevy.mjs CHANGED
@@ -133,11 +133,11 @@ function devUsage() {
133
133
  xevy dev <task-id-or-code> [--base <url>]
134
134
 
135
135
  Connects this terminal to the task's remote Dev Session. The command attaches
136
- to an existing session or starts one from a linked repository. It
137
- does not run a local coding agent, shell, Docker container, or repository clone.
136
+ to an existing session or starts one from a linked repository, then opens Pi's
137
+ native interactive terminal inside the isolated remote workspace.
138
138
 
139
- Inside the session:
140
- /status /logs /open /finish /stop /detach /help
139
+ Terminal control:
140
+ Ctrl+] Detach without stopping Pi or the Dev Session
141
141
 
142
142
  Credentials:
143
143
  XEVY_API_KEY takes precedence over ~/.config/xevy/credentials.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xevy/cli",
3
- "version": "0.1.13",
3
+ "version": "0.1.15",
4
4
  "description": "Xevy CLI — connect to remote Dev Sessions, configure credentials, pi, coding-agent skills, and MCP, and keep integrations current.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -23,6 +23,9 @@
23
23
  "engines": {
24
24
  "node": ">=18"
25
25
  },
26
+ "dependencies": {
27
+ "ws": "^8.18.3"
28
+ },
26
29
  "publishConfig": {
27
30
  "access": "public"
28
31
  }