@artifactshare/cli 0.15.3 → 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();
@@ -101,16 +105,34 @@ const CliAuthRefreshCredentialsResponseSchema = z.object({
101
105
  });
102
106
  z.object({ refresh_token: z.string().min(1).max(256) });
103
107
  z.object({ revoked: z.literal(true) });
104
- const DeviceAuthorizationPresetSchema = z.enum(["unrestricted", "agent"]);
108
+ const DeviceAuthorizationPresetSchema = z.enum([
109
+ "unrestricted",
110
+ "agent",
111
+ "publisher"
112
+ ]);
113
+ const PublisherClientNameSchema = z.string().transform((value) => value.trim().normalize("NFC")).refine((value) => Array.from(value).length >= 1 && Array.from(value).length <= 100 && /^[\p{L}\p{M}\p{N} ._()-]+$/u.test(value) && !/\p{Default_Ignorable_Code_Point}/u.test(value) && /[\p{L}\p{N}._()-]/u.test(value), "Use 1–100 letters, marks, numbers, spaces, or ._-()");
105
114
  z.object({
106
115
  client_id: z.literal(CLI_DEVICE_CLIENT_ID),
107
116
  preset: DeviceAuthorizationPresetSchema.optional(),
108
- device_name: z.string().max(100).nullable().optional(),
117
+ device_name: z.string().nullable().optional(),
109
118
  project_selector: z.string().refine((value) => {
110
119
  const size = Array.from(value.trim()).length;
111
120
  return size >= 1 && size <= 120;
112
121
  }, "project_selector must contain 1 to 120 Unicode code points after trimming").optional()
113
122
  }).superRefine((value, context) => {
123
+ if (value.preset === "publisher") {
124
+ const name = PublisherClientNameSchema.safeParse(value.device_name);
125
+ if (!name.success) context.addIssue({
126
+ code: "custom",
127
+ path: ["device_name"],
128
+ message: "A valid publisher client name is required"
129
+ });
130
+ else value.device_name = name.data;
131
+ } else if (value.device_name != null && value.device_name.length > 100) context.addIssue({
132
+ code: "custom",
133
+ path: ["device_name"],
134
+ message: "device_name must contain at most 100 characters"
135
+ });
114
136
  if (value.preset !== "agent" && value.project_selector !== void 0) context.addIssue({
115
137
  code: "custom",
116
138
  path: ["project_selector"],
@@ -136,7 +158,12 @@ const DeviceTokenResponseSchema = z.object({
136
158
  token_type: z.string().min(1).refine((value) => value.toLowerCase() === "bearer", { message: "token_type must be Bearer" }),
137
159
  expires_in: z.number().int().nonnegative().optional()
138
160
  });
161
+ const PublisherApprovalChoiceSchema = z.discriminatedUnion("mode", [z.object({ mode: z.literal("create-new") }).strict(), z.object({
162
+ mode: z.literal("continue-existing"),
163
+ client_id: stringId
164
+ }).strict()]);
139
165
  z.object({
166
+ publisher: PublisherApprovalChoiceSchema.optional(),
140
167
  userCode: stringId,
141
168
  project_id: stringId.optional()
142
169
  });
@@ -157,7 +184,18 @@ const AgentApprovalSchema = z.object({
157
184
  fixedProject: FixedAgentApprovalProjectSchema.nullable(),
158
185
  fixedProjectError: z.boolean()
159
186
  });
160
- z.object({ agentApproval: AgentApprovalSchema.nullable() });
187
+ const PublisherApprovalSchema = z.object({
188
+ preset: z.literal("publisher"),
189
+ requestedName: PublisherClientNameSchema,
190
+ clients: z.array(z.object({
191
+ id: stringId,
192
+ name: PublisherClientNameSchema
193
+ }))
194
+ });
195
+ z.object({
196
+ publisherApproval: PublisherApprovalSchema.nullable().optional(),
197
+ agentApproval: AgentApprovalSchema.nullable()
198
+ });
161
199
  const CliUserSchema = z.object({
162
200
  id: stringId,
163
201
  email: z.string()
@@ -166,14 +204,28 @@ const CliWorkspaceSchema = z.object({
166
204
  id: stringId,
167
205
  hosted_domain: z.string().nullable()
168
206
  });
207
+ const DoctorAuthoritySchema = z.object({
208
+ preset: DeviceAuthorizationPresetSchema,
209
+ project_id: stringId.nullable(),
210
+ publisher_client_id: stringId.optional(),
211
+ publisher_client_name: PublisherClientNameSchema.optional()
212
+ }).superRefine((value, context) => {
213
+ if (value.preset === "publisher" && (value.project_id !== null || !value.publisher_client_id || !value.publisher_client_name)) context.addIssue({
214
+ code: "custom",
215
+ message: "Publisher diagnostics require a client and no project"
216
+ });
217
+ if (value.preset !== "publisher" && (value.publisher_client_id !== void 0 || value.publisher_client_name !== void 0)) context.addIssue({
218
+ code: "custom",
219
+ message: "Client attribution requires the publisher preset"
220
+ });
221
+ });
169
222
  const CliWhoamiResponseSchema = z.object({
170
223
  user: CliUserSchema,
171
224
  workspace: CliWorkspaceSchema,
172
- auth: z.object({ kind: z.literal("bearer_or_session") }).optional()
173
- });
174
- const DoctorAuthoritySchema = z.object({
175
- preset: DeviceAuthorizationPresetSchema,
176
- project_id: stringId.nullable()
225
+ auth: z.object({
226
+ kind: z.literal("bearer_or_session"),
227
+ authority: DoctorAuthoritySchema.optional()
228
+ }).optional()
177
229
  });
178
230
  const DoctorUploadSchema = z.union([z.object({ ok: z.literal(true) }), z.object({
179
231
  ok: z.literal(false),
@@ -316,6 +368,24 @@ const ArtifactReadResponseSchema = z.object({
316
368
  comments: z.array(z.lazy(() => CommentThreadSchema)).optional(),
317
369
  comments_has_more: z.boolean().optional()
318
370
  });
371
+ const PublisherSingleFileReadResponseSchema = ArtifactReadResponseSchema.extend({ visibility: VisibilitySchema });
372
+ const PublisherStaticSiteReadResponseSchema = z.object({
373
+ id: stringId,
374
+ share_url: url,
375
+ version_id: stringId,
376
+ artifact_kind: z.literal("static_site"),
377
+ visibility: VisibilitySchema,
378
+ project_id: stringId.nullable(),
379
+ link_expires_at: nullableTimestamp,
380
+ retain_versions: z.number().int().min(1).nullable()
381
+ });
382
+ z.union([PublisherSingleFileReadResponseSchema, PublisherStaticSiteReadResponseSchema]);
383
+ z.object({ retain_versions: z.number().int().min(1).nullable() }).strict();
384
+ z.object({ publisher_client_id: stringId }).strict();
385
+ z.object({
386
+ id: stringId,
387
+ publisher_client_id: stringId
388
+ }).strict();
319
389
  const ArtifactDeleteResponseSchema = z.object({
320
390
  id: stringId,
321
391
  deleted: z.literal(true)
@@ -334,7 +404,7 @@ const DownloadManifestFileSchema = z.object({
334
404
  sha256: z.string()
335
405
  });
336
406
  const DownloadManifestResponseSchema = z.object({
337
- id: stringId,
407
+ id: ArtifactIdSchema,
338
408
  share_url: url,
339
409
  version_id: stringId,
340
410
  artifact_kind: UploadArtifactKindSchema,
@@ -343,7 +413,7 @@ const DownloadManifestResponseSchema = z.object({
343
413
  project_id: stringId.nullable().optional()
344
414
  });
345
415
  const ArtifactsListEntrySchema = z.object({
346
- id: stringId,
416
+ id: ArtifactIdSchema,
347
417
  title: z.string(),
348
418
  share_url: url,
349
419
  visibility: VisibilitySchema,
@@ -383,13 +453,16 @@ const CommentMessageSchema = z.object({
383
453
  updated_at: timestamp
384
454
  });
385
455
  const CommentThreadSchema = z.object({
456
+ message_count: z.number().int().nonnegative(),
457
+ reply_count: z.number().int().nonnegative(),
458
+ older_cursor: z.string().nullable(),
386
459
  id: stringId,
387
460
  status: z.enum(["open", "resolved"]),
388
461
  resolved_at: nullableTimestamp,
389
462
  created_at: timestamp,
390
463
  updated_at: timestamp,
391
464
  anchor: CommentAnchorSchema,
392
- messages: z.array(CommentMessageSchema)
465
+ messages: z.array(CommentMessageSchema).max(51)
393
466
  });
394
467
  const CommentPostRequestSchema = z.object({
395
468
  action: z.never().optional(),
@@ -447,13 +520,17 @@ const CommentPostResponseSchema = z.object({
447
520
  share_url: url.nullable().optional(),
448
521
  thread_id: stringId,
449
522
  reply: z.boolean(),
450
- thread: CommentThreadSchema
523
+ thread: CommentThreadSchema.optional(),
524
+ changed_message: CommentMessageSchema.optional(),
525
+ refresh_required: z.boolean().optional()
451
526
  });
452
527
  const CommentActionResponseSchema = z.object({
453
528
  artifact_id: stringId,
454
529
  share_url: url.nullable().optional(),
455
530
  thread_id: stringId,
456
- thread: CommentThreadSchema
531
+ thread: CommentThreadSchema.optional(),
532
+ changed_message: CommentMessageSchema.optional(),
533
+ refresh_required: z.boolean().optional()
457
534
  });
458
535
  const CommentDeleteResponseSchema = z.object({
459
536
  artifact_id: stringId,
@@ -461,6 +538,8 @@ const CommentDeleteResponseSchema = z.object({
461
538
  thread_id: stringId,
462
539
  deleted: z.literal(true),
463
540
  thread_deleted: z.boolean(),
541
+ deleted_message_id: stringId.optional(),
542
+ refresh_required: z.boolean().optional(),
464
543
  thread: CommentThreadSchema.optional()
465
544
  });
466
545
  const ProjectListEntrySchema = z.object({
@@ -665,6 +744,9 @@ const BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
665
744
  "unarchive"
666
745
  ]);
667
746
  const VALUE_FLAGS = /* @__PURE__ */ new Set([
747
+ "before",
748
+ "limit",
749
+ "around-message-id",
668
750
  "add-email",
669
751
  "agent",
670
752
  "base-url",
@@ -828,6 +910,20 @@ function apiError(body) {
828
910
  }
829
911
  function mapApiError(status, body, options = {}) {
830
912
  const { code: apiCode, message: apiMessage } = apiError(body);
913
+ if (apiCode === "rate-limited" || apiCode === "thread-capacity") {
914
+ const raw = isRecord$1(body) && isRecord$1(body.error) ? body.error : void 0;
915
+ const details = raw && isRecord$1(raw.details) ? raw.details : void 0;
916
+ return cliError({
917
+ code: apiCode === "rate-limited" ? "rate_limited" : "thread_capacity",
918
+ message: apiMessage ?? "Comment posting refused.",
919
+ why: apiCode === "rate-limited" ? "The comment posting limit for this minute was reached." : "This thread has reached its capacity of 500 stored messages.",
920
+ hint: apiCode === "rate-limited" ? "Wait until retry_at before retrying the unsent comment." : "Start a new thread, or delete messages from this thread before replying.",
921
+ agentRecoverable: true,
922
+ requiresHuman: false,
923
+ recovery: { kind: apiCode === "rate-limited" ? "retry_later" : "change_input" },
924
+ ...details ? { details } : {}
925
+ });
926
+ }
831
927
  if (status === 401) {
832
928
  if (!options.authenticated) return authRequiredError(options.baseUrl ?? "https://artifactshare.com");
833
929
  const source = options.credentialSource;
@@ -1584,6 +1680,16 @@ function resolveArtifactId(input) {
1584
1680
  } catch {
1585
1681
  return null;
1586
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
+ }
1587
1693
  const linkHostMatch = url.hostname.match(/^([A-Za-z0-9]{10})(?:--v-[a-f0-9]+)?\.artifactshare\.link$/);
1588
1694
  if (linkHostMatch?.[1]) return linkHostMatch[1];
1589
1695
  const sandboxMatch = url.hostname.match(/^([A-Za-z0-9]+)(?:--v-[a-f0-9]+)?\.sandbox\./);
@@ -1613,7 +1719,7 @@ function targetResolutionError(input, command) {
1613
1719
  code: "target_not_found",
1614
1720
  message: "Artifact target could not be resolved.",
1615
1721
  why: `${TARGET_COMMAND_LABELS[command]} only accepts an artifact ID, share URL, or sandbox URL.`,
1616
- 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.",
1617
1723
  agentRecoverable: true,
1618
1724
  requiresHuman: false,
1619
1725
  recovery: { kind: "change_input" },
@@ -1884,6 +1990,10 @@ function humanSuccess(command, data) {
1884
1990
  const withWarnings = warnings.length ? `${output}${warnings.map((message) => `Warning: ${message}`).join("\n")}\n` : output;
1885
1991
  return suffix ? `${withWarnings}${suffix}` : withWarnings;
1886
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
+ }
1887
1997
  if (command === "doctor") return doctorHumanOutput(data);
1888
1998
  if (command === "open") return openHumanOutput(data);
1889
1999
  if (command === "init") return initHumanOutput(data);
@@ -2068,8 +2178,10 @@ function isLocalHostname(hostname) {
2068
2178
  }
2069
2179
  function apiUrl(path, baseUrl) {
2070
2180
  const url = new URL(baseUrl);
2071
- url.pathname = `${url.pathname.replace(/\/$/, "")}${path}`;
2072
- url.search = "";
2181
+ const basePath = url.pathname.replace(/\/$/, "");
2182
+ const queryStart = path.indexOf("?");
2183
+ url.pathname = `${basePath}${queryStart < 0 ? path : path.slice(0, queryStart)}`;
2184
+ url.search = queryStart < 0 ? "" : path.slice(queryStart);
2073
2185
  url.hash = "";
2074
2186
  return url;
2075
2187
  }
@@ -2476,9 +2588,6 @@ async function resolveDefaultVisibility(key, repositoryConfig) {
2476
2588
  async function readProjectConfigAtDirectory(directory, kind) {
2477
2589
  return await readJsonFile(join(directory, kind === "local" ? PROJECT_CONFIG_LOCAL_PATH : PROJECT_CONFIG_PATH));
2478
2590
  }
2479
- async function readRawLocalProjectConfig(cwd = process.cwd()) {
2480
- return await readJsonFile(projectConfigLocalPath(cwd));
2481
- }
2482
2591
  function configString(value) {
2483
2592
  return nonEmpty(typeof value === "string" ? value : void 0) ?? null;
2484
2593
  }
@@ -3119,7 +3228,7 @@ async function clearPendingDeviceAuth(baseUrl, profile) {
3119
3228
  }
3120
3229
  function isPendingDeviceAuth(value) {
3121
3230
  if (!isRecord$1(value)) return false;
3122
- return typeof value.base_url === "string" && typeof value.profile === "string" && (value.preset === void 0 || value.preset === "unrestricted" || value.preset === "agent") && typeof value.device_code === "string" && typeof value.verification_uri === "string" && (typeof value.verification_uri_complete === "string" || value.verification_uri_complete === null) && typeof value.user_code === "string" && typeof value.expires_at === "string" && typeof value.interval_seconds === "number" && typeof value.created_at === "string";
3231
+ return typeof value.base_url === "string" && typeof value.profile === "string" && (value.preset === void 0 || value.preset === "unrestricted" || value.preset === "agent" || value.preset === "publisher") && typeof value.device_code === "string" && typeof value.verification_uri === "string" && (typeof value.verification_uri_complete === "string" || value.verification_uri_complete === null) && typeof value.user_code === "string" && typeof value.expires_at === "string" && typeof value.interval_seconds === "number" && typeof value.created_at === "string";
3123
3232
  }
3124
3233
  function resolveConfigHome(env, fallbackHome = homedir, platform = process.platform) {
3125
3234
  const override = nonEmpty(env.ARTIFACTSHARE_CONFIG_HOME);
@@ -3477,7 +3586,7 @@ function pendingDeviceAuthFromCode(profile, options, code) {
3477
3586
  return {
3478
3587
  base_url: baseUrlOf(options),
3479
3588
  profile,
3480
- preset: options.preset === "agent" ? "agent" : "unrestricted",
3589
+ preset: options.preset === "publisher" ? "publisher" : options.preset === "agent" ? "agent" : "unrestricted",
3481
3590
  device_code: code.device_code,
3482
3591
  verification_uri: code.verification_uri,
3483
3592
  verification_uri_complete: code.verification_uri_complete ?? null,
@@ -3597,6 +3706,11 @@ async function verifyProfileTokenAccount(profile, token, options, init) {
3597
3706
  ok: false,
3598
3707
  error: whoamiResult.error
3599
3708
  };
3709
+ const auth = isRecord$1(whoamiResult.body) && isRecord$1(whoamiResult.body.auth) ? whoamiResult.body.auth : null;
3710
+ if (auth?.authority !== void 0 && !DoctorAuthoritySchema.safeParse(auth.authority).success) return {
3711
+ ok: false,
3712
+ error: validationError("Token authority response was invalid.", "Retry with a supported credential. The token has not been saved.", "service_error")
3713
+ };
3600
3714
  const whoami = whoamiProfile(whoamiResult.body);
3601
3715
  const profiles = config.profiles ?? {};
3602
3716
  const expectedEmail = nonEmpty((Object.hasOwn(profiles, profile) ? profiles[profile] : void 0)?.email);
@@ -3640,7 +3754,7 @@ async function writeProfileConfig(profile, options, tokenStore, whoami) {
3640
3754
  email: whoami.email ?? currentProfile?.email ?? null,
3641
3755
  workspace_id: whoami.workspace_id,
3642
3756
  token_store: tokenStore,
3643
- preset: options.preset === "agent" || options.preset === "unrestricted" ? options.preset : currentProfile?.preset ?? "unrestricted",
3757
+ preset: whoami.preset ?? (options.preset === "publisher" || options.preset === "agent" || options.preset === "unrestricted" ? options.preset : currentProfile?.preset ?? "unrestricted"),
3644
3758
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
3645
3759
  }
3646
3760
  }
@@ -3648,9 +3762,12 @@ async function writeProfileConfig(profile, options, tokenStore, whoami) {
3648
3762
  }
3649
3763
  async function resolveAuthorizationPreset(profile, options) {
3650
3764
  const requested = nonEmpty(options.preset);
3765
+ const stored = (await readGlobalConfig())?.profiles?.[profile]?.preset;
3766
+ if (requested === "publisher" || !requested && stored === "publisher") return { error: validationError("Publisher login is not supported by this CLI.", "Use the device API and explicitly continue your existing publisher client in the browser.") };
3651
3767
  if (requested && requested !== "agent" && requested !== "unrestricted") return { error: validationError(`Unknown authorization preset: ${requested}`, "Use --preset agent or --preset unrestricted.") };
3652
3768
  if (requested === "agent" || requested === "unrestricted") return { value: requested };
3653
- return { value: (await readGlobalConfig())?.profiles?.[profile]?.preset ?? "unrestricted" };
3769
+ if (stored !== void 0 && stored !== "agent" && stored !== "unrestricted") return { error: validationError("Unknown stored authorization preset.", "Select a supported preset explicitly.") };
3770
+ return { value: stored ?? "unrestricted" };
3654
3771
  }
3655
3772
  function deviceNameForProfile(profile) {
3656
3773
  const prefix = `Artifact Share CLI on ${platform()} ${arch()} (`;
@@ -3678,6 +3795,7 @@ function deviceTokenError(body) {
3678
3795
  function whoamiProfile(body) {
3679
3796
  const contracted = CliWhoamiResponseSchema.safeParse(body);
3680
3797
  if (contracted.success) return {
3798
+ ...contracted.data.auth?.authority ? { preset: contracted.data.auth.authority.preset } : {},
3681
3799
  email: contracted.data.user.email,
3682
3800
  workspace_id: contracted.data.workspace.id,
3683
3801
  hosted_domain: contracted.data.workspace.hosted_domain
@@ -3685,7 +3803,10 @@ function whoamiProfile(body) {
3685
3803
  const record = isRecord$1(body) ? body : null;
3686
3804
  const user = record && isRecord$1(record.user) ? record.user : null;
3687
3805
  const workspace = record && isRecord$1(record.workspace) ? record.workspace : null;
3806
+ const auth = record && isRecord$1(record.auth) ? record.auth : null;
3807
+ const preset = (auth && isRecord$1(auth.authority) ? auth.authority : null)?.preset;
3688
3808
  return {
3809
+ ...preset === "publisher" || preset === "agent" || preset === "unrestricted" ? { preset } : {},
3689
3810
  email: typeof user?.email === "string" ? user.email : null,
3690
3811
  workspace_id: typeof workspace?.id === "string" ? workspace.id : null,
3691
3812
  hosted_domain: typeof workspace?.hosted_domain === "string" ? workspace.hosted_domain : null
@@ -3845,6 +3966,7 @@ async function handleJsonPendingAuth(command, credential, options, mode, rerun)
3845
3966
  if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
3846
3967
  if (!await canAttemptProfileTokenSave(profile, options)) return writeFailure(command, tokenStoreUnavailableError(profile, "native_store_unavailable"), mode, 1);
3847
3968
  const existing = await readPendingDeviceAuth(baseUrl, profile);
3969
+ if (existing?.preset === "publisher") return writeFailure(command, validationError("Publisher login cannot be resumed by this CLI.", "Use the device API and approve an existing or new publisher client in the browser."), mode, 1);
3848
3970
  if (existing && !isPendingExpired(existing)) {
3849
3971
  const exchange = await exchangeDeviceTokenOnce(options, existing.device_code, request.init);
3850
3972
  if ("error" in exchange) {
@@ -3869,6 +3991,7 @@ async function handleJsonPendingAuth(command, credential, options, mode, rerun)
3869
3991
  else return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing, extraDetails), mode, 1);
3870
3992
  } else if (existing) await clearPendingDeviceAuth(baseUrl, profile);
3871
3993
  const preset = (await readGlobalConfig())?.profiles?.[profile]?.preset ?? "unrestricted";
3994
+ if (preset !== "agent" && preset !== "unrestricted") return writeFailure(command, validationError("This preset cannot log in through the CLI.", "Use the device API to approve or continue the publisher client."), mode, 1);
3872
3995
  const code = await requestDeviceCode(options, request.init, {
3873
3996
  preset,
3874
3997
  deviceName: deviceNameForProfile(profile)
@@ -11104,12 +11227,20 @@ async function runCommentsList(parsed, mode) {
11104
11227
  const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
11105
11228
  if (target.error) return writeFailure(command, target.error, mode, 1);
11106
11229
  const artifactId = target.artifactId;
11230
+ const page = new URLSearchParams();
11231
+ for (const [key, value] of Object.entries({
11232
+ thread_id: parsed.options.threadId,
11233
+ before: parsed.options.before,
11234
+ limit: parsed.options.limit,
11235
+ around_message_id: parsed.options.aroundMessageId
11236
+ })) if (value !== void 0) page.set(key, value);
11237
+ if ([...page.values()].some((value) => value.length === 0) || page.size > 0 && !parsed.options.threadId || parsed.options.before !== void 0 && parsed.options.aroundMessageId !== void 0 || parsed.options.limit !== void 0 && (!/^[1-9]\d*$/.test(parsed.options.limit) || Number(parsed.options.limit) > 50 || !parsed.options.before && !parsed.options.aroundMessageId)) return writeFailure(command, validationError("Invalid comment page options.", "Use --thread-id with --before or --around-message-id and a limit from 1 to 50."), mode, 1);
11107
11238
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
11108
11239
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
11109
11240
  const request = await requestConfig(parsed.options);
11110
11241
  if (request.error) return writeFailure(command, request.error, mode, 1);
11111
11242
  const result = await runAuthenticatedApi(credential, parsed.options, async (current) => {
11112
- const comments = await apiGet(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, current.token, parsed.options, request.init, {
11243
+ const comments = await apiGet(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments${page.size ? `?${page}` : ""}`, current.token, parsed.options, request.init, {
11113
11244
  artifactTarget: true,
11114
11245
  credentialSource: current.source,
11115
11246
  profile: current.profile,
@@ -11173,7 +11304,9 @@ async function runCommentsPost(parsed, mode) {
11173
11304
  share_url: configString(postedResponse?.share_url ?? postedRaw?.share_url),
11174
11305
  thread_id: threadId,
11175
11306
  reply: (postedResponse?.reply ?? postedRaw?.reply) === true,
11176
- thread: postedResponse?.thread ?? postedRaw?.thread ?? null
11307
+ thread: postedResponse?.thread ?? postedRaw?.thread ?? null,
11308
+ changed_message: postedResponse?.changed_message ?? postedRaw?.changed_message,
11309
+ refresh_required: postedResponse?.refresh_required ?? postedRaw?.refresh_required
11177
11310
  }, mode);
11178
11311
  }
11179
11312
  async function runCommentsEdit(parsed, mode) {
@@ -11194,12 +11327,14 @@ async function runCommentsEdit(parsed, mode) {
11194
11327
  const actionRaw = isRecord$1(result) ? result : null;
11195
11328
  const threadId = configString(actionResponse?.thread_id ?? actionRaw?.thread_id);
11196
11329
  const thread = actionResponse?.thread ?? actionRaw?.thread;
11197
- if (!threadId || thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
11330
+ if (!threadId) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
11198
11331
  writeSuccess(command, {
11199
11332
  artifact_id: target.artifactId,
11200
11333
  share_url: configString(actionResponse?.share_url ?? actionRaw?.share_url),
11201
11334
  thread_id: threadId,
11202
- thread
11335
+ thread,
11336
+ changed_message: actionResponse?.changed_message ?? actionRaw?.changed_message,
11337
+ refresh_required: actionResponse?.refresh_required ?? actionRaw?.refresh_required
11203
11338
  }, mode);
11204
11339
  }
11205
11340
  async function runCommentsResolve(parsed, mode) {
@@ -11236,6 +11371,8 @@ async function runCommentsDelete(parsed, mode) {
11236
11371
  share_url: configString(deleteResponse?.share_url ?? deleteRaw?.share_url),
11237
11372
  thread_id: responseThreadId,
11238
11373
  deleted: true,
11374
+ deleted_message_id: deleteResponse?.deleted_message_id ?? deleteRaw?.deleted_message_id,
11375
+ refresh_required: deleteResponse?.refresh_required ?? deleteRaw?.refresh_required,
11239
11376
  thread_deleted: (deleteResponse?.thread_deleted ?? deleteRaw?.thread_deleted) === true,
11240
11377
  ...(deleteResponse?.thread ?? deleteRaw?.thread) !== void 0 ? { thread: deleteResponse?.thread ?? deleteRaw?.thread } : {}
11241
11378
  }, mode);
@@ -11257,12 +11394,14 @@ async function runCommentsStatus(parsed, mode, command, action) {
11257
11394
  const actionRaw = isRecord$1(result) ? result : null;
11258
11395
  const responseThreadId = configString(actionResponse?.thread_id ?? actionRaw?.thread_id);
11259
11396
  const thread = actionResponse?.thread ?? actionRaw?.thread;
11260
- if (!responseThreadId || thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
11397
+ if (!responseThreadId) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
11261
11398
  writeSuccess(command, {
11262
11399
  artifact_id: target.artifactId,
11263
11400
  share_url: configString(actionResponse?.share_url ?? actionRaw?.share_url),
11264
11401
  thread_id: responseThreadId,
11265
- thread
11402
+ thread,
11403
+ changed_message: actionResponse?.changed_message ?? actionRaw?.changed_message,
11404
+ refresh_required: actionResponse?.refresh_required ?? actionRaw?.refresh_required
11266
11405
  }, mode);
11267
11406
  }
11268
11407
  async function postCommentAction(parsed, command, artifactId, payload, mode) {
@@ -11458,6 +11597,13 @@ async function runDoctor(parsed, mode) {
11458
11597
  const authority = doctorAuthority(auth?.authority);
11459
11598
  if (authority) data.auth.authority = authority;
11460
11599
  applyAgentDestinationDiagnostic(data, authority);
11600
+ if (authority?.preset === "publisher") data.destination = {
11601
+ ok: true,
11602
+ type: "home",
11603
+ project_id: null,
11604
+ code: "publisher_scope",
11605
+ hint: `Publisher ${authority.publisher_client_name}: create private files or static sites in home; read, update, prune versions and delete artifacts created by or assigned to this client. Use the API; publisher CLI login and publishing workflows are not supported.`
11606
+ };
11461
11607
  data.upload.checked = true;
11462
11608
  data.upload.ok = upload?.ok === true;
11463
11609
  if (!data.upload.ok) {
@@ -11469,6 +11615,12 @@ async function runDoctor(parsed, mode) {
11469
11615
  function doctorAuthority(value) {
11470
11616
  if (!value || typeof value !== "object") return null;
11471
11617
  const authority = value;
11618
+ if (authority.preset === "publisher" && authority.project_id === null && typeof authority.publisher_client_id === "string" && typeof authority.publisher_client_name === "string") return {
11619
+ preset: "publisher",
11620
+ project_id: null,
11621
+ publisher_client_id: authority.publisher_client_id,
11622
+ publisher_client_name: authority.publisher_client_name
11623
+ };
11472
11624
  if (authority.preset === "agent" && typeof authority.project_id === "string" && authority.project_id) return {
11473
11625
  preset: "agent",
11474
11626
  project_id: authority.project_id
@@ -11602,45 +11754,636 @@ async function runChangelog(_parsed, mode) {
11602
11754
  return writeSuccess("changelog", await buildChangelogData(await loadCliVersion()), mode);
11603
11755
  }
11604
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
11605
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
+ };
11606
12361
  let undiciModule;
11607
12362
  async function createUploadForm() {
11608
12363
  const { FormData } = undiciModule ??= await import("undici");
11609
12364
  return new FormData();
11610
12365
  }
11611
- async function prepareUploadPayload(targetPath, fileStat, initialForm) {
11612
- const form = initialForm ?? await createUploadForm();
11613
- if (fileStat.isDirectory()) {
11614
- let files;
11615
- try {
11616
- files = await collectDirectoryFiles(resolve(targetPath));
11617
- } catch (error) {
11618
- if (error instanceof CollectDirectoryFilesError) return { error: validationError(error.message, error.hint) };
11619
- throw error;
11620
- }
11621
- if (files.length === 0) return { error: validationError("Directory has no shareable files.", "Add index.html or index.md and retry.") };
11622
- for (const file of files) form.append("file", await blobFor(file.path), file.relativePath);
11623
- return { payload: {
11624
- form,
11625
- kind: "static_site"
11626
- } };
11627
- }
11628
- if (fileStat.isFile()) {
11629
- 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);
11630
12372
  return { payload: {
11631
12373
  form,
11632
- kind: artifactKindForFile(targetPath)
12374
+ kind: selection.directory ? "static_site" : artifactKindForFile(selection.files[0].name)
11633
12375
  } };
12376
+ } catch (error) {
12377
+ return { error: uploadReadError(error, targetPath) };
11634
12378
  }
11635
- return { error: validationError("Path must be a file or directory.", "Pass a regular file or directory.") };
11636
12379
  }
11637
- async function prepareDownloadPlan(manifest, outputPath, force) {
12380
+ async function prepareDownloadPlan(manifest, outputPath, force, boundary = new WriteBoundary(), treePreflighted = false) {
11638
12381
  if (manifest.files.length === 0) return { error: validationError("Download manifest contains no files.", "Check the artifact and retry.") };
11639
12382
  if (outputPath === "") return { error: validationError("--output requires a non-empty directory.", "Pass --output <path> or omit --output to use the artifact ID.") };
11640
12383
  const root = resolve(outputPath);
11641
- const existing = await lstat(root).catch(() => null);
11642
- if (existing?.isSymbolicLink()) return { error: validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry.") };
11643
- 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({
11644
12387
  code: "output_exists",
11645
12388
  message: "Output path already exists.",
11646
12389
  why: "Download will not write into an existing path unless --force is set.",
@@ -11649,22 +12392,29 @@ async function prepareDownloadPlan(manifest, outputPath, force) {
11649
12392
  requiresHuman: false,
11650
12393
  recovery: { kind: "change_input" }
11651
12394
  }) };
11652
- 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);
11653
12397
  const seen = /* @__PURE__ */ new Set();
12398
+ const directories = /* @__PURE__ */ new Set();
12399
+ const foldCase = process.platform === "win32" || process.platform === "darwin";
11654
12400
  const relativeFiles = [];
11655
12401
  for (const file of manifest.files) {
11656
12402
  const relativePath = downloadRelativePath(file.path);
11657
- if (relativePath.error) return { error: relativePath.error };
11658
- if (seen.has(relativePath.value)) return { error: validationError("Download manifest contains duplicate file paths.", "Retry later. If this repeats, report the artifact ID.") };
11659
- 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);
11660
12409
  relativeFiles.push({
11661
12410
  ...file,
11662
- relativePath: relativePath.value
12411
+ relativePath
11663
12412
  });
11664
12413
  }
11665
12414
  const parent = dirname(root);
11666
- await mkdir(parent, { recursive: true });
11667
- 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);
11668
12418
  const files = [];
11669
12419
  for (const file of relativeFiles) {
11670
12420
  const targetPath = resolve(tempRoot, file.relativePath);
@@ -11676,15 +12426,15 @@ async function prepareDownloadPlan(manifest, outputPath, force) {
11676
12426
  return { value: {
11677
12427
  root,
11678
12428
  tempRoot,
11679
- replaceExisting: Boolean(existing),
11680
- files
12429
+ files,
12430
+ boundary
11681
12431
  } };
11682
12432
  }
11683
12433
  function downloadRelativePath(path) {
11684
- 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)}.`);
11685
12435
  const segments = path.split("/").slice(1);
11686
- 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.") };
11687
- 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("/");
11688
12438
  }
11689
12439
  function verifyDownloadedBytes(file, bytes) {
11690
12440
  if (bytes.byteLength !== file.size_bytes) return { error: downloadIntegrityError(file.path, "size mismatch") };
@@ -11704,60 +12454,18 @@ function downloadIntegrityError(path, reason) {
11704
12454
  recovery: { kind: "retry_later" }
11705
12455
  });
11706
12456
  }
11707
- function backupPathFor(root) {
11708
- return join(dirname(root), `.${basename(root)}.old-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
11709
- }
11710
- async function pathExists(path) {
11711
- return Boolean(await lstat(path).catch(() => null));
11712
- }
11713
12457
  function downloadFileSystemError(error) {
12458
+ if (error instanceof WriteBoundaryError || error instanceof DownloadManifestError) return error.error;
11714
12459
  return cliError({
11715
12460
  code: "download_failed",
11716
- message: "Could not write downloaded files.",
11717
- 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.",
11718
12463
  hint: "Check --output permissions and available disk space, then retry.",
11719
12464
  agentRecoverable: true,
11720
12465
  requiresHuman: false,
11721
12466
  recovery: { kind: "change_input" }
11722
12467
  });
11723
12468
  }
11724
- async function collectDirectoryFiles(root) {
11725
- const results = [];
11726
- async function visit(dir) {
11727
- for (const entry of await readdir(dir, { withFileTypes: true })) {
11728
- if (entry.name === "__MACOSX") continue;
11729
- const fullPath = join(dir, entry.name);
11730
- if (entry.isSymbolicLink()) throw new CollectDirectoryFilesError("Directory contains a symbolic link.", "Remove or replace symlinked files and directories before sharing.");
11731
- if (entry.isDirectory()) {
11732
- if (EXCLUDED_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
11733
- await visit(fullPath);
11734
- continue;
11735
- }
11736
- if (!entry.isFile() || IGNORED_FILENAMES.has(entry.name) || entry.name.startsWith(".")) continue;
11737
- const relativePath = relative(root, fullPath).split(sep).join("/");
11738
- results.push({
11739
- path: fullPath,
11740
- relativePath
11741
- });
11742
- }
11743
- }
11744
- await visit(root);
11745
- results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
11746
- return results;
11747
- }
11748
- var CollectDirectoryFilesError = class extends Error {
11749
- hint;
11750
- constructor(message, hint) {
11751
- super(message);
11752
- this.name = "CollectDirectoryFilesError";
11753
- this.hint = hint;
11754
- }
11755
- };
11756
- async function blobFor(path) {
11757
- const chunks = [];
11758
- for await (const chunk of createReadStream(path)) chunks.push(chunk);
11759
- return new Blob(chunks, { type: contentTypeFor(path) });
11760
- }
11761
12469
  function contentTypeFor(path) {
11762
12470
  if (path.endsWith(".html")) return "text/html";
11763
12471
  if (path.endsWith(".md")) return "text/markdown";
@@ -11774,6 +12482,14 @@ function artifactKindForFile(path) {
11774
12482
  }
11775
12483
  //#endregion
11776
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
+ };
11777
12493
  function fileDownloadError(error, path, notFound = false) {
11778
12494
  const message = `Could not download file "${path}".`;
11779
12495
  return {
@@ -11783,42 +12499,78 @@ function fileDownloadError(error, path, notFound = false) {
11783
12499
  hint: notFound ? `Retry the download. If it fails again, check file "${path}" in the artifact.` : `File "${path}": ${error.hint}`
11784
12500
  };
11785
12501
  }
11786
- 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;
11787
12514
  try {
11788
- const parsed = JSON.parse(await readFile(join(output, "index.json"), "utf8"));
11789
- if (!Array.isArray(parsed.artifacts)) return /* @__PURE__ */ new Map();
11790
- const previous = /* @__PURE__ */ new Map();
11791
- for (const entry of parsed.artifacts) {
11792
- if (entry === null || typeof entry !== "object") return /* @__PURE__ */ new Map();
11793
- const { id, version_id } = entry;
11794
- if (typeof id !== "string") return /* @__PURE__ */ new Map();
11795
- if (typeof version_id === "string") previous.set(id, version_id);
11796
- }
11797
- return previous;
12515
+ parsed = JSON.parse(text);
11798
12516
  } catch {
11799
12517
  return /* @__PURE__ */ new Map();
11800
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;
12527
+ }
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
+ }
11801
12550
  }
11802
- async function runDownload(parsed, mode, isRetry = false) {
12551
+ async function runDownloadInternal(parsed, mode, isRetry = false, boundary) {
11803
12552
  const command = "download";
11804
12553
  const projectId = parsed.options.projectId?.trim();
11805
12554
  if (projectId !== void 0 || parsed.positionals.length === 0) {
11806
- 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);
11807
- 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);
11808
12557
  }
11809
12558
  const target = parseArtifactTarget(parsed.positionals[0], "download", "Pass an artifact ID or share URL to download.");
11810
- if (target.error) return writeFailure(command, target.error, mode, 1);
12559
+ if (target.error) throw new DownloadFailure(target.error);
11811
12560
  const artifactId = target.artifactId;
12561
+ const input = parsed.positionals[0];
12562
+ if (!/^https?:\/\//i.test(input)) validateIds([{ id: input }]);
12563
+ validateIds([{ id: artifactId }]);
11812
12564
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
11813
12565
  if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11814
12566
  const request = await requestConfig(parsed.options);
11815
- if (request.error) return writeFailure(command, request.error, mode, 1);
12567
+ if (request.error) throw new DownloadFailure(request.error);
11816
12568
  const baseUrl = baseUrlOf(parsed.options);
11817
12569
  const manifestResponse = await cliFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/download`, baseUrl), {
11818
12570
  headers: { Authorization: `Bearer ${credential.token}` },
11819
12571
  ...request.init
11820
12572
  });
11821
- if ("networkError" in manifestResponse) return writeFailure(command, networkError(manifestResponse.networkError), mode, 1);
12573
+ if ("networkError" in manifestResponse) throw new DownloadFailure(networkError(manifestResponse.networkError));
11822
12574
  const body = await readJson(manifestResponse);
11823
12575
  if (!manifestResponse.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(manifestResponse.status, body, {
11824
12576
  authenticated: true,
@@ -11829,64 +12581,50 @@ async function runDownload(parsed, mode, isRetry = false) {
11829
12581
  profileCredentialKind: credential.profileCredentialKind,
11830
12582
  botProfile: credential.botProfile
11831
12583
  }), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11832
- if (!downloadManifestFields(body)) return writeFailure(command, serviceError("Download manifest succeeded but the response did not include file metadata."), mode, 1);
11833
- const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force));
11834
- if (plan.error) return writeFailure(command, plan.error, mode, 1);
11835
- let completed = false;
11836
- let backupRoot = null;
11837
- try {
11838
- for (const file of plan.value.files) {
11839
- const fileResponse = await cliFetch(downloadFileUrl(baseUrl, artifactId, file.path), {
11840
- headers: { Authorization: `Bearer ${credential.token}` },
11841
- ...request.init
11842
- });
11843
- if ("networkError" in fileResponse) return writeFailure(command, fileDownloadError(networkError(fileResponse.networkError), file.path), mode, 1);
11844
- if (!fileResponse.ok) {
11845
- const fileBody = await readJson(fileResponse);
11846
- const apiError = isRecord$1(fileBody) ? fileBody.error : void 0;
11847
- const notFound = fileResponse.status === 404 || apiError === "not-found" || isRecord$1(apiError) && apiError.code === "not-found";
11848
- return handleAuthenticatedCredentialFailure(command, fileDownloadError(mapApiError(fileResponse.status, fileBody, {
11849
- authenticated: true,
11850
- ...!notFound ? { artifactTarget: true } : {},
11851
- baseUrl,
11852
- credentialSource: credential.source,
11853
- profile: credential.profile,
11854
- profileCredentialKind: credential.profileCredentialKind,
11855
- botProfile: credential.botProfile
11856
- }), file.path, notFound), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11857
- }
11858
- let fileBody;
11859
- try {
11860
- fileBody = await fileResponse.arrayBuffer();
11861
- } catch (error) {
11862
- return writeFailure(command, fileDownloadError(networkError(error), file.path), mode, 1);
11863
- }
11864
- const bytes = Buffer.from(fileBody);
11865
- const verified = verifyDownloadedBytes(file, bytes);
11866
- if (verified.error) return writeFailure(command, verified.error, mode, 1);
11867
- await mkdir(dirname(file.targetPath), { recursive: true });
11868
- await writeFile(file.targetPath, bytes);
11869
- }
11870
- if (plan.value.replaceExisting) {
11871
- backupRoot = backupPathFor(plan.value.root);
11872
- await rename(plan.value.root, backupRoot);
11873
- }
11874
- await rename(plan.value.tempRoot, plan.value.root);
11875
- completed = true;
11876
- if (backupRoot) await rm(backupRoot, {
11877
- recursive: true,
11878
- force: true
11879
- }).catch(() => {});
11880
- } catch (error) {
11881
- if (backupRoot && !await pathExists(plan.value.root) && await pathExists(backupRoot)) await rename(backupRoot, plan.value.root).catch(() => {});
11882
- return writeFailure(command, downloadFileSystemError(error), mode, 1);
11883
- } finally {
11884
- if (!completed) await rm(plan.value.tempRoot, {
11885
- recursive: true,
11886
- force: true
11887
- }).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);
11888
12622
  }
12623
+ await boundary.replace(plan.value.tempRoot, plan.value.root);
12624
+ boundary.keep(plan.value.root);
12625
+ await boundary.finish();
11889
12626
  return writeSuccess(command, {
12627
+ backup_paths: boundary.backupPaths,
11890
12628
  artifact: {
11891
12629
  id: body.id,
11892
12630
  url: body.share_url,
@@ -11900,12 +12638,12 @@ async function runDownload(parsed, mode, isRetry = false) {
11900
12638
  }
11901
12639
  }, mode);
11902
12640
  }
11903
- async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12641
+ async function runProjectDownload(parsed, mode, projectId, isRetry = false, boundary) {
11904
12642
  const command = "download";
11905
12643
  const resolved = await resolveCredential(parsed.options, await resolveProjectConfig());
11906
12644
  if (!resolved.ok) return handleCredentialFailure(command, resolved, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11907
12645
  const request = await requestConfig(parsed.options);
11908
- if (request.error) return writeFailure(command, request.error, mode, 1);
12646
+ if (request.error) throw new DownloadFailure(request.error);
11909
12647
  const baseUrl = baseUrlOf(parsed.options);
11910
12648
  let credential = resolved;
11911
12649
  let refreshAttempted = false;
@@ -11938,7 +12676,7 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
11938
12676
  ...request.init
11939
12677
  });
11940
12678
  };
11941
- const output = parsed.options.output.trim();
12679
+ const output = resolve(parsed.options.output.trim());
11942
12680
  const list = async (cursor) => {
11943
12681
  const url = apiUrl("/api/cli/artifacts", baseUrl);
11944
12682
  url.searchParams.set("project_id", projectId);
@@ -11987,12 +12725,22 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
11987
12725
  first = false;
11988
12726
  cursor = page.data.has_more && page.data.next_cursor ? page.data.next_cursor : void 0;
11989
12727
  } while (cursor);
11990
- if (listError && first) return writeFailure(command, listError, mode, 1);
11991
- 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);
11992
- const previousVersions = await readPreviousVersions(output);
11993
- 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);
11994
12742
  const results = entries.map((item) => ({
11995
- id: String(item.id),
12743
+ id: item.id,
11996
12744
  title: String(item.title ?? ""),
11997
12745
  ...typeof item.owner_email === "string" ? { owner_email: item.owner_email } : {},
11998
12746
  updated_at: String(item.updated_at ?? ""),
@@ -12009,107 +12757,87 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12009
12757
  continue;
12010
12758
  }
12011
12759
  const root = join(output, result.id);
12012
- const rootStat = await lstat(root).catch(() => null);
12013
- const rootExists = rootStat !== null;
12014
- const response = await authFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(result.id)}/download`, baseUrl));
12015
- if ("networkError" in response) {
12016
- result.reason = "network failed";
12017
- continue;
12018
- }
12019
- if (!response.ok) {
12020
- const body = await readJson(response);
12021
- if (mapApiError(response.status, body, {
12022
- authenticated: true,
12023
- baseUrl,
12024
- artifactTarget: true
12025
- }).code === "unsupported_kind") {
12026
- result.status = "skipped";
12027
- result.reason = "unsupported-kind";
12028
- } else result.reason = `download failed (${response.status})`;
12029
- continue;
12030
- }
12031
- const body = await readJson(response);
12032
- if (!downloadManifestFields(body)) {
12033
- result.reason = "invalid download manifest";
12034
- continue;
12035
- }
12036
- if (!parsed.options.force && rootStat?.isDirectory() && previousVersions.get(result.id) === body.version_id) {
12037
- result.status = "unchanged";
12038
- result.version_id = body.version_id;
12039
- result.path = root;
12040
- delete result.reason;
12041
- continue;
12042
- }
12043
- if (rootExists && !parsed.options.force) {
12044
- result.reason = "artifact output already exists";
12045
- continue;
12046
- }
12047
- const plan = await prepareDownloadPlan(body, root, Boolean(parsed.options.force));
12048
- if (plan.error) {
12049
- result.reason = plan.error.message;
12050
- continue;
12051
- }
12052
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
+ }
12053
12798
  for (const file of plan.value.files) {
12054
12799
  const fileResponse = await authFetch(downloadFileUrl(baseUrl, result.id, file.path));
12055
- if ("networkError" in fileResponse) throw new Error(`Could not download file "${file.path}": network failed`);
12056
- 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})`);
12057
12802
  let fileBody;
12058
12803
  try {
12059
12804
  fileBody = await fileResponse.arrayBuffer();
12060
12805
  } catch {
12061
- 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`);
12062
12807
  }
12063
12808
  const bytes = Buffer.from(fileBody);
12064
12809
  const verified = verifyDownloadedBytes(file, bytes);
12065
- if (verified.error) throw new Error(verified.error.message);
12066
- await mkdir(dirname(file.targetPath), { recursive: true });
12067
- await writeFile(file.targetPath, bytes);
12810
+ if (verified.error) throw new DownloadFileError(verified.error.message);
12811
+ await boundary.write(file.targetPath, bytes);
12068
12812
  }
12069
- let backupRoot = null;
12070
- try {
12071
- if (plan.value.replaceExisting) {
12072
- backupRoot = backupPathFor(plan.value.root);
12073
- await rename(plan.value.root, backupRoot);
12074
- }
12075
- await rename(plan.value.tempRoot, plan.value.root);
12076
- } catch (error) {
12077
- if (backupRoot && !await pathExists(plan.value.root) && await pathExists(backupRoot)) await rename(backupRoot, plan.value.root).catch(() => {});
12078
- throw error;
12079
- }
12080
- if (backupRoot) await rm(backupRoot, {
12081
- recursive: true,
12082
- force: true
12083
- }).catch(() => {});
12813
+ await boundary.replace(plan.value.tempRoot, plan.value.root);
12814
+ boundary.keep(plan.value.root);
12084
12815
  result.status = "ok";
12085
12816
  result.version_id = body.version_id;
12086
12817
  result.path = root;
12087
12818
  delete result.reason;
12088
12819
  } catch (error) {
12089
- result.reason = error instanceof Error ? error.message : "download failed";
12090
- await rm(plan.value.tempRoot, {
12091
- recursive: true,
12092
- force: true
12093
- }).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";
12094
12823
  }
12095
12824
  }
12096
- try {
12097
- await writeFile(join(output, "index.json"), JSON.stringify({
12098
- project_id: projectId,
12099
- artifacts: results
12100
- }, null, 2) + "\n");
12101
- } catch (error) {
12102
- return writeFailure(command, downloadFileSystemError(error), mode, 1);
12103
- }
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"));
12104
12830
  const counts = {
12105
12831
  ok: results.filter((r) => r.status === "ok").length,
12106
12832
  unchanged: results.filter((r) => r.status === "unchanged").length,
12107
12833
  skipped: results.filter((r) => r.status === "skipped").length,
12108
12834
  failed: results.filter((r) => r.status === "failed").length
12109
12835
  };
12836
+ await boundary.finish();
12110
12837
  process.exitCode = counts.failed > 0 ? 1 : 0;
12111
12838
  return writeSuccess(command, {
12112
12839
  project_id: projectId,
12840
+ backup_paths: boundary.backupPaths,
12113
12841
  ...counts,
12114
12842
  failures: results.filter((r) => r.status === "failed").map((r) => ({
12115
12843
  id: r.id,
@@ -12220,66 +12948,57 @@ function parseEditData(body) {
12220
12948
  }
12221
12949
  //#endregion
12222
12950
  //#region src/git-exclude.ts
12223
- async function ensureGitExclude(cwd) {
12224
- const git = await findGitDir(cwd);
12225
- if (!git) return {
12226
- applied: false,
12227
- warning: null
12228
- };
12229
- const excludePath = join(git.gitDir, "info", "exclude");
12230
- 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;
12231
12956
  try {
12232
- const existing = await readFile(excludePath, "utf8").catch(() => "");
12233
- 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 {
12234
12980
  applied: false,
12235
12981
  warning: null
12236
12982
  };
12237
- await mkdir(dirname(excludePath), { recursive: true });
12238
- const prefix = existing.endsWith("\n") || existing.length === 0 ? "" : "\n";
12239
- 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();
12240
12988
  return {
12241
12989
  applied: true,
12242
12990
  warning: null
12243
12991
  };
12244
12992
  } catch {
12993
+ try {
12994
+ await boundary.cleanup();
12995
+ } catch {}
12245
12996
  return {
12246
12997
  applied: false,
12247
- warning: `Could not update ${excludePath}; keep ${PROJECT_CONFIG_LOCAL_PATH} out of version control manually.`
12248
- };
12249
- }
12250
- }
12251
- function excludeLines(text) {
12252
- return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
12253
- }
12254
- async function findGitDir(start) {
12255
- let current = resolve(start);
12256
- const root = resolve(current, "/");
12257
- while (true) {
12258
- const gitDir = await resolveGitDir(join(current, ".git"));
12259
- if (gitDir) return {
12260
- gitDir,
12261
- workTree: current
12998
+ warning: `Could not update ${excludePath}; add ${line} to the repository's Git excludes manually.`
12262
12999
  };
12263
- if (current === root) return null;
12264
- current = dirname(current);
12265
13000
  }
12266
13001
  }
12267
- async function resolveGitDir(gitPath) {
12268
- const info = await stat(gitPath).catch(() => null);
12269
- if (!info) return null;
12270
- if (info.isDirectory()) return gitPath;
12271
- if (!info.isFile()) return null;
12272
- const text = await readFile(gitPath, "utf8").catch(() => null);
12273
- if (!text) return null;
12274
- const gitDir = text.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
12275
- if (!gitDir) return null;
12276
- const resolvedGitDir = resolve(dirname(gitPath), gitDir);
12277
- const commonDir = await readFile(join(resolvedGitDir, "commondir"), "utf8").then((value) => value.trim()).catch(() => null);
12278
- return commonDir ? resolve(resolvedGitDir, commonDir) : resolvedGitDir;
12279
- }
12280
- function gitPattern(path) {
12281
- return path.split("\\").join("/");
12282
- }
12283
13002
  //#endregion
12284
13003
  //#region src/command-runners/init.ts
12285
13004
  function runInit(parsed, mode) {
@@ -12330,28 +13049,50 @@ function onboardingNextSteps(signedIn) {
12330
13049
  async function runInitConfig(parsed, mode, profile, projectId) {
12331
13050
  const command = "init";
12332
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);
12333
- const resolved = await resolveProjectConfig();
12334
- if (profile) {
12335
- if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
12336
- const globalConfig = await readGlobalConfig();
12337
- if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
12338
- }
12339
- const next = {
12340
- ...await readRawLocalProjectConfig() ?? {},
12341
- ...profile ? { default_profile: profile } : {},
12342
- ...projectId ? { default_project_id: projectId } : {}
12343
- };
13052
+ const boundary = new WriteBoundary();
12344
13053
  const path = projectConfigLocalPath();
12345
- await mkdir(dirname(path), { recursive: true });
12346
- await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
12347
- const gitExclude = await ensureGitExclude(process.cwd());
12348
- const data = configData(next, resolved);
12349
- delete data.read_path;
12350
- if (gitExclude.warning) data.git_exclude_warning = gitExclude.warning;
12351
- if (gitExclude.applied) data.git_exclude_applied = true;
12352
- 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
+ }
12353
13094
  }
12354
- function configData(config, resolved) {
13095
+ function configData(config) {
12355
13096
  return {
12356
13097
  mode: "config",
12357
13098
  path: PROJECT_CONFIG_LOCAL_PATH,
@@ -12359,8 +13100,7 @@ function configData(config, resolved) {
12359
13100
  config: {
12360
13101
  default_profile: configString(config.default_profile),
12361
13102
  default_project_id: configString(config.default_project_id)
12362
- },
12363
- ...resolved.path ? { read_path: resolved.path } : {}
13103
+ }
12364
13104
  };
12365
13105
  }
12366
13106
  //#endregion
@@ -12662,7 +13402,7 @@ async function importBotTokenProfile(command, profile, token, parsed, mode) {
12662
13402
  //#endregion
12663
13403
  //#region src/command-runners/share.ts
12664
13404
  const MAX_SHARE_KEY_LENGTH = 128;
12665
- async function runShare(parsed, mode, isRetry = false) {
13405
+ async function runShare(parsed, mode, isRetry = false, prepared) {
12666
13406
  const command = "share";
12667
13407
  const targetPath = parsed.positionals[0];
12668
13408
  if (!targetPath) return writeFailure(command, validationError("Path is required.", "Pass a file or directory to share."), mode, 1);
@@ -12672,9 +13412,13 @@ async function runShare(parsed, mode, isRetry = false) {
12672
13412
  shareKey = (typeof parsed.options.key === "string" ? parsed.options.key : "").trim();
12673
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);
12674
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);
12675
13419
  const project = await resolveProjectConfig();
12676
13420
  const credential = await resolveCredential(parsed.options, project);
12677
- 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);
12678
13422
  const baseUrl = baseUrlOf(parsed.options);
12679
13423
  const hasProjectFlag = "project" in parsed.options;
12680
13424
  let destinationOptions = parsed.options;
@@ -12682,14 +13426,10 @@ async function runShare(parsed, mode, isRetry = false) {
12682
13426
  if (hasProjectFlag) {
12683
13427
  projectName = nonEmpty(typeof parsed.options.project === "string" ? parsed.options.project : "");
12684
13428
  if (!projectName) return writeFailure(command, validationError("--project requires a value.", "Pass --project <name> and retry."), mode, 1);
12685
- const conflict = destinationConflictError(parsed.options);
12686
- if (conflict) return writeFailure(command, conflict, mode, 1);
12687
13429
  } else {
12688
13430
  const earlyDestination = resolveDestination(parsed.options, project.config);
12689
13431
  if (earlyDestination.error) return writeFailure(command, earlyDestination.error, mode, 1);
12690
13432
  }
12691
- const fileStat = await stat(targetPath).catch(() => null);
12692
- if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
12693
13433
  const request = await requestConfig(parsed.options);
12694
13434
  if (request.error) return writeFailure(command, request.error, mode, 1);
12695
13435
  if (hasProjectFlag && projectName) {
@@ -12701,7 +13441,7 @@ async function runShare(parsed, mode, isRetry = false) {
12701
13441
  profileCredentialKind: credential.profileCredentialKind,
12702
13442
  botProfile: credential.botProfile
12703
13443
  });
12704
- 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);
12705
13445
  const { project: _project, ...rest } = parsed.options;
12706
13446
  destinationOptions = {
12707
13447
  ...rest,
@@ -12711,6 +13451,7 @@ async function runShare(parsed, mode, isRetry = false) {
12711
13451
  const destination = resolveDestination(destinationOptions, project.config);
12712
13452
  if (destination.error) return writeFailure(command, destination.error, mode, 1);
12713
13453
  const initialForm = await createUploadForm();
13454
+ for (const [name, value] of upload.payload.form) initialForm.append(name, value);
12714
13455
  const grantEmails = arrayOption(parsed.options.grantEmail);
12715
13456
  const defaultVisibility = parsed.options.visibility || destination.containerId ? null : await resolveDefaultVisibility("home_audience", await resolveSharedProjectConfig());
12716
13457
  if (defaultVisibility && "error" in defaultVisibility) return writeFailure(command, defaultVisibility.error, mode, 1);
@@ -12724,8 +13465,6 @@ async function runShare(parsed, mode, isRetry = false) {
12724
13465
  const uploadQuery = {};
12725
13466
  if (shareKey !== null) uploadQuery.publish_key = shareKey;
12726
13467
  if (parsed.options.expectedVersion) uploadQuery.expected_version = parsed.options.expectedVersion;
12727
- const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
12728
- if (upload.error) return writeFailure(command, upload.error, mode, 1);
12729
13468
  if (upload.payload.kind === "static_site") {
12730
13469
  uploadQuery.artifact_kind = "static_site";
12731
13470
  if (destination.containerId) uploadQuery.container_id = destination.containerId;
@@ -12735,7 +13474,7 @@ async function runShare(parsed, mode, isRetry = false) {
12735
13474
  const uploaded = await postShareUpload({
12736
13475
  uploadUrl,
12737
13476
  token: credential.token,
12738
- form: upload.payload.form,
13477
+ form: initialForm,
12739
13478
  requestInit: request.init,
12740
13479
  errorOptions: {
12741
13480
  authenticated: true,
@@ -12752,7 +13491,7 @@ async function runShare(parsed, mode, isRetry = false) {
12752
13491
  }, baseUrl, upload.payload.kind);
12753
13492
  if ("error" in uploaded) {
12754
13493
  if (uploaded.error.code === "network_failed") return writeFailure(command, uploaded.error, mode, 1);
12755
- 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);
12756
13495
  }
12757
13496
  const { id, url, versionId, artifactKind, visibility, linkExpiresAt, created, warnings } = uploaded.body;
12758
13497
  return writeSuccess(command, {
@@ -12827,7 +13566,7 @@ async function runResolve(parsed, mode) {
12827
13566
  }
12828
13567
  //#endregion
12829
13568
  //#region src/command-runners/update.ts
12830
- async function runUpdate(parsed, mode, isRetry = false) {
13569
+ async function runUpdate(parsed, mode, isRetry = false, prepared) {
12831
13570
  const command = "update";
12832
13571
  const artifactInput = parsed.positionals[0];
12833
13572
  const targetPath = parsed.positionals[1];
@@ -12839,15 +13578,13 @@ async function runUpdate(parsed, mode, isRetry = false) {
12839
13578
  if (!artifactId) return writeFailure(command, targetResolutionError(artifactInput, "update"), mode, 1);
12840
13579
  const label = VersionLabelInputSchema.optional().safeParse(parsed.options.label);
12841
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);
12842
13583
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
12843
- if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
12844
- const fileStat = await stat(targetPath).catch(() => null);
12845
- 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);
12846
13585
  const baseUrl = baseUrlOf(parsed.options);
12847
13586
  const request = await requestConfig(parsed.options);
12848
13587
  if (request.error) return writeFailure(command, request.error, mode, 1);
12849
- const upload = await prepareUploadPayload(targetPath, fileStat);
12850
- if (upload.error) return writeFailure(command, upload.error, mode, 1);
12851
13588
  const updateQuery = label.data !== void 0 ? { label: label.data } : {};
12852
13589
  if (upload.payload.kind === "static_site") updateQuery.artifact_kind = "static_site";
12853
13590
  if (parsed.options.expectedVersion) updateQuery.expected_version = parsed.options.expectedVersion;
@@ -12870,7 +13607,7 @@ async function runUpdate(parsed, mode, isRetry = false) {
12870
13607
  profile: credential.profile,
12871
13608
  profileCredentialKind: credential.profileCredentialKind,
12872
13609
  botProfile: credential.botProfile
12873
- }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
13610
+ }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true, upload), isRetry);
12874
13611
  const responseBody = isContract(ARTIFACT_VERSION_UPDATE_RESPONSE_SCHEMA, body) ? body : null;
12875
13612
  const id = responseBody?.id ?? artifactId;
12876
13613
  const result = {
@@ -12891,7 +13628,7 @@ async function runUpdate(parsed, mode, isRetry = false) {
12891
13628
  }
12892
13629
  //#endregion
12893
13630
  //#region src/command-runners/append.ts
12894
- async function runAppend(parsed, mode, isRetry = false) {
13631
+ async function runAppend(parsed, mode, isRetry = false, preparedContent) {
12895
13632
  const command = "append";
12896
13633
  const input = parsed.positionals[0];
12897
13634
  const path = parsed.positionals[1];
@@ -12899,17 +13636,30 @@ async function runAppend(parsed, mode, isRetry = false) {
12899
13636
  if (!path) return writeFailure(command, validationError("Path is required.", "Pass a non-empty UTF-8 file."), mode, 1);
12900
13637
  const id = resolveArtifactId(input);
12901
13638
  if (!id) return writeFailure(command, targetResolutionError(input, "append"), mode, 1);
12902
- const s = await stat(path).catch(() => null);
12903
- 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);
12904
- const bytes = await readFile(path);
12905
- let content;
12906
- try {
12907
- content = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
12908
- } catch {
12909
- 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
+ }
12910
13660
  }
12911
13661
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
12912
- 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);
12913
13663
  const request = await requestConfig(parsed.options);
12914
13664
  if (request.error) return writeFailure(command, request.error, mode, 1);
12915
13665
  const response = await cliFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(id)}/append`, baseUrlOf(parsed.options)), {
@@ -12932,7 +13682,7 @@ async function runAppend(parsed, mode, isRetry = false) {
12932
13682
  profile: credential.profile,
12933
13683
  profileCredentialKind: credential.profileCredentialKind,
12934
13684
  botProfile: credential.botProfile
12935
- }), credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
13685
+ }), credential, parsed.options, mode, () => runAppend(parsed, mode, true, content), isRetry);
12936
13686
  const responseBody = isContract(ARTIFACT_APPEND_RESPONSE_SCHEMA, body) ? body : null;
12937
13687
  const success = {
12938
13688
  artifact: {
@@ -13701,7 +14451,15 @@ Common failures:
13701
14451
  auth_required Set ARTIFACTSHARE_TOKEN before share
13702
14452
  self_upload_disabled Sign in with Google or Microsoft to upload your own files
13703
14453
  file_too_large Reduce file or directory size and retry
14454
+ upload_read_failed Check filesystem availability and permissions, then retry
13704
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
13705
14463
  key_target_moved The artifact for --key moved; update it by ID or use a new key
13706
14464
  key_kind_mismatch The artifact for --key is a different kind; use a new key`
13707
14465
  });
@@ -13718,7 +14476,7 @@ const updateDefinition = define({
13718
14476
  artifactIdOrUrl: {
13719
14477
  type: "positional",
13720
14478
  toKebab: true,
13721
- 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"
13722
14480
  },
13723
14481
  path: {
13724
14482
  type: "positional",
@@ -13735,7 +14493,7 @@ const updateDefinition = define({
13735
14493
  }
13736
14494
  },
13737
14495
  examples: `Target:
13738
- 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.
13739
14497
  Titles and project names are not updated directly; resolve them to an ID first.
13740
14498
 
13741
14499
  Access:
@@ -13756,7 +14514,15 @@ Common failures:
13756
14514
  artifact_kind_mismatch Use a file for single-file artifacts or a directory for static sites
13757
14515
  self_upload_disabled Sign in with Google or Microsoft to upload your own files
13758
14516
  file_too_large Reduce file or directory size and retry
13759
- 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`
13760
14526
  });
13761
14527
  const appendDefinition = define({
13762
14528
  name: "append",
@@ -13774,7 +14540,18 @@ const appendDefinition = define({
13774
14540
  description: "Non-empty UTF-8 file to append"
13775
14541
  }
13776
14542
  },
13777
- 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`
13778
14555
  });
13779
14556
  const editDefinition = define({
13780
14557
  name: "edit",
@@ -13785,7 +14562,7 @@ const editDefinition = define({
13785
14562
  artifactIdOrUrl: {
13786
14563
  type: "positional",
13787
14564
  toKebab: true,
13788
- 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"
13789
14566
  },
13790
14567
  title: {
13791
14568
  type: "string",
@@ -13805,7 +14582,7 @@ const editDefinition = define({
13805
14582
  retainVersions: {
13806
14583
  type: "string",
13807
14584
  toKebab: true,
13808
- description: "Keep the latest N versions; use all to clear retention (owner only)"
14585
+ description: "N or all (owner only). Keeps the latest N versions; publisher-managed artifacts count only publisher versions and keep all versions people added. Older eligible versions are permanently deleted; all clears the limit."
13809
14586
  },
13810
14587
  noLinkExpiry: {
13811
14588
  type: "boolean",
@@ -13863,7 +14640,7 @@ const deleteDefinition = define({
13863
14640
  artifactIdOrUrl: {
13864
14641
  type: "positional",
13865
14642
  toKebab: true,
13866
- 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"
13867
14644
  }
13868
14645
  },
13869
14646
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare delete abc123def4 --json
@@ -13909,7 +14686,7 @@ const downloadDefinition = define({
13909
14686
  type: "positional",
13910
14687
  toKebab: true,
13911
14688
  required: false,
13912
- 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"
13913
14690
  },
13914
14691
  projectId: {
13915
14692
  type: "string",
@@ -13924,7 +14701,7 @@ const downloadDefinition = define({
13924
14701
  force: {
13925
14702
  type: "boolean",
13926
14703
  toKebab: true,
13927
- description: "Allow writing into an existing output directory"
14704
+ description: "Replace existing output; retain backups for recovery"
13928
14705
  }
13929
14706
  },
13930
14707
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare download abc123def4 --json
@@ -13933,12 +14710,20 @@ const downloadDefinition = define({
13933
14710
 
13934
14711
  Use resolve first when a user gives a title or project name, then pass the id here.
13935
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.
13936
14721
 
13937
14722
  Common failures:
13938
14723
  auth_required Set ARTIFACTSHARE_TOKEN before download
13939
14724
  target_not_found Retry with an artifact ID, share URL, or sandbox URL
13940
14725
  output_exists Choose another --output path or pass --force
13941
- validation_failed Check --output and downloaded file paths`
14726
+ validation_failed Check the named ID/path; use a regular directory without links`
13942
14727
  });
13943
14728
  const openDefinition = define({
13944
14729
  name: "open",
@@ -13949,7 +14734,7 @@ const openDefinition = define({
13949
14734
  artifactIdOrUrl: {
13950
14735
  type: "positional",
13951
14736
  toKebab: true,
13952
- 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"
13953
14738
  }
13954
14739
  },
13955
14740
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare open https://artifactshare.com/a/abc123def4 --json
@@ -13978,7 +14763,7 @@ const moveDefinition = define({
13978
14763
  artifactIdOrUrl: {
13979
14764
  type: "positional",
13980
14765
  toKebab: true,
13981
- 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"
13982
14767
  },
13983
14768
  projectId: {
13984
14769
  type: "string",
@@ -14013,7 +14798,7 @@ const artifactsGetDefinition = define({
14013
14798
  artifactIdOrUrl: {
14014
14799
  type: "positional",
14015
14800
  toKebab: true,
14016
- 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"
14017
14802
  },
14018
14803
  offset: {
14019
14804
  type: "string",
@@ -14105,16 +14890,38 @@ const commentsListDefinition = define({
14105
14890
  toKebab: true,
14106
14891
  args: {
14107
14892
  ...commonArgs,
14893
+ threadId: {
14894
+ type: "string",
14895
+ toKebab: true,
14896
+ description: "Read one thread, including threads outside the panel"
14897
+ },
14898
+ before: {
14899
+ type: "string",
14900
+ description: "Read older replies using older_cursor; requires --thread-id"
14901
+ },
14902
+ limit: {
14903
+ type: "string",
14904
+ description: "Replies per page (1–50, default 50); requires --before or --around-message-id"
14905
+ },
14906
+ aroundMessageId: {
14907
+ type: "string",
14908
+ toKebab: true,
14909
+ description: "Read a bounded page containing this message; requires --thread-id"
14910
+ },
14108
14911
  artifactIdOrUrl: {
14109
14912
  type: "positional",
14110
14913
  toKebab: true,
14111
- 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"
14112
14915
  }
14113
14916
  },
14114
14917
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare comments list abc123def4 --json
14115
14918
 
14116
14919
  Returns up to 50 threads (open threads first); has_more reports whether more exist.
14117
- Each thread carries its messages, status, and quoted-text anchor when present.
14920
+ Each thread carries its first message and latest three replies, message_count,
14921
+ reply_count, older_cursor, status, and quoted-text anchor when present.
14922
+ Read older replies with --thread-id <id> --before <older_cursor> --limit 50.
14923
+ Repeat with the returned older_cursor until null. --around-message-id <id>
14924
+ loads a target-containing page; do not combine it with --before.
14118
14925
 
14119
14926
  Common failures:
14120
14927
  auth_required Set ARTIFACTSHARE_TOKEN before comments list
@@ -14129,7 +14936,7 @@ const commentsPostDefinition = define({
14129
14936
  artifactIdOrUrl: {
14130
14937
  type: "positional",
14131
14938
  toKebab: true,
14132
- 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"
14133
14940
  },
14134
14941
  body: {
14135
14942
  type: "string",
@@ -14182,7 +14989,7 @@ const commentThreadActionArgs = {
14182
14989
  artifactIdOrUrl: {
14183
14990
  type: "positional",
14184
14991
  toKebab: true,
14185
- 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"
14186
14993
  },
14187
14994
  threadId: {
14188
14995
  type: "string",
@@ -14195,7 +15002,7 @@ const commentMessageActionArgs = {
14195
15002
  artifactIdOrUrl: {
14196
15003
  type: "positional",
14197
15004
  toKebab: true,
14198
- 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"
14199
15006
  },
14200
15007
  messageId: {
14201
15008
  type: "string",
@@ -14648,7 +15455,11 @@ const projectsListDefinition = define({
14648
15455
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare projects list --json
14649
15456
 
14650
15457
  is_default marks the working-directory default project from .artifactshare/config.json.
14651
- 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.`
14652
15463
  });
14653
15464
  const projectsCreateDefinition = define({
14654
15465
  name: "create",
@@ -14919,6 +15730,9 @@ and Cursor skills. Cursor project scope is not auto-installed; use skills instal
14919
15730
  data.mode is "onboarding".
14920
15731
  With --profile or --project-id, init saves working-directory defaults to
14921
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.
14922
15736
 
14923
15737
  Common failures:
14924
15738
  skill_update_conflict An unmanaged or broken skill file exists; inspect it before overwriting