@xevy/cli 0.1.10 → 0.1.12
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 +42 -0
- package/bin/dev-session.mjs +920 -0
- package/bin/xevy.mjs +74 -12
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -57,6 +57,7 @@ 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 VI22-07 # attach to a task's remote Dev Session
|
|
60
61
|
```
|
|
61
62
|
|
|
62
63
|
That's it — you're set up. The sections below are reference for when you need more detail.
|
|
@@ -137,6 +138,47 @@ xevy # interactive pi session with Xevy
|
|
|
137
138
|
xevy "summarise this repo" # forwards the prompt to pi
|
|
138
139
|
```
|
|
139
140
|
|
|
141
|
+
## `xevy dev`
|
|
142
|
+
|
|
143
|
+
Connect an interactive terminal to the coding agent attached to a task's remote
|
|
144
|
+
Dev Session:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
xevy dev VI22-07
|
|
148
|
+
xevy dev cb49c02e-66d8-4475-95a8-6f3930643ec8
|
|
149
|
+
xevy dev VI22-07 --base https://xevy.example.com
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
The CLI resolves an exact task ID or task code, attaches to its existing Dev
|
|
153
|
+
Session, or starts one from an eligible running Preview. When several accessible
|
|
154
|
+
tasks share a code, or several repositories have eligible Previews, 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.
|
|
157
|
+
|
|
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.
|
|
162
|
+
|
|
163
|
+
Available commands while attached:
|
|
164
|
+
|
|
165
|
+
```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, queue Preview redeploy, 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
|
|
173
|
+
```
|
|
174
|
+
|
|
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.
|
|
177
|
+
|
|
178
|
+
Host precedence is `--base`, `XEVY_BASE`, the saved credentials `baseUrl`, then
|
|
179
|
+
`https://xevy.ai`. API-key precedence is `XEVY_API_KEY`, then the saved key in
|
|
180
|
+
`~/.config/xevy/credentials`.
|
|
181
|
+
|
|
140
182
|
## Options
|
|
141
183
|
|
|
142
184
|
```
|
|
@@ -0,0 +1,920 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import readline from "node:readline";
|
|
3
|
+
|
|
4
|
+
const DEFAULT_BASE = "https://xevy.ai";
|
|
5
|
+
const TERMINAL_EXECUTION_STATUSES = new Set(["succeeded", "failed", "cancelled"]);
|
|
6
|
+
const SESSION_READY_STATUSES = new Set(["ready", "busy"]);
|
|
7
|
+
const SESSION_PENDING_STATUSES = new Set(["provisioning", "installing", "starting"]);
|
|
8
|
+
const SESSION_TERMINAL_STATUSES = new Set(["failed", "stopped", "expired"]);
|
|
9
|
+
const ACTIVE_EXECUTION_STATUSES = new Set(["queued", "running"]);
|
|
10
|
+
const HISTORY_LIMIT = 6;
|
|
11
|
+
const HEARTBEAT_INTERVAL_MS = 60_000;
|
|
12
|
+
const SESSION_POLL_INTERVAL_MS = 2_000;
|
|
13
|
+
const SESSION_START_TIMEOUT_MS = 10 * 60_000;
|
|
14
|
+
const EXECUTION_RECONNECT_LIMIT = 8;
|
|
15
|
+
|
|
16
|
+
export function parseCredentialsText(source) {
|
|
17
|
+
const values = {};
|
|
18
|
+
for (const line of String(source || "").split(/\r?\n/)) {
|
|
19
|
+
const separator = line.indexOf("=");
|
|
20
|
+
if (separator < 1) continue;
|
|
21
|
+
const key = line.slice(0, separator).trim();
|
|
22
|
+
const value = line.slice(separator + 1).trim();
|
|
23
|
+
if (key) values[key] = value;
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
baseUrl: values.baseUrl || null,
|
|
27
|
+
token: values.token || null,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function normalizeBaseUrl(value) {
|
|
32
|
+
const raw = String(value || DEFAULT_BASE).trim().replace(/\/+$/, "");
|
|
33
|
+
let parsed;
|
|
34
|
+
try {
|
|
35
|
+
parsed = new URL(raw);
|
|
36
|
+
} catch {
|
|
37
|
+
throw new Error(`Invalid Xevy base URL: ${raw}`);
|
|
38
|
+
}
|
|
39
|
+
const local = ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname);
|
|
40
|
+
if (parsed.protocol !== "https:" && !(local && parsed.protocol === "http:")) {
|
|
41
|
+
throw new Error("The Xevy base URL must use HTTPS (HTTP is allowed only for localhost).");
|
|
42
|
+
}
|
|
43
|
+
if (parsed.username || parsed.password || parsed.search || parsed.hash) {
|
|
44
|
+
throw new Error("The Xevy base URL cannot include credentials, a query, or a fragment.");
|
|
45
|
+
}
|
|
46
|
+
parsed.pathname = parsed.pathname.replace(/\/+$/, "");
|
|
47
|
+
return parsed.toString().replace(/\/$/, "");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function parseDevCommandArgs(argv) {
|
|
51
|
+
const args = [...argv];
|
|
52
|
+
let taskReference = "";
|
|
53
|
+
let base = null;
|
|
54
|
+
while (args.length > 0) {
|
|
55
|
+
const argument = args.shift();
|
|
56
|
+
if (argument === "-h" || argument === "--help") return { help: true, taskReference: "", base: null };
|
|
57
|
+
if (argument === "--base") {
|
|
58
|
+
const value = args.shift();
|
|
59
|
+
if (!value) throw new Error("Missing value for --base");
|
|
60
|
+
base = value;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (argument.startsWith("-")) throw new Error(`Unknown option for \`xevy dev\`: ${argument}.`);
|
|
64
|
+
if (taskReference) throw new Error("`xevy dev` accepts one task ID or task code.");
|
|
65
|
+
taskReference = argument;
|
|
66
|
+
}
|
|
67
|
+
if (!taskReference) throw new Error("Usage: xevy dev <task-id-or-code> [--base <url>]");
|
|
68
|
+
return { help: false, taskReference, base };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function resolveDevConnection({
|
|
72
|
+
explicitBase,
|
|
73
|
+
environmentBase,
|
|
74
|
+
storedBase,
|
|
75
|
+
environmentToken,
|
|
76
|
+
storedToken,
|
|
77
|
+
}) {
|
|
78
|
+
const base = normalizeBaseUrl(explicitBase || environmentBase || storedBase || DEFAULT_BASE);
|
|
79
|
+
const token = String(environmentToken || storedToken || "").trim();
|
|
80
|
+
return { base, token };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function redactSensitive(value, secrets = []) {
|
|
84
|
+
let text = String(value ?? "");
|
|
85
|
+
for (const secret of secrets) {
|
|
86
|
+
if (!secret) continue;
|
|
87
|
+
text = text.split(String(secret)).join("[redacted]");
|
|
88
|
+
}
|
|
89
|
+
return text
|
|
90
|
+
.replace(/xevy_pk_[A-Za-z0-9._~-]+/g, "xevy_pk_[redacted]")
|
|
91
|
+
.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);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function createSseDecoder(onEvent) {
|
|
97
|
+
let buffer = "";
|
|
98
|
+
|
|
99
|
+
const dispatch = (frame) => {
|
|
100
|
+
let event = "message";
|
|
101
|
+
const data = [];
|
|
102
|
+
for (const line of frame.split(/\r\n|\r|\n/)) {
|
|
103
|
+
if (!line || line.startsWith(":")) continue;
|
|
104
|
+
const colon = line.indexOf(":");
|
|
105
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
106
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
107
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
108
|
+
if (field === "event") event = value || "message";
|
|
109
|
+
if (field === "data") data.push(value);
|
|
110
|
+
}
|
|
111
|
+
if (data.length > 0) onEvent({ event, data: data.join("\n") });
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const drain = () => {
|
|
115
|
+
while (true) {
|
|
116
|
+
const match = /\r\n\r\n|\n\n|\r\r/.exec(buffer);
|
|
117
|
+
if (!match) return;
|
|
118
|
+
const frame = buffer.slice(0, match.index);
|
|
119
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
120
|
+
if (frame) dispatch(frame);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
push(chunk) {
|
|
126
|
+
buffer += String(chunk || "");
|
|
127
|
+
drain();
|
|
128
|
+
},
|
|
129
|
+
finish() {
|
|
130
|
+
drain();
|
|
131
|
+
if (buffer.trim()) dispatch(buffer);
|
|
132
|
+
buffer = "";
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function browserCommandFor(platform, url) {
|
|
138
|
+
const parsed = new URL(url);
|
|
139
|
+
const local = ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname);
|
|
140
|
+
if (parsed.protocol !== "https:" && !(local && parsed.protocol === "http:")) {
|
|
141
|
+
throw new Error("Refusing to open a non-HTTPS Dev Session URL.");
|
|
142
|
+
}
|
|
143
|
+
if (platform === "darwin") return { command: "open", args: [parsed.toString()] };
|
|
144
|
+
if (platform === "win32") {
|
|
145
|
+
return {
|
|
146
|
+
command: "rundll32.exe",
|
|
147
|
+
args: ["url.dll,FileProtocolHandler", parsed.toString()],
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
return { command: "xdg-open", args: [parsed.toString()] };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function extractApiError(payload, fallback) {
|
|
154
|
+
if (typeof payload === "string" && payload.trim()) return payload.trim();
|
|
155
|
+
if (!payload || typeof payload !== "object") return fallback;
|
|
156
|
+
const nested = payload.error;
|
|
157
|
+
if (typeof nested === "string" && nested.trim()) return nested.trim();
|
|
158
|
+
if (nested && typeof nested === "object" && typeof nested.message === "string") {
|
|
159
|
+
return nested.message.trim() || fallback;
|
|
160
|
+
}
|
|
161
|
+
if (typeof payload.message === "string" && payload.message.trim()) return payload.message.trim();
|
|
162
|
+
return fallback;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
class DevSessionApiError extends Error {
|
|
166
|
+
constructor(status, message, payload) {
|
|
167
|
+
super(message);
|
|
168
|
+
this.name = "DevSessionApiError";
|
|
169
|
+
this.status = status;
|
|
170
|
+
this.code = payload && typeof payload === "object"
|
|
171
|
+
? payload.code || payload.error?.code || null
|
|
172
|
+
: null;
|
|
173
|
+
this.executionId = payload && typeof payload === "object"
|
|
174
|
+
? payload.executionId || null
|
|
175
|
+
: null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function createApiClient({ base, token, fetchImpl, registerController, secrets }) {
|
|
180
|
+
const request = async (path, options = {}) => {
|
|
181
|
+
const controller = new AbortController();
|
|
182
|
+
const release = registerController(controller);
|
|
183
|
+
const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 20_000);
|
|
184
|
+
timeout.unref?.();
|
|
185
|
+
const externalSignal = options.signal;
|
|
186
|
+
const abort = () => controller.abort();
|
|
187
|
+
if (externalSignal?.aborted) controller.abort();
|
|
188
|
+
else externalSignal?.addEventListener("abort", abort, { once: true });
|
|
189
|
+
let streamHandoff = false;
|
|
190
|
+
const cleanup = () => {
|
|
191
|
+
clearTimeout(timeout);
|
|
192
|
+
externalSignal?.removeEventListener("abort", abort);
|
|
193
|
+
release();
|
|
194
|
+
};
|
|
195
|
+
try {
|
|
196
|
+
const response = await fetchImpl(`${base}${path}`, {
|
|
197
|
+
method: options.method || "GET",
|
|
198
|
+
headers: {
|
|
199
|
+
Accept: options.stream ? "text/event-stream" : "application/json",
|
|
200
|
+
Authorization: `Bearer ${token}`,
|
|
201
|
+
...(options.body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
202
|
+
},
|
|
203
|
+
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
|
204
|
+
signal: controller.signal,
|
|
205
|
+
});
|
|
206
|
+
if (options.stream) {
|
|
207
|
+
if (response.ok) {
|
|
208
|
+
streamHandoff = true;
|
|
209
|
+
return { response, close: cleanup };
|
|
210
|
+
}
|
|
211
|
+
} else if (response.ok) {
|
|
212
|
+
if (response.status === 204) return null;
|
|
213
|
+
return await response.json();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
let payload = null;
|
|
217
|
+
try {
|
|
218
|
+
payload = await response.json();
|
|
219
|
+
} catch {
|
|
220
|
+
// Intentionally do not print arbitrary response bodies.
|
|
221
|
+
}
|
|
222
|
+
const fallback = `Xevy request failed (HTTP ${response.status}).`;
|
|
223
|
+
const message = redactSensitive(extractApiError(payload, fallback), secrets);
|
|
224
|
+
throw new DevSessionApiError(response.status, message, payload);
|
|
225
|
+
} catch (error) {
|
|
226
|
+
if (error instanceof DevSessionApiError) throw error;
|
|
227
|
+
if (controller.signal.aborted) {
|
|
228
|
+
const reason = externalSignal?.aborted ? "Dev Session detached." : "Xevy request timed out.";
|
|
229
|
+
throw new Error(reason);
|
|
230
|
+
}
|
|
231
|
+
throw new Error(redactSensitive(
|
|
232
|
+
`Could not reach Xevy: ${error instanceof Error ? error.message : String(error)}`,
|
|
233
|
+
secrets,
|
|
234
|
+
));
|
|
235
|
+
} finally {
|
|
236
|
+
if (!streamHandoff) cleanup();
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
return { request };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function canonicalSessionUrl(hostname) {
|
|
243
|
+
if (!hostname) return null;
|
|
244
|
+
const candidate = /^https?:\/\//i.test(hostname) ? hostname : `https://${hostname}`;
|
|
245
|
+
const parsed = new URL(candidate);
|
|
246
|
+
const local = ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname);
|
|
247
|
+
if (parsed.protocol !== "https:" && !(local && parsed.protocol === "http:")) return null;
|
|
248
|
+
return parsed.toString().replace(/\/$/, "");
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function formatTask(task) {
|
|
252
|
+
const code = task.taskCode ? `${task.taskCode} · ` : "";
|
|
253
|
+
return `${code}${task.title} (${task.workspaceIdentifier}/${task.projectIdentifier})`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function selectOne({ items, label, describe, interactive, ask, writeLine }) {
|
|
257
|
+
if (items.length === 0) return null;
|
|
258
|
+
if (items.length === 1) return items[0];
|
|
259
|
+
writeLine(`Multiple ${label} match:`);
|
|
260
|
+
items.forEach((item, index) => writeLine(` ${index + 1}. ${describe(item)}`));
|
|
261
|
+
if (!interactive) {
|
|
262
|
+
throw new Error(`Multiple ${label} match; rerun interactively and choose one.`);
|
|
263
|
+
}
|
|
264
|
+
while (true) {
|
|
265
|
+
const answer = await ask(`Choose ${label.slice(0, -1)} [1-${items.length}]: `);
|
|
266
|
+
const index = Number.parseInt(answer, 10) - 1;
|
|
267
|
+
if (Number.isInteger(index) && index >= 0 && index < items.length) return items[index];
|
|
268
|
+
writeLine(`Enter a number from 1 to ${items.length}.`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function executionCreatedAt(execution) {
|
|
273
|
+
const value = Date.parse(execution.createdAt || "");
|
|
274
|
+
return Number.isFinite(value) ? value : 0;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function sessionExecutions(executions, branch, actions = ["dev-session"]) {
|
|
278
|
+
return executions
|
|
279
|
+
.filter((execution) => actions.includes(execution.action) && execution.branchName === branch)
|
|
280
|
+
.sort((a, b) => executionCreatedAt(b) - executionCreatedAt(a));
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function activeExecutionForSession(executions, branch) {
|
|
284
|
+
const active = executions
|
|
285
|
+
.filter((execution) => execution.action === "dev-session" && ACTIVE_EXECUTION_STATUSES.has(execution.status))
|
|
286
|
+
.sort((a, b) => executionCreatedAt(b) - executionCreatedAt(a));
|
|
287
|
+
return active.find((execution) => execution.branchName === branch)
|
|
288
|
+
// A newly queued run can briefly precede branch resolution. The server
|
|
289
|
+
// permits only one active task execution, so a null branch is a safe
|
|
290
|
+
// transitional fallback; a different concrete branch is never attached.
|
|
291
|
+
|| active.find((execution) => !execution.branchName)
|
|
292
|
+
|| null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function messageText(message) {
|
|
296
|
+
return typeof message?.content === "string" ? message.content.trim() : "";
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function renderPersistedMessage(message, state, writeLine) {
|
|
300
|
+
if (!message || (message.id && state.messageIds.has(message.id))) return;
|
|
301
|
+
if (message.id) state.messageIds.add(message.id);
|
|
302
|
+
const text = messageText(message);
|
|
303
|
+
if (!text && !message.toolName) return;
|
|
304
|
+
if (message.role === "assistant") {
|
|
305
|
+
state.currentExecutionAssistantSeen = true;
|
|
306
|
+
state.pendingAssistantText = "";
|
|
307
|
+
}
|
|
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}`);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function renderStreamEvent(eventName, payload, state, writeLine, secrets) {
|
|
328
|
+
const event = payload && typeof payload === "object" ? payload : {};
|
|
329
|
+
const type = event.type || eventName;
|
|
330
|
+
if (type === "message" && event.message) {
|
|
331
|
+
renderPersistedMessage(event.message, state, writeLine);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
// Persisted message events are the authoritative text. Ignoring deltas avoids
|
|
335
|
+
// printing the same assistant answer again during post-stream reconciliation.
|
|
336
|
+
if (type === "text_delta") {
|
|
337
|
+
if (typeof event.text === "string") state.pendingAssistantText += event.text;
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
if (type === "usage" || type === "heartbeat" || type === "end") return;
|
|
341
|
+
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)}` : ""}`);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
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)}` : ""}`);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (type === "status" || eventName === "snapshot") {
|
|
360
|
+
const status = event.status;
|
|
361
|
+
if (status && status !== state.lastExecutionStatus) {
|
|
362
|
+
state.lastExecutionStatus = status;
|
|
363
|
+
writeLine(`execution> ${status}${event.errorMessage ? ` — ${redactSensitive(event.errorMessage, secrets)}` : ""}`);
|
|
364
|
+
}
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
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
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async function consumeExecutionStream({ api, taskId, executionId, state, writeLine, secrets, signal }) {
|
|
377
|
+
const stream = await api.request(
|
|
378
|
+
`/api/tasks/${encodeURIComponent(taskId)}/ai/executions/${encodeURIComponent(executionId)}/stream`,
|
|
379
|
+
{ stream: true, timeoutMs: 30 * 60_000, signal },
|
|
380
|
+
);
|
|
381
|
+
const { response } = stream;
|
|
382
|
+
if (!response.body) {
|
|
383
|
+
stream.close();
|
|
384
|
+
throw new Error("Xevy returned an empty execution stream.");
|
|
385
|
+
}
|
|
386
|
+
const reader = response.body.getReader();
|
|
387
|
+
const decoder = new TextDecoder();
|
|
388
|
+
const sse = createSseDecoder(({ event, data }) => {
|
|
389
|
+
let payload = data;
|
|
390
|
+
try {
|
|
391
|
+
payload = JSON.parse(data);
|
|
392
|
+
} catch {
|
|
393
|
+
// Non-JSON SSE data is intentionally ignored unless it is a safe server line.
|
|
394
|
+
if (event === "chunk" && data.trim().startsWith("[server]")) {
|
|
395
|
+
payload = { type: "chunk", text: data };
|
|
396
|
+
} else {
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
renderStreamEvent(event, payload, state, writeLine, secrets);
|
|
401
|
+
});
|
|
402
|
+
try {
|
|
403
|
+
while (true) {
|
|
404
|
+
const { done, value } = await reader.read();
|
|
405
|
+
if (done) break;
|
|
406
|
+
sse.push(decoder.decode(value, { stream: true }));
|
|
407
|
+
}
|
|
408
|
+
sse.push(decoder.decode());
|
|
409
|
+
sse.finish();
|
|
410
|
+
} finally {
|
|
411
|
+
try { await reader.cancel(); } catch { /* already closed */ }
|
|
412
|
+
stream.close();
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function reconcileExecution({ api, taskId, executionId, state, writeLine }) {
|
|
417
|
+
const [execution, messageResult] = await Promise.all([
|
|
418
|
+
api.request(`/api/tasks/${encodeURIComponent(taskId)}/ai/executions/${encodeURIComponent(executionId)}`),
|
|
419
|
+
api.request(`/api/tasks/${encodeURIComponent(taskId)}/ai/executions/${encodeURIComponent(executionId)}/messages`),
|
|
420
|
+
]);
|
|
421
|
+
for (const message of messageResult?.messages || []) {
|
|
422
|
+
renderPersistedMessage(message, state, writeLine);
|
|
423
|
+
}
|
|
424
|
+
return { execution, messageCount: (messageResult?.messages || []).length };
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
async function followExecution({
|
|
428
|
+
api,
|
|
429
|
+
taskId,
|
|
430
|
+
executionId,
|
|
431
|
+
state,
|
|
432
|
+
writeLine,
|
|
433
|
+
secrets,
|
|
434
|
+
signal,
|
|
435
|
+
sleep,
|
|
436
|
+
}) {
|
|
437
|
+
state.pendingAssistantText = "";
|
|
438
|
+
state.currentExecutionAssistantSeen = false;
|
|
439
|
+
state.liveToolMessageBudget.clear();
|
|
440
|
+
state.lastToolStreamKey = null;
|
|
441
|
+
let reconnects = 0;
|
|
442
|
+
while (true) {
|
|
443
|
+
let streamError = null;
|
|
444
|
+
try {
|
|
445
|
+
await consumeExecutionStream({ api, taskId, executionId, state, writeLine, secrets, signal });
|
|
446
|
+
} catch (error) {
|
|
447
|
+
if (signal?.aborted) throw error;
|
|
448
|
+
streamError = error;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
let reconciled = null;
|
|
452
|
+
try {
|
|
453
|
+
reconciled = await reconcileExecution({ api, taskId, executionId, state, writeLine });
|
|
454
|
+
} catch (error) {
|
|
455
|
+
if (signal?.aborted) throw error;
|
|
456
|
+
streamError ||= error;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const execution = reconciled?.execution;
|
|
460
|
+
if (execution && TERMINAL_EXECUTION_STATUSES.has(execution.status)) {
|
|
461
|
+
let previousCount = reconciled.messageCount;
|
|
462
|
+
let stablePasses = 0;
|
|
463
|
+
const settleDelays = [100, 200, 400, 800];
|
|
464
|
+
for (let index = 0; index < settleDelays.length; index += 1) {
|
|
465
|
+
if (state.currentExecutionAssistantSeen) break;
|
|
466
|
+
await sleep(settleDelays[index], signal);
|
|
467
|
+
try {
|
|
468
|
+
const next = await reconcileExecution({ api, taskId, executionId, state, writeLine });
|
|
469
|
+
stablePasses = next.messageCount === previousCount ? stablePasses + 1 : 0;
|
|
470
|
+
previousCount = next.messageCount;
|
|
471
|
+
if (index >= 2 && stablePasses >= 2 && !state.pendingAssistantText.trim()) break;
|
|
472
|
+
} catch (error) {
|
|
473
|
+
if (signal?.aborted) throw error;
|
|
474
|
+
// A terminal execution is already durable. A transient read failure
|
|
475
|
+
// should not discard its result or turn a successful run into a CLI failure.
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
if (!state.currentExecutionAssistantSeen && state.pendingAssistantText.trim()) {
|
|
479
|
+
writeLine(`xevy> ${state.pendingAssistantText.trim()}`);
|
|
480
|
+
state.pendingAssistantText = "";
|
|
481
|
+
state.currentExecutionAssistantSeen = true;
|
|
482
|
+
}
|
|
483
|
+
return execution;
|
|
484
|
+
}
|
|
485
|
+
if (reconnects >= EXECUTION_RECONNECT_LIMIT) {
|
|
486
|
+
throw new Error("The agent is still running, but the activity stream could not be reattached. Rerun `xevy dev` to resume safely.");
|
|
487
|
+
}
|
|
488
|
+
reconnects += 1;
|
|
489
|
+
writeLine(streamError ? "Connection lost; reconnecting…" : "Agent still running; reconnecting…");
|
|
490
|
+
await sleep(Math.min(1_000 * 2 ** (reconnects - 1), 8_000), signal);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
async function showHistory({ api, taskId, branch, state, writeLine }) {
|
|
495
|
+
const result = await api.request(`/api/tasks/${encodeURIComponent(taskId)}/ai/executions`);
|
|
496
|
+
const executions = sessionExecutions(result?.executions || [], branch).slice(0, HISTORY_LIMIT).reverse();
|
|
497
|
+
if (executions.length === 0) return result?.executions || [];
|
|
498
|
+
writeLine("\nRecent Dev Session conversation:");
|
|
499
|
+
for (const execution of executions) {
|
|
500
|
+
const messages = await api.request(
|
|
501
|
+
`/api/tasks/${encodeURIComponent(taskId)}/ai/executions/${encodeURIComponent(execution.id)}/messages`,
|
|
502
|
+
);
|
|
503
|
+
for (const message of messages?.messages || []) renderPersistedMessage(message, state, writeLine);
|
|
504
|
+
}
|
|
505
|
+
return result?.executions || [];
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function defaultSleep(milliseconds, signal) {
|
|
509
|
+
return new Promise((resolve, reject) => {
|
|
510
|
+
if (signal?.aborted) return reject(new Error("Dev Session detached."));
|
|
511
|
+
const cleanup = () => signal?.removeEventListener("abort", abort);
|
|
512
|
+
const timer = setTimeout(() => {
|
|
513
|
+
cleanup();
|
|
514
|
+
resolve();
|
|
515
|
+
}, milliseconds);
|
|
516
|
+
const abort = () => {
|
|
517
|
+
clearTimeout(timer);
|
|
518
|
+
cleanup();
|
|
519
|
+
reject(new Error("Dev Session detached."));
|
|
520
|
+
};
|
|
521
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async function waitForReady({ api, sessionPath, initialSession, writeLine, sleep, signal }) {
|
|
526
|
+
let session = initialSession;
|
|
527
|
+
let lastStatus = null;
|
|
528
|
+
const deadline = Date.now() + SESSION_START_TIMEOUT_MS;
|
|
529
|
+
while (!SESSION_READY_STATUSES.has(session.status)) {
|
|
530
|
+
if (session.status !== lastStatus) {
|
|
531
|
+
writeLine(`session> ${session.status}`);
|
|
532
|
+
lastStatus = session.status;
|
|
533
|
+
}
|
|
534
|
+
if (SESSION_TERMINAL_STATUSES.has(session.status)) {
|
|
535
|
+
throw new Error(session.error || `Dev Session ${session.status}.`);
|
|
536
|
+
}
|
|
537
|
+
if (!SESSION_PENDING_STATUSES.has(session.status)) {
|
|
538
|
+
throw new Error(`Unexpected Dev Session status: ${session.status}`);
|
|
539
|
+
}
|
|
540
|
+
if (Date.now() >= deadline) {
|
|
541
|
+
throw new Error("Dev Session startup is taking longer than expected. It remains active; rerun `xevy dev` to attach later.");
|
|
542
|
+
}
|
|
543
|
+
await sleep(SESSION_POLL_INTERVAL_MS, signal);
|
|
544
|
+
const result = await api.request(`${sessionPath}/`, { signal });
|
|
545
|
+
if (!result?.session) throw new Error("The Dev Session disappeared while starting.");
|
|
546
|
+
session = result.session;
|
|
547
|
+
}
|
|
548
|
+
if (session.status !== lastStatus) writeLine(`session> ${session.status}`);
|
|
549
|
+
return session;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function sessionSummary(task, session, writeLine) {
|
|
553
|
+
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");
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function commandHelp(writeLine) {
|
|
564
|
+
writeLine("Commands:");
|
|
565
|
+
writeLine(" /status Refresh session status");
|
|
566
|
+
writeLine(" /logs Show the latest Dev Session logs");
|
|
567
|
+
writeLine(" /open Open a fresh one-use Dev Session URL");
|
|
568
|
+
writeLine(" /finish Merge into the task branch, redeploy Preview, and stop");
|
|
569
|
+
writeLine(" /stop Stop the Dev Session without finishing");
|
|
570
|
+
writeLine(" /detach Leave it running and exit this CLI");
|
|
571
|
+
writeLine(" /help Show these commands");
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
async function confirmAction({ interactive, ask, action }) {
|
|
575
|
+
if (!interactive) throw new Error(`/${action} requires an interactive confirmation.`);
|
|
576
|
+
const answer = (await ask(`${action === "finish" ? "Finish, merge, redeploy Preview, and stop" : "Stop this Dev Session"}? [y/N]: `)).toLowerCase();
|
|
577
|
+
return answer === "y" || answer === "yes";
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async function launchBrowser({ api, sessionPath, platform, spawnImpl, writeLaunchLine }) {
|
|
581
|
+
const result = await api.request(`${sessionPath}/open`, { method: "POST", body: {} });
|
|
582
|
+
const launchUrl = result?.launchUrl;
|
|
583
|
+
if (!launchUrl) throw new Error("Xevy did not return a Dev Session launch URL.");
|
|
584
|
+
// The one-use ticket is the one intentional secret-bearing output: users on
|
|
585
|
+
// headless hosts must be able to copy the complete URL. Other output remains
|
|
586
|
+
// redacted, and the URL is never included in an error or debug dump.
|
|
587
|
+
writeLaunchLine(`Open: ${launchUrl}`);
|
|
588
|
+
const command = browserCommandFor(platform, launchUrl);
|
|
589
|
+
try {
|
|
590
|
+
const child = spawnImpl(command.command, command.args, {
|
|
591
|
+
detached: true,
|
|
592
|
+
shell: false,
|
|
593
|
+
stdio: "ignore",
|
|
594
|
+
});
|
|
595
|
+
child?.on?.("error", () => {});
|
|
596
|
+
child?.unref?.();
|
|
597
|
+
} catch {
|
|
598
|
+
// Printing the URL is the guaranteed path; browser launch is best-effort.
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Attach to a task-scoped Dev Session without running local Pi or a local shell.
|
|
604
|
+
* Dependencies are injectable so transport, SSE, and lifecycle behavior can be
|
|
605
|
+
* tested without contacting a real Xevy host.
|
|
606
|
+
*/
|
|
607
|
+
export async function runDevSession(options) {
|
|
608
|
+
const base = normalizeBaseUrl(options.base);
|
|
609
|
+
const token = String(options.token || "").trim();
|
|
610
|
+
if (!token.startsWith("xevy_pk_")) {
|
|
611
|
+
throw new Error("A Xevy API key is required. Run `xevy setup --credentials` first.");
|
|
612
|
+
}
|
|
613
|
+
const taskReference = String(options.taskReference || "").trim();
|
|
614
|
+
if (!taskReference) throw new Error("Usage: xevy dev <task-id-or-code> [--base <url>]");
|
|
615
|
+
|
|
616
|
+
const fetchImpl = options.fetchImpl || globalThis.fetch;
|
|
617
|
+
if (typeof fetchImpl !== "function") throw new Error("This Node.js version does not provide fetch.");
|
|
618
|
+
const input = options.input || process.stdin;
|
|
619
|
+
const output = options.output || process.stdout;
|
|
620
|
+
const interactive = options.interactive ?? Boolean(input.isTTY && output.isTTY);
|
|
621
|
+
const platform = options.platform || process.platform;
|
|
622
|
+
const spawnImpl = options.spawnImpl || spawn;
|
|
623
|
+
const sleep = options.sleep || defaultSleep;
|
|
624
|
+
const secrets = [token];
|
|
625
|
+
const writeLine = (value = "") => output.write(`${redactSensitive(value, secrets)}\n`);
|
|
626
|
+
const writeLaunchLine = (value) => output.write(`${String(value)}\n`);
|
|
627
|
+
|
|
628
|
+
const controllers = new Set();
|
|
629
|
+
const registerController = (controller) => {
|
|
630
|
+
controllers.add(controller);
|
|
631
|
+
return () => controllers.delete(controller);
|
|
632
|
+
};
|
|
633
|
+
const detachController = new AbortController();
|
|
634
|
+
const abortLocalWork = () => {
|
|
635
|
+
if (!detachController.signal.aborted) detachController.abort();
|
|
636
|
+
for (const controller of controllers) controller.abort();
|
|
637
|
+
};
|
|
638
|
+
const api = createApiClient({ base, token, fetchImpl, registerController, secrets });
|
|
639
|
+
|
|
640
|
+
let rl = null;
|
|
641
|
+
let pendingAnswer = null;
|
|
642
|
+
let detached = false;
|
|
643
|
+
const detach = (announce = true) => {
|
|
644
|
+
if (detached) return;
|
|
645
|
+
detached = true;
|
|
646
|
+
abortLocalWork();
|
|
647
|
+
if (pendingAnswer) {
|
|
648
|
+
pendingAnswer("");
|
|
649
|
+
pendingAnswer = null;
|
|
650
|
+
}
|
|
651
|
+
rl?.close();
|
|
652
|
+
if (announce) writeLine("Detached. The Dev Session is still running.");
|
|
653
|
+
};
|
|
654
|
+
const ask = (question) => {
|
|
655
|
+
if (!interactive) throw new Error("Interactive input is unavailable.");
|
|
656
|
+
if (typeof options.askImpl === "function") {
|
|
657
|
+
return Promise.resolve(options.askImpl(question)).then((answer) => String(answer || "").trim());
|
|
658
|
+
}
|
|
659
|
+
if (!rl) {
|
|
660
|
+
rl = readline.createInterface({ input, output, terminal: true });
|
|
661
|
+
rl.on("SIGINT", () => detach());
|
|
662
|
+
rl.on("close", () => {
|
|
663
|
+
if (pendingAnswer) {
|
|
664
|
+
pendingAnswer("");
|
|
665
|
+
pendingAnswer = null;
|
|
666
|
+
}
|
|
667
|
+
if (!detached) detach();
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
return new Promise((resolve) => {
|
|
671
|
+
pendingAnswer = resolve;
|
|
672
|
+
rl.question(question, (answer) => {
|
|
673
|
+
pendingAnswer = null;
|
|
674
|
+
resolve(String(answer || "").trim());
|
|
675
|
+
});
|
|
676
|
+
});
|
|
677
|
+
};
|
|
678
|
+
const onSigint = () => detach();
|
|
679
|
+
process.on("SIGINT", onSigint);
|
|
680
|
+
|
|
681
|
+
let heartbeat = null;
|
|
682
|
+
let task;
|
|
683
|
+
let session;
|
|
684
|
+
try {
|
|
685
|
+
// Validate both host and key before resolving any task context.
|
|
686
|
+
await api.request("/api/profile", { signal: detachController.signal });
|
|
687
|
+
const search = await api.request("/api/tasks/search", {
|
|
688
|
+
method: "POST",
|
|
689
|
+
body: { taskIdentifier: taskReference },
|
|
690
|
+
signal: detachController.signal,
|
|
691
|
+
});
|
|
692
|
+
const tasks = search?.tasks || [];
|
|
693
|
+
if (tasks.length === 0) throw new Error(`No accessible task matches '${taskReference}'.`);
|
|
694
|
+
task = await selectOne({
|
|
695
|
+
items: tasks,
|
|
696
|
+
label: "tasks",
|
|
697
|
+
describe: formatTask,
|
|
698
|
+
interactive,
|
|
699
|
+
ask,
|
|
700
|
+
writeLine,
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
const sessionPath = `/api/projects/${encodeURIComponent(task.workspaceIdentifier)}/${encodeURIComponent(task.projectIdentifier)}/tasks/${encodeURIComponent(task.id)}/live-session`;
|
|
704
|
+
const current = await api.request(`${sessionPath}/`, { signal: detachController.signal });
|
|
705
|
+
session = current?.session || null;
|
|
706
|
+
if (!session) {
|
|
707
|
+
const repositoryResult = await api.request(`${sessionPath}/repositories`, { signal: detachController.signal });
|
|
708
|
+
const repositories = (repositoryResult?.repos || []).filter((repository) => repository.eligibleForDevSession);
|
|
709
|
+
if (repositories.length === 0) {
|
|
710
|
+
throw new Error("No linked repository has a running Preview. Deploy Preview first, then rerun `xevy dev`.");
|
|
711
|
+
}
|
|
712
|
+
const repository = await selectOne({
|
|
713
|
+
items: repositories,
|
|
714
|
+
label: "repositories",
|
|
715
|
+
describe: (item) => `${item.displayName || item.role}${item.previewStatus ? ` · Preview ${item.previewStatus}` : ""}`,
|
|
716
|
+
interactive,
|
|
717
|
+
ask,
|
|
718
|
+
writeLine,
|
|
719
|
+
});
|
|
720
|
+
writeLine(`Starting Dev Session with ${repository.displayName || repository.role}…`);
|
|
721
|
+
const started = await api.request(`${sessionPath}/`, {
|
|
722
|
+
method: "POST",
|
|
723
|
+
body: { runtimeRepositoryId: repository.id },
|
|
724
|
+
signal: detachController.signal,
|
|
725
|
+
timeoutMs: 60_000,
|
|
726
|
+
});
|
|
727
|
+
session = started?.session;
|
|
728
|
+
if (!session) throw new Error("Xevy accepted the request but returned no Dev Session.");
|
|
729
|
+
} else {
|
|
730
|
+
writeLine("Attaching to the existing Dev Session…");
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
let heartbeatFailures = 0;
|
|
734
|
+
const sendHeartbeat = () => {
|
|
735
|
+
if (detached) return;
|
|
736
|
+
void api.request(`${sessionPath}/heartbeat`, { method: "POST", body: {}, timeoutMs: 20_000 })
|
|
737
|
+
.then((result) => {
|
|
738
|
+
heartbeatFailures = 0;
|
|
739
|
+
if (result?.session) session = result.session;
|
|
740
|
+
})
|
|
741
|
+
.catch(() => {
|
|
742
|
+
heartbeatFailures += 1;
|
|
743
|
+
if (heartbeatFailures === 3) {
|
|
744
|
+
writeLine("Heartbeat unavailable; this session remains subject to server expiry.");
|
|
745
|
+
}
|
|
746
|
+
});
|
|
747
|
+
};
|
|
748
|
+
sendHeartbeat();
|
|
749
|
+
heartbeat = setInterval(sendHeartbeat, options.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS);
|
|
750
|
+
heartbeat.unref?.();
|
|
751
|
+
|
|
752
|
+
session = await waitForReady({
|
|
753
|
+
api,
|
|
754
|
+
sessionPath,
|
|
755
|
+
initialSession: session,
|
|
756
|
+
writeLine,
|
|
757
|
+
sleep,
|
|
758
|
+
signal: detachController.signal,
|
|
759
|
+
});
|
|
760
|
+
sessionSummary(task, session, writeLine);
|
|
761
|
+
|
|
762
|
+
const renderState = {
|
|
763
|
+
messageIds: new Set(),
|
|
764
|
+
lastExecutionStatus: null,
|
|
765
|
+
pendingAssistantText: "",
|
|
766
|
+
currentExecutionAssistantSeen: false,
|
|
767
|
+
liveToolMessageBudget: new Map(),
|
|
768
|
+
lastToolStreamKey: null,
|
|
769
|
+
};
|
|
770
|
+
const executions = await showHistory({ api, taskId: task.id, branch: session.config.branch, state: renderState, writeLine });
|
|
771
|
+
const active = activeExecutionForSession(executions, session.config.branch);
|
|
772
|
+
if (active) {
|
|
773
|
+
writeLine(`\nReattaching to active agent turn ${active.id}…`);
|
|
774
|
+
const completed = await followExecution({
|
|
775
|
+
api,
|
|
776
|
+
taskId: task.id,
|
|
777
|
+
executionId: active.id,
|
|
778
|
+
state: renderState,
|
|
779
|
+
writeLine,
|
|
780
|
+
secrets,
|
|
781
|
+
signal: detachController.signal,
|
|
782
|
+
sleep,
|
|
783
|
+
});
|
|
784
|
+
if (completed.status === "failed") throw new Error(completed.errorMessage || "The Dev Session agent turn failed.");
|
|
785
|
+
if (completed.status === "cancelled") writeLine("The previous agent turn was cancelled.");
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
if (!interactive) {
|
|
789
|
+
writeLine("Attached successfully. Rerun in an interactive terminal to prompt the agent.");
|
|
790
|
+
return { task, session, detached: true };
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
while (!detached) {
|
|
794
|
+
const prompt = await ask("dev> ");
|
|
795
|
+
if (detached) break;
|
|
796
|
+
if (!prompt) continue;
|
|
797
|
+
if (prompt === "/help") {
|
|
798
|
+
commandHelp(writeLine);
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
if (prompt === "/detach") {
|
|
802
|
+
detach();
|
|
803
|
+
break;
|
|
804
|
+
}
|
|
805
|
+
if (prompt === "/status") {
|
|
806
|
+
const result = await api.request(`${sessionPath}/`, { signal: detachController.signal });
|
|
807
|
+
if (!result?.session) throw new Error("No active Dev Session remains for this task.");
|
|
808
|
+
session = result.session;
|
|
809
|
+
sessionSummary(task, session, writeLine);
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
if (prompt === "/logs") {
|
|
813
|
+
const logs = await api.request(`${sessionPath}/logs?limit=80`, { signal: detachController.signal });
|
|
814
|
+
for (const line of logs?.lines || []) writeLine(line);
|
|
815
|
+
if (!(logs?.lines || []).length) writeLine("No Dev Session logs yet.");
|
|
816
|
+
continue;
|
|
817
|
+
}
|
|
818
|
+
if (prompt === "/open") {
|
|
819
|
+
await launchBrowser({ api, sessionPath, platform, spawnImpl, writeLaunchLine });
|
|
820
|
+
continue;
|
|
821
|
+
}
|
|
822
|
+
if (prompt === "/stop") {
|
|
823
|
+
if (!(await confirmAction({ interactive, ask, action: "stop" }))) {
|
|
824
|
+
writeLine("Stop cancelled.");
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
await api.request(`${sessionPath}/stop`, { method: "POST", body: {}, signal: detachController.signal });
|
|
828
|
+
writeLine("Dev Session stopped. Its pushed branch is preserved for a safe resume.");
|
|
829
|
+
detached = true;
|
|
830
|
+
break;
|
|
831
|
+
}
|
|
832
|
+
if (prompt === "/finish") {
|
|
833
|
+
if (!(await confirmAction({ interactive, ask, action: "finish" }))) {
|
|
834
|
+
writeLine("Finish cancelled.");
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
const result = await api.request(`${sessionPath}/finish`, {
|
|
838
|
+
method: "POST",
|
|
839
|
+
body: {},
|
|
840
|
+
signal: detachController.signal,
|
|
841
|
+
});
|
|
842
|
+
writeLine(`Finishing through agent execution ${result.executionId}…`);
|
|
843
|
+
const completed = await followExecution({
|
|
844
|
+
api,
|
|
845
|
+
taskId: task.id,
|
|
846
|
+
executionId: result.executionId,
|
|
847
|
+
state: renderState,
|
|
848
|
+
writeLine,
|
|
849
|
+
secrets,
|
|
850
|
+
signal: detachController.signal,
|
|
851
|
+
sleep,
|
|
852
|
+
});
|
|
853
|
+
if (completed.status !== "succeeded") {
|
|
854
|
+
throw new Error(completed.errorMessage || `Finish ${completed.status}.`);
|
|
855
|
+
}
|
|
856
|
+
writeLine("Finished: the Dev Session branch was merged into the task branch and Preview redeploy was queued.");
|
|
857
|
+
detached = true;
|
|
858
|
+
break;
|
|
859
|
+
}
|
|
860
|
+
if (prompt.startsWith("/")) {
|
|
861
|
+
writeLine(`Unknown command '${prompt}'. Use /help.`);
|
|
862
|
+
continue;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
let result;
|
|
866
|
+
try {
|
|
867
|
+
result = await api.request(`${sessionPath}/prompt`, {
|
|
868
|
+
method: "POST",
|
|
869
|
+
body: { prompt },
|
|
870
|
+
signal: detachController.signal,
|
|
871
|
+
});
|
|
872
|
+
} catch (error) {
|
|
873
|
+
if (error instanceof DevSessionApiError && error.status === 409) {
|
|
874
|
+
let executionId = error.executionId;
|
|
875
|
+
if (!executionId) {
|
|
876
|
+
const currentExecutions = await api.request(`/api/tasks/${encodeURIComponent(task.id)}/ai/executions`);
|
|
877
|
+
executionId = activeExecutionForSession(
|
|
878
|
+
currentExecutions?.executions || [],
|
|
879
|
+
session.config.branch,
|
|
880
|
+
)?.id;
|
|
881
|
+
}
|
|
882
|
+
if (!executionId) throw error;
|
|
883
|
+
result = { executionId, status: "running" };
|
|
884
|
+
writeLine("Another Dev Session turn is already active; attaching to it.");
|
|
885
|
+
} else {
|
|
886
|
+
throw error;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
const completed = await followExecution({
|
|
890
|
+
api,
|
|
891
|
+
taskId: task.id,
|
|
892
|
+
executionId: result.executionId,
|
|
893
|
+
state: renderState,
|
|
894
|
+
writeLine,
|
|
895
|
+
secrets,
|
|
896
|
+
signal: detachController.signal,
|
|
897
|
+
sleep,
|
|
898
|
+
});
|
|
899
|
+
if (completed.status === "succeeded") {
|
|
900
|
+
writeLine(`Saved to Dev Session branch ${session.config.branch}.`);
|
|
901
|
+
} else if (completed.status === "cancelled") {
|
|
902
|
+
writeLine("Agent turn cancelled; the Dev Session remains attached.");
|
|
903
|
+
} else {
|
|
904
|
+
writeLine(`Agent turn failed: ${completed.errorMessage || "unknown error"}`);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
return { task, session, detached: true };
|
|
908
|
+
} catch (error) {
|
|
909
|
+
if (detached && /detached/i.test(error instanceof Error ? error.message : String(error))) {
|
|
910
|
+
return { task, session, detached: true };
|
|
911
|
+
}
|
|
912
|
+
throw new Error(redactSensitive(error instanceof Error ? error.message : String(error), secrets));
|
|
913
|
+
} finally {
|
|
914
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
915
|
+
process.off("SIGINT", onSigint);
|
|
916
|
+
abortLocalWork();
|
|
917
|
+
if (pendingAnswer) pendingAnswer("");
|
|
918
|
+
rl?.close();
|
|
919
|
+
}
|
|
920
|
+
}
|
package/bin/xevy.mjs
CHANGED
|
@@ -18,6 +18,12 @@ import os from "node:os";
|
|
|
18
18
|
import path from "node:path";
|
|
19
19
|
import readline from "node:readline";
|
|
20
20
|
import { fileURLToPath } from "node:url";
|
|
21
|
+
import {
|
|
22
|
+
parseCredentialsText,
|
|
23
|
+
parseDevCommandArgs,
|
|
24
|
+
resolveDevConnection,
|
|
25
|
+
runDevSession,
|
|
26
|
+
} from "./dev-session.mjs";
|
|
21
27
|
|
|
22
28
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
23
29
|
const pkgRoot = path.resolve(here, "..");
|
|
@@ -90,6 +96,7 @@ function usage() {
|
|
|
90
96
|
xevy setup [options] Choose credentials, pi, skills, and MCP setup
|
|
91
97
|
xevy update [--base u] Refresh the pi extensions + coding-agent skills/MCP
|
|
92
98
|
xevy check [--base u] Report skill updates or missing coding-agent targets
|
|
99
|
+
xevy dev <task> Attach to a remote task Dev Session
|
|
93
100
|
|
|
94
101
|
Options:
|
|
95
102
|
--base <url> Xevy host (default: XEVY_BASE or ${DEFAULT_BASE})
|
|
@@ -111,6 +118,7 @@ Examples:
|
|
|
111
118
|
npx @xevy/cli setup --credentials --mcp -a codex
|
|
112
119
|
npx @xevy/cli setup --all -y
|
|
113
120
|
npx @xevy/cli update
|
|
121
|
+
npx @xevy/cli dev VI22-07
|
|
114
122
|
npx @xevy/cli
|
|
115
123
|
|
|
116
124
|
Install globally to drop the npx prefix:
|
|
@@ -119,6 +127,23 @@ Install globally to drop the npx prefix:
|
|
|
119
127
|
xevy`);
|
|
120
128
|
}
|
|
121
129
|
|
|
130
|
+
function devUsage() {
|
|
131
|
+
console.log(`Xevy Dev Session
|
|
132
|
+
|
|
133
|
+
xevy dev <task-id-or-code> [--base <url>]
|
|
134
|
+
|
|
135
|
+
Connects this terminal to the task's remote Dev Session. The command attaches
|
|
136
|
+
to an existing session or starts one from an eligible Preview repository. It
|
|
137
|
+
does not run a local coding agent, shell, Docker container, or repository clone.
|
|
138
|
+
|
|
139
|
+
Inside the session:
|
|
140
|
+
/status /logs /open /finish /stop /detach /help
|
|
141
|
+
|
|
142
|
+
Credentials:
|
|
143
|
+
XEVY_API_KEY takes precedence over ~/.config/xevy/credentials.
|
|
144
|
+
Host precedence: --base, XEVY_BASE, saved baseUrl, https://xevy.ai.`);
|
|
145
|
+
}
|
|
146
|
+
|
|
122
147
|
function parseArgv(argv) {
|
|
123
148
|
const base = process.env.XEVY_BASE?.replace(/\/$/, "") || DEFAULT_BASE;
|
|
124
149
|
const args = [...argv];
|
|
@@ -129,6 +154,17 @@ function parseArgv(argv) {
|
|
|
129
154
|
if (first === "-h" || first === "--help" || first === "help") return { command: "help", base };
|
|
130
155
|
if (first === "-v" || first === "--version") return { command: "version", base };
|
|
131
156
|
|
|
157
|
+
if (first === "dev") {
|
|
158
|
+
args.shift();
|
|
159
|
+
try {
|
|
160
|
+
const parsed = parseDevCommandArgs(args);
|
|
161
|
+
if (parsed.help) return { command: "dev-help" };
|
|
162
|
+
return { command: "dev", taskReference: parsed.taskReference, base: parsed.base };
|
|
163
|
+
} catch (error) {
|
|
164
|
+
die(error instanceof Error ? error.message : String(error));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
132
168
|
if (first === "setup" || first === "update" || first === "check") {
|
|
133
169
|
const command = args.shift();
|
|
134
170
|
const opts = {
|
|
@@ -307,21 +343,23 @@ function writeCredentials(base, token) {
|
|
|
307
343
|
}
|
|
308
344
|
}
|
|
309
345
|
|
|
310
|
-
|
|
311
|
-
function readStoredToken() {
|
|
346
|
+
function readStoredCredentials() {
|
|
312
347
|
try {
|
|
313
|
-
if (!fs.existsSync(CREDENTIALS_FILE)) return null;
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
}
|
|
320
|
-
}
|
|
348
|
+
if (!fs.existsSync(CREDENTIALS_FILE)) return { baseUrl: null, token: null };
|
|
349
|
+
const parsed = parseCredentialsText(fs.readFileSync(CREDENTIALS_FILE, "utf-8"));
|
|
350
|
+
return {
|
|
351
|
+
baseUrl: parsed.baseUrl,
|
|
352
|
+
token: parsed.token?.startsWith(API_KEY_PREFIX) ? parsed.token : null,
|
|
353
|
+
};
|
|
321
354
|
} catch {
|
|
322
355
|
// ignore unreadable credentials
|
|
323
356
|
}
|
|
324
|
-
return null;
|
|
357
|
+
return { baseUrl: null, token: null };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Return the stored xevy_pk_ token from the credentials file, or null. */
|
|
361
|
+
function readStoredToken() {
|
|
362
|
+
return readStoredCredentials().token;
|
|
325
363
|
}
|
|
326
364
|
|
|
327
365
|
function readEnvironmentToken() {
|
|
@@ -332,7 +370,10 @@ function readEnvironmentToken() {
|
|
|
332
370
|
async function validateApiKey(base, token) {
|
|
333
371
|
let response;
|
|
334
372
|
try {
|
|
335
|
-
|
|
373
|
+
// `/api/auth/*` is intentionally session-only and rejects API keys.
|
|
374
|
+
// `/api/profile` is a lightweight authenticated endpoint that accepts both
|
|
375
|
+
// browser JWTs and API keys, making it suitable for credential validation.
|
|
376
|
+
response = await fetch(`${base}/api/profile`, {
|
|
336
377
|
headers: { Authorization: `Bearer ${token}` },
|
|
337
378
|
signal: AbortSignal.timeout(10_000),
|
|
338
379
|
});
|
|
@@ -607,14 +648,35 @@ function open(opts) {
|
|
|
607
648
|
process.exit(r.status ?? 0);
|
|
608
649
|
}
|
|
609
650
|
|
|
651
|
+
async function dev(opts) {
|
|
652
|
+
const stored = readStoredCredentials();
|
|
653
|
+
const { base, token } = resolveDevConnection({
|
|
654
|
+
explicitBase: opts.base,
|
|
655
|
+
environmentBase: process.env.XEVY_BASE,
|
|
656
|
+
storedBase: stored.baseUrl,
|
|
657
|
+
environmentToken: readEnvironmentToken(),
|
|
658
|
+
storedToken: stored.token,
|
|
659
|
+
});
|
|
660
|
+
if (!token) {
|
|
661
|
+
die("A Xevy API key is required. Run `xevy setup --credentials` first.");
|
|
662
|
+
}
|
|
663
|
+
await runDevSession({
|
|
664
|
+
base,
|
|
665
|
+
token,
|
|
666
|
+
taskReference: opts.taskReference,
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
|
|
610
670
|
async function main() {
|
|
611
671
|
const opts = parseArgv(process.argv.slice(2));
|
|
612
672
|
|
|
613
673
|
if (opts.command === "help") return usage();
|
|
674
|
+
if (opts.command === "dev-help") return devUsage();
|
|
614
675
|
if (opts.command === "version") return console.log(readCliVersion());
|
|
615
676
|
if (opts.command === "setup") return setup(opts);
|
|
616
677
|
if (opts.command === "update") return update(opts);
|
|
617
678
|
if (opts.command === "check") return check(opts);
|
|
679
|
+
if (opts.command === "dev") return dev(opts);
|
|
618
680
|
if (opts.command === "open") return open(opts);
|
|
619
681
|
}
|
|
620
682
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xevy/cli",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Xevy CLI —
|
|
3
|
+
"version": "0.1.12",
|
|
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": [
|
|
7
7
|
"xevy",
|