hypha-cli 0.1.6 → 0.1.7

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.
@@ -0,0 +1,764 @@
1
+ import { statSync, readFileSync, mkdirSync, createWriteStream, readdirSync } from 'fs';
2
+ import { join, dirname, basename } from 'path';
3
+ import { e as hasFlag, p as positionalArgs, f as formatJson, a as formatTable, r as resolveServerUrl, i as getFlag, g as getFlagInt, c as connectToHypha, b as resolveToken, m as printProgress, h as humanSize } from './helpers-DWQC3Lr8.mjs';
4
+ import { p as parseArtifactPath, b as buildFileUrl, d as determineCpDirection, r as resolveArtifactId } from './artifactPath-DCtvp6Go.mjs';
5
+ import 'os';
6
+
7
+ async function uploadFile(artifactManager, artifactId, localPath, remotePath, onProgress) {
8
+ const stat = statSync(localPath);
9
+ const totalBytes = stat.size;
10
+ onProgress?.({ phase: "reading", bytesTransferred: 0, totalBytes, fileName: remotePath });
11
+ const putUrl = await artifactManager.put_file({
12
+ artifact_id: artifactId,
13
+ file_path: remotePath,
14
+ _rkwargs: true
15
+ });
16
+ if (!putUrl || typeof putUrl !== "string") {
17
+ throw new Error(`put_file returned invalid URL for ${remotePath}: ${putUrl}`);
18
+ }
19
+ const content = readFileSync(localPath);
20
+ onProgress?.({ phase: "uploading", bytesTransferred: 0, totalBytes, fileName: remotePath });
21
+ const resp = await fetch(putUrl, {
22
+ method: "PUT",
23
+ body: content,
24
+ headers: {
25
+ "Content-Type": "application/octet-stream",
26
+ "Content-Length": String(totalBytes)
27
+ }
28
+ });
29
+ if (!resp.ok) {
30
+ const body = await resp.text().catch(() => "");
31
+ throw new Error(`Upload failed for ${remotePath}: ${resp.status} ${resp.statusText} ${body}`);
32
+ }
33
+ onProgress?.({ phase: "complete", bytesTransferred: totalBytes, totalBytes, fileName: remotePath });
34
+ }
35
+ async function downloadFile(artifactManager, artifactId, remotePath, localPath, onProgress) {
36
+ const getResult = await artifactManager.get_file({
37
+ artifact_id: artifactId,
38
+ file_path: remotePath,
39
+ _rkwargs: true
40
+ });
41
+ const getUrl = typeof getResult === "string" ? getResult : getResult?.url;
42
+ if (!getUrl || typeof getUrl !== "string") {
43
+ throw new Error(`get_file returned invalid result for ${remotePath}: ${JSON.stringify(getResult)}`);
44
+ }
45
+ const resp = await fetch(getUrl);
46
+ if (!resp.ok) {
47
+ throw new Error(`Download failed for ${remotePath}: ${resp.status} ${resp.statusText}`);
48
+ }
49
+ const totalBytes = parseInt(resp.headers.get("content-length") || "0", 10);
50
+ let bytesTransferred = 0;
51
+ onProgress?.({ phase: "downloading", bytesTransferred: 0, totalBytes, fileName: remotePath });
52
+ mkdirSync(dirname(localPath), { recursive: true });
53
+ const fileStream = createWriteStream(localPath);
54
+ const reader = resp.body?.getReader();
55
+ if (!reader) {
56
+ throw new Error("Response body is not readable");
57
+ }
58
+ try {
59
+ while (true) {
60
+ const { done, value } = await reader.read();
61
+ if (done) break;
62
+ fileStream.write(value);
63
+ bytesTransferred += value.length;
64
+ onProgress?.({
65
+ phase: "downloading",
66
+ bytesTransferred,
67
+ totalBytes: totalBytes || bytesTransferred,
68
+ fileName: remotePath
69
+ });
70
+ }
71
+ } finally {
72
+ fileStream.end();
73
+ reader.releaseLock();
74
+ }
75
+ await new Promise((resolve, reject) => {
76
+ fileStream.on("finish", resolve);
77
+ fileStream.on("error", reject);
78
+ });
79
+ onProgress?.({ phase: "complete", bytesTransferred, totalBytes: totalBytes || bytesTransferred, fileName: remotePath });
80
+ }
81
+ async function uploadDirectory(artifactManager, artifactId, localDir, remoteBase, onProgress) {
82
+ const files = collectLocalFiles(localDir);
83
+ let uploaded = 0;
84
+ for (const relPath of files) {
85
+ const localPath = join(localDir, relPath);
86
+ const remotePath = remoteBase ? `${remoteBase}/${relPath}` : relPath;
87
+ await uploadFile(artifactManager, artifactId, localPath, remotePath, onProgress);
88
+ uploaded++;
89
+ }
90
+ return uploaded;
91
+ }
92
+ async function downloadDirectory(artifactManager, artifactId, remotePath, localDir, onProgress) {
93
+ const files = await artifactManager.list_files({
94
+ artifact_id: artifactId,
95
+ dir_path: remotePath || "",
96
+ _rkwargs: true
97
+ });
98
+ const fileList = Array.isArray(files) ? files : files?.items || [];
99
+ let downloaded = 0;
100
+ for (const entry of fileList) {
101
+ if (entry.type === "directory") {
102
+ const subRemote = remotePath ? `${remotePath}/${entry.name}` : entry.name;
103
+ const subLocal = join(localDir, entry.name);
104
+ downloaded += await downloadDirectory(artifactManager, artifactId, subRemote, subLocal, onProgress);
105
+ } else {
106
+ const remoteFile = remotePath ? `${remotePath}/${entry.name}` : entry.name;
107
+ const localFile = join(localDir, entry.name);
108
+ await downloadFile(artifactManager, artifactId, remoteFile, localFile, onProgress);
109
+ downloaded++;
110
+ }
111
+ }
112
+ return downloaded;
113
+ }
114
+ const IGNORED_DIRS = /* @__PURE__ */ new Set([
115
+ "__pycache__",
116
+ ".git",
117
+ ".venv",
118
+ "node_modules",
119
+ ".idea",
120
+ ".pytest_cache",
121
+ ".mypy_cache",
122
+ "build",
123
+ "dist"
124
+ ]);
125
+ function collectLocalFiles(dir, base = "") {
126
+ const entries = readdirSync(dir, { withFileTypes: true });
127
+ const files = [];
128
+ for (const entry of entries) {
129
+ if (entry.name.startsWith(".") && entry.name !== ".env.example") continue;
130
+ if (entry.isDirectory() && IGNORED_DIRS.has(entry.name)) continue;
131
+ const relPath = base ? `${base}/${entry.name}` : entry.name;
132
+ if (entry.isDirectory()) {
133
+ files.push(...collectLocalFiles(join(dir, entry.name), relPath));
134
+ } else {
135
+ files.push(relPath);
136
+ }
137
+ }
138
+ return files;
139
+ }
140
+
141
+ function printArtifactsHelp() {
142
+ console.log(`hypha artifacts \u2014 manage artifacts
143
+
144
+ Usage: hypha artifacts <command> [options]
145
+
146
+ Commands:
147
+ ls [artifact[:path]] List artifacts or files in artifact
148
+ cat <artifact>:<path> Read file content to stdout
149
+ cp <src> <dest> [-r] Upload/download files (scp-style)
150
+ rm <artifact>[:<path>] Delete artifact or file
151
+ create <alias> [options] Create a new artifact
152
+ info <artifact> [--json] Show artifact metadata
153
+ search <query> [options] Search artifacts
154
+ commit <artifact> [options] Commit staged changes
155
+ edit <artifact> [options] Edit artifact metadata
156
+ discard <artifact> Discard staged changes
157
+
158
+ Aliases: list \u2192 ls, mkdir \u2192 create, find \u2192 search
159
+ Shorthand: "hypha art" is an alias for "hypha artifacts"
160
+
161
+ Artifact addressing:
162
+ alias Artifact in current workspace
163
+ workspace/alias Artifact in specific workspace
164
+ artifact:path/to/file File inside artifact
165
+
166
+ Copy examples:
167
+ hypha art cp ./data.csv model:data/train.csv Upload file
168
+ hypha art cp model:weights.bin ./local/ Download file
169
+ hypha art cp ./dataset/ model:data/ -r Upload directory
170
+
171
+ Common options:
172
+ --json Output as JSON
173
+ --long, -l Long listing format (with sizes)
174
+ --recursive, -r Recursive operation
175
+ --force, -f Skip confirmation`);
176
+ }
177
+ async function connectAndGetArtifactManager() {
178
+ const server = await connectToHypha();
179
+ const am = await server.getService("public/artifact-manager");
180
+ return { server, am };
181
+ }
182
+ function makeProgressCallback() {
183
+ return (p) => {
184
+ if (p.totalBytes > 0) {
185
+ printProgress(p.fileName, p.bytesTransferred, p.totalBytes);
186
+ }
187
+ };
188
+ }
189
+ async function fetchWithAuth(url, init) {
190
+ const token = resolveToken();
191
+ const headers = new Headers(init?.headers);
192
+ if (token) {
193
+ headers.set("Authorization", `Bearer ${token}`);
194
+ }
195
+ return fetch(url, { ...init, headers });
196
+ }
197
+ async function artifactsLs(args) {
198
+ if (hasFlag(args, "--help", "-h")) {
199
+ console.log(`hypha artifacts ls \u2014 list artifacts or files
200
+
201
+ Usage: hypha artifacts ls [artifact[:path]] [options]
202
+
203
+ With no argument, lists all artifacts in the workspace.
204
+ With artifact:path, lists files in the artifact.
205
+
206
+ Options:
207
+ --json Output as JSON
208
+ --long, -l Long listing format (with sizes, types)
209
+
210
+ Alias: hypha artifacts list`);
211
+ return;
212
+ }
213
+ const json = hasFlag(args, "--json");
214
+ const long = hasFlag(args, "--long", "-l");
215
+ const pos = positionalArgs(args)[0];
216
+ if (!pos) {
217
+ const { server: server2, am } = await connectAndGetArtifactManager();
218
+ try {
219
+ const artifacts = await am.list({
220
+ _rkwargs: true
221
+ });
222
+ const list = Array.isArray(artifacts) ? artifacts : artifacts?.items || [];
223
+ if (json) {
224
+ console.log(formatJson(list));
225
+ return;
226
+ }
227
+ if (list.length === 0) {
228
+ console.log("No artifacts found.");
229
+ return;
230
+ }
231
+ if (long) {
232
+ const rows = [["ALIAS", "TYPE", "MODIFIED", "DESCRIPTION"]];
233
+ for (const art of list) {
234
+ const manifest = art.manifest || {};
235
+ rows.push([
236
+ art.alias || art.id || "",
237
+ art.type || "",
238
+ art.last_modified ? new Date(art.last_modified * 1e3).toISOString().slice(0, 10) : "",
239
+ (manifest.description || "").slice(0, 50)
240
+ ]);
241
+ }
242
+ console.log(formatTable(rows));
243
+ } else {
244
+ for (const art of list) {
245
+ console.log(art.alias || art.id || "");
246
+ }
247
+ }
248
+ } finally {
249
+ await server2.disconnect();
250
+ }
251
+ return;
252
+ }
253
+ const parsed = parseArtifactPath(pos);
254
+ const serverUrl = resolveServerUrl();
255
+ const { server } = await connectAndGetArtifactManager();
256
+ const workspace = parsed.workspace || server.config.workspace;
257
+ try {
258
+ const url = buildFileUrl(serverUrl, workspace, parsed.alias, parsed.filePath);
259
+ const resp = await fetchWithAuth(url);
260
+ if (!resp.ok) {
261
+ if (resp.status === 404) {
262
+ console.error(`Not found: ${pos}`);
263
+ process.exit(1);
264
+ }
265
+ throw new Error(`List files failed: ${resp.status} ${resp.statusText}`);
266
+ }
267
+ const data = await resp.json();
268
+ const files = Array.isArray(data) ? data : data.items || [];
269
+ if (json) {
270
+ console.log(formatJson(files));
271
+ return;
272
+ }
273
+ if (files.length === 0) {
274
+ console.log("No files found.");
275
+ return;
276
+ }
277
+ if (long) {
278
+ const rows = [["SIZE", "TYPE", "NAME"]];
279
+ for (const f of files) {
280
+ rows.push([
281
+ f.type === "directory" ? "-" : humanSize(f.size || 0),
282
+ f.type || "file",
283
+ f.type === "directory" ? `${f.name}/` : f.name
284
+ ]);
285
+ }
286
+ console.log(formatTable(rows));
287
+ } else {
288
+ for (const f of files) {
289
+ console.log(f.type === "directory" ? `${f.name}/` : f.name);
290
+ }
291
+ }
292
+ } finally {
293
+ await server.disconnect();
294
+ }
295
+ }
296
+ async function artifactsCat(args) {
297
+ if (hasFlag(args, "--help", "-h")) {
298
+ console.log(`hypha artifacts cat \u2014 read file content to stdout
299
+
300
+ Usage: hypha artifacts cat <artifact>:<path>
301
+
302
+ Examples:
303
+ hypha art cat model:README.md
304
+ hypha art cat ws/model:data/config.json`);
305
+ return;
306
+ }
307
+ const pos = positionalArgs(args)[0];
308
+ if (!pos) {
309
+ console.error("Usage: hypha artifacts cat <artifact>:<path>");
310
+ process.exit(1);
311
+ }
312
+ const parsed = parseArtifactPath(pos);
313
+ if (!parsed.filePath) {
314
+ console.error("File path required. Use artifact:path/to/file syntax.");
315
+ process.exit(1);
316
+ }
317
+ const serverUrl = resolveServerUrl();
318
+ const { server } = await connectAndGetArtifactManager();
319
+ const workspace = parsed.workspace || server.config.workspace;
320
+ try {
321
+ const url = buildFileUrl(serverUrl, workspace, parsed.alias, parsed.filePath);
322
+ const resp = await fetchWithAuth(url, { redirect: "follow" });
323
+ if (!resp.ok) {
324
+ if (resp.status === 404) {
325
+ console.error(`File not found: ${parsed.filePath}`);
326
+ process.exit(1);
327
+ }
328
+ throw new Error(`Read failed: ${resp.status} ${resp.statusText}`);
329
+ }
330
+ const reader = resp.body?.getReader();
331
+ if (!reader) {
332
+ const text = await resp.text();
333
+ process.stdout.write(text);
334
+ return;
335
+ }
336
+ const decoder = new TextDecoder();
337
+ while (true) {
338
+ const { done, value } = await reader.read();
339
+ if (done) break;
340
+ process.stdout.write(decoder.decode(value, { stream: true }));
341
+ }
342
+ } finally {
343
+ await server.disconnect();
344
+ }
345
+ }
346
+ async function artifactsCp(args) {
347
+ if (hasFlag(args, "--help", "-h")) {
348
+ console.log(`hypha artifacts cp \u2014 upload/download files (scp-style)
349
+
350
+ Usage: hypha artifacts cp <src> <dest> [-r] [--commit]
351
+
352
+ Options:
353
+ -r, --recursive Copy directories recursively
354
+ --commit Auto-commit after upload
355
+
356
+ Examples:
357
+ hypha art cp ./data.csv model:data/train.csv Upload file
358
+ hypha art cp model:weights.bin ./local/ Download file
359
+ hypha art cp ./dataset/ model:data/ -r Upload directory
360
+ hypha art cp ./file.txt model:file.txt --commit Upload and commit`);
361
+ return;
362
+ }
363
+ const pos = positionalArgs(args, []);
364
+ const recursive = hasFlag(args, "--recursive", "-r");
365
+ const autoCommit = hasFlag(args, "--commit");
366
+ if (pos.length < 2) {
367
+ console.error("Usage: hypha artifacts cp <src> <dest> [-r] [--commit]");
368
+ console.error(" Upload: hypha artifacts cp ./file.txt artifact:path/");
369
+ console.error(" Download: hypha artifacts cp artifact:path/file.txt ./local/");
370
+ process.exit(1);
371
+ }
372
+ const [src, dest] = pos;
373
+ const direction = determineCpDirection(src, dest);
374
+ const { server, am } = await connectAndGetArtifactManager();
375
+ const onProgress = makeProgressCallback();
376
+ try {
377
+ if (direction === "upload") {
378
+ const parsed = parseArtifactPath(dest);
379
+ const artifactId = resolveArtifactId(parsed, server.config.workspace);
380
+ await am.edit({
381
+ artifact_id: artifactId,
382
+ stage: true,
383
+ _rkwargs: true
384
+ });
385
+ const stat = statSync(src);
386
+ if (stat.isDirectory()) {
387
+ if (!recursive) {
388
+ console.error("Source is a directory. Use -r to copy directories.");
389
+ process.exit(1);
390
+ }
391
+ const count = await uploadDirectory(am, artifactId, src, parsed.filePath || "", onProgress);
392
+ if (autoCommit) {
393
+ await am.commit({ artifact_id: artifactId, _rkwargs: true });
394
+ console.log(`
395
+ Uploaded ${count} files and committed.`);
396
+ } else {
397
+ console.log(`
398
+ Uploaded ${count} files. Run \`hypha artifacts commit ${parsed.alias}\` to finalize.`);
399
+ }
400
+ } else {
401
+ const remotePath = parsed.filePath || basename(src);
402
+ await uploadFile(am, artifactId, src, remotePath, onProgress);
403
+ if (autoCommit) {
404
+ await am.commit({ artifact_id: artifactId, _rkwargs: true });
405
+ console.log(`
406
+ Uploaded and committed: ${remotePath}`);
407
+ } else {
408
+ console.log(`
409
+ Uploaded: ${remotePath}. Run \`hypha artifacts commit ${parsed.alias}\` to finalize.`);
410
+ }
411
+ }
412
+ } else {
413
+ const parsed = parseArtifactPath(src);
414
+ const artifactId = resolveArtifactId(parsed, server.config.workspace);
415
+ if (!parsed.filePath) {
416
+ console.error("Source must include a file path (e.g., artifact:path/to/file).");
417
+ console.error("Use `hypha artifacts ls artifact:` to see available files.");
418
+ process.exit(1);
419
+ }
420
+ if (parsed.filePath.endsWith("/") && recursive) {
421
+ const count = await downloadDirectory(am, artifactId, parsed.filePath.replace(/\/$/, ""), dest, onProgress);
422
+ console.log(`
423
+ Downloaded ${count} files to ${dest}`);
424
+ } else {
425
+ const localDest = dest.endsWith("/") ? join(dest, basename(parsed.filePath)) : dest;
426
+ await downloadFile(am, artifactId, parsed.filePath, localDest, onProgress);
427
+ console.log(`
428
+ Downloaded: ${localDest}`);
429
+ }
430
+ }
431
+ } finally {
432
+ await server.disconnect();
433
+ }
434
+ }
435
+ async function artifactsRm(args) {
436
+ if (hasFlag(args, "--help", "-h")) {
437
+ console.log(`hypha artifacts rm \u2014 delete artifact or file
438
+
439
+ Usage: hypha artifacts rm <artifact>[:<path>] [-r] [-f]
440
+
441
+ Without :path, deletes the entire artifact (requires --force).
442
+ With :path, deletes a single file.
443
+
444
+ Options:
445
+ -r, --recursive Delete recursively (for collections)
446
+ -f, --force Skip confirmation for whole-artifact deletion`);
447
+ return;
448
+ }
449
+ const pos = positionalArgs(args)[0];
450
+ const force = hasFlag(args, "--force", "-f");
451
+ const recursive = hasFlag(args, "--recursive", "-r");
452
+ if (!pos) {
453
+ console.error("Usage: hypha artifacts rm <artifact>[:<path>] [-r] [-f]");
454
+ process.exit(1);
455
+ }
456
+ const parsed = parseArtifactPath(pos);
457
+ const { server, am } = await connectAndGetArtifactManager();
458
+ const artifactId = resolveArtifactId(parsed, server.config.workspace);
459
+ try {
460
+ if (parsed.filePath) {
461
+ await am.remove_file({
462
+ artifact_id: artifactId,
463
+ file_path: parsed.filePath,
464
+ _rkwargs: true
465
+ });
466
+ console.log(`Removed: ${parsed.filePath}`);
467
+ } else {
468
+ if (!force) {
469
+ console.error(`This will delete the entire artifact "${parsed.alias}". Use --force to confirm.`);
470
+ process.exit(1);
471
+ }
472
+ await am.delete({
473
+ artifact_id: artifactId,
474
+ delete_files: true,
475
+ recursive,
476
+ _rkwargs: true
477
+ });
478
+ console.log(`Deleted: ${parsed.alias}`);
479
+ }
480
+ } finally {
481
+ await server.disconnect();
482
+ }
483
+ }
484
+ async function artifactsCreate(args) {
485
+ if (hasFlag(args, "--help", "-h")) {
486
+ console.log(`hypha artifacts create \u2014 create a new artifact
487
+
488
+ Usage: hypha artifacts create <alias> [options]
489
+
490
+ Options:
491
+ --type <type> Artifact type (default: generic)
492
+ --parent <id> Parent artifact ID (for collections)
493
+ --json Output as JSON
494
+
495
+ Types: generic, collection, application, model, dataset
496
+
497
+ Alias: hypha artifacts mkdir`);
498
+ return;
499
+ }
500
+ const pos = positionalArgs(args, ["--type", "--parent"])[0];
501
+ const type = getFlag(args, "--type") || "generic";
502
+ const parent = getFlag(args, "--parent");
503
+ const json = hasFlag(args, "--json");
504
+ if (!pos) {
505
+ console.error("Usage: hypha artifacts create <alias> [--type T] [--parent P]");
506
+ console.error("Types: generic, collection, application, model, dataset");
507
+ process.exit(1);
508
+ }
509
+ const { server, am } = await connectAndGetArtifactManager();
510
+ try {
511
+ const createOpts = {
512
+ alias: pos,
513
+ type,
514
+ manifest: { name: pos },
515
+ _rkwargs: true
516
+ };
517
+ if (parent) createOpts.parent_id = parent;
518
+ const result = await am.create(createOpts);
519
+ await am.commit({ artifact_id: result.id || pos, _rkwargs: true });
520
+ if (json) {
521
+ console.log(formatJson(result));
522
+ } else {
523
+ console.log(`Created: ${result.alias || pos} (type: ${type})`);
524
+ }
525
+ } finally {
526
+ await server.disconnect();
527
+ }
528
+ }
529
+ async function artifactsInfo(args) {
530
+ if (hasFlag(args, "--help", "-h")) {
531
+ console.log(`hypha artifacts info \u2014 show artifact metadata
532
+
533
+ Usage: hypha artifacts info <artifact> [--json]
534
+
535
+ Options:
536
+ --json Output as JSON`);
537
+ return;
538
+ }
539
+ const pos = positionalArgs(args)[0];
540
+ const json = hasFlag(args, "--json");
541
+ if (!pos) {
542
+ console.error("Usage: hypha artifacts info <artifact> [--json]");
543
+ process.exit(1);
544
+ }
545
+ const parsed = parseArtifactPath(pos);
546
+ const { server, am } = await connectAndGetArtifactManager();
547
+ const artifactId = resolveArtifactId(parsed, server.config.workspace);
548
+ try {
549
+ const info = await am.read({
550
+ artifact_id: artifactId,
551
+ _rkwargs: true
552
+ });
553
+ if (json) {
554
+ console.log(formatJson(info));
555
+ } else {
556
+ const manifest = info.manifest || {};
557
+ console.log(`Alias: ${info.alias || artifactId}`);
558
+ console.log(`ID: ${info.id || ""}`);
559
+ console.log(`Type: ${info.type || "generic"}`);
560
+ console.log(`Name: ${manifest.name || ""}`);
561
+ console.log(`Description: ${manifest.description || ""}`);
562
+ console.log(`Workspace: ${info.workspace || ""}`);
563
+ if (info.created_at) console.log(`Created: ${new Date(info.created_at * 1e3).toISOString()}`);
564
+ if (info.last_modified) console.log(`Modified: ${new Date(info.last_modified * 1e3).toISOString()}`);
565
+ if (info.versions?.length) {
566
+ console.log(`Versions: ${info.versions.map((v) => v.name || v.version || v).join(", ")}`);
567
+ }
568
+ if (info.download_count) console.log(`Downloads: ${info.download_count}`);
569
+ if (info.view_count) console.log(`Views: ${info.view_count}`);
570
+ }
571
+ } finally {
572
+ await server.disconnect();
573
+ }
574
+ }
575
+ async function artifactsSearch(args) {
576
+ if (hasFlag(args, "--help", "-h")) {
577
+ console.log(`hypha artifacts search \u2014 search artifacts
578
+
579
+ Usage: hypha artifacts search <query> [options]
580
+
581
+ Options:
582
+ --type <type> Filter by artifact type
583
+ --limit <n> Max results (default: 20)
584
+ --json Output as JSON
585
+
586
+ Alias: hypha artifacts find`);
587
+ return;
588
+ }
589
+ const pos = positionalArgs(args, ["--type", "--limit"])[0];
590
+ const type = getFlag(args, "--type");
591
+ const limit = getFlagInt(args, "--limit") || 20;
592
+ const json = hasFlag(args, "--json");
593
+ if (!pos) {
594
+ console.error("Usage: hypha artifacts search <query> [--type T] [--limit N] [--json]");
595
+ process.exit(1);
596
+ }
597
+ const { server, am } = await connectAndGetArtifactManager();
598
+ try {
599
+ const searchOpts = {
600
+ keywords: pos,
601
+ limit,
602
+ _rkwargs: true
603
+ };
604
+ if (type) {
605
+ searchOpts.filters = { type };
606
+ }
607
+ const results = await am.list(searchOpts);
608
+ const list = Array.isArray(results) ? results : results?.items || [];
609
+ if (json) {
610
+ console.log(formatJson(list));
611
+ return;
612
+ }
613
+ if (list.length === 0) {
614
+ console.log("No results found.");
615
+ return;
616
+ }
617
+ const rows = [["ALIAS", "TYPE", "NAME", "DESCRIPTION"]];
618
+ for (const art of list) {
619
+ const manifest = art.manifest || {};
620
+ rows.push([
621
+ art.alias || art.id || "",
622
+ art.type || "",
623
+ manifest.name || "",
624
+ (manifest.description || "").slice(0, 40)
625
+ ]);
626
+ }
627
+ console.log(formatTable(rows));
628
+ } finally {
629
+ await server.disconnect();
630
+ }
631
+ }
632
+ async function artifactsCommit(args) {
633
+ if (hasFlag(args, "--help", "-h")) {
634
+ console.log(`hypha artifacts commit \u2014 commit staged changes
635
+
636
+ Usage: hypha artifacts commit <artifact> [options]
637
+
638
+ Options:
639
+ --version <version> Version tag (e.g., v1.0)
640
+ --message, -m <msg> Commit message`);
641
+ return;
642
+ }
643
+ const pos = positionalArgs(args, ["--version", "--message"])[0];
644
+ const version = getFlag(args, "--version");
645
+ const message = getFlag(args, "--message", "-m");
646
+ if (!pos) {
647
+ console.error("Usage: hypha artifacts commit <artifact> [--version V] [--message M]");
648
+ process.exit(1);
649
+ }
650
+ const parsed = parseArtifactPath(pos);
651
+ const { server, am } = await connectAndGetArtifactManager();
652
+ const artifactId = resolveArtifactId(parsed, server.config.workspace);
653
+ try {
654
+ const commitOpts = {
655
+ artifact_id: artifactId,
656
+ _rkwargs: true
657
+ };
658
+ if (version) commitOpts.version = version;
659
+ if (message) commitOpts.comment = message;
660
+ await am.commit(commitOpts);
661
+ console.log(`Committed: ${parsed.alias}${version ? ` (version: ${version})` : ""}`);
662
+ } finally {
663
+ await server.disconnect();
664
+ }
665
+ }
666
+ async function artifactsEdit(args) {
667
+ if (hasFlag(args, "--help", "-h")) {
668
+ console.log(`hypha artifacts edit \u2014 edit artifact metadata
669
+
670
+ Usage: hypha artifacts edit <artifact> [options]
671
+
672
+ Options:
673
+ --name <name> Update display name
674
+ --description <desc> Update description
675
+ --type <type> Update artifact type
676
+ --stage Enter staging mode for file operations`);
677
+ return;
678
+ }
679
+ const pos = positionalArgs(args, ["--name", "--description", "--type"])[0];
680
+ const name = getFlag(args, "--name");
681
+ const description = getFlag(args, "--description");
682
+ const type = getFlag(args, "--type");
683
+ const stage = hasFlag(args, "--stage");
684
+ if (!pos) {
685
+ console.error("Usage: hypha artifacts edit <artifact> [--name N] [--description D] [--type T] [--stage]");
686
+ process.exit(1);
687
+ }
688
+ const parsed = parseArtifactPath(pos);
689
+ const { server, am } = await connectAndGetArtifactManager();
690
+ const artifactId = resolveArtifactId(parsed, server.config.workspace);
691
+ try {
692
+ const editOpts = {
693
+ artifact_id: artifactId,
694
+ _rkwargs: true
695
+ };
696
+ const manifest = {};
697
+ if (name) manifest.name = name;
698
+ if (description) manifest.description = description;
699
+ if (Object.keys(manifest).length > 0) editOpts.manifest = manifest;
700
+ if (type) editOpts.type = type;
701
+ if (stage) editOpts.stage = true;
702
+ await am.edit(editOpts);
703
+ console.log(`Updated: ${parsed.alias}`);
704
+ } finally {
705
+ await server.disconnect();
706
+ }
707
+ }
708
+ async function artifactsDiscard(args) {
709
+ if (hasFlag(args, "--help", "-h")) {
710
+ console.log(`hypha artifacts discard \u2014 discard staged changes
711
+
712
+ Usage: hypha artifacts discard <artifact>`);
713
+ return;
714
+ }
715
+ const pos = positionalArgs(args)[0];
716
+ if (!pos) {
717
+ console.error("Usage: hypha artifacts discard <artifact>");
718
+ process.exit(1);
719
+ }
720
+ const parsed = parseArtifactPath(pos);
721
+ const { server, am } = await connectAndGetArtifactManager();
722
+ const artifactId = resolveArtifactId(parsed, server.config.workspace);
723
+ try {
724
+ await am.discard_changes({ artifact_id: artifactId, _rkwargs: true });
725
+ console.log(`Discarded staged changes: ${parsed.alias}`);
726
+ } finally {
727
+ await server.disconnect();
728
+ }
729
+ }
730
+ async function handleArtifactsCommand(args) {
731
+ const sub = args[0];
732
+ const commandArgs = args.slice(1);
733
+ if (!sub || sub === "--help" || sub === "-h") {
734
+ printArtifactsHelp();
735
+ return;
736
+ }
737
+ if (sub === "ls" || sub === "list") {
738
+ await artifactsLs(commandArgs);
739
+ } else if (sub === "cat") {
740
+ await artifactsCat(commandArgs);
741
+ } else if (sub === "cp") {
742
+ await artifactsCp(commandArgs);
743
+ } else if (sub === "rm") {
744
+ await artifactsRm(commandArgs);
745
+ } else if (sub === "create" || sub === "mkdir") {
746
+ await artifactsCreate(commandArgs);
747
+ } else if (sub === "info") {
748
+ await artifactsInfo(commandArgs);
749
+ } else if (sub === "search" || sub === "find") {
750
+ await artifactsSearch(commandArgs);
751
+ } else if (sub === "commit") {
752
+ await artifactsCommit(commandArgs);
753
+ } else if (sub === "edit") {
754
+ await artifactsEdit(commandArgs);
755
+ } else if (sub === "discard") {
756
+ await artifactsDiscard(commandArgs);
757
+ } else {
758
+ console.error(`Unknown artifacts command: ${sub}`);
759
+ printArtifactsHelp();
760
+ process.exit(1);
761
+ }
762
+ }
763
+
764
+ export { artifactsLs, handleArtifactsCommand };