@dreamlake/dreamlake-cli 0.99.0 → 0.100.0
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/dist/cli/hosts/inventory.d.ts +28 -0
- package/dist/cli/hosts/inventory.js +68 -3
- package/dist/cli/hosts/picker.d.ts +34 -0
- package/dist/cli/hosts/picker.js +116 -0
- package/dist/cli/hosts/ssh.d.ts +16 -0
- package/dist/cli/hosts/ssh.js +47 -3
- package/dist/cli/version.d.ts +1 -1
- package/dist/cli/version.js +1 -1
- package/package.json +9 -9
|
@@ -33,8 +33,36 @@ export declare function listHosts(opts: {
|
|
|
33
33
|
}, request?: typeof hostRequest): Promise<HostInventory>;
|
|
34
34
|
/** A stored state without a verified runtime observation is not availability. */
|
|
35
35
|
export declare function hostConnection(enrollments?: HostEnrollmentStatus[]): string;
|
|
36
|
+
export declare function cell(value: unknown): string;
|
|
37
|
+
/** Column widths come from the plain text; `decorate` runs after padding so escape codes never shift columns. */
|
|
38
|
+
export declare function table(rows: string[][], decorate?: (value: string, row: number, column: number) => string): string;
|
|
36
39
|
export declare function formatHostsList(result: HostInventory, all?: boolean): string;
|
|
37
40
|
export declare function formatHostStatus(result: {
|
|
38
41
|
host: HostSummary;
|
|
39
42
|
enrollments?: HostEnrollmentStatus[];
|
|
40
43
|
}): string;
|
|
44
|
+
/**
|
|
45
|
+
* Bold and underline every case-insensitive occurrence; the surrounding text keeps the terminal's own
|
|
46
|
+
* colors. `reset` ends each highlight; a caller drawing inside another attribute passes `\x1b[22;24m`.
|
|
47
|
+
*/
|
|
48
|
+
export declare function highlightMatches(value: string, keyword: string, reset?: string): string;
|
|
49
|
+
export interface HostMatches {
|
|
50
|
+
keyword: string;
|
|
51
|
+
hosts: HostSummary[];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Hosts whose ID or name contains the keyword, case-insensitively, best match first. A
|
|
55
|
+
* `namespace/group/host` selector that matches nothing as a whole falls back to its last segment.
|
|
56
|
+
*/
|
|
57
|
+
export declare function matchHosts(hosts: HostSummary[], selector: string): HostMatches;
|
|
58
|
+
/**
|
|
59
|
+
* Shell-style completion of a typed host toward `name`: the next `/`-terminated prefix of `name` that
|
|
60
|
+
* is longer than `query` and still contains it (case-insensitively), or the whole name when none does.
|
|
61
|
+
* `bos14` → `team/bos14/` → `team/bos14/bos14-ctrl`; `te` → `team/` → `team/bos14/` → ….
|
|
62
|
+
*/
|
|
63
|
+
export declare function completeHostSegment(query: string, name: string): string;
|
|
64
|
+
export declare const HOST_MATCH_LIMIT = 20;
|
|
65
|
+
/** The `hosts list` columns for a set of hosts: header row first. */
|
|
66
|
+
export declare function hostRows(hosts: HostSummary[]): string[][];
|
|
67
|
+
/** The `hosts list` table restricted to keyword matches, for a terminal reader; `color` adds the highlight. */
|
|
68
|
+
export declare function formatHostMatches(result: HostInventory, matches: HostMatches, color: boolean, command?: string, limit?: number): string;
|
|
@@ -61,12 +61,13 @@ export function hostConnection(enrollments = []) {
|
|
|
61
61
|
return "unknown";
|
|
62
62
|
return enrollments.every(e => e.state === "offline") ? "offline" : "unknown";
|
|
63
63
|
}
|
|
64
|
-
function cell(value) {
|
|
64
|
+
export function cell(value) {
|
|
65
65
|
return typeof value === "string" && value ? value.replace(/[\x00-\x1f\x7f-\x9f]/g, " ") : "unknown";
|
|
66
66
|
}
|
|
67
|
-
|
|
67
|
+
/** Column widths come from the plain text; `decorate` runs after padding so escape codes never shift columns. */
|
|
68
|
+
export function table(rows, decorate = value => value) {
|
|
68
69
|
const widths = rows[0].map((_, i) => rows.reduce((width, row) => Math.max(width, row[i].length), 0));
|
|
69
|
-
return rows.map(row => row.map((value, i) => i === row.length - 1 ? value : value.padEnd(widths[i])).join(" ")).join("\n");
|
|
70
|
+
return rows.map((row, r) => row.map((value, i) => decorate(i === row.length - 1 ? value : value.padEnd(widths[i]), r, i)).join(" ")).join("\n");
|
|
70
71
|
}
|
|
71
72
|
export function formatHostsList(result, all = false) {
|
|
72
73
|
const rows = [["ID", "NAME", "CATALOG", "CONNECTION"], ...result.hosts.map(host => [cell(host.id), cell(host.name), cell(host.catalog?.catalogState), hostConnection(host.enrollments)])];
|
|
@@ -89,3 +90,67 @@ export function formatHostStatus(result) {
|
|
|
89
90
|
lines.push("No enrollments.");
|
|
90
91
|
return lines.join("\n");
|
|
91
92
|
}
|
|
93
|
+
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
94
|
+
/**
|
|
95
|
+
* Bold and underline every case-insensitive occurrence; the surrounding text keeps the terminal's own
|
|
96
|
+
* colors. `reset` ends each highlight; a caller drawing inside another attribute passes `\x1b[22;24m`.
|
|
97
|
+
*/
|
|
98
|
+
export function highlightMatches(value, keyword, reset = "\x1b[0m") {
|
|
99
|
+
if (!keyword)
|
|
100
|
+
return value;
|
|
101
|
+
return value.replace(new RegExp(escapeRegExp(keyword), "gi"), match => `\x1b[1;4m${match}${reset}`);
|
|
102
|
+
}
|
|
103
|
+
/** Exact name or host segment first, then names or host segments the keyword starts, then containing names, then IDs; inventory order within each. */
|
|
104
|
+
function matchRank(host, needle) {
|
|
105
|
+
const name = host.name.toLowerCase(), last = name.split("/").at(-1);
|
|
106
|
+
return name === needle || last === needle ? 0 : name.startsWith(needle) || last.startsWith(needle) ? 1 : name.includes(needle) ? 2 : 3;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Hosts whose ID or name contains the keyword, case-insensitively, best match first. A
|
|
110
|
+
* `namespace/group/host` selector that matches nothing as a whole falls back to its last segment.
|
|
111
|
+
*/
|
|
112
|
+
export function matchHosts(hosts, selector) {
|
|
113
|
+
const keywords = [...new Set([selector, selector.split("/").filter(Boolean).at(-1) ?? ""].filter(Boolean))];
|
|
114
|
+
for (const keyword of keywords) {
|
|
115
|
+
const needle = keyword.toLowerCase();
|
|
116
|
+
const matched = hosts.filter(host => host.id.toLowerCase().includes(needle) || host.name.toLowerCase().includes(needle))
|
|
117
|
+
.sort((a, b) => matchRank(a, needle) - matchRank(b, needle));
|
|
118
|
+
if (matched.length)
|
|
119
|
+
return { keyword, hosts: matched };
|
|
120
|
+
}
|
|
121
|
+
// Nothing matched even the broadest keyword tried; report that one.
|
|
122
|
+
return { keyword: keywords.at(-1) ?? selector, hosts: [] };
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Shell-style completion of a typed host toward `name`: the next `/`-terminated prefix of `name` that
|
|
126
|
+
* is longer than `query` and still contains it (case-insensitively), or the whole name when none does.
|
|
127
|
+
* `bos14` → `team/bos14/` → `team/bos14/bos14-ctrl`; `te` → `team/` → `team/bos14/` → ….
|
|
128
|
+
*/
|
|
129
|
+
export function completeHostSegment(query, name) {
|
|
130
|
+
const needle = query.toLowerCase();
|
|
131
|
+
const segments = name.split("/");
|
|
132
|
+
for (let i = 1; i < segments.length; i++) {
|
|
133
|
+
const prefix = segments.slice(0, i).join("/") + "/";
|
|
134
|
+
if (prefix.length > query.length && prefix.toLowerCase().includes(needle))
|
|
135
|
+
return prefix;
|
|
136
|
+
}
|
|
137
|
+
return name;
|
|
138
|
+
}
|
|
139
|
+
export const HOST_MATCH_LIMIT = 20;
|
|
140
|
+
/** The `hosts list` columns for a set of hosts: header row first. */
|
|
141
|
+
export function hostRows(hosts) {
|
|
142
|
+
return [["ID", "NAME", "CATALOG", "CONNECTION"], ...hosts.map(host => [cell(host.id), cell(host.name), cell(host.catalog?.catalogState), hostConnection(host.enrollments)])];
|
|
143
|
+
}
|
|
144
|
+
/** The `hosts list` table restricted to keyword matches, for a terminal reader; `color` adds the highlight. */
|
|
145
|
+
export function formatHostMatches(result, matches, color, command = "ssh", limit = HOST_MATCH_LIMIT) {
|
|
146
|
+
const quoted = JSON.stringify(matches.keyword);
|
|
147
|
+
if (!matches.hosts.length)
|
|
148
|
+
return `No hosts match ${quoted} in namespace ${result.namespace}. Run dreamlake hosts list --all to see every host.`;
|
|
149
|
+
const shown = matches.hosts.slice(0, limit);
|
|
150
|
+
const rows = hostRows(shown);
|
|
151
|
+
const decorate = (value, row, column) => color && row > 0 && column < 2 ? highlightMatches(value, matches.keyword) : value;
|
|
152
|
+
const more = matches.hosts.length > shown.length ? ` Showing ${shown.length}; narrow the keyword to see the rest.` : "";
|
|
153
|
+
const next = matches.hosts.length === 1 ? `Connect with: dreamlake ${command} ${cell(matches.hosts[0].name)}` : "Connect with the full NAME or ID.";
|
|
154
|
+
return [`Hosts matching ${quoted} in namespace ${result.namespace}:`, table(rows, decorate),
|
|
155
|
+
`${matches.hosts.length} of ${result.total} hosts match.${more} ${next}`].join("\n");
|
|
156
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type HostInventory, type HostMatches } from "./inventory.js";
|
|
2
|
+
/** The terminal a person is typing into. `process.stdin`/`process.stderr` in the CLI; any pair of streams in tests. */
|
|
3
|
+
export interface PickerIO {
|
|
4
|
+
input: NodeJS.ReadableStream & {
|
|
5
|
+
isTTY?: boolean;
|
|
6
|
+
setRawMode?: (mode: boolean) => unknown;
|
|
7
|
+
};
|
|
8
|
+
output: {
|
|
9
|
+
write(text: string): unknown;
|
|
10
|
+
columns?: number;
|
|
11
|
+
};
|
|
12
|
+
color: boolean;
|
|
13
|
+
}
|
|
14
|
+
export interface PickerState {
|
|
15
|
+
query: string;
|
|
16
|
+
cursor: number;
|
|
17
|
+
}
|
|
18
|
+
/** Matches for what is typed so far; an empty query lists the whole inventory. */
|
|
19
|
+
export declare function pickerMatches(inventory: HostInventory, query: string): HostMatches;
|
|
20
|
+
/** One frame of the picker: the command being built, the match table with the cursor row marked, and a count. */
|
|
21
|
+
export declare function renderPicker(inventory: HostInventory, selector: string, command: "ssh" | "exec", state: PickerState, color: boolean, limit?: number): string;
|
|
22
|
+
/** Pure key handling, so the loop and the tests share one definition. */
|
|
23
|
+
export declare function reducePicker(inventory: HostInventory, state: PickerState, key: string): {
|
|
24
|
+
state: PickerState;
|
|
25
|
+
done?: "pick" | "cancel";
|
|
26
|
+
};
|
|
27
|
+
/** Split a raw-mode chunk into keys: arrow sequences stay whole, everything else is one character per key. */
|
|
28
|
+
export declare function splitKeys(chunk: string): string[];
|
|
29
|
+
/**
|
|
30
|
+
* Interactive host picker for a selector that named no host. Lists keyword matches with the best one
|
|
31
|
+
* highlighted; typing filters, Tab completes toward the highlighted host one segment at a time, Enter
|
|
32
|
+
* resolves to that host's full name, and Esc or Ctrl-C resolves to undefined. Draws on `io.output`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function pickHost(inventory: HostInventory, selector: string, command: "ssh" | "exec", io: PickerIO): Promise<string | undefined>;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { HOST_MATCH_LIMIT, completeHostSegment, highlightMatches, hostRows, matchHosts, table } from "./inventory.js";
|
|
2
|
+
const ESC = "\x1b", INVERSE = "\x1b[7m", DIM = "\x1b[2m", RESET = "\x1b[0m";
|
|
3
|
+
const plainLength = (text) => text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").length;
|
|
4
|
+
/** Matches for what is typed so far; an empty query lists the whole inventory. */
|
|
5
|
+
export function pickerMatches(inventory, query) {
|
|
6
|
+
return query ? matchHosts(inventory.hosts, query) : { keyword: "", hosts: inventory.hosts };
|
|
7
|
+
}
|
|
8
|
+
/** One frame of the picker: the command being built, the match table with the cursor row marked, and a count. */
|
|
9
|
+
export function renderPicker(inventory, selector, command, state, color, limit = HOST_MATCH_LIMIT) {
|
|
10
|
+
const matches = pickerMatches(inventory, state.query);
|
|
11
|
+
const paint = (text, code) => color ? `${code}${text}${RESET}` : text;
|
|
12
|
+
const lines = [
|
|
13
|
+
paint(`Host ${JSON.stringify(selector)} not found. ↑↓ move · Tab complete · Enter connect · Esc cancel`, DIM),
|
|
14
|
+
`> dreamlake ${command} ${state.query}${paint("▏", DIM)}`,
|
|
15
|
+
];
|
|
16
|
+
if (!matches.hosts.length) {
|
|
17
|
+
lines.push(`No hosts match ${JSON.stringify(matches.keyword)} in namespace ${inventory.namespace}. Keep typing or press Esc.`);
|
|
18
|
+
return lines.join("\n");
|
|
19
|
+
}
|
|
20
|
+
const start = Math.max(0, Math.min(state.cursor - Math.floor(limit / 2), matches.hosts.length - limit));
|
|
21
|
+
const shown = matches.hosts.slice(start, start + limit);
|
|
22
|
+
const selectedRow = (row) => row > 0 && start + row - 1 === state.cursor;
|
|
23
|
+
// Inside the inverse cursor row the highlight ends with "bold/underline off" so the inverse survives.
|
|
24
|
+
const decorate = (value, row, column) => color && row > 0 && column < 2 ? highlightMatches(value, matches.keyword, selectedRow(row) ? "\x1b[22;24m" : RESET) : value;
|
|
25
|
+
lines.push(...table(hostRows(shown), decorate).split("\n").map((line, row) => selectedRow(row) ? `${paint("❯", "\x1b[32m")} ${color ? `${INVERSE}${line}${RESET}` : line}` : ` ${line}`));
|
|
26
|
+
const hidden = matches.hosts.length - shown.length;
|
|
27
|
+
lines.push(`${matches.hosts.length} of ${inventory.total} hosts match.${hidden ? ` Showing ${shown.length}; type more to narrow.` : ""}`);
|
|
28
|
+
return lines.join("\n");
|
|
29
|
+
}
|
|
30
|
+
/** Pure key handling, so the loop and the tests share one definition. */
|
|
31
|
+
export function reducePicker(inventory, state, key) {
|
|
32
|
+
const count = pickerMatches(inventory, state.query).hosts.length;
|
|
33
|
+
const clamp = (cursor) => Math.max(0, Math.min(cursor, count - 1));
|
|
34
|
+
if (key === `${ESC}[A`)
|
|
35
|
+
return { state: { ...state, cursor: clamp(state.cursor - 1) } };
|
|
36
|
+
if (key === `${ESC}[B`)
|
|
37
|
+
return { state: { ...state, cursor: clamp(state.cursor + 1) } };
|
|
38
|
+
if (key === ESC || key === "\x03" || key === "\x04")
|
|
39
|
+
return { state, done: "cancel" };
|
|
40
|
+
if (key === "\r" || key === "\n")
|
|
41
|
+
return count ? { state, done: "pick" } : { state };
|
|
42
|
+
if (key === "\t") {
|
|
43
|
+
const target = pickerMatches(inventory, state.query).hosts[clamp(state.cursor)];
|
|
44
|
+
return target ? { state: { query: completeHostSegment(state.query, target.name), cursor: 0 } } : { state };
|
|
45
|
+
}
|
|
46
|
+
if (key === "\x7f" || key === "\b")
|
|
47
|
+
return { state: { query: state.query.slice(0, -1), cursor: 0 } };
|
|
48
|
+
if (key === "\x15")
|
|
49
|
+
return { state: { query: "", cursor: 0 } };
|
|
50
|
+
if (key.length === 1 && key >= " " && key !== "\x7f")
|
|
51
|
+
return { state: { query: state.query + key, cursor: 0 } };
|
|
52
|
+
return { state };
|
|
53
|
+
}
|
|
54
|
+
/** Split a raw-mode chunk into keys: arrow sequences stay whole, everything else is one character per key. */
|
|
55
|
+
export function splitKeys(chunk) {
|
|
56
|
+
const keys = [];
|
|
57
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
58
|
+
if (chunk[i] === ESC && chunk[i + 1] === "[" && /[A-D]/.test(chunk[i + 2] ?? "")) {
|
|
59
|
+
keys.push(chunk.slice(i, i + 3));
|
|
60
|
+
i += 2;
|
|
61
|
+
}
|
|
62
|
+
else if (chunk[i] === ESC && chunk[i + 1] === "[") {
|
|
63
|
+
i = chunk.length;
|
|
64
|
+
} // An unknown CSI sequence; drop the rest of the chunk.
|
|
65
|
+
else
|
|
66
|
+
keys.push(chunk[i]);
|
|
67
|
+
}
|
|
68
|
+
return keys;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Interactive host picker for a selector that named no host. Lists keyword matches with the best one
|
|
72
|
+
* highlighted; typing filters, Tab completes toward the highlighted host one segment at a time, Enter
|
|
73
|
+
* resolves to that host's full name, and Esc or Ctrl-C resolves to undefined. Draws on `io.output`.
|
|
74
|
+
*/
|
|
75
|
+
export function pickHost(inventory, selector, command, io) {
|
|
76
|
+
let state = { query: selector, cursor: 0 };
|
|
77
|
+
let drawn = 0;
|
|
78
|
+
const draw = () => {
|
|
79
|
+
const width = io.output.columns;
|
|
80
|
+
const lines = renderPicker(inventory, selector, command, state, io.color).split("\n")
|
|
81
|
+
.map(line => width && plainLength(line) >= width ? line.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").slice(0, width - 1) : line);
|
|
82
|
+
io.output.write(`${drawn > 1 ? `${ESC}[${drawn - 1}A` : ""}\r${ESC}[0J${lines.join("\n")}`);
|
|
83
|
+
drawn = lines.length;
|
|
84
|
+
};
|
|
85
|
+
const clear = () => { io.output.write(`${drawn > 1 ? `${ESC}[${drawn - 1}A` : ""}\r${ESC}[0J${ESC}[?25h`); drawn = 0; };
|
|
86
|
+
const raw = io.input.isTTY && typeof io.input.setRawMode === "function";
|
|
87
|
+
return new Promise(resolve => {
|
|
88
|
+
const finish = (picked) => {
|
|
89
|
+
io.input.off("data", onData);
|
|
90
|
+
if (raw)
|
|
91
|
+
io.input.setRawMode(false);
|
|
92
|
+
io.input.pause();
|
|
93
|
+
clear();
|
|
94
|
+
if (picked !== undefined)
|
|
95
|
+
io.output.write(`dreamlake ${command} ${picked}\n`);
|
|
96
|
+
resolve(picked);
|
|
97
|
+
};
|
|
98
|
+
const onData = (chunk) => {
|
|
99
|
+
for (const key of splitKeys(chunk.toString())) {
|
|
100
|
+
const next = reducePicker(inventory, state, key);
|
|
101
|
+
state = next.state;
|
|
102
|
+
if (next.done === "cancel")
|
|
103
|
+
return finish(undefined);
|
|
104
|
+
if (next.done === "pick")
|
|
105
|
+
return finish(pickerMatches(inventory, state.query).hosts[state.cursor].name);
|
|
106
|
+
}
|
|
107
|
+
draw();
|
|
108
|
+
};
|
|
109
|
+
if (raw)
|
|
110
|
+
io.input.setRawMode(true);
|
|
111
|
+
io.input.on("data", onData);
|
|
112
|
+
io.input.resume();
|
|
113
|
+
io.output.write(`${ESC}[?25l`);
|
|
114
|
+
draw();
|
|
115
|
+
});
|
|
116
|
+
}
|
package/dist/cli/hosts/ssh.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { Duplex } from 'node:stream';
|
|
|
3
3
|
import WebSocket from 'ws';
|
|
4
4
|
import type { Command } from 'commander';
|
|
5
5
|
import { hostRequest } from './api.js';
|
|
6
|
+
import { type HostInventory } from './inventory.js';
|
|
6
7
|
/** Wait the server's Retry-After (capped at 5s) or exponential backoff, whichever is longer. */
|
|
7
8
|
export declare function busyRetryDelay(attempt: number, retryAt?: string, now?: number): number;
|
|
8
9
|
export interface SshTarget {
|
|
@@ -46,8 +47,23 @@ export interface SshIO {
|
|
|
46
47
|
socket: (url: string, ticket: string) => WebSocket;
|
|
47
48
|
spawn: (args: string[]) => ChildProcess;
|
|
48
49
|
chooseTarget?: (targets: SshTarget[]) => Promise<string>;
|
|
50
|
+
/** Whether a person is reading stderr; host suggestions and their highlight are terminal-only. */
|
|
51
|
+
terminal?: () => boolean;
|
|
52
|
+
/** Whether a person can also type (stdin is a terminal); only then does the picker replace the static list. */
|
|
53
|
+
interactive?: () => boolean;
|
|
54
|
+
/** The interactive picker: resolves to a full host name, or undefined when the person cancels. */
|
|
55
|
+
pick?: (inventory: HostInventory, selector: string, command: 'ssh' | 'exec') => Promise<string | undefined>;
|
|
49
56
|
}
|
|
50
57
|
export declare const defaultSshIO: SshIO;
|
|
58
|
+
/** Only a selector that named no host earns suggestions; auth, namespace and transport errors pass through unchanged. */
|
|
59
|
+
export declare function isHostLookupMiss(error: unknown): boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Every host in the namespace the selector points at (its first segment, else the configured one),
|
|
62
|
+
* for suggesting what a partial or misspelled selector meant. Throws when the inventory cannot be read.
|
|
63
|
+
*/
|
|
64
|
+
export declare function suggestionInventory(selector: string, opts: SshOptions, io?: SshIO): Promise<HostInventory>;
|
|
65
|
+
/** The `hosts list` table filtered to the selector's keyword, with every match highlighted, for a terminal reader who cannot type back. */
|
|
66
|
+
export declare function suggestHosts(selector: string, opts: SshOptions, command: 'ssh' | 'exec', io?: SshIO): Promise<string>;
|
|
51
67
|
export declare function chooseSshTarget(targets: SshTarget[], selector: string, opts: SshOptions, argv: string[] | undefined, choose?: SshIO['chooseTarget']): Promise<SshTarget>;
|
|
52
68
|
export declare function sshPublicKey(value: string): string;
|
|
53
69
|
export declare function validateSshTarget(t: SshTarget, hostId: string, namespace: string): void;
|
package/dist/cli/hosts/ssh.js
CHANGED
|
@@ -11,7 +11,8 @@ import WebSocket from 'ws';
|
|
|
11
11
|
import { select } from '@inquirer/prompts';
|
|
12
12
|
import { HostApiError, hostApiPath, hostRequest } from './api.js';
|
|
13
13
|
import { hostStatus } from './enroll.js';
|
|
14
|
-
import { resolveHostNamespace } from './inventory.js';
|
|
14
|
+
import { formatHostMatches, listHosts, matchHosts, resolveHostNamespace } from './inventory.js';
|
|
15
|
+
import { pickHost } from './picker.js';
|
|
15
16
|
const ID = /^[a-f0-9]{24}$/;
|
|
16
17
|
// Same budget as the browser relay: 4 delegation attempts within 25s.
|
|
17
18
|
const BUSY_MAX_ATTEMPTS = 4, BUSY_RETRY_BUDGET_MS = 25000;
|
|
@@ -21,11 +22,34 @@ export function busyRetryDelay(attempt, retryAt, now = Date.now()) {
|
|
|
21
22
|
return Math.max(Number.isFinite(hinted) ? hinted : 0, 1000 * 2 ** (attempt - 1));
|
|
22
23
|
}
|
|
23
24
|
export const defaultSshIO = {
|
|
24
|
-
request: hostRequest, fetch: (...args) => fetch(...args),
|
|
25
|
+
request: hostRequest, fetch: (...args) => fetch(...args), terminal: () => Boolean(process.stderr.isTTY),
|
|
26
|
+
interactive: () => Boolean(process.stdin.isTTY && process.stderr.isTTY),
|
|
27
|
+
pick: (inventory, selector, command) => pickHost(inventory, selector, command, { input: process.stdin, output: process.stderr, color: !process.env.NO_COLOR }),
|
|
25
28
|
socket: (url, ticket) => new WebSocket(url, 'nymph-ssh.v1', { headers: { Authorization: `Bearer ${ticket}` },
|
|
26
29
|
perMessageDeflate: false, maxPayload: 65537, handshakeTimeout: 10000, followRedirects: false }),
|
|
27
30
|
spawn: args => spawn('ssh', args, { stdio: 'inherit' }),
|
|
28
31
|
};
|
|
32
|
+
/** Only a selector that named no host earns suggestions; auth, namespace and transport errors pass through unchanged. */
|
|
33
|
+
export function isHostLookupMiss(error) {
|
|
34
|
+
if (error instanceof HostApiError)
|
|
35
|
+
return error.status === 403 || error.status === 404;
|
|
36
|
+
const message = error instanceof Error ? error.message : '';
|
|
37
|
+
return message.startsWith('Host selector must be') || message.startsWith('Host not found');
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Every host in the namespace the selector points at (its first segment, else the configured one),
|
|
41
|
+
* for suggesting what a partial or misspelled selector meant. Throws when the inventory cannot be read.
|
|
42
|
+
*/
|
|
43
|
+
export async function suggestionInventory(selector, opts, io = defaultSshIO) {
|
|
44
|
+
const parts = selector.split('/');
|
|
45
|
+
const namespace = parts.length === 3 && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(parts[0]) && !opts.namespace ? parts[0] : await resolveHostNamespace(opts.namespace);
|
|
46
|
+
return listHosts({ namespace, all: true }, io.request);
|
|
47
|
+
}
|
|
48
|
+
/** The `hosts list` table filtered to the selector's keyword, with every match highlighted, for a terminal reader who cannot type back. */
|
|
49
|
+
export async function suggestHosts(selector, opts, command, io = defaultSshIO) {
|
|
50
|
+
const inventory = await suggestionInventory(selector, opts, io);
|
|
51
|
+
return formatHostMatches(inventory, matchHosts(inventory.hosts, selector), !process.env.NO_COLOR, command);
|
|
52
|
+
}
|
|
29
53
|
export async function chooseSshTarget(targets, selector, opts, argv, choose) {
|
|
30
54
|
if (targets.length === 0)
|
|
31
55
|
throw new Error('No ready SSH enrollment for this host');
|
|
@@ -145,7 +169,27 @@ export async function runHostSsh(selector, opts, argv, io = defaultSshIO) {
|
|
|
145
169
|
throw new Error('--timeout must be 1–duration seconds');
|
|
146
170
|
if (opts.enrollment !== undefined && !ID.test(opts.enrollment))
|
|
147
171
|
throw new Error('Use an exact enrollment ID');
|
|
148
|
-
|
|
172
|
+
let detail;
|
|
173
|
+
try {
|
|
174
|
+
detail = await hostStatus(selector, opts, io.request);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
if (!isHostLookupMiss(error) || !io.terminal?.())
|
|
178
|
+
throw error;
|
|
179
|
+
const command = argv === undefined ? 'ssh' : 'exec';
|
|
180
|
+
const inventory = await suggestionInventory(selector, opts, io).catch(() => undefined);
|
|
181
|
+
if (!inventory)
|
|
182
|
+
throw error;
|
|
183
|
+
if (!io.interactive?.() || !io.pick) {
|
|
184
|
+
throw new Error(`${error instanceof Error ? error.message : 'Host lookup failed'}\n${formatHostMatches(inventory, matchHosts(inventory.hosts, selector), !process.env.NO_COLOR, command)}`);
|
|
185
|
+
}
|
|
186
|
+
// A person is typing: let them pick the host they meant. Cancelling keeps the original error and exit code.
|
|
187
|
+
const picked = await io.pick(inventory, selector, command);
|
|
188
|
+
if (picked === undefined)
|
|
189
|
+
throw error;
|
|
190
|
+
selector = picked;
|
|
191
|
+
detail = await hostStatus(selector, opts, io.request);
|
|
192
|
+
}
|
|
149
193
|
const namespace = selector.includes('/') ? selector.split('/')[0] : await resolveHostNamespace(opts.namespace);
|
|
150
194
|
if (!ID.test(detail?.host?.id) || !Array.isArray(detail.enrollments))
|
|
151
195
|
throw new Error('Invalid host response');
|
package/dist/cli/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
1
|
+
export declare const VERSION = "0.100.0";
|
package/dist/cli/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dreamlake/dreamlake-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.100.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/dreamlake-ai/dreamlake-cli.git"
|
|
@@ -35,13 +35,13 @@
|
|
|
35
35
|
"node": ">=18"
|
|
36
36
|
},
|
|
37
37
|
"optionalDependencies": {
|
|
38
|
-
"@dreamlake/dreamlake-cli-darwin-arm64": "0.
|
|
39
|
-
"@dreamlake/dreamlake-cli-darwin-x64": "0.
|
|
40
|
-
"@dreamlake/dreamlake-cli-linux-x64": "0.
|
|
41
|
-
"@dreamlake/dreamlake-cli-linux-arm64": "0.
|
|
42
|
-
"@dreamlake/dreamlake-cli-linux-x64-musl": "0.
|
|
43
|
-
"@dreamlake/dreamlake-cli-linux-arm64-musl": "0.
|
|
44
|
-
"@dreamlake/dreamlake-cli-win32-x64": "0.
|
|
45
|
-
"@dreamlake/dreamlake-cli-win32-arm64": "0.
|
|
38
|
+
"@dreamlake/dreamlake-cli-darwin-arm64": "0.100.0",
|
|
39
|
+
"@dreamlake/dreamlake-cli-darwin-x64": "0.100.0",
|
|
40
|
+
"@dreamlake/dreamlake-cli-linux-x64": "0.100.0",
|
|
41
|
+
"@dreamlake/dreamlake-cli-linux-arm64": "0.100.0",
|
|
42
|
+
"@dreamlake/dreamlake-cli-linux-x64-musl": "0.100.0",
|
|
43
|
+
"@dreamlake/dreamlake-cli-linux-arm64-musl": "0.100.0",
|
|
44
|
+
"@dreamlake/dreamlake-cli-win32-x64": "0.100.0",
|
|
45
|
+
"@dreamlake/dreamlake-cli-win32-arm64": "0.100.0"
|
|
46
46
|
}
|
|
47
47
|
}
|