@dreamlake/dreamlake-cli 0.104.2 → 0.104.4

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.
@@ -13,6 +13,7 @@ export interface ArtifactPushArgs extends DreamlakeOpts {
13
13
  entry?: string;
14
14
  site?: boolean;
15
15
  spa?: boolean;
16
+ siteConfig?: string;
16
17
  title?: string;
17
18
  kind?: string;
18
19
  artifactId?: string;
@@ -1,3 +1,4 @@
1
+ import { readSiteConfig } from './siteConfig.js';
1
2
  import { collectionList } from "../collection-list.js";
2
3
  import { registerShareCommands } from "../share.js";
3
4
  // `dreamlake artifact push|list|delete|restore`.
@@ -94,6 +95,8 @@ export async function runDreamlakeArtifactPush(args, deps = {}) {
94
95
  directory = stat.isDirectory();
95
96
  if (args.site && !directory)
96
97
  throw new Error('--site requires a built static directory');
98
+ if (args.siteConfig && !args.site)
99
+ throw new Error('--site-config requires --site');
97
100
  if (args.spa && !args.site)
98
101
  throw new Error('--spa requires --site');
99
102
  if (!directory && !stat.isFile())
@@ -106,7 +109,7 @@ export async function runDreamlakeArtifactPush(args, deps = {}) {
106
109
  fail("incremental artifacts are limited to 512 MiB");
107
110
  return 1;
108
111
  }
109
- site = args.site ? collectSite(args.file, args.entry, args.spa) : undefined;
112
+ site = args.site ? collectSite(args.file, args.entry, args.spa, readSiteConfig(args.siteConfig)) : undefined;
110
113
  content = site ? site.content : directory ? packPages(args.file, args.entry) : readFileSync(args.file);
111
114
  }
112
115
  catch (error) {
@@ -150,7 +153,9 @@ export async function runDreamlakeArtifactPush(args, deps = {}) {
150
153
  return 1;
151
154
  if (site) {
152
155
  const capability = await jsonRequest('GET', `${ctx.remote}/artifacts/site-capabilities`, token);
153
- if (capability.status !== 200 || capability.body?.schema !== 'dreamlake-artifact-files/1') {
156
+ const caps = capability.body;
157
+ const needsPublicData = site.manifest.schema === 'dreamlake-artifact-files/2';
158
+ if (capability.status !== 200 || caps?.schema !== 'dreamlake-artifact-files/1' || (needsPublicData && (!caps.supportedSchemas?.includes('dreamlake-artifact-files/2') || caps.features?.publicDataOrigins !== true))) {
154
159
  fail('Static artifact hosting is unavailable on this server; no files were uploaded.');
155
160
  return 1;
156
161
  }
@@ -224,6 +229,12 @@ export async function runDreamlakeArtifactPush(args, deps = {}) {
224
229
  let storedContent = content;
225
230
  if (site) {
226
231
  const result = await uploadSite(site, backend);
232
+ if (site.manifest.schema === 'dreamlake-artifact-files/2') {
233
+ const grant = await jsonRequest('POST', `${ctx.remote}/namespaces/${encodeURIComponent(namespace)}/artifacts/${encodeURIComponent(artifactId)}/site-public-data-grants`, token, { manifest: site.hash });
234
+ const binding = grant.body;
235
+ if (grant.status !== 200 || binding?.manifest !== site.hash || JSON.stringify(binding.origins) !== JSON.stringify(site.manifest.network?.publicDataOrigins))
236
+ throw new Error('Public data authorization failed; no artifact version was published. Owner or Project ADMIN access is required.');
237
+ }
227
238
  process.stdout.write(` site: ${site.manifest.files.length} files, ${result.uploadedFiles} new files, ${result.uploadedBytes} bytes uploaded\n`);
228
239
  }
229
240
  else if (incremental) {
@@ -403,6 +414,7 @@ export function registerArtifactCommand(program) {
403
414
  .argument("<file>", "file or self-contained HTML page directory to push")
404
415
  .option("--entry <path>", "entry page for a directory (default: index.html)")
405
416
  .option("--site", "upload a static build with files loaded on demand (requires site hosting)")
417
+ .option("--site-config <file>", "site network configuration (default: ./artifact.config.json when present)")
406
418
  .option("--spa", "serve the site entry for extensionless client routes (requires --site)")
407
419
  .option("--title <title>", "human title (default: file stem)")
408
420
  .option("--kind <kind>", "html, react, markdown, svg, code, mermaid (default: auto)")
@@ -1,7 +1,7 @@
1
1
  import { type DreamdbBackend, type UploadFile } from '../compat/s3-backend.js';
2
2
  import { type SiteManifest } from './siteFormat.js';
3
3
  /** Snapshot the manifest before any network writes; retain file metadata, not media buffers. */
4
- export declare function collectSite(directory: string, entry?: string, spa?: boolean): {
4
+ export declare function collectSite(directory: string, entry?: string, spa?: boolean, publicDataOrigins?: string[]): {
5
5
  manifest: SiteManifest;
6
6
  objects: Map<string, UploadFile>;
7
7
  json: Buffer<ArrayBuffer>;
@@ -2,7 +2,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, read
2
2
  import path from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { S3_SINGLE_PUT_MAX_BYTES } from '../compat/s3-backend.js';
5
- import { encodeSiteDescriptor, SITE_MAX_FILES, SITE_MANIFEST_MAX_BYTES, siteFileKey, siteManifestKey, validSitePath, validateSiteManifest } from './siteFormat.js';
5
+ import { encodeSiteDescriptor, SITE_MAX_FILES, SITE_MANIFEST_MAX_BYTES, siteFileKey, siteManifestKey, validSitePath, validateSiteManifest, validatePublicDataOrigins } from './siteFormat.js';
6
6
  const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
7
7
  /** Hash with bounded memory; a signed upload rejects source changes before publication. */
8
8
  function inspectFile(file, html) {
@@ -35,10 +35,15 @@ function inspectFile(file, html) {
35
35
  }
36
36
  }
37
37
  /** Snapshot the manifest before any network writes; retain file metadata, not media buffers. */
38
- export function collectSite(directory, entry = 'index.html', spa = false) {
38
+ export function collectSite(directory, entry = 'index.html', spa = false, publicDataOrigins = []) {
39
39
  if (!lstatSync(directory).isDirectory())
40
40
  throw new Error('Site must be a directory, not a symlink');
41
41
  const manifest = { schema: 'dreamlake-artifact-files/1', entry, spa, files: [] };
42
+ const origins = validatePublicDataOrigins(publicDataOrigins);
43
+ if (origins.length) {
44
+ manifest.schema = 'dreamlake-artifact-files/2';
45
+ manifest.network = { publicDataOrigins: origins };
46
+ }
42
47
  const objects = new Map();
43
48
  let bytes = 0;
44
49
  let visited = 0;
@@ -79,7 +84,7 @@ export function collectSite(directory, entry = 'index.html', spa = false) {
79
84
  if (json.length > SITE_MANIFEST_MAX_BYTES)
80
85
  throw new Error('Artifact manifest exceeds 2 MiB');
81
86
  const hash = sha(json);
82
- return { manifest, objects, json, hash, content: Buffer.from(encodeSiteDescriptor(hash)), bytes };
87
+ return { manifest, objects, json, hash, content: Buffer.from(encodeSiteDescriptor(hash, manifest.schema)), bytes };
83
88
  }
84
89
  /** Conditional immutable writes; publish the manifest only after every file exists. */
85
90
  export async function uploadSite(site, backend) {
@@ -98,12 +103,27 @@ export async function uploadSite(site, backend) {
98
103
  throw new Error('Artifact file upload conflict; retry the push');
99
104
  return result.status === 'created';
100
105
  }
106
+ /*
107
+ * One bounded batched storage query when supported, as the chunked path
108
+ * already does. Each worker used to spend a round trip asking whether a file
109
+ * was already there and a second uploading it, with the question occupying an
110
+ * upload slot — a 50-file push paid 50 such pairs across 8 slots. Site object
111
+ * keys are content-addressed under one prefix, so a single scoped listing
112
+ * answers all of them.
113
+ *
114
+ * Older or custom backends keep their per-object HEAD path, and the batched
115
+ * query itself falls back to parallel HEADs whenever the listing cannot
116
+ * prove absence.
117
+ */
118
+ const existing = backend.hasMany && entries.length
119
+ ? await backend.hasMany(entries.map(([hash]) => siteFileKey(hash)))
120
+ : null;
101
121
  await Promise.all(Array.from({ length: Math.min(8, entries.length) }, async () => {
102
122
  while (next < entries.length && !failure) {
103
123
  const [hash, data] = entries[next++];
104
124
  try {
105
125
  const key = siteFileKey(hash);
106
- if ((await backend.head(key)).exists)
126
+ if (existing ? existing.has(key) : (await backend.head(key)).exists)
107
127
  continue;
108
128
  const result = await backend.putFile(key, data, { ifNoneMatchStar: true });
109
129
  if (result.status !== 'created' && !(await backend.head(key)).exists)
@@ -0,0 +1 @@
1
+ export declare function readSiteConfig(file?: string): string[];
@@ -0,0 +1,15 @@
1
+ import { existsSync, lstatSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { validatePublicDataOrigins } from './siteFormat.js';
4
+ export function readSiteConfig(file) {
5
+ const target = file ?? path.resolve('artifact.config.json');
6
+ if (!file && !existsSync(target))
7
+ return [];
8
+ const stat = lstatSync(target);
9
+ if (!stat.isFile() || stat.size > 16 * 1024)
10
+ throw new Error('Site configuration must be a regular file of at most 16 KiB');
11
+ const config = JSON.parse(readFileSync(target, 'utf8'));
12
+ if (config?.schema !== 'dreamlake-artifact-config/1' || Object.keys(config).some(key => !['schema', 'network'].includes(key)) || !config.network || Object.keys(config.network).some(key => key !== 'publicDataOrigins'))
13
+ throw new Error('Invalid artifact site configuration');
14
+ return validatePublicDataOrigins(config.network.publicDataOrigins);
15
+ }
@@ -1,4 +1,5 @@
1
1
  export declare const SITE_PREFIX = "<!--DREAMLAKE-ARTIFACT-FILES/1-->\n<script type=\"application/json\" id=\"dreamlake-artifact-files\">";
2
+ export declare const SITE_V2_PREFIX: string;
2
3
  export declare const SITE_SUFFIX = "</script>\n<p>This artifact requires a viewer with static-site support.</p>";
3
4
  export declare const SITE_MAX_FILES = 4096;
4
5
  export declare const SITE_MANIFEST_MAX_BYTES: number;
@@ -8,7 +9,10 @@ export interface SiteFile {
8
9
  size: number;
9
10
  }
10
11
  export interface SiteManifest {
11
- schema: 'dreamlake-artifact-files/1';
12
+ schema: 'dreamlake-artifact-files/1' | 'dreamlake-artifact-files/2';
13
+ network?: {
14
+ publicDataOrigins: string[];
15
+ };
12
16
  entry: string;
13
17
  spa: boolean;
14
18
  files: SiteFile[];
@@ -19,7 +23,8 @@ export interface SiteDescriptor {
19
23
  export declare const isHash: (s: unknown) => s is string;
20
24
  export declare function validSitePath(s: unknown): s is string;
21
25
  export declare function validateSiteManifest(value: unknown): SiteManifest;
22
- export declare function encodeSiteDescriptor(manifest: string): string;
26
+ export declare function encodeSiteDescriptor(manifest: string, schema?: SiteManifest['schema']): string;
23
27
  export declare function decodeSiteDescriptor(content: string): SiteDescriptor | null;
24
28
  export declare const siteManifestKey: (hash: string) => string;
25
29
  export declare const siteFileKey: (hash: string) => string;
30
+ export declare function validatePublicDataOrigins(value: unknown): string[];
@@ -1,6 +1,7 @@
1
1
  // Wire contract shared with dreamlake-server/src/services/artifactSiteFormat.ts
2
2
  // and dreamlake-ai/frame/siteFormat.ts. Never change v1 in place.
3
3
  export const SITE_PREFIX = '<!--DREAMLAKE-ARTIFACT-FILES/1-->\n<script type="application/json" id="dreamlake-artifact-files">';
4
+ export const SITE_V2_PREFIX = SITE_PREFIX.replace('FILES/1', 'FILES/2');
4
5
  export const SITE_SUFFIX = '</script>\n<p>This artifact requires a viewer with static-site support.</p>';
5
6
  export const SITE_MAX_FILES = 4096;
6
7
  export const SITE_MANIFEST_MAX_BYTES = 2 * 1024 * 1024;
@@ -13,10 +14,17 @@ export function validSitePath(s) {
13
14
  }
14
15
  export function validateSiteManifest(value) {
15
16
  const m = value;
16
- if (!m || m.schema !== 'dreamlake-artifact-files/1' || !validSitePath(m.entry) ||
17
+ if (!m || !['dreamlake-artifact-files/1', 'dreamlake-artifact-files/2'].includes(m.schema) || !validSitePath(m.entry) ||
17
18
  !/\.html?$/i.test(m.entry) || typeof m.spa !== 'boolean' || !Array.isArray(m.files) ||
18
19
  !m.files.length || m.files.length > SITE_MAX_FILES)
19
20
  throw new Error('Invalid artifact site manifest');
21
+ if (m.schema === 'dreamlake-artifact-files/2') {
22
+ const origins = validatePublicDataOrigins(m.network?.publicDataOrigins);
23
+ if (!origins.length || JSON.stringify(origins) !== JSON.stringify(m.network?.publicDataOrigins))
24
+ throw new Error('Non-canonical public data origins');
25
+ }
26
+ else if (m.network !== undefined)
27
+ throw new Error('Network declarations require artifact site v2');
20
28
  const paths = new Set();
21
29
  let total = 0;
22
30
  for (const f of m.files) {
@@ -34,20 +42,34 @@ export function validateSiteManifest(value) {
34
42
  throw new Error('Artifact entry page is missing');
35
43
  return m;
36
44
  }
37
- export function encodeSiteDescriptor(manifest) {
45
+ export function encodeSiteDescriptor(manifest, schema = 'dreamlake-artifact-files/1') {
38
46
  if (!isHash(manifest))
39
47
  throw new Error('Invalid artifact manifest hash');
40
- return SITE_PREFIX + JSON.stringify({ manifest }) + SITE_SUFFIX;
48
+ return (schema === 'dreamlake-artifact-files/2' ? SITE_V2_PREFIX : SITE_PREFIX) + JSON.stringify({ manifest }) + SITE_SUFFIX;
41
49
  }
42
50
  export function decodeSiteDescriptor(content) {
43
51
  if (!content.startsWith('<!--DREAMLAKE-ARTIFACT-FILES/'))
44
52
  return null;
45
- if (!content.startsWith(SITE_PREFIX) || !content.endsWith(SITE_SUFFIX) || content.length > 4096)
53
+ const prefix = content.startsWith(SITE_V2_PREFIX) ? SITE_V2_PREFIX : SITE_PREFIX;
54
+ if (!content.startsWith(prefix) || !content.endsWith(SITE_SUFFIX) || content.length > 4096)
46
55
  throw new Error('Unsupported artifact site format');
47
- const value = JSON.parse(content.slice(SITE_PREFIX.length, -SITE_SUFFIX.length));
56
+ const value = JSON.parse(content.slice(prefix.length, -SITE_SUFFIX.length));
48
57
  if (!isHash(value?.manifest))
49
58
  throw new Error('Invalid artifact manifest hash');
50
59
  return { manifest: value.manifest };
51
60
  }
52
61
  export const siteManifestKey = (hash) => `artifact-files/v1/manifests/${hash}.json`;
53
62
  export const siteFileKey = (hash) => `artifact-files/v1/objects/${hash}`;
63
+ export function validatePublicDataOrigins(value) {
64
+ if (!Array.isArray(value) || value.length > 16)
65
+ throw new Error('publicDataOrigins must contain at most 16 HTTPS origins');
66
+ const origins = value.map(origin => {
67
+ if (typeof origin !== 'string' || origin.length > 2048)
68
+ throw new Error('Invalid public data origin');
69
+ const url = new URL(origin);
70
+ if (url.protocol !== 'https:' || url.port || !/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(url.hostname) || url.username || url.password || url.search || url.hash || url.pathname !== '/' || origin.includes('*') || url.hostname === 'localhost' || url.hostname.endsWith('.localhost') || url.hostname.includes(':') || /^\d+\.\d+\.\d+\.\d+$/.test(url.hostname))
71
+ throw new Error('Public data origins require exact HTTPS hostnames without paths or credentials');
72
+ return url.origin;
73
+ });
74
+ return [...new Set(origins)].sort();
75
+ }
@@ -30,8 +30,17 @@ function unquote(etag) {
30
30
  return undefined;
31
31
  return etag.replace(/^"|"$/g, "");
32
32
  }
33
- const CHUNK_KEY = /^artifact-chunks\/v1\/[a-f0-9]{64}\.gz$/;
34
- const CHUNK_PREFIX = 'artifact-chunks/v1/';
33
+ /*
34
+ * Key families a single scoped LIST can resolve.
35
+ *
36
+ * Both are content-addressed under their own prefix, so one listing answers
37
+ * every question about a whole push. A batch must be uniform: the listing takes
38
+ * one prefix, and mixing families would leave half the keys unresolved.
39
+ */
40
+ const EXISTENCE_FAMILIES = [
41
+ { pattern: /^artifact-chunks\/v1\/[a-f0-9]{64}\.gz$/, prefix: 'artifact-chunks/v1/' },
42
+ { pattern: /^artifact-files\/v1\/objects\/[a-f0-9]{64}$/, prefix: 'artifact-files/v1/objects/' },
43
+ ];
35
44
  const EXISTENCE_CONCURRENCY = 8;
36
45
  const EXISTENCE_LIST_PAGES = 4;
37
46
  const EXISTENCE_LIST_BYTES = 2 * 1024 * 1024;
@@ -174,7 +183,8 @@ export class S3Backend {
174
183
  throw failure;
175
184
  return found;
176
185
  };
177
- if (wanted.size <= EXISTENCE_CONCURRENCY || [...wanted].some(key => !CHUNK_KEY.test(key)))
186
+ const family = EXISTENCE_FAMILIES.find(candidate => [...wanted].every(key => candidate.pattern.test(key)));
187
+ if (wanted.size <= EXISTENCE_CONCURRENCY || !family)
178
188
  return probeRemaining();
179
189
  const base = new URL(this.base);
180
190
  const segments = base.pathname.replace(/^\/+|\/+$/g, '').split('/');
@@ -183,7 +193,7 @@ export class S3Backend {
183
193
  return probeRemaining();
184
194
  const datasetPrefix = decodeURIComponent(segments.join('/'));
185
195
  const relativePrefix = datasetPrefix ? `${datasetPrefix}/` : '';
186
- const prefix = `${relativePrefix}${CHUNK_PREFIX}`;
196
+ const prefix = `${relativePrefix}${family.prefix}`;
187
197
  const seenTokens = new Set();
188
198
  let token;
189
199
  for (let page = 0; page < EXISTENCE_LIST_PAGES; page++) {
@@ -195,14 +205,14 @@ export class S3Backend {
195
205
  if (!response.ok) {
196
206
  const code = xmlValue(text, 'Code');
197
207
  if (['ExpiredToken', 'InvalidToken', 'InvalidAccessKeyId', 'SignatureDoesNotMatch', 'TokenRefreshRequired', 'RequestExpired'].includes(code ?? ''))
198
- throw new Error(`LIST artifact chunks → ${response.status} (${code})`);
208
+ throw new Error(`LIST ${family.prefix} → ${response.status} (${code})`);
199
209
  // Some compatible stores deny listing but permit scoped object reads.
200
210
  // Expired credentials, signature errors and transient failures propagate.
201
211
  if ((response.status === 403 && (!code || code === 'AccessDenied')) ||
202
212
  response.status === 405 || response.status === 501 ||
203
213
  (response.status === 400 && ['NotImplemented', 'NotSupported', 'UnsupportedOperation'].includes(code ?? '')))
204
214
  return probeRemaining();
205
- throw new Error(`LIST artifact chunks → ${response.status}${code ? ` (${code})` : ''}`);
215
+ throw new Error(`LIST ${family.prefix} → ${response.status}${code ? ` (${code})` : ''}`);
206
216
  }
207
217
  if (/<!DOCTYPE|<!ENTITY/i.test(text) || !/<ListBucketResult(?:\s[^>]*)?>/.test(text) || !/<\/ListBucketResult>\s*$/.test(text))
208
218
  throw new Error('Invalid S3 listing response');
@@ -34,7 +34,7 @@ export const helpExamples = {
34
34
  "experiments binding": "dreamlake experiments binding --namespace fortyfive --json",
35
35
  "experiments connect": "dreamlake experiments connect research --namespace fortyfive --json\n# Apply only after reviewing the preview. Use its actual revision, not this example's 0.\ndreamlake experiments connect \"$DASH_NAMESPACE_ID\" --namespace fortyfive --instance-id \"$DASH_INSTANCE_ID\" --apply --expected-revision 0 --json",
36
36
  "experiments disconnect": "dreamlake experiments disconnect --namespace fortyfive --json\n# Replace 1 with the revision returned by this preview.\ndreamlake experiments disconnect --namespace fortyfive --apply --expected-revision 1 --json",
37
- "hosts list": "dreamlake hosts list\ndreamlake hosts list --namespace geyang --group workstations\ndreamlake hosts list --json\ndreamlake hosts list --all",
37
+ "hosts list": "dreamlake hosts list\ndreamlake hosts list --namespace geyang --group workstations\ndreamlake hosts list --json\ndreamlake hosts list --all\ndreamlake hosts list --wide\ndreamlake hosts --fields\ndreamlake hosts --format '{name} {user} {ips} {network_freshness}'\ndreamlake hosts --probe --format '{name} {ip} {public_ip} {macs} {uptime}'",
38
38
  "hosts status": "dreamlake hosts status geyang/workstations/worker\ndreamlake hosts status HOST_ID --namespace geyang --json\ndreamlake hosts status 'geyang/workstations/*' --page 2 --page-size 100 --json",
39
39
  "hosts lifecycle": "dreamlake hosts lifecycle HOST_ID --namespace geyang --json",
40
40
  "hosts archive": "dreamlake hosts archive HOST_ID --namespace geyang --request-id archive-example-1 --expected-revision 0 --json",
@@ -1,3 +1,5 @@
1
+ import { HOST_FIELDS, DEFAULT_HOST_FORMAT, formatHostFields, validateHostFormat } from './view.js';
2
+ import { probeHostInventory } from './probe.js';
1
3
  import { registerHostRenameCommand } from './rename.js';
2
4
  import { registerHostMoveCommand } from './move.js';
3
5
  import { collectionList } from "../collection-list.js";
@@ -139,11 +141,30 @@ export function registerHostsCommand(program) {
139
141
  .option("--group <group>", "limit to one group")
140
142
  .option("--archived <mode>", "catalog visibility: exclude (default), include, or only")
141
143
  .option("--all", "include offline hosts and hosts with unknown connection state")
144
+ .option("--wide", "also show enrollment ID, OS, architecture, CPU count, Nymph version, and last seen")
145
+ .option("--format <template>", "one line per enrollment using {field} placeholders; see --fields")
146
+ .option("--fields", "list format placeholders without contacting hosts")
147
+ .option("--probe", "inspect IPs, MACs, public egress IP and uptime over SSH (Python 3 required)")
142
148
  .option("--json", "emit machine-readable output")
143
149
  .action(async (opts) => {
144
150
  try {
145
- const result = await listHosts({ namespace: await resolveHostNamespace(opts.namespace), group: opts.group, archived: opts.archived, all: opts.all });
146
- console.log(opts.json ? JSON.stringify(result, null, 2) : formatHostsList(result, opts.all));
151
+ if (opts.fields) {
152
+ if (opts.format !== undefined || opts.probe || opts.wide)
153
+ throw new Error('--fields cannot be combined with --format, --probe or --wide');
154
+ console.log(opts.json ? JSON.stringify({ fields: HOST_FIELDS, default: DEFAULT_HOST_FORMAT }, null, 2) : formatHostFields());
155
+ return;
156
+ }
157
+ if (opts.format !== undefined) {
158
+ if (opts.json || opts.wide)
159
+ throw new Error('Choose --format, --wide or --json');
160
+ validateHostFormat(opts.format);
161
+ }
162
+ let result = await listHosts({ namespace: await resolveHostNamespace(opts.namespace), group: opts.group, archived: opts.archived, all: opts.all });
163
+ if (opts.probe)
164
+ result = await probeHostInventory(result);
165
+ console.log(opts.json ? JSON.stringify(result, null, 2) : formatHostsList(result, opts.all, opts.wide, Date.now(), opts.format));
166
+ if (opts.probe && result.hosts.some(h => h.enrollments?.some(e => ['error', 'partial'].includes(e.probe?.status ?? ''))))
167
+ process.exitCode = 1;
147
168
  }
148
169
  catch (error) {
149
170
  const message = error instanceof Error ? error.message : "Host listing failed";
@@ -1,12 +1,32 @@
1
+ import { type HostProbe } from './view.js';
1
2
  import { hostRequest } from "./api.js";
2
3
  export declare function resolveHostNamespace(explicit?: string): Promise<string>;
3
4
  export interface HostEnrollmentStatus {
4
5
  id: string;
5
6
  machineId?: string;
7
+ lakeshoreId?: string;
8
+ connectedAt?: string | null;
9
+ probe?: HostProbe;
6
10
  unixUser?: string;
7
11
  state?: string;
8
12
  statusVerified?: boolean;
9
13
  lastSeenAt?: string | null;
14
+ hostname?: string | null;
15
+ network?: {
16
+ observedAt: string;
17
+ addresses: {
18
+ interface: string;
19
+ address: string;
20
+ family: "IPv4" | "IPv6";
21
+ }[];
22
+ } | null;
23
+ system?: {
24
+ os: string | null;
25
+ arch: string | null;
26
+ cpuModel: string | null;
27
+ cpuCores: number | null;
28
+ nymphVersion: string | null;
29
+ } | null;
10
30
  }
11
31
  export interface HostSummary {
12
32
  namespaceId?: string;
@@ -39,11 +59,23 @@ export declare function hostConnection(enrollments?: HostEnrollmentStatus[]): st
39
59
  export declare function cell(value: unknown): string;
40
60
  /** Column widths come from the plain text; `decorate` runs after padding so escape codes never shift columns. */
41
61
  export declare function table(rows: string[][], decorate?: (value: string, row: number, column: number) => string): string;
42
- export declare function formatHostsList(result: HostInventory, all?: boolean): string;
62
+ /** Inventory is an observation, never an SSH destination or proof of reachability. */
63
+ export declare function networkView(enrollment: HostEnrollmentStatus, now: number): {
64
+ addresses: {
65
+ interface: string;
66
+ address: string;
67
+ family: "IPv4" | "IPv6";
68
+ }[];
69
+ freshness: string;
70
+ source: string;
71
+ observedAt: string;
72
+ text: string;
73
+ };
74
+ export declare function formatHostsList(result: HostInventory, all?: boolean, wide?: boolean, now?: number, format?: string): string;
43
75
  export declare function formatHostStatus(result: {
44
76
  host: HostSummary;
45
77
  enrollments?: HostEnrollmentStatus[];
46
- }): string;
78
+ }, now?: number): string;
47
79
  /**
48
80
  * Bold and underline every case-insensitive occurrence; the surrounding text keeps the terminal's own
49
81
  * colors. `reset` ends each highlight; a caller drawing inside another attribute passes `\x1b[22;24m`.
@@ -1,5 +1,7 @@
1
+ import { renderHostRows } from './view.js';
1
2
  import { resolveNamespace, resolveRemote, resolveToken } from "../config.js";
2
3
  import { hostApiPath, hostRequest } from "./api.js";
4
+ import { isIP } from "node:net";
3
5
  const segment = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
4
6
  export async function resolveHostNamespace(explicit) {
5
7
  if (explicit !== undefined) {
@@ -69,11 +71,31 @@ export function table(rows, decorate = value => value) {
69
71
  const widths = rows[0].map((_, i) => rows.reduce((width, row) => Math.max(width, row[i].length), 0));
70
72
  return rows.map((row, r) => row.map((value, i) => decorate(i === row.length - 1 ? value : value.padEnd(widths[i]), r, i)).join(" ")).join("\n");
71
73
  }
72
- export function formatHostsList(result, all = false) {
73
- const rows = [["ID", "NAME", "CATALOG", "CONNECTION"], ...result.hosts.map(host => [cell(host.id), cell(host.name), cell(host.catalog?.catalogState), hostConnection(host.enrollments)])];
74
- return `Namespace: ${result.namespace}\n${table(rows)}\n${result.total} hosts. ${result.group ? `Group: ${result.group}.` : "All groups."} All pages.\n${all ? "All connection states." : "Active (verified online) only. Use --all to include offline and unknown hosts."}`;
74
+ /** Inventory is an observation, never an SSH destination or proof of reachability. */
75
+ export function networkView(enrollment, now) {
76
+ const p = enrollment.probe;
77
+ const probeNetwork = p && ['ok', 'partial'].includes(p.status) && p.observedAt && p.interfaces && (p.status === 'ok' || p.interfaces.length)
78
+ ? { observedAt: p.observedAt, addresses: p.interfaces.flatMap(i => i.ips.map(address => ({ interface: i.name, address, family: isIP(address) === 4 ? 'IPv4' : 'IPv6' }))) }
79
+ : null;
80
+ const network = enrollment.statusVerified === true ? probeNetwork ?? enrollment.network : null;
81
+ const sampled = typeof network?.observedAt === "string" ? Date.parse(network.observedAt) : NaN;
82
+ if (!network || !Number.isFinite(sampled) || sampled > now + 5000 || !Array.isArray(network.addresses)) {
83
+ return { addresses: [], freshness: "unknown", observedAt: "unknown", source: "unknown", text: "unknown" };
84
+ }
85
+ const addresses = network.addresses.filter(a => a && typeof a.interface === "string" && typeof a.address === "string" && isIP(a.address));
86
+ if (network.addresses.length && !addresses.length)
87
+ return { addresses: [], freshness: "unknown", observedAt: "unknown", source: "unknown", text: "unknown" };
88
+ const freshness = enrollment.state !== "online" || now - sampled > 90_000 ? "stale" : "fresh";
89
+ const ips = [...new Set(addresses.map(a => a.address))].join(", ") || "none";
90
+ return { addresses, freshness, source: network === probeNetwork ? "ssh" : "inventory", observedAt: new Date(sampled).toISOString(), text: `${ips}${freshness === "stale" ? " (stale)" : ""}` };
91
+ }
92
+ export function formatHostsList(result, all = false, wide = false, now = Date.now(), format) {
93
+ const rows = renderHostRows(result, format, now, wide);
94
+ if (format !== undefined)
95
+ return rows;
96
+ return `Namespace: ${result.namespace}\n${rows}\n${result.total} hosts. ${result.group ? `Group: ${result.group}.` : "All groups."} All pages.\n${all ? "All connection states." : "Active (verified online) only. Use --all to include offline and unknown hosts."}\nOne row per enrollment. IPs are reported interface addresses; unknown means unavailable. Use ${wide ? "hosts status HOST" : "--wide or hosts status HOST"} for details.`;
75
97
  }
76
- export function formatHostStatus(result) {
98
+ export function formatHostStatus(result, now = Date.now()) {
77
99
  const enrollments = result.enrollments ?? [];
78
100
  const lines = [
79
101
  `Host: ${cell(result.host.id)}`, `Name: ${cell(result.host.name)}`,
@@ -88,6 +110,14 @@ export function formatHostStatus(result) {
88
110
  ]));
89
111
  else
90
112
  lines.push("No enrollments.");
113
+ for (const enrollment of enrollments) {
114
+ const system = enrollment.statusVerified === true ? enrollment.system : null;
115
+ const network = networkView(enrollment, now);
116
+ lines.push("", `Enrollment: ${cell(enrollment.id)}`, `Machine ID: ${cell(enrollment.machineId)}`, `Hostname: ${cell(enrollment.statusVerified === true ? enrollment.hostname : null)}`, `OS: ${cell(system?.os)}`, `Architecture: ${cell(system?.arch)}`, `CPU: ${cell(system?.cpuModel)}`, `CPU cores: ${typeof system?.cpuCores === "number" && Number.isSafeInteger(system.cpuCores) && system.cpuCores > 0 ? system.cpuCores : "unknown"}`, `Nymph: ${cell(system?.nymphVersion)}`, `IP addresses: ${network.text}`, `Network observed at: ${network.observedAt}`, `Network freshness: ${network.freshness}`);
117
+ if (network.addresses.length)
118
+ lines.push(table([["INTERFACE", "ADDRESS", "FAMILY"],
119
+ ...network.addresses.map(a => [cell(a.interface), cell(a.address), isIP(a.address) === 4 ? "IPv4" : "IPv6"])]));
120
+ }
91
121
  return lines.join("\n");
92
122
  }
93
123
  const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -0,0 +1,8 @@
1
+ import type { HostEnrollmentStatus, HostInventory, HostSummary } from './inventory.js';
2
+ import type { HostProbe } from './view.js';
3
+ /** Read-only, no packages, no privilege escalation. Works with Linux ip or macOS ifconfig. */
4
+ export declare const HOST_PROBE_PYTHON: string;
5
+ export declare function parseHostProbe(output: string): HostProbe;
6
+ export declare function probeHost(host: HostSummary, enrollment: HostEnrollmentStatus, namespace: string): Promise<HostProbe>;
7
+ /** At most two sessions, explicit enrollment IDs; a failed host cannot discard other observations. */
8
+ export declare function probeHostInventory(result: HostInventory, probe?: typeof probeHost): Promise<HostInventory>;
@@ -0,0 +1,105 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { isIP } from 'node:net';
3
+ import { defaultSshIO, runHostSsh } from './ssh.js';
4
+ /** Read-only, no packages, no privilege escalation. Works with Linux ip or macOS ifconfig. */
5
+ export const HOST_PROBE_PYTHON = String.raw `
6
+ import json, platform, socket, subprocess, time, re, ipaddress
7
+ r = dict(hostname=socket.gethostname(), platform=platform.system(), arch=platform.machine(), observedAt=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), interfaces=[], uptimeSeconds=None, publicIp=None)
8
+ errors=[]
9
+ def run(args):
10
+ return subprocess.check_output(args, timeout=10, stderr=subprocess.DEVNULL).decode()
11
+ def add(name, ips, mac=None):
12
+ addresses=[]
13
+ for a in ips:
14
+ try:
15
+ ip=ipaddress.ip_address(a.split('%')[0])
16
+ if not ip.is_loopback and not ip.is_unspecified: addresses.append(str(ip))
17
+ except ValueError: pass
18
+ if name == 'lo' or name.startswith('lo0'): return
19
+ if not isinstance(mac,str) or not re.fullmatch(r'(?:[0-9a-fA-F]{2}:){5,19}[0-9a-fA-F]{2}',mac): mac=None
20
+ r['interfaces'].append(dict(name=name, ips=addresses, mac=mac))
21
+ try:
22
+ if platform.system() == 'Linux':
23
+ for i in json.loads(run(['ip','-j','address','show'])):
24
+ add(i['ifname'], [a['local'] for a in i.get('addr_info',[])], i.get('address'))
25
+ else:
26
+ text=run(['/sbin/ifconfig','-a'])
27
+ for block in re.split(r'\n(?=\S)',text):
28
+ name=block.split(':',1)[0]
29
+ ips=re.findall(r'\binet6?\s+([^\s]+)',block)
30
+ mac=re.search(r'\bether\s+([0-9a-fA-F:]+)',block)
31
+ add(name,ips,mac.group(1) if mac else None)
32
+ except Exception: errors.append('interface inspection unavailable')
33
+ try:
34
+ if platform.system() == 'Linux':
35
+ with open('/proc/uptime') as f: r['uptimeSeconds']=float(f.read().split()[0])
36
+ else:
37
+ boot=run(['/usr/sbin/sysctl','-n','kern.boottime'])
38
+ r['uptimeSeconds']=max(0,time.time()-int(re.search(r'sec = (\d+)',boot).group(1)))
39
+ except Exception: errors.append('system uptime unavailable')
40
+ try:
41
+ ip=run(['curl','-fsS','--connect-timeout','5','--max-time','8','https://ifconfig.me/ip']).strip()
42
+ r['publicIp']=str(ipaddress.ip_address(ip))
43
+ except Exception: errors.append('public IP lookup unavailable')
44
+ r['status']='partial' if errors else 'ok'
45
+ if errors: r['error']='; '.join(errors)
46
+ print(json.dumps(r))
47
+ `;
48
+ export function parseHostProbe(output) {
49
+ const p = JSON.parse(output);
50
+ if (!p || !['ok', 'partial'].includes(p.status) || typeof p.hostname !== 'string' ||
51
+ typeof p.observedAt !== 'string' || !Number.isFinite(Date.parse(p.observedAt)) || !Array.isArray(p.interfaces) ||
52
+ p.interfaces.length > 1024 || p.interfaces.some((i) => !i || typeof i.name !== 'string' || !Array.isArray(i.ips) ||
53
+ i.ips.some((ip) => typeof ip !== 'string' || !isIP(ip)) || (i.mac != null && (typeof i.mac !== 'string' || !/^(?:[0-9a-f]{2}:){5,19}[0-9a-f]{2}$/i.test(i.mac)))) ||
54
+ (p.publicIp != null && (typeof p.publicIp !== 'string' || !isIP(p.publicIp))) ||
55
+ (p.uptimeSeconds != null && (typeof p.uptimeSeconds !== 'number' || !Number.isFinite(p.uptimeSeconds) || p.uptimeSeconds < 0))) {
56
+ throw new Error('Invalid host probe response');
57
+ }
58
+ return p;
59
+ }
60
+ export async function probeHost(host, enrollment, namespace) {
61
+ if (enrollment.statusVerified !== true)
62
+ return { status: 'unverified' };
63
+ if (enrollment.state !== 'online')
64
+ return { status: 'offline' };
65
+ let output = '', overflow = false;
66
+ try {
67
+ const code = await runHostSsh(host.id, { namespace, enrollment: enrollment.id, timeout: '30', duration: '120' }, ['python3', '-c', HOST_PROBE_PYTHON], { ...defaultSshIO, spawn: args => {
68
+ const child = spawn('ssh', args, { stdio: ['ignore', 'pipe', 'pipe'] });
69
+ child.stdout.on('data', chunk => {
70
+ if (Buffer.byteLength(output) + chunk.length > 262144) {
71
+ overflow = true;
72
+ child.kill();
73
+ }
74
+ else
75
+ output += chunk.toString('utf8');
76
+ });
77
+ // Session credentials and arbitrary remote stderr are never included in the field view.
78
+ child.stderr.resume();
79
+ return child;
80
+ } });
81
+ if (overflow)
82
+ throw new Error('Host probe output exceeded 256 KiB');
83
+ if (code !== 0)
84
+ throw new Error(`Host probe SSH exited ${code}`);
85
+ return parseHostProbe(output);
86
+ }
87
+ catch (error) {
88
+ return { status: 'error', error: error instanceof Error ? error.message : 'Host probe failed' };
89
+ }
90
+ }
91
+ /** At most two sessions, explicit enrollment IDs; a failed host cannot discard other observations. */
92
+ export async function probeHostInventory(result, probe = probeHost) {
93
+ const enriched = { ...result, hosts: result.hosts.map(h => ({ ...h, enrollments: h.enrollments?.map(e => ({ ...e })) })) };
94
+ const queue = enriched.hosts.flatMap(h => (h.enrollments ?? []).map(e => ({ h, e })));
95
+ async function worker() {
96
+ for (;;) {
97
+ const item = queue.shift();
98
+ if (!item)
99
+ return;
100
+ item.e.probe = await probe(item.h, item.e, result.namespace);
101
+ }
102
+ }
103
+ await Promise.all([worker(), worker()]);
104
+ return enriched;
105
+ }
@@ -0,0 +1,64 @@
1
+ import type { HostEnrollmentStatus, HostInventory, HostSummary } from './inventory.js';
2
+ export declare const HOST_FIELDS: {
3
+ readonly id: "Host ID";
4
+ readonly name: "Full namespace/group/host name";
5
+ readonly namespace: "Namespace slug";
6
+ readonly group: "Group name";
7
+ readonly catalog: "Active or archived catalog state";
8
+ readonly catalog_revision: "Catalog revision";
9
+ readonly archived_at: "Catalog archive timestamp";
10
+ readonly connection: "Verified connection state for this enrollment";
11
+ readonly enrollment: "Enrollment ID";
12
+ readonly machine_id: "Nymph machine ID";
13
+ readonly lakeshore_id: "Lakeshore connection ID";
14
+ readonly user: "Enrolled Unix user";
15
+ readonly state: "Reported enrollment state";
16
+ readonly verified: "Whether presence is verified";
17
+ readonly hostname: "Reported hostname (SSH observation takes precedence)";
18
+ readonly ip: "First observed interface IPv4, then IPv6";
19
+ readonly ip_source: "ssh or inventory; no hostname inference";
20
+ readonly ips: "All observed interface IPs (inventory or SSH probe)";
21
+ readonly public_ip: "Public egress IP from HTTPS ifconfig.me (SSH probe)";
22
+ readonly mac: "MAC of the interface selected by ip (SSH probe)";
23
+ readonly macs: "All observed interface MAC addresses (SSH probe)";
24
+ readonly interfaces: "Observed interface names (inventory or SSH probe)";
25
+ readonly platform: "Operating system (inventory or SSH probe)";
26
+ readonly arch: "CPU architecture (inventory or SSH probe)";
27
+ readonly cpu_model: "Reported CPU model";
28
+ readonly cpu_cores: "Reported CPU core count";
29
+ readonly nymph_version: "Reported Nymph version";
30
+ readonly network_observed_at: "Interface inventory observation time";
31
+ readonly network_freshness: "fresh, stale or unknown interface observation";
32
+ readonly uptime: "System uptime, human readable (SSH probe); not connection duration";
33
+ readonly uptime_seconds: "System uptime in seconds (SSH probe)";
34
+ readonly connected_at: "Backend-reported connection start, when supplied";
35
+ readonly online_for: "Verified connection duration, only when connected_at is supplied";
36
+ readonly last_seen: "Last heartbeat timestamp";
37
+ readonly seen_ago: "Time since last heartbeat";
38
+ readonly observed_at: "SSH probe timestamp";
39
+ readonly probe_status: "ok, partial, error, offline, unverified, or not_requested";
40
+ readonly probe_error: "SSH or individual probe failure";
41
+ };
42
+ export type HostField = keyof typeof HOST_FIELDS;
43
+ export declare const DEFAULT_HOST_FORMAT = "{id} {name} {catalog} {connection} {hostname} {user} {ips}";
44
+ export interface HostProbe {
45
+ status: string;
46
+ error?: string;
47
+ observedAt?: string;
48
+ hostname?: string;
49
+ platform?: string;
50
+ arch?: string;
51
+ uptimeSeconds?: number | null;
52
+ publicIp?: string | null;
53
+ interfaces?: {
54
+ name: string;
55
+ ips: string[];
56
+ mac?: string;
57
+ }[];
58
+ }
59
+ export declare function validateHostFormat(format: string): void;
60
+ export declare function formatHostFields(): string;
61
+ export declare function duration(seconds: number): string;
62
+ export declare function hostFields(host: HostSummary, enrollment: HostEnrollmentStatus | undefined, now?: number): Record<HostField, string>;
63
+ /** One row per enrollment: observations from different machines are never combined. */
64
+ export declare function renderHostRows(result: HostInventory, format?: string, now?: number, wide?: boolean): string;
@@ -0,0 +1,100 @@
1
+ import { isIP } from 'node:net';
2
+ import { hostConnection, networkView } from './inventory.js';
3
+ export const HOST_FIELDS = {
4
+ id: 'Host ID', name: 'Full namespace/group/host name', namespace: 'Namespace slug', group: 'Group name',
5
+ catalog: 'Active or archived catalog state', catalog_revision: 'Catalog revision', archived_at: 'Catalog archive timestamp',
6
+ connection: 'Verified connection state for this enrollment', enrollment: 'Enrollment ID', machine_id: 'Nymph machine ID',
7
+ lakeshore_id: 'Lakeshore connection ID', user: 'Enrolled Unix user', state: 'Reported enrollment state', verified: 'Whether presence is verified',
8
+ hostname: 'Reported hostname (SSH observation takes precedence)', ip: 'First observed interface IPv4, then IPv6',
9
+ ip_source: 'ssh or inventory; no hostname inference',
10
+ ips: 'All observed interface IPs (inventory or SSH probe)', public_ip: 'Public egress IP from HTTPS ifconfig.me (SSH probe)',
11
+ mac: 'MAC of the interface selected by ip (SSH probe)', macs: 'All observed interface MAC addresses (SSH probe)', interfaces: 'Observed interface names (inventory or SSH probe)',
12
+ platform: 'Operating system (inventory or SSH probe)', arch: 'CPU architecture (inventory or SSH probe)',
13
+ cpu_model: 'Reported CPU model', cpu_cores: 'Reported CPU core count', nymph_version: 'Reported Nymph version',
14
+ network_observed_at: 'Interface inventory observation time', network_freshness: 'fresh, stale or unknown interface observation',
15
+ uptime: 'System uptime, human readable (SSH probe); not connection duration', uptime_seconds: 'System uptime in seconds (SSH probe)',
16
+ connected_at: 'Backend-reported connection start, when supplied', online_for: 'Verified connection duration, only when connected_at is supplied',
17
+ last_seen: 'Last heartbeat timestamp', seen_ago: 'Time since last heartbeat',
18
+ observed_at: 'SSH probe timestamp', probe_status: 'ok, partial, error, offline, unverified, or not_requested',
19
+ probe_error: 'SSH or individual probe failure',
20
+ };
21
+ export const DEFAULT_HOST_FORMAT = '{id} {name} {catalog} {connection} {hostname} {user} {ips}';
22
+ export function validateHostFormat(format) {
23
+ if (!format || format.length > 4096)
24
+ throw new Error('--format must contain 1–4096 characters');
25
+ const rest = format.replace(/\{([^{}]+)\}/g, (_, key) => {
26
+ if (!Object.hasOwn(HOST_FIELDS, key))
27
+ throw new Error(`Unknown host field: ${key}. Use --fields to list supported fields.`);
28
+ return '';
29
+ });
30
+ if (/[{}]/.test(rest))
31
+ throw new Error('Invalid --format placeholder; use {field}. Use --fields for supported fields.');
32
+ }
33
+ export function formatHostFields() {
34
+ return `Default: ${DEFAULT_HOST_FORMAT}\n\n` + Object.entries(HOST_FIELDS).map(([key, description]) => `{${key}} ${description}`).join('\n');
35
+ }
36
+ function cell(value) {
37
+ if (value === null || value === undefined || value === '')
38
+ return 'unknown';
39
+ return String(value).replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
40
+ }
41
+ export function duration(seconds) {
42
+ const n = Math.floor(seconds);
43
+ if (n < 60)
44
+ return `${n}s`;
45
+ if (n < 3600)
46
+ return `${Math.floor(n / 60)}m ${n % 60}s`;
47
+ if (n < 86400)
48
+ return `${Math.floor(n / 3600)}h ${Math.floor(n % 3600 / 60)}m`;
49
+ return `${Math.floor(n / 86400)}d ${Math.floor(n % 86400 / 3600)}h`;
50
+ }
51
+ function elapsed(value, now) {
52
+ const ms = typeof value === 'string' ? Date.parse(value) : NaN;
53
+ return Number.isFinite(ms) && ms <= now ? duration((now - ms) / 1000) : 'unknown';
54
+ }
55
+ export function hostFields(host, enrollment, now = Date.now()) {
56
+ const e = enrollment, p = e?.probe;
57
+ const hostname = p?.hostname || (e?.statusVerified === true ? e.hostname : undefined);
58
+ const network = networkView(e ?? { id: '' }, now);
59
+ const system = e?.statusVerified === true ? e.system : null;
60
+ const rank = (ip) => isIP(ip) === 4 ? 0 : /^fe[89ab]/i.test(ip) ? 2 : 1;
61
+ const ips = [...new Set(network.addresses.map(a => a.address))].sort((a, b) => rank(a) - rank(b));
62
+ const ip = ips[0];
63
+ const uptime = p?.uptimeSeconds;
64
+ const validUptime = typeof uptime === 'number' && Number.isFinite(uptime) && uptime >= 0;
65
+ const connection = hostConnection(e ? [e] : []);
66
+ const raw = {
67
+ id: host.id, name: host.name, namespace: host.name.split('/')[0], group: host.name.split('/')[1],
68
+ catalog: host.catalog?.catalogState, catalog_revision: host.catalog?.revision, archived_at: host.catalog?.archivedAt,
69
+ connection, enrollment: e?.id, machine_id: e?.machineId, lakeshore_id: e?.lakeshoreId, user: e?.unixUser, state: e?.state,
70
+ verified: e ? e.statusVerified === true ? 'yes' : 'no' : undefined,
71
+ hostname, ip, ip_source: ips.length ? network.source : undefined,
72
+ ips: network.freshness === 'unknown' ? undefined : ips.join(',') || 'none', public_ip: p?.publicIp, mac: p?.interfaces?.find(i => i.ips.includes(ip ?? ''))?.mac, macs: [...new Set(p?.interfaces?.map(i => i.mac).filter(Boolean))].join(','),
73
+ interfaces: [...new Set(network.addresses.map(a => a.interface))].join(','), platform: p?.platform || system?.os, arch: p?.arch || system?.arch,
74
+ cpu_model: system?.cpuModel, cpu_cores: typeof system?.cpuCores === 'number' && Number.isSafeInteger(system.cpuCores) && system.cpuCores > 0 ? system.cpuCores : undefined,
75
+ nymph_version: system?.nymphVersion, network_observed_at: network.observedAt, network_freshness: network.freshness,
76
+ uptime: validUptime ? duration(uptime) : undefined, uptime_seconds: validUptime ? Math.floor(uptime) : undefined,
77
+ connected_at: e?.connectedAt, online_for: connection === 'online' ? elapsed(e?.connectedAt, now) : undefined,
78
+ last_seen: e?.lastSeenAt, seen_ago: elapsed(e?.lastSeenAt, now), observed_at: p?.observedAt,
79
+ probe_status: p?.status ?? 'not_requested', probe_error: p?.error,
80
+ };
81
+ return Object.fromEntries(Object.entries(raw).map(([k, v]) => [k, cell(v)]));
82
+ }
83
+ /** One row per enrollment: observations from different machines are never combined. */
84
+ export function renderHostRows(result, format, now = Date.now(), wide = false) {
85
+ const template = format ?? DEFAULT_HOST_FORMAT;
86
+ validateHostFormat(template);
87
+ const values = result.hosts.flatMap(h => (h.enrollments?.length ? h.enrollments : [undefined]).map(e => hostFields(h, e, now)));
88
+ if (format !== undefined)
89
+ return values.map(v => template.replace(/\{([^{}]+)\}/g, (_, k) => v[k])).join('\n');
90
+ const probed = result.hosts.some(h => h.enrollments?.some(e => e.probe));
91
+ const columns = ['id', 'name', 'catalog', 'connection', 'hostname', 'user', 'ips',
92
+ ...(wide ? ['enrollment', 'platform', 'arch', 'cpu_cores', 'nymph_version', 'last_seen'] : []),
93
+ ...(probed ? ['public_ip', 'mac', 'uptime', 'online_for'] : [])];
94
+ const headers = ['ID', 'NAME', 'CATALOG', 'CONNECTION', 'HOSTNAME', 'USER', 'IP ADDRESSES',
95
+ ...(wide ? ['ENROLLMENT', 'OS', 'ARCH', 'CPUS', 'NYMPH', 'LAST SEEN'] : []),
96
+ ...(probed ? ['PUBLIC IP', 'MAC', 'UPTIME', 'ONLINE FOR'] : [])];
97
+ const rows = [headers, ...values.map(v => columns.map(k => k === 'ips' && v.network_freshness === 'stale' ? `${v[k]} (stale)` : v[k]))];
98
+ const widths = columns.map((_, i) => rows.reduce((width, r) => Math.max(width, r[i].length), 0));
99
+ return rows.map(r => r.map((v, i) => i === columns.length - 1 ? v : v.padEnd(widths[i])).join(' ')).join('\n');
100
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "0.104.2";
1
+ export declare const VERSION = "0.104.4";
@@ -6,4 +6,4 @@
6
6
  // value means a binary that re-installs the same version forever.
7
7
  //
8
8
  // Editing this by hand does nothing for a release; bump package.json.
9
- export const VERSION = "0.104.2";
9
+ export const VERSION = "0.104.4";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamlake/dreamlake-cli",
3
- "version": "0.104.2",
3
+ "version": "0.104.4",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/dreamlake-ai/dreamlake-cli.git"
@@ -36,13 +36,13 @@
36
36
  "node": ">=18"
37
37
  },
38
38
  "optionalDependencies": {
39
- "@dreamlake/dreamlake-cli-darwin-arm64": "0.104.2",
40
- "@dreamlake/dreamlake-cli-darwin-x64": "0.104.2",
41
- "@dreamlake/dreamlake-cli-linux-x64": "0.104.2",
42
- "@dreamlake/dreamlake-cli-linux-arm64": "0.104.2",
43
- "@dreamlake/dreamlake-cli-linux-x64-musl": "0.104.2",
44
- "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.104.2",
45
- "@dreamlake/dreamlake-cli-win32-x64": "0.104.2",
46
- "@dreamlake/dreamlake-cli-win32-arm64": "0.104.2"
39
+ "@dreamlake/dreamlake-cli-darwin-arm64": "0.104.4",
40
+ "@dreamlake/dreamlake-cli-darwin-x64": "0.104.4",
41
+ "@dreamlake/dreamlake-cli-linux-x64": "0.104.4",
42
+ "@dreamlake/dreamlake-cli-linux-arm64": "0.104.4",
43
+ "@dreamlake/dreamlake-cli-linux-x64-musl": "0.104.4",
44
+ "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.104.4",
45
+ "@dreamlake/dreamlake-cli-win32-x64": "0.104.4",
46
+ "@dreamlake/dreamlake-cli-win32-arm64": "0.104.4"
47
47
  }
48
48
  }