@artifactshare/cli 0.16.0 → 0.17.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/index.js CHANGED
@@ -2,13 +2,14 @@
2
2
  import { C as defaultPreviewNotificationRegistration, D as isPreviewAnchor, O as isPreviewAnnotation, S as createPreviewNotificationCoordinator, T as PREVIEW_MUTATION_HEADER, _ as resolveLiveSession, a as annotationsFilePath, b as updateSessionNotificationRegistration, c as isSessionId, d as previewsDir, f as probeSession, g as removeSessionFile, h as releaseStaleClaim, i as cursorNotificationRegistration, k as isPreviewDoneItemInput, l as previewIdentityPath, m as readSessionFile, n as CURSOR_ACP_NOTIFICATION_TIMEOUT_MS, o as claimSessionStart, p as processAlive, r as createCursorAcpAdapter, s as isConnectionRefused, u as previewRealpath, v as sessionIdForPath, w as samePreviewNotificationRegistration, x as writeSessionFile, y as tokenFingerprint } from "./cursor-notification-Hz6fuACK.js";
3
3
  import { cli, define, lazy } from "gunshi";
4
4
  import { generate } from "gunshi/generator";
5
- import { chmodSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, watch, writeFileSync } from "node:fs";
5
+ import { chmodSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, watch, writeFileSync } from "node:fs";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { z } from "zod";
8
8
  import { execFile, spawn } from "node:child_process";
9
- import { appendFile, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
9
+ import * as fs from "node:fs/promises";
10
+ import { chmod, lstat, mkdir, readFile, realpath, rm, rmdir, stat, writeFile } from "node:fs/promises";
10
11
  import { arch, homedir, platform } from "node:os";
11
- import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
12
+ import path, { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
12
13
  import { createHash, randomUUID } from "node:crypto";
13
14
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
14
15
  import { Blob, Buffer as Buffer$1 } from "node:buffer";
@@ -18,6 +19,9 @@ import { promisify } from "node:util";
18
19
  //#region ../contract/dist/index.js
19
20
  const CLI_DEVICE_CLIENT_ID = "artifactshare-cli";
20
21
  const stringId = z.string().min(1);
22
+ const artifactIdPattern = /^[a-z0-9]{10}$/;
23
+ const ArtifactIdSchema = z.string().regex(artifactIdPattern);
24
+ const isArtifactId = (value) => typeof value === "string" && artifactIdPattern.test(value);
21
25
  const timestamp = z.string().min(1);
22
26
  const url = z.string().url();
23
27
  const nullableTimestamp = timestamp.nullable();
@@ -400,7 +404,7 @@ const DownloadManifestFileSchema = z.object({
400
404
  sha256: z.string()
401
405
  });
402
406
  const DownloadManifestResponseSchema = z.object({
403
- id: stringId,
407
+ id: ArtifactIdSchema,
404
408
  share_url: url,
405
409
  version_id: stringId,
406
410
  artifact_kind: UploadArtifactKindSchema,
@@ -409,7 +413,7 @@ const DownloadManifestResponseSchema = z.object({
409
413
  project_id: stringId.nullable().optional()
410
414
  });
411
415
  const ArtifactsListEntrySchema = z.object({
412
- id: stringId,
416
+ id: ArtifactIdSchema,
413
417
  title: z.string(),
414
418
  share_url: url,
415
419
  visibility: VisibilitySchema,
@@ -1676,6 +1680,16 @@ function resolveArtifactId(input) {
1676
1680
  } catch {
1677
1681
  return null;
1678
1682
  }
1683
+ const contentHostMatch = url.hostname.match(/^[al]-([a-z0-9]{10})--v-((?:[a-f0-9]{2})+)\.(?:artifactshareusercontent\.com|usercontent\.localhost)$/);
1684
+ const artifactId = contentHostMatch?.[1];
1685
+ const encodedVersion = contentHostMatch?.[2];
1686
+ if (artifactId && encodedVersion && url.hostname.indexOf(".") <= 63) try {
1687
+ const bytes = Uint8Array.from(encodedVersion.match(/../g), (byte) => Number.parseInt(byte, 16));
1688
+ const version = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1689
+ if (version && Buffer.from(version).toString("hex") === encodedVersion) return artifactId;
1690
+ } catch {
1691
+ return null;
1692
+ }
1679
1693
  const linkHostMatch = url.hostname.match(/^([A-Za-z0-9]{10})(?:--v-[a-f0-9]+)?\.artifactshare\.link$/);
1680
1694
  if (linkHostMatch?.[1]) return linkHostMatch[1];
1681
1695
  const sandboxMatch = url.hostname.match(/^([A-Za-z0-9]+)(?:--v-[a-f0-9]+)?\.sandbox\./);
@@ -1705,7 +1719,7 @@ function targetResolutionError(input, command) {
1705
1719
  code: "target_not_found",
1706
1720
  message: "Artifact target could not be resolved.",
1707
1721
  why: `${TARGET_COMMAND_LABELS[command]} only accepts an artifact ID, share URL, or sandbox URL.`,
1708
- hint: "Retry with an artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL. If you only have a title, resolve it to an ID first.",
1722
+ hint: "Retry with an artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL. If you only have a title, resolve it to an ID first.",
1709
1723
  agentRecoverable: true,
1710
1724
  requiresHuman: false,
1711
1725
  recovery: { kind: "change_input" },
@@ -1976,6 +1990,10 @@ function humanSuccess(command, data) {
1976
1990
  const withWarnings = warnings.length ? `${output}${warnings.map((message) => `Warning: ${message}`).join("\n")}\n` : output;
1977
1991
  return suffix ? `${withWarnings}${suffix}` : withWarnings;
1978
1992
  }
1993
+ if (command === "download" && isRecord$1(data) && Array.isArray(data.backup_paths)) {
1994
+ const recovery = data.backup_paths.map((path) => `Original data retained at ${String(path)}; inspect it before manual cleanup.`).join("\n");
1995
+ return `${JSON.stringify(data, null, 2)}\n${recovery ? `${recovery}\n` : ""}`;
1996
+ }
1979
1997
  if (command === "doctor") return doctorHumanOutput(data);
1980
1998
  if (command === "open") return openHumanOutput(data);
1981
1999
  if (command === "init") return initHumanOutput(data);
@@ -2570,9 +2588,6 @@ async function resolveDefaultVisibility(key, repositoryConfig) {
2570
2588
  async function readProjectConfigAtDirectory(directory, kind) {
2571
2589
  return await readJsonFile(join(directory, kind === "local" ? PROJECT_CONFIG_LOCAL_PATH : PROJECT_CONFIG_PATH));
2572
2590
  }
2573
- async function readRawLocalProjectConfig(cwd = process.cwd()) {
2574
- return await readJsonFile(projectConfigLocalPath(cwd));
2575
- }
2576
2591
  function configString(value) {
2577
2592
  return nonEmpty(typeof value === "string" ? value : void 0) ?? null;
2578
2593
  }
@@ -11739,45 +11754,636 @@ async function runChangelog(_parsed, mode) {
11739
11754
  return writeSuccess("changelog", await buildChangelogData(await loadCliVersion()), mode);
11740
11755
  }
11741
11756
  //#endregion
11757
+ //#region src/write-boundary.ts
11758
+ var WriteBoundaryError = class extends Error {
11759
+ path;
11760
+ error;
11761
+ constructor(path, hint = "Choose a regular directory without links, check retained recovery paths, and retry.", message = `Unsafe or changed write path ${path}.`) {
11762
+ super(message);
11763
+ this.path = path;
11764
+ this.error = validationError(this.message, hint);
11765
+ }
11766
+ };
11767
+ var WriteFileSystemError = class extends Error {
11768
+ path;
11769
+ constructor(path, cause) {
11770
+ super(`Could not complete a filesystem operation at ${path}.`, { cause });
11771
+ this.path = path;
11772
+ }
11773
+ };
11774
+ const same = (a, b) => a.dev === b.dev && a.ino === b.ino && a.isDirectory() === b.isDirectory() && a.isFile() === b.isFile();
11775
+ /** Observed identity checks, not an atomic directory-relative filesystem API. */
11776
+ var WriteBoundary = class {
11777
+ dependencies;
11778
+ entries = /* @__PURE__ */ new Map();
11779
+ children = /* @__PURE__ */ new Map();
11780
+ trustedParents = /* @__PURE__ */ new Set();
11781
+ absent = /* @__PURE__ */ new Set();
11782
+ guards = /* @__PURE__ */ new Set();
11783
+ watch(...paths) {
11784
+ for (const path of paths) this.guards.add(resolve(path));
11785
+ }
11786
+ backupPaths = [];
11787
+ workspace;
11788
+ constructor(dependencies = {}) {
11789
+ this.dependencies = dependencies;
11790
+ }
11791
+ setEntry(path, entry) {
11792
+ this.entries.set(path, entry);
11793
+ const parent = dirname(path);
11794
+ if (parent === path) return;
11795
+ let children = this.children.get(parent);
11796
+ if (!children) this.children.set(parent, children = /* @__PURE__ */ new Set());
11797
+ children.add(path);
11798
+ }
11799
+ deleteEntry(path) {
11800
+ this.entries.delete(path);
11801
+ this.children.get(dirname(path))?.delete(path);
11802
+ }
11803
+ *subtree(path) {
11804
+ const entry = this.entries.get(path);
11805
+ if (entry) yield [path, entry];
11806
+ for (const child of this.children.get(path) ?? []) yield* this.subtree(child);
11807
+ }
11808
+ async outputParent(path) {
11809
+ path = resolve(path);
11810
+ if (this.entries.has(path)) {
11811
+ await this.record(path, true);
11812
+ return;
11813
+ }
11814
+ this.trustedParents.add(path);
11815
+ this.watch(path);
11816
+ if (!await this.record(path, true)) await this.outputParent(dirname(path));
11817
+ }
11818
+ async io(path, action) {
11819
+ try {
11820
+ return await action();
11821
+ } catch (error) {
11822
+ if (error instanceof WriteBoundaryError || error instanceof WriteFileSystemError) throw error;
11823
+ throw new WriteFileSystemError(path, error);
11824
+ }
11825
+ }
11826
+ async stat(path) {
11827
+ try {
11828
+ const s = await (this.trustedParents.has(path) ? this.dependencies.stat ?? ((name) => fs.stat(name, { bigint: true })) : this.dependencies.lstat ?? ((name) => fs.lstat(name, { bigint: true })))(path);
11829
+ if (s.isSymbolicLink() || !s.isDirectory() && !s.isFile() || typeof s.dev !== "bigint" || typeof s.ino !== "bigint" || s.ino <= 0n) throw new WriteBoundaryError(path);
11830
+ return s;
11831
+ } catch (error) {
11832
+ if (error.code === "ENOENT") return null;
11833
+ throw new WriteBoundaryError(path);
11834
+ }
11835
+ }
11836
+ async record(path, directory = false) {
11837
+ path = resolve(path);
11838
+ if (this.entries.has(path) || this.absent.has(path)) {
11839
+ await this.check(path);
11840
+ if (directory && this.entries.has(path) && !this.entries.get(path).stat.isDirectory()) throw new WriteBoundaryError(path);
11841
+ return this.entries.has(path);
11842
+ }
11843
+ const s = await this.stat(path);
11844
+ if (!s) {
11845
+ this.absent.add(path);
11846
+ return false;
11847
+ }
11848
+ if (directory && !s.isDirectory()) throw new WriteBoundaryError(path);
11849
+ this.setEntry(path, {
11850
+ stat: s,
11851
+ owned: false
11852
+ });
11853
+ await this.check(path);
11854
+ return true;
11855
+ }
11856
+ async check(...paths) {
11857
+ const selected = /* @__PURE__ */ new Set();
11858
+ for (const target of [
11859
+ ...this.guards,
11860
+ ...paths,
11861
+ ...this.workspace ? [this.workspace] : []
11862
+ ]) {
11863
+ let path = resolve(target);
11864
+ selected.add(path);
11865
+ while (!this.trustedParents.has(path)) {
11866
+ const parent = dirname(path);
11867
+ if (parent === path || !this.entries.has(parent)) break;
11868
+ selected.add(parent);
11869
+ path = parent;
11870
+ }
11871
+ }
11872
+ const observed = /* @__PURE__ */ new Map();
11873
+ const inspect = async (path) => {
11874
+ if (!observed.has(path)) observed.set(path, await this.stat(path));
11875
+ return observed.get(path);
11876
+ };
11877
+ for (const path of selected) {
11878
+ const entry = this.entries.get(path);
11879
+ if (!entry) {
11880
+ if (this.absent.has(path) && await inspect(path)) throw new WriteBoundaryError(path);
11881
+ continue;
11882
+ }
11883
+ const s = await inspect(path);
11884
+ if (!s || !same(s, entry.stat)) throw new WriteBoundaryError(path);
11885
+ const parent = this.entries.get(dirname(path));
11886
+ if (parent && !this.trustedParents.has(path)) {
11887
+ const physical = await (this.dependencies.realpath ?? fs.realpath)(path).catch(() => {
11888
+ throw new WriteBoundaryError(path);
11889
+ });
11890
+ const actualEntry = await inspect(physical);
11891
+ if (!actualEntry || !same(actualEntry, s)) throw new WriteBoundaryError(path);
11892
+ const actual = await inspect(dirname(physical));
11893
+ if (!actual || !same(actual, parent.stat)) throw new WriteBoundaryError(path);
11894
+ }
11895
+ }
11896
+ }
11897
+ async directory(path) {
11898
+ path = resolve(path);
11899
+ if (this.entries.has(path)) {
11900
+ await this.check(path);
11901
+ if (!this.entries.get(path).stat.isDirectory()) throw new WriteBoundaryError(path);
11902
+ return;
11903
+ }
11904
+ if (await this.record(path, true)) return;
11905
+ await this.directory(dirname(path));
11906
+ await this.before("create", path);
11907
+ await this.io(path, () => fs.mkdir(path));
11908
+ this.absent.delete(path);
11909
+ const s = await this.stat(path);
11910
+ if (!s?.isDirectory()) throw new WriteBoundaryError(path);
11911
+ this.setEntry(path, {
11912
+ stat: s,
11913
+ owned: true
11914
+ });
11915
+ await this.check(path);
11916
+ }
11917
+ async tree(path) {
11918
+ if (!await this.record(path)) return;
11919
+ if (this.entries.get(resolve(path)).stat.isDirectory()) {
11920
+ for (const name of await this.io(path, () => fs.readdir(path))) await this.tree(join(path, name));
11921
+ await this.check(path);
11922
+ }
11923
+ }
11924
+ async checkTree(path) {
11925
+ await this.check(path, ...[...this.subtree(resolve(path))].map(([name]) => name));
11926
+ }
11927
+ async before(phase, path, ...otherPaths) {
11928
+ await this.dependencies.checkpoint?.(phase, path);
11929
+ await this.check(path, ...otherPaths);
11930
+ }
11931
+ async privateDirectory(parent) {
11932
+ await this.directory(parent);
11933
+ await this.before("create", parent);
11934
+ const path = await this.io(parent, () => fs.mkdtemp(join(parent, ".artifactshare-")));
11935
+ const stat = await this.stat(path);
11936
+ if (!stat?.isDirectory()) throw new WriteBoundaryError(path);
11937
+ this.setEntry(path, {
11938
+ stat,
11939
+ owned: true
11940
+ });
11941
+ await this.check(path);
11942
+ return path;
11943
+ }
11944
+ async read(path) {
11945
+ path = resolve(path);
11946
+ if (!await this.record(path)) return null;
11947
+ const entry = this.entries.get(path);
11948
+ if (!entry.stat.isFile()) throw new WriteBoundaryError(path);
11949
+ await this.before("read", path);
11950
+ const handle = await this.io(path, () => (this.dependencies.open ?? fs.open)(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)));
11951
+ try {
11952
+ const s = await handle.stat({ bigint: true });
11953
+ if (!same(s, entry.stat)) throw new WriteBoundaryError(path);
11954
+ const text = await this.io(path, () => handle.readFile("utf8"));
11955
+ await this.check(path);
11956
+ const after = await handle.stat({ bigint: true });
11957
+ if (!same(after, s) || after.size !== s.size || after.mtimeNs !== s.mtimeNs) throw new WriteBoundaryError(path);
11958
+ return text;
11959
+ } finally {
11960
+ await this.io(path, () => handle.close());
11961
+ }
11962
+ }
11963
+ async write(path, content, mode) {
11964
+ path = resolve(path);
11965
+ await this.directory(dirname(path));
11966
+ if (await this.record(path)) throw new WriteBoundaryError(path);
11967
+ await this.before("create", path);
11968
+ const handle = await this.io(path, () => (this.dependencies.open ?? fs.open)(path, "wx", mode ?? 438));
11969
+ try {
11970
+ const stat = await handle.stat({ bigint: true });
11971
+ this.absent.delete(path);
11972
+ this.setEntry(path, {
11973
+ stat,
11974
+ owned: true
11975
+ });
11976
+ await this.check(path);
11977
+ await this.io(path, () => handle.writeFile(content));
11978
+ if (mode !== void 0) await this.io(path, () => handle.chmod(mode));
11979
+ await this.check(path);
11980
+ } finally {
11981
+ await this.io(path, () => handle.close());
11982
+ }
11983
+ }
11984
+ async move(source, destination, replace = false) {
11985
+ source = resolve(source);
11986
+ destination = resolve(destination);
11987
+ if (!this.entries.has(source)) throw new WriteBoundaryError(source);
11988
+ for (const path of [source, destination]) if (!this.entries.get(dirname(path))?.stat.isDirectory()) throw new WriteBoundaryError(dirname(path));
11989
+ await this.record(destination);
11990
+ if (!replace && this.entries.has(destination)) throw new WriteBoundaryError(destination);
11991
+ await this.before("rename", destination, source);
11992
+ await this.io(destination, () => (this.dependencies.rename ?? fs.rename)(source, destination));
11993
+ this.deleteEntry(destination);
11994
+ this.absent.delete(destination);
11995
+ const moved = [...this.subtree(source)];
11996
+ for (const [path] of moved) this.deleteEntry(path);
11997
+ for (const [path, entry] of moved) this.setEntry(destination + path.slice(source.length), entry);
11998
+ this.absent.add(source);
11999
+ await this.check(source, destination);
12000
+ }
12001
+ async replace(source, destination, retain = true) {
12002
+ const guarded = this.guards.has(resolve(destination));
12003
+ this.watch(destination);
12004
+ try {
12005
+ let backup;
12006
+ if (await this.record(destination)) {
12007
+ if (!retain) {
12008
+ await this.move(source, destination, true);
12009
+ return;
12010
+ }
12011
+ if (!this.workspace) throw new WriteBoundaryError(destination);
12012
+ backup = join(this.workspace, `backup-${randomUUID()}`);
12013
+ await this.move(destination, backup);
12014
+ this.backupPaths.push(backup);
12015
+ }
12016
+ try {
12017
+ await this.move(source, destination);
12018
+ } catch (error) {
12019
+ if (backup) try {
12020
+ await this.before("rollback", destination);
12021
+ await this.move(backup, destination);
12022
+ this.backupPaths.splice(this.backupPaths.indexOf(backup), 1);
12023
+ } catch (restoreError) {
12024
+ const failure = new WriteBoundaryError(destination, `Publication failed and backup restoration could not finish. Recover original data at ${backup}; inspect it before manual cleanup.`);
12025
+ Object.defineProperty(failure, "cause", { value: new AggregateError([error, restoreError]) });
12026
+ throw failure;
12027
+ }
12028
+ throw error;
12029
+ }
12030
+ } finally {
12031
+ if (!guarded) this.guards.delete(resolve(destination));
12032
+ }
12033
+ }
12034
+ async atomicWrite(path, content, retain = false, temporaryParent = dirname(path)) {
12035
+ await this.record(path);
12036
+ const temp = join(temporaryParent, `.artifactshare-${randomUUID()}.tmp`);
12037
+ const existing = this.entries.get(resolve(path));
12038
+ await this.write(temp, content, existing ? Number(existing.stat.mode & 511n) : void 0);
12039
+ await this.replace(temp, path, retain);
12040
+ }
12041
+ async cleanup() {
12042
+ const retained = (path) => this.backupPaths.some((backup) => backup === path || backup.startsWith(`${path}${sep}`));
12043
+ for (const [path, entry] of [...this.entries].reverse()) {
12044
+ if (!entry.owned || retained(path)) continue;
12045
+ await this.before("remove", path);
12046
+ if (entry.stat.isDirectory()) await this.io(path, () => (this.dependencies.rmdir ?? fs.rmdir)(path));
12047
+ else await this.io(path, () => (this.dependencies.unlink ?? fs.unlink)(path));
12048
+ this.deleteEntry(path);
12049
+ this.absent.add(path);
12050
+ }
12051
+ }
12052
+ async retainedWorkspace() {
12053
+ if (!this.workspace || !this.entries.has(this.workspace)) return;
12054
+ try {
12055
+ await this.check(this.workspace);
12056
+ if ((await fs.readdir(this.workspace)).length > 0) return this.workspace;
12057
+ } catch {}
12058
+ }
12059
+ async finish() {
12060
+ await this.cleanup();
12061
+ }
12062
+ keep(path) {
12063
+ path = resolve(path);
12064
+ for (const [, entry] of this.subtree(path)) entry.owned = false;
12065
+ for (let parent = dirname(path);; parent = dirname(parent)) {
12066
+ const entry = this.entries.get(parent);
12067
+ if (entry) entry.owned = false;
12068
+ if (dirname(parent) === parent) break;
12069
+ }
12070
+ }
12071
+ };
12072
+ //#endregion
12073
+ //#region src/upload-boundary.ts
12074
+ const hints = {
12075
+ parent_traversal: "Pass a direct absolute path without any .. component.",
12076
+ link: "Copy the file into the selection or pass the target by absolute path.",
12077
+ outside_cwd: "Pass an absolute path to select a file outside the current directory.",
12078
+ not_found: "Check the path and retry.",
12079
+ changed: "The selection changed while reading. Retry the command.",
12080
+ unsupported_guarantee: "Stable file identity (dev/ino) and the available no-follow open guarantee are required. Select a filesystem that supports them.",
12081
+ invalid_type: "Select a regular file or directory."
12082
+ };
12083
+ const messages = {
12084
+ parent_traversal: "Parent traversal (..) is not allowed",
12085
+ link: "A symbolic link is not allowed",
12086
+ outside_cwd: "The selection leaves the current directory",
12087
+ not_found: "Path was not found",
12088
+ changed: "The selection changed while reading",
12089
+ unsupported_guarantee: "The filesystem cannot provide the required guarantee",
12090
+ invalid_type: "Path must be a regular file or directory"
12091
+ };
12092
+ var UploadBoundaryError = class extends Error {
12093
+ error;
12094
+ constructor(display, reason, cause, guarantee) {
12095
+ super(`Upload path ${display}: ${messages[reason]}.`, { cause });
12096
+ this.error = cliError({
12097
+ code: "validation_failed",
12098
+ message: this.message,
12099
+ why: this.message,
12100
+ hint: guarantee ? `Required guarantee unavailable: ${guarantee}. Select a filesystem that supports it.` : hints[reason],
12101
+ agentRecoverable: true,
12102
+ requiresHuman: false,
12103
+ recovery: { kind: reason === "changed" ? "retry_later" : "change_input" },
12104
+ details: {
12105
+ path: display,
12106
+ reason,
12107
+ ...guarantee ? { guarantee } : {}
12108
+ }
12109
+ });
12110
+ Object.defineProperty(this.error, "cause", { value: cause });
12111
+ }
12112
+ };
12113
+ var UploadReadFailure = class extends Error {
12114
+ error;
12115
+ constructor(error, cause) {
12116
+ super(error.message, { cause });
12117
+ this.error = error;
12118
+ }
12119
+ };
12120
+ function uploadReadError(error, display) {
12121
+ if (error instanceof UploadReadFailure) return error.error;
12122
+ if (error instanceof UploadBoundaryError) return error.error;
12123
+ const result = cliError({
12124
+ code: "upload_read_failed",
12125
+ message: `Could not read upload path ${display}.`,
12126
+ why: "The local filesystem rejected an upload read.",
12127
+ hint: "Check filesystem availability and permissions, then retry.",
12128
+ agentRecoverable: true,
12129
+ requiresHuman: false,
12130
+ recovery: { kind: "retry_later" },
12131
+ details: {
12132
+ path: display,
12133
+ errno: error?.code
12134
+ }
12135
+ });
12136
+ Object.defineProperty(result, "cause", { value: error });
12137
+ return result;
12138
+ }
12139
+ async function prepareUploadSelection(input, singleFile = false, dependencies = {}) {
12140
+ const fail = (display, reason, cause, guarantee) => {
12141
+ throw new UploadBoundaryError(display, reason, cause, guarantee);
12142
+ };
12143
+ if (input.replace(/^[a-z]:/iu, "").split(/[\\/]/u).includes("..")) fail(input, "parent_traversal");
12144
+ const paths = dependencies.paths ?? path;
12145
+ const cwd = dependencies.cwd ?? process.cwd();
12146
+ const inspect = dependencies.lstat ?? ((name) => fs.lstat(name, { bigint: true }));
12147
+ const checkpoint = dependencies.checkpoint ?? (async () => {});
12148
+ const identity = (s, display) => {
12149
+ if (typeof s.dev !== "bigint" || typeof s.ino !== "bigint" || s.ino <= 0n) fail(display, "unsupported_guarantee", void 0, "stable file identity (dev/ino)");
12150
+ };
12151
+ const same = (a, b) => a.dev === b.dev && a.ino === b.ino;
12152
+ const sameFile = (actual, recorded) => actual.isFile() && same(actual, recorded) && actual.mode === recorded.mode && actual.size === recorded.size;
12153
+ const checkType = (s, display) => {
12154
+ if (s.isSymbolicLink()) fail(display, "link");
12155
+ identity(s, display);
12156
+ if (!s.isFile() && !s.isDirectory()) fail(display, "invalid_type");
12157
+ };
12158
+ const get = async (name, display, recorded = false) => {
12159
+ try {
12160
+ return await inspect(name);
12161
+ } catch (error) {
12162
+ const code = error.code;
12163
+ if (code === "ENOENT" || code === "ENOTDIR") fail(display, recorded ? "changed" : "not_found", error);
12164
+ if (code === "ELOOP") fail(display, "link", error);
12165
+ throw new UploadReadFailure(uploadReadError(error, display), error);
12166
+ }
12167
+ };
12168
+ const physicalPaths = /* @__PURE__ */ new Map();
12169
+ const physicalPath = async (name, display) => {
12170
+ const cached = physicalPaths.get(name);
12171
+ if (cached !== void 0) return cached;
12172
+ try {
12173
+ const resolved = await (dependencies.realpath ?? fs.realpath)(name);
12174
+ physicalPaths.set(name, resolved);
12175
+ return resolved;
12176
+ } catch (error) {
12177
+ const code = error.code;
12178
+ if (code === "ENOENT" || code === "ENOTDIR") fail(display, "changed", error);
12179
+ if (code === "ELOOP") fail(display, "link", error);
12180
+ throw new UploadReadFailure(uploadReadError(error, display), error);
12181
+ }
12182
+ };
12183
+ const checkPhysicalEntry = async (name, display, parent, storedName) => {
12184
+ const resolved = await physicalPath(name, display);
12185
+ if (storedName !== void 0 && storedName !== paths.basename(resolved)) fail(display, "link");
12186
+ const actualParent = await get(paths.dirname(resolved), display, true);
12187
+ checkType(actualParent, display);
12188
+ if (!actualParent.isDirectory() || !same(actualParent, parent)) fail(display, "link");
12189
+ };
12190
+ const recheck = async (entry, directory) => {
12191
+ const s = await get(entry.path, entry.display, true);
12192
+ if (s.isSymbolicLink()) fail(entry.display, "link");
12193
+ identity(s, entry.display);
12194
+ if (directory ? !s.isDirectory() || !same(s, entry.stat) : !sameFile(s, entry.stat)) fail(entry.display, "changed");
12195
+ };
12196
+ const checkChain = async (chain) => {
12197
+ for (const entry of chain) await recheck(entry, true);
12198
+ };
12199
+ let offending = input;
12200
+ try {
12201
+ const explicit = paths.isAbsolute(input) || paths.sep === "\\" && /^[a-z]:/iu.test(input);
12202
+ let selectedPath = paths.resolve(cwd, input);
12203
+ const chain = [];
12204
+ let selected;
12205
+ if (!explicit) {
12206
+ const root = await physicalPath(cwd, input);
12207
+ physicalPaths.set(root, root);
12208
+ const rootStat = await get(root, input);
12209
+ checkType(rootStat, input);
12210
+ chain.push({
12211
+ path: root,
12212
+ display: input,
12213
+ stat: rootStat
12214
+ });
12215
+ let cursor = root;
12216
+ const components = input.split(paths.sep === "\\" ? /[\\/]/u : /\//u).filter((part) => part !== "" && part !== ".");
12217
+ selected = rootStat;
12218
+ for (let index = 0; index < components.length; index++) {
12219
+ await checkChain(chain);
12220
+ cursor = paths.join(cursor, components[index]);
12221
+ selected = await get(cursor, input);
12222
+ checkType(selected, input);
12223
+ await checkPhysicalEntry(cursor, input, chain[chain.length - 1].stat);
12224
+ await checkChain(chain);
12225
+ if (index < components.length - 1) {
12226
+ if (!selected.isDirectory()) fail(input, "not_found");
12227
+ chain.push({
12228
+ path: cursor,
12229
+ display: input,
12230
+ stat: selected
12231
+ });
12232
+ }
12233
+ }
12234
+ if (components.length > 0) {
12235
+ const typed = await get(`${cwd}${cwd.endsWith(paths.sep) ? "" : paths.sep}${input}`, input);
12236
+ checkType(typed, input);
12237
+ if (!same(selected, typed)) fail(input, "outside_cwd");
12238
+ }
12239
+ selectedPath = cursor;
12240
+ } else {
12241
+ selected = await get(selectedPath, input);
12242
+ checkType(selected, input);
12243
+ const parent = await get(await physicalPath(paths.dirname(selectedPath), input), input);
12244
+ checkType(parent, input);
12245
+ await checkPhysicalEntry(selectedPath, input, parent);
12246
+ }
12247
+ if (singleFile && !selected.isFile()) fail(input, "invalid_type");
12248
+ const leaves = [];
12249
+ const visit = async (dir, parents, prefix) => {
12250
+ const current = [...parents, dir];
12251
+ await checkChain(current);
12252
+ offending = dir.display;
12253
+ let names;
12254
+ try {
12255
+ names = await (dependencies.readdir ?? fs.readdir)(dir.path);
12256
+ } catch (error) {
12257
+ const code = error.code;
12258
+ if (code === "ENOENT" || code === "ENOTDIR") fail(dir.display, "changed", error);
12259
+ if (code === "ELOOP") fail(dir.display, "link", error);
12260
+ throw error;
12261
+ }
12262
+ await checkChain(current);
12263
+ for (const name of names) {
12264
+ if (name.startsWith(".") || name === "__MACOSX" || EXCLUDED_DIR_NAMES.has(name) || IGNORED_FILENAMES.has(name)) continue;
12265
+ const display = prefix ? `${prefix}/${name}` : name;
12266
+ offending = display;
12267
+ await checkpoint("entry", paths.join(dir.path, name));
12268
+ await checkChain(current);
12269
+ const entry = {
12270
+ path: paths.join(dir.path, name),
12271
+ display,
12272
+ stat: await get(paths.join(dir.path, name), display, true)
12273
+ };
12274
+ checkType(entry.stat, display);
12275
+ await checkPhysicalEntry(entry.path, display, dir.stat, name);
12276
+ await checkChain(current);
12277
+ if (entry.stat.isDirectory()) await visit(entry, current, display);
12278
+ else leaves.push({
12279
+ ...entry,
12280
+ name: display,
12281
+ chain: current
12282
+ });
12283
+ }
12284
+ await checkChain(current);
12285
+ };
12286
+ const root = {
12287
+ path: selectedPath,
12288
+ display: input,
12289
+ stat: selected
12290
+ };
12291
+ if (selected.isDirectory()) await visit(root, chain, "");
12292
+ else leaves.push({
12293
+ ...root,
12294
+ name: paths.basename(await physicalPath(selectedPath, input)),
12295
+ chain
12296
+ });
12297
+ leaves.sort((a, b) => a.name.localeCompare(b.name));
12298
+ const files = [];
12299
+ for (const leaf of leaves) {
12300
+ offending = leaf.display;
12301
+ await checkpoint("before_open", leaf.path);
12302
+ await checkChain(leaf.chain);
12303
+ await recheck(leaf, false);
12304
+ let handle;
12305
+ try {
12306
+ handle = await (dependencies.open ?? fs.open)(leaf.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
12307
+ } catch (error) {
12308
+ const code = error.code;
12309
+ if (code === "ELOOP") fail(leaf.display, "link", error);
12310
+ if (code === "ENOENT" || code === "ENOTDIR") fail(leaf.display, "changed", error);
12311
+ if (constants.O_NOFOLLOW && (code === "EINVAL" || code === "ENOTSUP" || code === "EOPNOTSUPP")) fail(leaf.display, "unsupported_guarantee", error, "O_NOFOLLOW open");
12312
+ throw error;
12313
+ }
12314
+ let failed = false;
12315
+ try {
12316
+ const checkHandle = async () => {
12317
+ const s = await handle.stat({ bigint: true });
12318
+ identity(s, leaf.display);
12319
+ if (!sameFile(s, leaf.stat)) fail(leaf.display, "changed");
12320
+ };
12321
+ await checkpoint("after_open", leaf.path);
12322
+ await checkHandle();
12323
+ await checkChain(leaf.chain);
12324
+ await recheck(leaf, false);
12325
+ const bytes = await handle.readFile();
12326
+ await checkpoint("after_read", leaf.path);
12327
+ await checkHandle();
12328
+ await recheck(leaf, false);
12329
+ await checkChain(leaf.chain);
12330
+ if (BigInt(bytes.byteLength) !== leaf.stat.size) fail(leaf.display, "changed");
12331
+ files.push({
12332
+ name: leaf.name,
12333
+ blob: new Blob([bytes])
12334
+ });
12335
+ } catch (error) {
12336
+ failed = true;
12337
+ throw error;
12338
+ } finally {
12339
+ if (failed) await handle.close().catch(() => {});
12340
+ else await handle.close();
12341
+ }
12342
+ }
12343
+ return {
12344
+ directory: selected.isDirectory(),
12345
+ files
12346
+ };
12347
+ } catch (error) {
12348
+ if (error instanceof UploadBoundaryError || error instanceof UploadReadFailure) throw error;
12349
+ throw new UploadReadFailure(uploadReadError(error, offending), error);
12350
+ }
12351
+ }
12352
+ //#endregion
11742
12353
  //#region src/files.ts
12354
+ var DownloadManifestError = class extends Error {
12355
+ error;
12356
+ constructor(message) {
12357
+ super(message);
12358
+ this.error = validationError(message, "Retry later. If this repeats, report the artifact ID.");
12359
+ }
12360
+ };
11743
12361
  let undiciModule;
11744
12362
  async function createUploadForm() {
11745
12363
  const { FormData } = undiciModule ??= await import("undici");
11746
12364
  return new FormData();
11747
12365
  }
11748
- async function prepareUploadPayload(targetPath, fileStat, initialForm) {
11749
- const form = initialForm ?? await createUploadForm();
11750
- if (fileStat.isDirectory()) {
11751
- let files;
11752
- try {
11753
- files = await collectDirectoryFiles(resolve(targetPath));
11754
- } catch (error) {
11755
- if (error instanceof CollectDirectoryFilesError) return { error: validationError(error.message, error.hint) };
11756
- throw error;
11757
- }
11758
- if (files.length === 0) return { error: validationError("Directory has no shareable files.", "Add index.html or index.md and retry.") };
11759
- for (const file of files) form.append("file", await blobFor(file.path), file.relativePath);
11760
- return { payload: {
11761
- form,
11762
- kind: "static_site"
11763
- } };
11764
- }
11765
- if (fileStat.isFile()) {
11766
- form.append("file", await blobFor(targetPath), basename(targetPath));
12366
+ async function prepareUploadPayload(targetPath, dependencies) {
12367
+ try {
12368
+ const selection = await prepareUploadSelection(targetPath, false, dependencies);
12369
+ if (selection.directory && selection.files.length === 0) return { error: validationError("Directory has no shareable files.", "Add index.html or index.md and retry.") };
12370
+ const form = await createUploadForm();
12371
+ for (const file of selection.files) form.append("file", file.blob.slice(0, file.blob.size, contentTypeFor(file.name)), file.name);
11767
12372
  return { payload: {
11768
12373
  form,
11769
- kind: artifactKindForFile(targetPath)
12374
+ kind: selection.directory ? "static_site" : artifactKindForFile(selection.files[0].name)
11770
12375
  } };
12376
+ } catch (error) {
12377
+ return { error: uploadReadError(error, targetPath) };
11771
12378
  }
11772
- return { error: validationError("Path must be a file or directory.", "Pass a regular file or directory.") };
11773
12379
  }
11774
- async function prepareDownloadPlan(manifest, outputPath, force) {
12380
+ async function prepareDownloadPlan(manifest, outputPath, force, boundary = new WriteBoundary(), treePreflighted = false) {
11775
12381
  if (manifest.files.length === 0) return { error: validationError("Download manifest contains no files.", "Check the artifact and retry.") };
11776
12382
  if (outputPath === "") return { error: validationError("--output requires a non-empty directory.", "Pass --output <path> or omit --output to use the artifact ID.") };
11777
12383
  const root = resolve(outputPath);
11778
- const existing = await lstat(root).catch(() => null);
11779
- if (existing?.isSymbolicLink()) return { error: validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry.") };
11780
- if (existing && !force) return { error: cliError({
12384
+ if (boundary.workspace) await boundary.record(dirname(root), true);
12385
+ else await boundary.outputParent(dirname(root));
12386
+ if (await boundary.record(root, true) && !force) return { error: cliError({
11781
12387
  code: "output_exists",
11782
12388
  message: "Output path already exists.",
11783
12389
  why: "Download will not write into an existing path unless --force is set.",
@@ -11786,22 +12392,29 @@ async function prepareDownloadPlan(manifest, outputPath, force) {
11786
12392
  requiresHuman: false,
11787
12393
  recovery: { kind: "change_input" }
11788
12394
  }) };
11789
- if (existing && !existing.isDirectory()) return { error: validationError("Output path is not a directory.", "Choose a directory path or remove the existing file.") };
12395
+ if (treePreflighted) await boundary.checkTree(root);
12396
+ else await boundary.tree(root);
11790
12397
  const seen = /* @__PURE__ */ new Set();
12398
+ const directories = /* @__PURE__ */ new Set();
12399
+ const foldCase = process.platform === "win32" || process.platform === "darwin";
11791
12400
  const relativeFiles = [];
11792
12401
  for (const file of manifest.files) {
11793
12402
  const relativePath = downloadRelativePath(file.path);
11794
- if (relativePath.error) return { error: relativePath.error };
11795
- if (seen.has(relativePath.value)) return { error: validationError("Download manifest contains duplicate file paths.", "Retry later. If this repeats, report the artifact ID.") };
11796
- seen.add(relativePath.value);
12403
+ const key = foldCase ? relativePath.toLowerCase() : relativePath;
12404
+ const prefixes = [];
12405
+ for (let slash = key.indexOf("/"); slash !== -1; slash = key.indexOf("/", slash + 1)) prefixes.push(key.slice(0, slash));
12406
+ if (seen.has(key) || directories.has(key) || prefixes.some((prefix) => seen.has(prefix))) throw new DownloadManifestError(`Download manifest contains conflicting file path ${JSON.stringify(file.path)}.`);
12407
+ seen.add(key);
12408
+ for (const prefix of prefixes) directories.add(prefix);
11797
12409
  relativeFiles.push({
11798
12410
  ...file,
11799
- relativePath: relativePath.value
12411
+ relativePath
11800
12412
  });
11801
12413
  }
11802
12414
  const parent = dirname(root);
11803
- await mkdir(parent, { recursive: true });
11804
- const tempRoot = await mkdtemp(join(parent, `.${basename(root)}.tmp-`));
12415
+ await boundary.directory(parent);
12416
+ boundary.workspace ??= await boundary.privateDirectory(parent);
12417
+ const tempRoot = await boundary.privateDirectory(boundary.workspace);
11805
12418
  const files = [];
11806
12419
  for (const file of relativeFiles) {
11807
12420
  const targetPath = resolve(tempRoot, file.relativePath);
@@ -11813,15 +12426,15 @@ async function prepareDownloadPlan(manifest, outputPath, force) {
11813
12426
  return { value: {
11814
12427
  root,
11815
12428
  tempRoot,
11816
- replaceExisting: Boolean(existing),
11817
- files
12429
+ files,
12430
+ boundary
11818
12431
  } };
11819
12432
  }
11820
12433
  function downloadRelativePath(path) {
11821
- if (!path.startsWith("/") || path.includes("\0") || path.includes("\\")) return { error: validationError("Download manifest contains an invalid file path.", "Retry later. If this repeats, report the artifact ID.") };
12434
+ if (!path.startsWith("/") || path.includes("\0") || path.includes("\\")) throw new DownloadManifestError(`Download manifest contains invalid file path ${JSON.stringify(path)}.`);
11822
12435
  const segments = path.split("/").slice(1);
11823
- if (segments.length === 0 || segments.some((segment) => segment === "" || segment === "." || segment === "..")) return { error: validationError("Download manifest contains an unsafe file path.", "Retry later. If this repeats, report the artifact ID.") };
11824
- return { value: segments.join("/") };
12436
+ if (segments.length === 0 || segments.some((segment) => segment === "" || segment === "." || segment === ".." || process.platform === "win32" && (/[:*?"<>|]/u.test(segment) || /[. ]$/u.test(segment) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(segment)))) throw new DownloadManifestError(`Download manifest contains unsafe file path ${JSON.stringify(path)}.`);
12437
+ return segments.join("/");
11825
12438
  }
11826
12439
  function verifyDownloadedBytes(file, bytes) {
11827
12440
  if (bytes.byteLength !== file.size_bytes) return { error: downloadIntegrityError(file.path, "size mismatch") };
@@ -11841,60 +12454,18 @@ function downloadIntegrityError(path, reason) {
11841
12454
  recovery: { kind: "retry_later" }
11842
12455
  });
11843
12456
  }
11844
- function backupPathFor(root) {
11845
- return join(dirname(root), `.${basename(root)}.old-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
11846
- }
11847
- async function pathExists(path) {
11848
- return Boolean(await lstat(path).catch(() => null));
11849
- }
11850
12457
  function downloadFileSystemError(error) {
12458
+ if (error instanceof WriteBoundaryError || error instanceof DownloadManifestError) return error.error;
11851
12459
  return cliError({
11852
12460
  code: "download_failed",
11853
- message: "Could not write downloaded files.",
11854
- why: error instanceof Error ? error.message : "The local filesystem rejected a download operation.",
12461
+ message: error instanceof WriteFileSystemError ? error.message : "Could not write downloaded files.",
12462
+ why: "The local filesystem rejected a download operation. Check retained recovery paths before retrying.",
11855
12463
  hint: "Check --output permissions and available disk space, then retry.",
11856
12464
  agentRecoverable: true,
11857
12465
  requiresHuman: false,
11858
12466
  recovery: { kind: "change_input" }
11859
12467
  });
11860
12468
  }
11861
- async function collectDirectoryFiles(root) {
11862
- const results = [];
11863
- async function visit(dir) {
11864
- for (const entry of await readdir(dir, { withFileTypes: true })) {
11865
- if (entry.name === "__MACOSX") continue;
11866
- const fullPath = join(dir, entry.name);
11867
- if (entry.isSymbolicLink()) throw new CollectDirectoryFilesError("Directory contains a symbolic link.", "Remove or replace symlinked files and directories before sharing.");
11868
- if (entry.isDirectory()) {
11869
- if (EXCLUDED_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
11870
- await visit(fullPath);
11871
- continue;
11872
- }
11873
- if (!entry.isFile() || IGNORED_FILENAMES.has(entry.name) || entry.name.startsWith(".")) continue;
11874
- const relativePath = relative(root, fullPath).split(sep).join("/");
11875
- results.push({
11876
- path: fullPath,
11877
- relativePath
11878
- });
11879
- }
11880
- }
11881
- await visit(root);
11882
- results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
11883
- return results;
11884
- }
11885
- var CollectDirectoryFilesError = class extends Error {
11886
- hint;
11887
- constructor(message, hint) {
11888
- super(message);
11889
- this.name = "CollectDirectoryFilesError";
11890
- this.hint = hint;
11891
- }
11892
- };
11893
- async function blobFor(path) {
11894
- const chunks = [];
11895
- for await (const chunk of createReadStream(path)) chunks.push(chunk);
11896
- return new Blob(chunks, { type: contentTypeFor(path) });
11897
- }
11898
12469
  function contentTypeFor(path) {
11899
12470
  if (path.endsWith(".html")) return "text/html";
11900
12471
  if (path.endsWith(".md")) return "text/markdown";
@@ -11911,6 +12482,14 @@ function artifactKindForFile(path) {
11911
12482
  }
11912
12483
  //#endregion
11913
12484
  //#region src/command-runners/download.ts
12485
+ var DownloadFileError = class extends Error {};
12486
+ var DownloadFailure = class extends Error {
12487
+ error;
12488
+ constructor(error) {
12489
+ super(error.message);
12490
+ this.error = error;
12491
+ }
12492
+ };
11914
12493
  function fileDownloadError(error, path, notFound = false) {
11915
12494
  const message = `Could not download file "${path}".`;
11916
12495
  return {
@@ -11920,42 +12499,78 @@ function fileDownloadError(error, path, notFound = false) {
11920
12499
  hint: notFound ? `Retry the download. If it fails again, check file "${path}" in the artifact.` : `File "${path}": ${error.hint}`
11921
12500
  };
11922
12501
  }
11923
- async function readPreviousVersions(output) {
12502
+ function validateIds(entries) {
12503
+ const seen = /* @__PURE__ */ new Set();
12504
+ for (const entry of entries) {
12505
+ const id = isRecord$1(entry) ? entry.id : void 0;
12506
+ if (!isArtifactId(id) || seen.has(id.toLowerCase())) throw new WriteBoundaryError(`artifact ID ${typeof id === "string" ? JSON.stringify(id) : "(missing or non-string)"}`, "Use unique artifact IDs matching ^[a-z0-9]{10}$. Correct the endpoint or saved index and retry.");
12507
+ seen.add(id.toLowerCase());
12508
+ }
12509
+ }
12510
+ async function readPreviousVersions(output, boundary) {
12511
+ const text = await boundary.read(join(output, "index.json"));
12512
+ if (text === null) return /* @__PURE__ */ new Map();
12513
+ let parsed;
11924
12514
  try {
11925
- const parsed = JSON.parse(await readFile(join(output, "index.json"), "utf8"));
11926
- if (!Array.isArray(parsed.artifacts)) return /* @__PURE__ */ new Map();
11927
- const previous = /* @__PURE__ */ new Map();
11928
- for (const entry of parsed.artifacts) {
11929
- if (entry === null || typeof entry !== "object") return /* @__PURE__ */ new Map();
11930
- const { id, version_id } = entry;
11931
- if (typeof id !== "string") return /* @__PURE__ */ new Map();
11932
- if (typeof version_id === "string") previous.set(id, version_id);
11933
- }
11934
- return previous;
12515
+ parsed = JSON.parse(text);
11935
12516
  } catch {
11936
12517
  return /* @__PURE__ */ new Map();
11937
12518
  }
12519
+ if (!isRecord$1(parsed) || !Array.isArray(parsed.artifacts)) return /* @__PURE__ */ new Map();
12520
+ validateIds(parsed.artifacts);
12521
+ const previous = /* @__PURE__ */ new Map();
12522
+ for (const entry of parsed.artifacts) {
12523
+ if (entry.version_id !== void 0 && typeof entry.version_id !== "string") return /* @__PURE__ */ new Map();
12524
+ if (typeof entry.version_id === "string") previous.set(entry.id, entry.version_id);
12525
+ }
12526
+ return previous;
11938
12527
  }
11939
- async function runDownload(parsed, mode, isRetry = false) {
12528
+ async function runDownload(parsed, mode, isRetry = false, dependencies = {}) {
12529
+ const boundary = new WriteBoundary(dependencies);
12530
+ let primary;
12531
+ let cleanup;
12532
+ try {
12533
+ await runDownloadInternal(parsed, mode, isRetry, boundary);
12534
+ } catch (error) {
12535
+ primary = error;
12536
+ }
12537
+ try {
12538
+ await boundary.cleanup();
12539
+ } catch (error) {
12540
+ cleanup = error;
12541
+ }
12542
+ const error = primary ?? cleanup;
12543
+ if (error) {
12544
+ const failure = error instanceof DownloadFailure ? error.error : downloadFileSystemError(error);
12545
+ if (primary && cleanup) failure.hint += " Cleanup could not finish safely.";
12546
+ const retained = await boundary.retainedWorkspace();
12547
+ if (retained) failure.hint += ` Recover retained data at ${retained}; inspect it before manual cleanup.`;
12548
+ writeFailure("download", failure, mode, 1);
12549
+ }
12550
+ }
12551
+ async function runDownloadInternal(parsed, mode, isRetry = false, boundary) {
11940
12552
  const command = "download";
11941
12553
  const projectId = parsed.options.projectId?.trim();
11942
12554
  if (projectId !== void 0 || parsed.positionals.length === 0) {
11943
- if (!projectId || parsed.positionals.length > 0 || !parsed.options.output?.trim()) return writeFailure(command, validationError("Invalid project download arguments.", "Use download <target> or download --project-id <id> --output <dir>."), mode, 1);
11944
- return runProjectDownload(parsed, mode, projectId, isRetry);
12555
+ if (!projectId || parsed.positionals.length > 0 || !parsed.options.output?.trim()) throw new DownloadFailure(validationError("Invalid project download arguments.", "Use download <target> or download --project-id <id> --output <dir>."));
12556
+ return runProjectDownload(parsed, mode, projectId, isRetry, boundary);
11945
12557
  }
11946
12558
  const target = parseArtifactTarget(parsed.positionals[0], "download", "Pass an artifact ID or share URL to download.");
11947
- if (target.error) return writeFailure(command, target.error, mode, 1);
12559
+ if (target.error) throw new DownloadFailure(target.error);
11948
12560
  const artifactId = target.artifactId;
12561
+ const input = parsed.positionals[0];
12562
+ if (!/^https?:\/\//i.test(input)) validateIds([{ id: input }]);
12563
+ validateIds([{ id: artifactId }]);
11949
12564
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
11950
12565
  if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11951
12566
  const request = await requestConfig(parsed.options);
11952
- if (request.error) return writeFailure(command, request.error, mode, 1);
12567
+ if (request.error) throw new DownloadFailure(request.error);
11953
12568
  const baseUrl = baseUrlOf(parsed.options);
11954
12569
  const manifestResponse = await cliFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/download`, baseUrl), {
11955
12570
  headers: { Authorization: `Bearer ${credential.token}` },
11956
12571
  ...request.init
11957
12572
  });
11958
- if ("networkError" in manifestResponse) return writeFailure(command, networkError(manifestResponse.networkError), mode, 1);
12573
+ if ("networkError" in manifestResponse) throw new DownloadFailure(networkError(manifestResponse.networkError));
11959
12574
  const body = await readJson(manifestResponse);
11960
12575
  if (!manifestResponse.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(manifestResponse.status, body, {
11961
12576
  authenticated: true,
@@ -11966,64 +12581,50 @@ async function runDownload(parsed, mode, isRetry = false) {
11966
12581
  profileCredentialKind: credential.profileCredentialKind,
11967
12582
  botProfile: credential.botProfile
11968
12583
  }), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11969
- if (!downloadManifestFields(body)) return writeFailure(command, serviceError("Download manifest succeeded but the response did not include file metadata."), mode, 1);
11970
- const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force));
11971
- if (plan.error) return writeFailure(command, plan.error, mode, 1);
11972
- let completed = false;
11973
- let backupRoot = null;
11974
- try {
11975
- for (const file of plan.value.files) {
11976
- const fileResponse = await cliFetch(downloadFileUrl(baseUrl, artifactId, file.path), {
11977
- headers: { Authorization: `Bearer ${credential.token}` },
11978
- ...request.init
11979
- });
11980
- if ("networkError" in fileResponse) return writeFailure(command, fileDownloadError(networkError(fileResponse.networkError), file.path), mode, 1);
11981
- if (!fileResponse.ok) {
11982
- const fileBody = await readJson(fileResponse);
11983
- const apiError = isRecord$1(fileBody) ? fileBody.error : void 0;
11984
- const notFound = fileResponse.status === 404 || apiError === "not-found" || isRecord$1(apiError) && apiError.code === "not-found";
11985
- return handleAuthenticatedCredentialFailure(command, fileDownloadError(mapApiError(fileResponse.status, fileBody, {
11986
- authenticated: true,
11987
- ...!notFound ? { artifactTarget: true } : {},
11988
- baseUrl,
11989
- credentialSource: credential.source,
11990
- profile: credential.profile,
11991
- profileCredentialKind: credential.profileCredentialKind,
11992
- botProfile: credential.botProfile
11993
- }), file.path, notFound), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11994
- }
11995
- let fileBody;
11996
- try {
11997
- fileBody = await fileResponse.arrayBuffer();
11998
- } catch (error) {
11999
- return writeFailure(command, fileDownloadError(networkError(error), file.path), mode, 1);
12000
- }
12001
- const bytes = Buffer.from(fileBody);
12002
- const verified = verifyDownloadedBytes(file, bytes);
12003
- if (verified.error) return writeFailure(command, verified.error, mode, 1);
12004
- await mkdir(dirname(file.targetPath), { recursive: true });
12005
- await writeFile(file.targetPath, bytes);
12006
- }
12007
- if (plan.value.replaceExisting) {
12008
- backupRoot = backupPathFor(plan.value.root);
12009
- await rename(plan.value.root, backupRoot);
12010
- }
12011
- await rename(plan.value.tempRoot, plan.value.root);
12012
- completed = true;
12013
- if (backupRoot) await rm(backupRoot, {
12014
- recursive: true,
12015
- force: true
12016
- }).catch(() => {});
12017
- } catch (error) {
12018
- if (backupRoot && !await pathExists(plan.value.root) && await pathExists(backupRoot)) await rename(backupRoot, plan.value.root).catch(() => {});
12019
- return writeFailure(command, downloadFileSystemError(error), mode, 1);
12020
- } finally {
12021
- if (!completed) await rm(plan.value.tempRoot, {
12022
- recursive: true,
12023
- force: true
12024
- }).catch(() => {});
12584
+ if (!isRecord$1(body) || !("id" in body)) throw new DownloadFailure(serviceError("Download manifest succeeded but the response did not include file metadata."));
12585
+ validateIds([body]);
12586
+ if (isRecord$1(body) && body.id !== artifactId) throw new DownloadManifestError(`Manifest artifact ID ${JSON.stringify(body.id)} does not match ${artifactId}.`);
12587
+ if (!downloadManifestFields(body)) throw new DownloadFailure(serviceError("Download manifest succeeded but the response did not include file metadata."));
12588
+ boundary.watch(resolve(parsed.options.output ?? artifactId));
12589
+ const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force), boundary);
12590
+ if (plan.error) throw new DownloadFailure(plan.error);
12591
+ for (const file of plan.value.files) {
12592
+ const fileResponse = await cliFetch(downloadFileUrl(baseUrl, artifactId, file.path), {
12593
+ headers: { Authorization: `Bearer ${credential.token}` },
12594
+ ...request.init
12595
+ });
12596
+ if ("networkError" in fileResponse) throw new DownloadFailure(fileDownloadError(networkError(fileResponse.networkError), file.path));
12597
+ if (!fileResponse.ok) {
12598
+ const fileBody = await readJson(fileResponse);
12599
+ const apiError = isRecord$1(fileBody) ? fileBody.error : void 0;
12600
+ const notFound = fileResponse.status === 404 || apiError === "not-found" || isRecord$1(apiError) && apiError.code === "not-found";
12601
+ await boundary.cleanup();
12602
+ return handleAuthenticatedCredentialFailure(command, fileDownloadError(mapApiError(fileResponse.status, fileBody, {
12603
+ authenticated: true,
12604
+ ...!notFound ? { artifactTarget: true } : {},
12605
+ baseUrl,
12606
+ credentialSource: credential.source,
12607
+ profile: credential.profile,
12608
+ profileCredentialKind: credential.profileCredentialKind,
12609
+ botProfile: credential.botProfile
12610
+ }), file.path, notFound), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
12611
+ }
12612
+ let fileBody;
12613
+ try {
12614
+ fileBody = await fileResponse.arrayBuffer();
12615
+ } catch (error) {
12616
+ throw new DownloadFailure(fileDownloadError(networkError(error), file.path));
12617
+ }
12618
+ const bytes = Buffer.from(fileBody);
12619
+ const verified = verifyDownloadedBytes(file, bytes);
12620
+ if (verified.error) throw new DownloadFailure(verified.error);
12621
+ await boundary.write(file.targetPath, bytes);
12025
12622
  }
12623
+ await boundary.replace(plan.value.tempRoot, plan.value.root);
12624
+ boundary.keep(plan.value.root);
12625
+ await boundary.finish();
12026
12626
  return writeSuccess(command, {
12627
+ backup_paths: boundary.backupPaths,
12027
12628
  artifact: {
12028
12629
  id: body.id,
12029
12630
  url: body.share_url,
@@ -12037,12 +12638,12 @@ async function runDownload(parsed, mode, isRetry = false) {
12037
12638
  }
12038
12639
  }, mode);
12039
12640
  }
12040
- async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12641
+ async function runProjectDownload(parsed, mode, projectId, isRetry = false, boundary) {
12041
12642
  const command = "download";
12042
12643
  const resolved = await resolveCredential(parsed.options, await resolveProjectConfig());
12043
12644
  if (!resolved.ok) return handleCredentialFailure(command, resolved, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
12044
12645
  const request = await requestConfig(parsed.options);
12045
- if (request.error) return writeFailure(command, request.error, mode, 1);
12646
+ if (request.error) throw new DownloadFailure(request.error);
12046
12647
  const baseUrl = baseUrlOf(parsed.options);
12047
12648
  let credential = resolved;
12048
12649
  let refreshAttempted = false;
@@ -12075,7 +12676,7 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12075
12676
  ...request.init
12076
12677
  });
12077
12678
  };
12078
- const output = parsed.options.output.trim();
12679
+ const output = resolve(parsed.options.output.trim());
12079
12680
  const list = async (cursor) => {
12080
12681
  const url = apiUrl("/api/cli/artifacts", baseUrl);
12081
12682
  url.searchParams.set("project_id", projectId);
@@ -12124,12 +12725,22 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12124
12725
  first = false;
12125
12726
  cursor = page.data.has_more && page.data.next_cursor ? page.data.next_cursor : void 0;
12126
12727
  } while (cursor);
12127
- if (listError && first) return writeFailure(command, listError, mode, 1);
12128
- if ((await lstat(output).catch(() => null))?.isSymbolicLink()) return writeFailure(command, validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry."), mode, 1);
12129
- const previousVersions = await readPreviousVersions(output);
12130
- await mkdir(output, { recursive: true });
12728
+ if (listError && first) throw new DownloadFailure(listError);
12729
+ validateIds(entries);
12730
+ boundary.watch(output);
12731
+ await boundary.outputParent(dirname(output));
12732
+ await boundary.record(output, true);
12733
+ const previousVersions = await readPreviousVersions(output, boundary);
12734
+ for (const item of entries) {
12735
+ const root = join(output, item.id);
12736
+ await boundary.record(root, true);
12737
+ await boundary.tree(root);
12738
+ }
12739
+ await boundary.directory(output);
12740
+ boundary.keep(output);
12741
+ boundary.workspace = await boundary.privateDirectory(output);
12131
12742
  const results = entries.map((item) => ({
12132
- id: String(item.id),
12743
+ id: item.id,
12133
12744
  title: String(item.title ?? ""),
12134
12745
  ...typeof item.owner_email === "string" ? { owner_email: item.owner_email } : {},
12135
12746
  updated_at: String(item.updated_at ?? ""),
@@ -12146,107 +12757,87 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12146
12757
  continue;
12147
12758
  }
12148
12759
  const root = join(output, result.id);
12149
- const rootStat = await lstat(root).catch(() => null);
12150
- const rootExists = rootStat !== null;
12151
- const response = await authFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(result.id)}/download`, baseUrl));
12152
- if ("networkError" in response) {
12153
- result.reason = "network failed";
12154
- continue;
12155
- }
12156
- if (!response.ok) {
12157
- const body = await readJson(response);
12158
- if (mapApiError(response.status, body, {
12159
- authenticated: true,
12160
- baseUrl,
12161
- artifactTarget: true
12162
- }).code === "unsupported_kind") {
12163
- result.status = "skipped";
12164
- result.reason = "unsupported-kind";
12165
- } else result.reason = `download failed (${response.status})`;
12166
- continue;
12167
- }
12168
- const body = await readJson(response);
12169
- if (!downloadManifestFields(body)) {
12170
- result.reason = "invalid download manifest";
12171
- continue;
12172
- }
12173
- if (!parsed.options.force && rootStat?.isDirectory() && previousVersions.get(result.id) === body.version_id) {
12174
- result.status = "unchanged";
12175
- result.version_id = body.version_id;
12176
- result.path = root;
12177
- delete result.reason;
12178
- continue;
12179
- }
12180
- if (rootExists && !parsed.options.force) {
12181
- result.reason = "artifact output already exists";
12182
- continue;
12183
- }
12184
- const plan = await prepareDownloadPlan(body, root, Boolean(parsed.options.force));
12185
- if (plan.error) {
12186
- result.reason = plan.error.message;
12187
- continue;
12188
- }
12189
12760
  try {
12761
+ const rootExists = await boundary.record(root, true);
12762
+ const response = await authFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(result.id)}/download`, baseUrl));
12763
+ if ("networkError" in response) {
12764
+ result.reason = "network failed";
12765
+ continue;
12766
+ }
12767
+ if (!response.ok) {
12768
+ const body = await readJson(response);
12769
+ if (mapApiError(response.status, body, {
12770
+ authenticated: true,
12771
+ baseUrl,
12772
+ artifactTarget: true
12773
+ }).code === "unsupported_kind") {
12774
+ result.status = "skipped";
12775
+ result.reason = "unsupported-kind";
12776
+ } else result.reason = `download failed (${response.status})`;
12777
+ continue;
12778
+ }
12779
+ const body = await readJson(response);
12780
+ if (!isRecord$1(body) || body.id !== result.id) throw new DownloadManifestError(`Download manifest artifact ID does not match ${result.id}.`);
12781
+ if (!downloadManifestFields(body)) throw new DownloadManifestError(`Invalid download manifest for artifact ${result.id}.`);
12782
+ if (!parsed.options.force && rootExists && previousVersions.get(result.id) === body.version_id) {
12783
+ result.status = "unchanged";
12784
+ result.version_id = body.version_id;
12785
+ result.path = root;
12786
+ delete result.reason;
12787
+ continue;
12788
+ }
12789
+ if (rootExists && !parsed.options.force) {
12790
+ result.reason = "artifact output already exists";
12791
+ continue;
12792
+ }
12793
+ const plan = await prepareDownloadPlan(body, root, Boolean(parsed.options.force), boundary, true);
12794
+ if (plan.error) {
12795
+ result.reason = plan.error.message;
12796
+ continue;
12797
+ }
12190
12798
  for (const file of plan.value.files) {
12191
12799
  const fileResponse = await authFetch(downloadFileUrl(baseUrl, result.id, file.path));
12192
- if ("networkError" in fileResponse) throw new Error(`Could not download file "${file.path}": network failed`);
12193
- if (!fileResponse.ok) throw new Error(`Could not download file "${file.path}" (${fileResponse.status})`);
12800
+ if ("networkError" in fileResponse) throw new DownloadFileError(`Could not download file "${file.path}": network failed`);
12801
+ if (!fileResponse.ok) throw new DownloadFileError(`Could not download file "${file.path}" (${fileResponse.status})`);
12194
12802
  let fileBody;
12195
12803
  try {
12196
12804
  fileBody = await fileResponse.arrayBuffer();
12197
12805
  } catch {
12198
- throw new Error(`Could not download file "${file.path}": network failed while reading response body`);
12806
+ throw new DownloadFileError(`Could not download file "${file.path}": network failed while reading response body`);
12199
12807
  }
12200
12808
  const bytes = Buffer.from(fileBody);
12201
12809
  const verified = verifyDownloadedBytes(file, bytes);
12202
- if (verified.error) throw new Error(verified.error.message);
12203
- await mkdir(dirname(file.targetPath), { recursive: true });
12204
- await writeFile(file.targetPath, bytes);
12810
+ if (verified.error) throw new DownloadFileError(verified.error.message);
12811
+ await boundary.write(file.targetPath, bytes);
12205
12812
  }
12206
- let backupRoot = null;
12207
- try {
12208
- if (plan.value.replaceExisting) {
12209
- backupRoot = backupPathFor(plan.value.root);
12210
- await rename(plan.value.root, backupRoot);
12211
- }
12212
- await rename(plan.value.tempRoot, plan.value.root);
12213
- } catch (error) {
12214
- if (backupRoot && !await pathExists(plan.value.root) && await pathExists(backupRoot)) await rename(backupRoot, plan.value.root).catch(() => {});
12215
- throw error;
12216
- }
12217
- if (backupRoot) await rm(backupRoot, {
12218
- recursive: true,
12219
- force: true
12220
- }).catch(() => {});
12813
+ await boundary.replace(plan.value.tempRoot, plan.value.root);
12814
+ boundary.keep(plan.value.root);
12221
12815
  result.status = "ok";
12222
12816
  result.version_id = body.version_id;
12223
12817
  result.path = root;
12224
12818
  delete result.reason;
12225
12819
  } catch (error) {
12226
- result.reason = error instanceof Error ? error.message : "download failed";
12227
- await rm(plan.value.tempRoot, {
12228
- recursive: true,
12229
- force: true
12230
- }).catch(() => {});
12820
+ await boundary.check(output, dirname(output), boundary.workspace);
12821
+ if (error instanceof WriteBoundaryError) throw error;
12822
+ result.reason = error instanceof DownloadManifestError ? `${error.message} ${error.error.hint}` : error instanceof DownloadFileError ? error.message : "download failed; check filesystem availability and retry";
12231
12823
  }
12232
12824
  }
12233
- try {
12234
- await writeFile(join(output, "index.json"), JSON.stringify({
12235
- project_id: projectId,
12236
- artifacts: results
12237
- }, null, 2) + "\n");
12238
- } catch (error) {
12239
- return writeFailure(command, downloadFileSystemError(error), mode, 1);
12240
- }
12825
+ await boundary.atomicWrite(join(output, "index.json"), JSON.stringify({
12826
+ project_id: projectId,
12827
+ artifacts: results
12828
+ }, null, 2) + "\n", true, boundary.workspace);
12829
+ boundary.keep(join(output, "index.json"));
12241
12830
  const counts = {
12242
12831
  ok: results.filter((r) => r.status === "ok").length,
12243
12832
  unchanged: results.filter((r) => r.status === "unchanged").length,
12244
12833
  skipped: results.filter((r) => r.status === "skipped").length,
12245
12834
  failed: results.filter((r) => r.status === "failed").length
12246
12835
  };
12836
+ await boundary.finish();
12247
12837
  process.exitCode = counts.failed > 0 ? 1 : 0;
12248
12838
  return writeSuccess(command, {
12249
12839
  project_id: projectId,
12840
+ backup_paths: boundary.backupPaths,
12250
12841
  ...counts,
12251
12842
  failures: results.filter((r) => r.status === "failed").map((r) => ({
12252
12843
  id: r.id,
@@ -12357,66 +12948,57 @@ function parseEditData(body) {
12357
12948
  }
12358
12949
  //#endregion
12359
12950
  //#region src/git-exclude.ts
12360
- async function ensureGitExclude(cwd) {
12361
- const git = await findGitDir(cwd);
12362
- if (!git) return {
12363
- applied: false,
12364
- warning: null
12365
- };
12366
- const excludePath = join(git.gitDir, "info", "exclude");
12367
- const excludeEntry = gitPattern(relative(git.workTree, resolve(cwd, PROJECT_CONFIG_LOCAL_PATH)));
12951
+ async function ensureGitExclude(cwd, dependencies = {}) {
12952
+ const boundary = new WriteBoundary(dependencies);
12953
+ let repository = resolve(cwd);
12954
+ let excludePath = join(repository, ".git", "info", "exclude");
12955
+ let line = PROJECT_CONFIG_LOCAL_PATH;
12368
12956
  try {
12369
- const existing = await readFile(excludePath, "utf8").catch(() => "");
12370
- if (excludeLines(existing).includes(excludeEntry)) return {
12957
+ while (true) {
12958
+ await boundary.record(repository, true);
12959
+ const git = join(repository, ".git");
12960
+ if (await lstat(git).catch((error) => {
12961
+ if (error.code === "ENOENT") return null;
12962
+ throw error;
12963
+ })) break;
12964
+ const parent = dirname(repository);
12965
+ if (parent === repository) return {
12966
+ applied: false,
12967
+ warning: null
12968
+ };
12969
+ repository = parent;
12970
+ }
12971
+ const git = join(repository, ".git");
12972
+ excludePath = join(git, "info", "exclude");
12973
+ line = relative(repository, resolve(cwd, PROJECT_CONFIG_LOCAL_PATH)).split("\\").join("/");
12974
+ boundary.watch(join(git, "gitdir"), join(git, "commondir"));
12975
+ await boundary.record(git, true);
12976
+ for (const name of ["gitdir", "commondir"]) if (await boundary.record(join(git, name))) throw new Error("Redirect metadata");
12977
+ await boundary.record(dirname(excludePath), true);
12978
+ const existing = await boundary.read(excludePath) ?? "";
12979
+ if (existing.split("\n").some((value) => value.trim() === line)) return {
12371
12980
  applied: false,
12372
12981
  warning: null
12373
12982
  };
12374
- await mkdir(dirname(excludePath), { recursive: true });
12375
- const prefix = existing.endsWith("\n") || existing.length === 0 ? "" : "\n";
12376
- await appendFile(excludePath, `${prefix}${excludeEntry}\n`, "utf8");
12983
+ await boundary.directory(dirname(excludePath));
12984
+ const prefix = existing.length && !existing.endsWith("\n") ? "\n" : "";
12985
+ await boundary.atomicWrite(excludePath, `${existing}${prefix}${line}\n`);
12986
+ boundary.keep(excludePath);
12987
+ await boundary.cleanup();
12377
12988
  return {
12378
12989
  applied: true,
12379
12990
  warning: null
12380
12991
  };
12381
12992
  } catch {
12993
+ try {
12994
+ await boundary.cleanup();
12995
+ } catch {}
12382
12996
  return {
12383
12997
  applied: false,
12384
- warning: `Could not update ${excludePath}; keep ${PROJECT_CONFIG_LOCAL_PATH} out of version control manually.`
12998
+ warning: `Could not update ${excludePath}; add ${line} to the repository's Git excludes manually.`
12385
12999
  };
12386
13000
  }
12387
13001
  }
12388
- function excludeLines(text) {
12389
- return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
12390
- }
12391
- async function findGitDir(start) {
12392
- let current = resolve(start);
12393
- const root = resolve(current, "/");
12394
- while (true) {
12395
- const gitDir = await resolveGitDir(join(current, ".git"));
12396
- if (gitDir) return {
12397
- gitDir,
12398
- workTree: current
12399
- };
12400
- if (current === root) return null;
12401
- current = dirname(current);
12402
- }
12403
- }
12404
- async function resolveGitDir(gitPath) {
12405
- const info = await stat(gitPath).catch(() => null);
12406
- if (!info) return null;
12407
- if (info.isDirectory()) return gitPath;
12408
- if (!info.isFile()) return null;
12409
- const text = await readFile(gitPath, "utf8").catch(() => null);
12410
- if (!text) return null;
12411
- const gitDir = text.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
12412
- if (!gitDir) return null;
12413
- const resolvedGitDir = resolve(dirname(gitPath), gitDir);
12414
- const commonDir = await readFile(join(resolvedGitDir, "commondir"), "utf8").then((value) => value.trim()).catch(() => null);
12415
- return commonDir ? resolve(resolvedGitDir, commonDir) : resolvedGitDir;
12416
- }
12417
- function gitPattern(path) {
12418
- return path.split("\\").join("/");
12419
- }
12420
13002
  //#endregion
12421
13003
  //#region src/command-runners/init.ts
12422
13004
  function runInit(parsed, mode) {
@@ -12467,28 +13049,50 @@ function onboardingNextSteps(signedIn) {
12467
13049
  async function runInitConfig(parsed, mode, profile, projectId) {
12468
13050
  const command = "init";
12469
13051
  if (parsed.options.dryRun === true) return writeFailure(command, validationError("--dry-run is only supported without --profile or --project-id.", "Run init --dry-run by itself to preview the skill install, or drop --dry-run to save the defaults."), mode, 1);
12470
- const resolved = await resolveProjectConfig();
12471
- if (profile) {
12472
- if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
12473
- const globalConfig = await readGlobalConfig();
12474
- if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
12475
- }
12476
- const next = {
12477
- ...await readRawLocalProjectConfig() ?? {},
12478
- ...profile ? { default_profile: profile } : {},
12479
- ...projectId ? { default_project_id: projectId } : {}
12480
- };
13052
+ const boundary = new WriteBoundary();
12481
13053
  const path = projectConfigLocalPath();
12482
- await mkdir(dirname(path), { recursive: true });
12483
- await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
12484
- const gitExclude = await ensureGitExclude(process.cwd());
12485
- const data = configData(next, resolved);
12486
- delete data.read_path;
12487
- if (gitExclude.warning) data.git_exclude_warning = gitExclude.warning;
12488
- if (gitExclude.applied) data.git_exclude_applied = true;
12489
- return writeSuccess(command, data, mode);
13054
+ try {
13055
+ await boundary.outputParent(process.cwd());
13056
+ await boundary.record(dirname(path), true);
13057
+ const localText = await boundary.read(path);
13058
+ if (profile) {
13059
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
13060
+ const globalConfig = await readGlobalConfig();
13061
+ if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
13062
+ }
13063
+ let existing = {};
13064
+ if (localText !== null) try {
13065
+ const raw = JSON.parse(localText);
13066
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) existing = raw;
13067
+ } catch {}
13068
+ const next = {
13069
+ ...existing,
13070
+ ...profile ? { default_profile: profile } : {},
13071
+ ...projectId ? { default_project_id: projectId } : {}
13072
+ };
13073
+ await boundary.directory(dirname(path));
13074
+ await boundary.atomicWrite(path, `${JSON.stringify(next, null, 2)}\n`);
13075
+ boundary.keep(path);
13076
+ const gitExclude = await ensureGitExclude(process.cwd());
13077
+ const data = configData(next);
13078
+ delete data.read_path;
13079
+ if (gitExclude.warning) data.git_exclude_warning = gitExclude.warning;
13080
+ if (gitExclude.applied) data.git_exclude_applied = true;
13081
+ await boundary.cleanup();
13082
+ return writeSuccess(command, data, mode);
13083
+ } catch (error) {
13084
+ let cleanupFailed = false;
13085
+ try {
13086
+ await boundary.cleanup();
13087
+ } catch {
13088
+ cleanupFailed = true;
13089
+ }
13090
+ const failure = error instanceof WriteBoundaryError ? error.error : validationError(`Could not save config at ${path}.`, "Check directory permissions and retry.");
13091
+ if (cleanupFailed) failure.hint += ` Inspect temporary files in ${dirname(path)} before manual cleanup.`;
13092
+ return writeFailure(command, failure, mode, 1);
13093
+ }
12490
13094
  }
12491
- function configData(config, resolved) {
13095
+ function configData(config) {
12492
13096
  return {
12493
13097
  mode: "config",
12494
13098
  path: PROJECT_CONFIG_LOCAL_PATH,
@@ -12496,8 +13100,7 @@ function configData(config, resolved) {
12496
13100
  config: {
12497
13101
  default_profile: configString(config.default_profile),
12498
13102
  default_project_id: configString(config.default_project_id)
12499
- },
12500
- ...resolved.path ? { read_path: resolved.path } : {}
13103
+ }
12501
13104
  };
12502
13105
  }
12503
13106
  //#endregion
@@ -12799,7 +13402,7 @@ async function importBotTokenProfile(command, profile, token, parsed, mode) {
12799
13402
  //#endregion
12800
13403
  //#region src/command-runners/share.ts
12801
13404
  const MAX_SHARE_KEY_LENGTH = 128;
12802
- async function runShare(parsed, mode, isRetry = false) {
13405
+ async function runShare(parsed, mode, isRetry = false, prepared) {
12803
13406
  const command = "share";
12804
13407
  const targetPath = parsed.positionals[0];
12805
13408
  if (!targetPath) return writeFailure(command, validationError("Path is required.", "Pass a file or directory to share."), mode, 1);
@@ -12809,9 +13412,13 @@ async function runShare(parsed, mode, isRetry = false) {
12809
13412
  shareKey = (typeof parsed.options.key === "string" ? parsed.options.key : "").trim();
12810
13413
  if (shareKey.length === 0 || shareKey.length > MAX_SHARE_KEY_LENGTH) return writeFailure(command, validationError(`--key must be 1-${MAX_SHARE_KEY_LENGTH} characters after trimming.`, "Pass a short stable identifier, like a job name or PR number."), mode, 1);
12811
13414
  }
13415
+ const conflict = destinationConflictError(parsed.options);
13416
+ if (conflict) return writeFailure(command, conflict, mode, 1);
13417
+ const upload = prepared ?? await prepareUploadPayload(targetPath);
13418
+ if (upload.error) return writeFailure(command, upload.error, mode, 1);
12812
13419
  const project = await resolveProjectConfig();
12813
13420
  const credential = await resolveCredential(parsed.options, project);
12814
- if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
13421
+ if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runShare(parsed, mode, true, upload), isRetry);
12815
13422
  const baseUrl = baseUrlOf(parsed.options);
12816
13423
  const hasProjectFlag = "project" in parsed.options;
12817
13424
  let destinationOptions = parsed.options;
@@ -12819,14 +13426,10 @@ async function runShare(parsed, mode, isRetry = false) {
12819
13426
  if (hasProjectFlag) {
12820
13427
  projectName = nonEmpty(typeof parsed.options.project === "string" ? parsed.options.project : "");
12821
13428
  if (!projectName) return writeFailure(command, validationError("--project requires a value.", "Pass --project <name> and retry."), mode, 1);
12822
- const conflict = destinationConflictError(parsed.options);
12823
- if (conflict) return writeFailure(command, conflict, mode, 1);
12824
13429
  } else {
12825
13430
  const earlyDestination = resolveDestination(parsed.options, project.config);
12826
13431
  if (earlyDestination.error) return writeFailure(command, earlyDestination.error, mode, 1);
12827
13432
  }
12828
- const fileStat = await stat(targetPath).catch(() => null);
12829
- if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
12830
13433
  const request = await requestConfig(parsed.options);
12831
13434
  if (request.error) return writeFailure(command, request.error, mode, 1);
12832
13435
  if (hasProjectFlag && projectName) {
@@ -12838,7 +13441,7 @@ async function runShare(parsed, mode, isRetry = false) {
12838
13441
  profileCredentialKind: credential.profileCredentialKind,
12839
13442
  botProfile: credential.botProfile
12840
13443
  });
12841
- if (resolved.error) return handleAuthenticatedCredentialFailure(command, resolved.error, credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
13444
+ if (resolved.error) return handleAuthenticatedCredentialFailure(command, resolved.error, credential, parsed.options, mode, () => runShare(parsed, mode, true, upload), isRetry);
12842
13445
  const { project: _project, ...rest } = parsed.options;
12843
13446
  destinationOptions = {
12844
13447
  ...rest,
@@ -12848,6 +13451,7 @@ async function runShare(parsed, mode, isRetry = false) {
12848
13451
  const destination = resolveDestination(destinationOptions, project.config);
12849
13452
  if (destination.error) return writeFailure(command, destination.error, mode, 1);
12850
13453
  const initialForm = await createUploadForm();
13454
+ for (const [name, value] of upload.payload.form) initialForm.append(name, value);
12851
13455
  const grantEmails = arrayOption(parsed.options.grantEmail);
12852
13456
  const defaultVisibility = parsed.options.visibility || destination.containerId ? null : await resolveDefaultVisibility("home_audience", await resolveSharedProjectConfig());
12853
13457
  if (defaultVisibility && "error" in defaultVisibility) return writeFailure(command, defaultVisibility.error, mode, 1);
@@ -12861,8 +13465,6 @@ async function runShare(parsed, mode, isRetry = false) {
12861
13465
  const uploadQuery = {};
12862
13466
  if (shareKey !== null) uploadQuery.publish_key = shareKey;
12863
13467
  if (parsed.options.expectedVersion) uploadQuery.expected_version = parsed.options.expectedVersion;
12864
- const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
12865
- if (upload.error) return writeFailure(command, upload.error, mode, 1);
12866
13468
  if (upload.payload.kind === "static_site") {
12867
13469
  uploadQuery.artifact_kind = "static_site";
12868
13470
  if (destination.containerId) uploadQuery.container_id = destination.containerId;
@@ -12872,7 +13474,7 @@ async function runShare(parsed, mode, isRetry = false) {
12872
13474
  const uploaded = await postShareUpload({
12873
13475
  uploadUrl,
12874
13476
  token: credential.token,
12875
- form: upload.payload.form,
13477
+ form: initialForm,
12876
13478
  requestInit: request.init,
12877
13479
  errorOptions: {
12878
13480
  authenticated: true,
@@ -12889,7 +13491,7 @@ async function runShare(parsed, mode, isRetry = false) {
12889
13491
  }, baseUrl, upload.payload.kind);
12890
13492
  if ("error" in uploaded) {
12891
13493
  if (uploaded.error.code === "network_failed") return writeFailure(command, uploaded.error, mode, 1);
12892
- return handleAuthenticatedCredentialFailure(command, uploaded.error, credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
13494
+ return handleAuthenticatedCredentialFailure(command, uploaded.error, credential, parsed.options, mode, () => runShare(parsed, mode, true, upload), isRetry);
12893
13495
  }
12894
13496
  const { id, url, versionId, artifactKind, visibility, linkExpiresAt, created, warnings } = uploaded.body;
12895
13497
  return writeSuccess(command, {
@@ -12964,7 +13566,7 @@ async function runResolve(parsed, mode) {
12964
13566
  }
12965
13567
  //#endregion
12966
13568
  //#region src/command-runners/update.ts
12967
- async function runUpdate(parsed, mode, isRetry = false) {
13569
+ async function runUpdate(parsed, mode, isRetry = false, prepared) {
12968
13570
  const command = "update";
12969
13571
  const artifactInput = parsed.positionals[0];
12970
13572
  const targetPath = parsed.positionals[1];
@@ -12976,15 +13578,13 @@ async function runUpdate(parsed, mode, isRetry = false) {
12976
13578
  if (!artifactId) return writeFailure(command, targetResolutionError(artifactInput, "update"), mode, 1);
12977
13579
  const label = VersionLabelInputSchema.optional().safeParse(parsed.options.label);
12978
13580
  if (!label.success) return writeFailure(command, validationError("Invalid version label.", label.error.issues[0]?.message ?? "Check the label and retry."), mode, 1);
13581
+ const upload = prepared ?? await prepareUploadPayload(targetPath);
13582
+ if (upload.error) return writeFailure(command, upload.error, mode, 1);
12979
13583
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
12980
- if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
12981
- const fileStat = await stat(targetPath).catch(() => null);
12982
- if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
13584
+ if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true, upload), isRetry);
12983
13585
  const baseUrl = baseUrlOf(parsed.options);
12984
13586
  const request = await requestConfig(parsed.options);
12985
13587
  if (request.error) return writeFailure(command, request.error, mode, 1);
12986
- const upload = await prepareUploadPayload(targetPath, fileStat);
12987
- if (upload.error) return writeFailure(command, upload.error, mode, 1);
12988
13588
  const updateQuery = label.data !== void 0 ? { label: label.data } : {};
12989
13589
  if (upload.payload.kind === "static_site") updateQuery.artifact_kind = "static_site";
12990
13590
  if (parsed.options.expectedVersion) updateQuery.expected_version = parsed.options.expectedVersion;
@@ -13007,7 +13607,7 @@ async function runUpdate(parsed, mode, isRetry = false) {
13007
13607
  profile: credential.profile,
13008
13608
  profileCredentialKind: credential.profileCredentialKind,
13009
13609
  botProfile: credential.botProfile
13010
- }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
13610
+ }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true, upload), isRetry);
13011
13611
  const responseBody = isContract(ARTIFACT_VERSION_UPDATE_RESPONSE_SCHEMA, body) ? body : null;
13012
13612
  const id = responseBody?.id ?? artifactId;
13013
13613
  const result = {
@@ -13028,7 +13628,7 @@ async function runUpdate(parsed, mode, isRetry = false) {
13028
13628
  }
13029
13629
  //#endregion
13030
13630
  //#region src/command-runners/append.ts
13031
- async function runAppend(parsed, mode, isRetry = false) {
13631
+ async function runAppend(parsed, mode, isRetry = false, preparedContent) {
13032
13632
  const command = "append";
13033
13633
  const input = parsed.positionals[0];
13034
13634
  const path = parsed.positionals[1];
@@ -13036,17 +13636,30 @@ async function runAppend(parsed, mode, isRetry = false) {
13036
13636
  if (!path) return writeFailure(command, validationError("Path is required.", "Pass a non-empty UTF-8 file."), mode, 1);
13037
13637
  const id = resolveArtifactId(input);
13038
13638
  if (!id) return writeFailure(command, targetResolutionError(input, "append"), mode, 1);
13039
- const s = await stat(path).catch(() => null);
13040
- if (!s || !s.isFile() || s.size === 0) return writeFailure(command, validationError("Path must be a non-empty file.", "Append supports one non-empty UTF-8 file for Markdown or HTML artifacts."), mode, 1);
13041
- const bytes = await readFile(path);
13042
- let content;
13043
- try {
13044
- content = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
13045
- } catch {
13046
- return writeFailure(command, validationError("File is not valid UTF-8.", "Use a non-empty UTF-8 file and retry."), mode, 1);
13639
+ let content = preparedContent;
13640
+ if (content === void 0) {
13641
+ let selection;
13642
+ try {
13643
+ selection = await prepareUploadSelection(path, true);
13644
+ } catch (error) {
13645
+ const failure = uploadReadError(error, path);
13646
+ if (failure.details?.reason === "invalid_type") {
13647
+ failure.message = `Upload path ${path}: Path must be a non-empty file.`;
13648
+ failure.why = failure.message;
13649
+ failure.hint = "Append supports one non-empty UTF-8 file for Markdown or HTML artifacts.";
13650
+ }
13651
+ return writeFailure(command, failure, mode, 1);
13652
+ }
13653
+ const file = selection.files[0];
13654
+ if (file.blob.size === 0) return writeFailure(command, validationError("Path must be a non-empty file.", "Append supports one non-empty UTF-8 file for Markdown or HTML artifacts."), mode, 1);
13655
+ try {
13656
+ content = new TextDecoder("utf-8", { fatal: true }).decode(await file.blob.arrayBuffer());
13657
+ } catch {
13658
+ return writeFailure(command, validationError("File is not valid UTF-8.", "Use a non-empty UTF-8 file and retry."), mode, 1);
13659
+ }
13047
13660
  }
13048
13661
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
13049
- if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
13662
+ if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runAppend(parsed, mode, true, content), isRetry);
13050
13663
  const request = await requestConfig(parsed.options);
13051
13664
  if (request.error) return writeFailure(command, request.error, mode, 1);
13052
13665
  const response = await cliFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(id)}/append`, baseUrlOf(parsed.options)), {
@@ -13069,7 +13682,7 @@ async function runAppend(parsed, mode, isRetry = false) {
13069
13682
  profile: credential.profile,
13070
13683
  profileCredentialKind: credential.profileCredentialKind,
13071
13684
  botProfile: credential.botProfile
13072
- }), credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
13685
+ }), credential, parsed.options, mode, () => runAppend(parsed, mode, true, content), isRetry);
13073
13686
  const responseBody = isContract(ARTIFACT_APPEND_RESPONSE_SCHEMA, body) ? body : null;
13074
13687
  const success = {
13075
13688
  artifact: {
@@ -13838,7 +14451,15 @@ Common failures:
13838
14451
  auth_required Set ARTIFACTSHARE_TOKEN before share
13839
14452
  self_upload_disabled Sign in with Google or Microsoft to upload your own files
13840
14453
  file_too_large Reduce file or directory size and retry
14454
+ upload_read_failed Check filesystem availability and permissions, then retry
13841
14455
  validation_failed Check file type (.html / .md for single files) and directory layout
14456
+ link Copy into the selection or pass the target by absolute path
14457
+ outside_cwd Pass an absolute path
14458
+ parent_traversal Pass a direct absolute path without any .. component
14459
+ changed The selection changed while reading; retry
14460
+ not_found Check the path and retry
14461
+ invalid_type Select a regular file or directory
14462
+ unsupported_guarantee Select a filesystem with stable dev/ino and no-follow support
13842
14463
  key_target_moved The artifact for --key moved; update it by ID or use a new key
13843
14464
  key_kind_mismatch The artifact for --key is a different kind; use a new key`
13844
14465
  });
@@ -13855,7 +14476,7 @@ const updateDefinition = define({
13855
14476
  artifactIdOrUrl: {
13856
14477
  type: "positional",
13857
14478
  toKebab: true,
13858
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14479
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
13859
14480
  },
13860
14481
  path: {
13861
14482
  type: "positional",
@@ -13872,7 +14493,7 @@ const updateDefinition = define({
13872
14493
  }
13873
14494
  },
13874
14495
  examples: `Target:
13875
- Accepts an artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL.
14496
+ Accepts an artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL.
13876
14497
  Titles and project names are not updated directly; resolve them to an ID first.
13877
14498
 
13878
14499
  Access:
@@ -13893,7 +14514,15 @@ Common failures:
13893
14514
  artifact_kind_mismatch Use a file for single-file artifacts or a directory for static sites
13894
14515
  self_upload_disabled Sign in with Google or Microsoft to upload your own files
13895
14516
  file_too_large Reduce file or directory size and retry
13896
- validation_failed Check file type (.html / .md for single files) and directory layout`
14517
+ upload_read_failed Check filesystem availability and permissions, then retry
14518
+ validation_failed Check file type (.html / .md for single files) and directory layout
14519
+ link Copy into the selection or pass the target by absolute path
14520
+ outside_cwd Pass an absolute path
14521
+ parent_traversal Pass a direct absolute path without any .. component
14522
+ changed The selection changed while reading; retry
14523
+ not_found Check the path and retry
14524
+ invalid_type Select a regular file or directory
14525
+ unsupported_guarantee Select a filesystem with stable dev/ino and no-follow support`
13897
14526
  });
13898
14527
  const appendDefinition = define({
13899
14528
  name: "append",
@@ -13911,7 +14540,18 @@ const appendDefinition = define({
13911
14540
  description: "Non-empty UTF-8 file to append"
13912
14541
  }
13913
14542
  },
13914
- examples: `Append <path> without a separator and create a new version at the existing share URL.\n\nFor Markdown, the file is added at the end of the current source. For HTML, it is inserted immediately before an ASCII case-insensitive </body> closing tag; when the tag is absent, it is added at the end.\n\nStatic sites are not supported. Use update to replace the full source instead.`
14543
+ examples: `Append <path> without a separator and create a new version at the existing share URL.\n\nFor Markdown, the file is added at the end of the current source. For HTML, it is inserted immediately before an ASCII case-insensitive </body> closing tag; when the tag is absent, it is added at the end.\n\nStatic sites are not supported. Use update to replace the full source instead.
14544
+
14545
+ Common failures:
14546
+ upload_read_failed Check filesystem availability and permissions, then retry
14547
+ validation_failed Check the selected file
14548
+ link Copy into the selection or pass the target by absolute path
14549
+ outside_cwd Pass an absolute path
14550
+ parent_traversal Pass a direct absolute path without any .. component
14551
+ changed The selection changed while reading; retry
14552
+ not_found Check the path and retry
14553
+ invalid_type Select a regular file
14554
+ unsupported_guarantee Select a filesystem with stable dev/ino and no-follow support`
13915
14555
  });
13916
14556
  const editDefinition = define({
13917
14557
  name: "edit",
@@ -13922,7 +14562,7 @@ const editDefinition = define({
13922
14562
  artifactIdOrUrl: {
13923
14563
  type: "positional",
13924
14564
  toKebab: true,
13925
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14565
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
13926
14566
  },
13927
14567
  title: {
13928
14568
  type: "string",
@@ -14000,7 +14640,7 @@ const deleteDefinition = define({
14000
14640
  artifactIdOrUrl: {
14001
14641
  type: "positional",
14002
14642
  toKebab: true,
14003
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14643
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14004
14644
  }
14005
14645
  },
14006
14646
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare delete abc123def4 --json
@@ -14046,7 +14686,7 @@ const downloadDefinition = define({
14046
14686
  type: "positional",
14047
14687
  toKebab: true,
14048
14688
  required: false,
14049
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14689
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14050
14690
  },
14051
14691
  projectId: {
14052
14692
  type: "string",
@@ -14061,7 +14701,7 @@ const downloadDefinition = define({
14061
14701
  force: {
14062
14702
  type: "boolean",
14063
14703
  toKebab: true,
14064
- description: "Allow writing into an existing output directory"
14704
+ description: "Replace existing output; retain backups for recovery"
14065
14705
  }
14066
14706
  },
14067
14707
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare download abc123def4 --json
@@ -14070,12 +14710,20 @@ const downloadDefinition = define({
14070
14710
 
14071
14711
  Use resolve first when a user gives a title or project name, then pass the id here.
14072
14712
  Download writes files to a directory so the result can be inspected or passed to update.
14713
+ Artifact IDs must match ^[a-z0-9]{10}$; invalid or duplicate list/index IDs fail before writes.
14714
+ Download accepts linked output parents and rechecks their resolved directory identities.
14715
+ Links in the output root, index, and every listed artifact are rejected, regardless of --force.
14716
+ Project preflight checks every listed artifact tree, including unchanged versions, but not unrelated content.
14717
+ Network failures and invalid manifest paths, bodies, or identities have individual artifact results; a boundary error aborts the remaining publications.
14718
+ Replacement retains originals and previous indexes in data.backup_paths after success; inspect them before manual cleanup.
14719
+ Identity checks detect observed swaps;
14720
+ Node path-based operations cannot guarantee atomic confinement against concurrent changes.
14073
14721
 
14074
14722
  Common failures:
14075
14723
  auth_required Set ARTIFACTSHARE_TOKEN before download
14076
14724
  target_not_found Retry with an artifact ID, share URL, or sandbox URL
14077
14725
  output_exists Choose another --output path or pass --force
14078
- validation_failed Check --output and downloaded file paths`
14726
+ validation_failed Check the named ID/path; use a regular directory without links`
14079
14727
  });
14080
14728
  const openDefinition = define({
14081
14729
  name: "open",
@@ -14086,7 +14734,7 @@ const openDefinition = define({
14086
14734
  artifactIdOrUrl: {
14087
14735
  type: "positional",
14088
14736
  toKebab: true,
14089
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14737
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14090
14738
  }
14091
14739
  },
14092
14740
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare open https://artifactshare.com/a/abc123def4 --json
@@ -14115,7 +14763,7 @@ const moveDefinition = define({
14115
14763
  artifactIdOrUrl: {
14116
14764
  type: "positional",
14117
14765
  toKebab: true,
14118
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14766
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14119
14767
  },
14120
14768
  projectId: {
14121
14769
  type: "string",
@@ -14150,7 +14798,7 @@ const artifactsGetDefinition = define({
14150
14798
  artifactIdOrUrl: {
14151
14799
  type: "positional",
14152
14800
  toKebab: true,
14153
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14801
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14154
14802
  },
14155
14803
  offset: {
14156
14804
  type: "string",
@@ -14263,7 +14911,7 @@ const commentsListDefinition = define({
14263
14911
  artifactIdOrUrl: {
14264
14912
  type: "positional",
14265
14913
  toKebab: true,
14266
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14914
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14267
14915
  }
14268
14916
  },
14269
14917
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare comments list abc123def4 --json
@@ -14288,7 +14936,7 @@ const commentsPostDefinition = define({
14288
14936
  artifactIdOrUrl: {
14289
14937
  type: "positional",
14290
14938
  toKebab: true,
14291
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14939
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14292
14940
  },
14293
14941
  body: {
14294
14942
  type: "string",
@@ -14341,7 +14989,7 @@ const commentThreadActionArgs = {
14341
14989
  artifactIdOrUrl: {
14342
14990
  type: "positional",
14343
14991
  toKebab: true,
14344
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14992
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14345
14993
  },
14346
14994
  threadId: {
14347
14995
  type: "string",
@@ -14354,7 +15002,7 @@ const commentMessageActionArgs = {
14354
15002
  artifactIdOrUrl: {
14355
15003
  type: "positional",
14356
15004
  toKebab: true,
14357
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15005
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14358
15006
  },
14359
15007
  messageId: {
14360
15008
  type: "string",
@@ -14807,7 +15455,11 @@ const projectsListDefinition = define({
14807
15455
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare projects list --json
14808
15456
 
14809
15457
  is_default marks the working-directory default project from .artifactshare/config.json.
14810
- Use a project id with share --project-id or init --project-id.`
15458
+ Use a project id with share --project-id or init --project-id.
15459
+ Only active, authorized destinations are listed. Private projects require creator access,
15460
+ team-plan owner/admin access, or a verified contributor/manager grant. Free/plus
15461
+ admin status and viewer or artifact-only grants do not authorize placement.
15462
+ Agents and bots retain their fixed-project and verified-grant limits; publishers cannot select projects.`
14811
15463
  });
14812
15464
  const projectsCreateDefinition = define({
14813
15465
  name: "create",
@@ -15078,6 +15730,9 @@ and Cursor skills. Cursor project scope is not auto-installed; use skills instal
15078
15730
  data.mode is "onboarding".
15079
15731
  With --profile or --project-id, init saves working-directory defaults to
15080
15732
  .artifactshare/config.local.json instead (data.mode is "config"); secrets are never written there.
15733
+ Config saves preserve unknown keys and refuse linked or changed paths.
15734
+ Only a regular repository .git directory can receive an info/exclude update.
15735
+ Git worktrees/submodules still save config; git_exclude_warning gives the exact line to add manually.
15081
15736
 
15082
15737
  Common failures:
15083
15738
  skill_update_conflict An unmanaged or broken skill file exists; inspect it before overwriting