@artifactshare/cli 0.1.1 → 0.1.3

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
@@ -1,14 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
2
+ import { appendFile, chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
3
3
  import { cli, define, lazy } from "gunshi";
4
- import { Agent } from "undici";
5
4
  import { spawn } from "node:child_process";
6
5
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
6
  import { createReadStream } from "node:fs";
8
7
  import { createHash } from "node:crypto";
9
8
  import { setTimeout } from "node:timers/promises";
10
9
  import { homedir } from "node:os";
10
+ //#region src/constants.ts
11
+ const DEFAULT_BASE_URL = "https://artifactshare.com";
11
12
  const DEVICE_CLIENT_ID = "artifactshare-cli";
13
+ const CLI_INVOCATION = "npx --yes @artifactshare/cli";
14
+ const TOKEN_ENV_VAR = "ARTIFACTSHARE_TOKEN";
15
+ const TOKEN_OPTION = "--token";
12
16
  const IGNORED_FILENAMES = new Set([
13
17
  ".DS_Store",
14
18
  "Thumbs.db",
@@ -69,7 +73,11 @@ const COMMAND_NAMES = new Set([
69
73
  const SUBCOMMANDS = {
70
74
  artifacts: ["get"],
71
75
  comments: ["list", "post"],
72
- profiles: ["list", "use"],
76
+ profiles: [
77
+ "list",
78
+ "use",
79
+ "import-token"
80
+ ],
73
81
  projects: ["list"],
74
82
  skills: [
75
83
  "install",
@@ -79,6 +87,7 @@ const SUBCOMMANDS = {
79
87
  ]
80
88
  };
81
89
  const UPDATE_OPTION_KEYS = new Set([
90
+ "allowPlaintextTokenStore",
82
91
  "baseUrl",
83
92
  "help",
84
93
  "insecureLocalhost",
@@ -88,8 +97,8 @@ const UPDATE_OPTION_KEYS = new Set([
88
97
  ]);
89
98
  //#endregion
90
99
  //#region src/errors.ts
91
- const REQUEST_ACCESS_COMMAND$1 = "npx @artifactshare/cli request-access --json";
92
- const PROJECTS_LIST_COMMAND = "npx @artifactshare/cli projects list --json";
100
+ const REQUEST_ACCESS_COMMAND$1 = `${CLI_INVOCATION} request-access --json`;
101
+ const PROJECTS_LIST_COMMAND = `${CLI_INVOCATION} projects list --json`;
93
102
  function apiError(body) {
94
103
  const error = body?.error;
95
104
  if (typeof error === "string") return {
@@ -103,7 +112,7 @@ function apiError(body) {
103
112
  }
104
113
  function mapApiError(status, body, options = {}) {
105
114
  const { code: apiCode, message: apiMessage } = apiError(body);
106
- if (status === 401) return options.authenticated ? tokenInvalidError() : authRequiredError();
115
+ if (status === 401) return options.authenticated ? tokenInvalidError() : authRequiredError(options.baseUrl ?? "https://artifactshare.com");
107
116
  if (apiCode === "upload-not-allowed") return cliError({
108
117
  code: "upload_not_allowed",
109
118
  message: "This account cannot publish yet.",
@@ -178,7 +187,7 @@ function mapApiError(status, body, options = {}) {
178
187
  code: "thread_not_found",
179
188
  message: apiMessage ?? "Comment thread was not found.",
180
189
  why: "No comment thread with that ID exists on this artifact.",
181
- hint: "Run npx @artifactshare/cli comments list <artifact-id> --json and retry with a listed thread id.",
190
+ hint: `Run ${CLI_INVOCATION} comments list <artifact-id> --json and retry with a listed thread id.`,
182
191
  agentRecoverable: true,
183
192
  requiresHuman: false,
184
193
  recovery: { kind: "change_input" }
@@ -205,7 +214,7 @@ function mapApiError(status, body, options = {}) {
205
214
  code: "quote_not_found",
206
215
  message: apiMessage ?? "The quoted text was not found in the artifact.",
207
216
  why: "The --quote value must match the artifact text exactly.",
208
- hint: "Copy the exact text from npx @artifactshare/cli artifacts get <artifact-id>, or add --quote-before / --quote-after to pick the right occurrence.",
217
+ hint: `Copy the exact text from ${CLI_INVOCATION} artifacts get <artifact-id>, or add --quote-before / --quote-after to pick the right occurrence.`,
209
218
  agentRecoverable: true,
210
219
  requiresHuman: false,
211
220
  recovery: { kind: "change_input" }
@@ -338,15 +347,58 @@ function serviceError(message) {
338
347
  recovery: { kind: "retry_later" }
339
348
  });
340
349
  }
341
- function authRequiredError() {
350
+ function tokensUrl(baseUrl) {
351
+ return `${baseUrl.replace(/\/$/, "")}/settings/tokens`;
352
+ }
353
+ function authRecoveryDetails(baseUrl, loginCommand = `${CLI_INVOCATION} login --profile default`) {
354
+ return {
355
+ token_url: tokensUrl(baseUrl),
356
+ env_var: TOKEN_ENV_VAR,
357
+ login_command: loginCommand,
358
+ token_option: TOKEN_OPTION
359
+ };
360
+ }
361
+ function authRequiredError(baseUrl) {
362
+ const url = tokensUrl(baseUrl);
342
363
  return cliError({
343
364
  code: "auth_required",
344
365
  message: "Login is required.",
345
- why: "No ARTIFACTSHARE_TOKEN or --token value was provided.",
346
- hint: "Run npx @artifactshare/cli login --profile default, or set ARTIFACTSHARE_TOKEN.",
366
+ why: `No ${TOKEN_ENV_VAR} or ${TOKEN_OPTION} value was provided.`,
367
+ hint: `In an interactive terminal, run ${CLI_INVOCATION} login --profile default. In agents or CI, issue a token at ${url}, then set ${TOKEN_ENV_VAR} or pass ${TOKEN_OPTION}.`,
347
368
  agentRecoverable: false,
348
369
  requiresHuman: true,
349
- recovery: { kind: "ask_human" }
370
+ recovery: { kind: "ask_human" },
371
+ details: authRecoveryDetails(baseUrl)
372
+ });
373
+ }
374
+ function deviceAuthErrorDetails(pending) {
375
+ const openUrl = pending.verification_uri_complete ?? pending.verification_uri;
376
+ return {
377
+ profile: pending.profile,
378
+ verification_uri: pending.verification_uri,
379
+ verification_uri_complete: pending.verification_uri_complete,
380
+ user_code: pending.user_code,
381
+ expires_at: pending.expires_at,
382
+ interval_seconds: pending.interval_seconds,
383
+ instruction: `Open ${openUrl} and enter code ${pending.user_code} to sign in.`,
384
+ retry_hint: "After approval in the browser, rerun the same command to continue."
385
+ };
386
+ }
387
+ function authRequiredWithDeviceAuthError(baseUrl, pending) {
388
+ const device = deviceAuthErrorDetails(pending);
389
+ const openUrl = pending.verification_uri_complete ?? pending.verification_uri;
390
+ return cliError({
391
+ code: "auth_required",
392
+ message: "Login is required.",
393
+ why: `No ${TOKEN_ENV_VAR} or ${TOKEN_OPTION} value was provided.`,
394
+ hint: `Open ${openUrl} and enter code ${pending.user_code}. ${device.retry_hint}`,
395
+ agentRecoverable: false,
396
+ requiresHuman: true,
397
+ recovery: { kind: "ask_human" },
398
+ details: {
399
+ ...authRecoveryDetails(baseUrl, `${CLI_INVOCATION} login --profile ${pending.profile}`),
400
+ ...device
401
+ }
350
402
  });
351
403
  }
352
404
  function tokenInvalidError() {
@@ -354,7 +406,7 @@ function tokenInvalidError() {
354
406
  code: "token_invalid",
355
407
  message: "The bearer token is invalid or expired.",
356
408
  why: "Artifact Share rejected the Authorization bearer token.",
357
- hint: "Refresh ARTIFACTSHARE_TOKEN or sign in again, then retry.",
409
+ hint: `Refresh ${TOKEN_ENV_VAR} or sign in again, then retry.`,
358
410
  agentRecoverable: false,
359
411
  requiresHuman: true,
360
412
  recovery: { kind: "ask_human" }
@@ -365,13 +417,13 @@ function authDeniedError(profile) {
365
417
  code: "auth_denied",
366
418
  message: "Login was denied.",
367
419
  why: "The device login request was denied in the browser.",
368
- hint: `Run npx @artifactshare/cli login --profile ${profile} again if you want to sign in.`,
420
+ hint: `Run ${CLI_INVOCATION} login --profile ${profile} again if you want to sign in.`,
369
421
  agentRecoverable: false,
370
422
  requiresHuman: true,
371
423
  recovery: { kind: "ask_human" },
372
424
  details: {
373
425
  profile,
374
- suggested_command: `npx @artifactshare/cli login --profile ${profile}`
426
+ suggested_command: `${CLI_INVOCATION} login --profile ${profile}`
375
427
  }
376
428
  });
377
429
  }
@@ -380,22 +432,22 @@ function authExpiredError(profile) {
380
432
  code: "auth_expired",
381
433
  message: "Login expired.",
382
434
  why: "The device login was not completed before the code expired.",
383
- hint: `Run npx @artifactshare/cli login --profile ${profile} again.`,
435
+ hint: `Run ${CLI_INVOCATION} login --profile ${profile} again.`,
384
436
  agentRecoverable: false,
385
437
  requiresHuman: true,
386
438
  recovery: { kind: "ask_human" },
387
439
  details: {
388
440
  profile,
389
- suggested_command: `npx @artifactshare/cli login --profile ${profile}`
441
+ suggested_command: `${CLI_INVOCATION} login --profile ${profile}`
390
442
  }
391
443
  });
392
444
  }
393
445
  function authAccountMismatchError(profile, expectedEmail, actualEmail) {
394
446
  return cliError({
395
447
  code: "auth_account_mismatch",
396
- message: "Login used a different account than this profile expects.",
397
- why: `Profile "${profile}" is already associated with ${expectedEmail}, but the browser approved ${actualEmail}.`,
398
- hint: "Choose the expected Google account in the browser, or use another --profile name.",
448
+ message: "The credential uses a different account than this profile expects.",
449
+ why: `Profile "${profile}" is already associated with ${expectedEmail}, but the credential identifies ${actualEmail ?? "an unknown account"}.`,
450
+ hint: "Use a credential for the expected account, or use another --profile name.",
399
451
  agentRecoverable: false,
400
452
  requiresHuman: true,
401
453
  recovery: { kind: "ask_human" },
@@ -411,7 +463,7 @@ function profileNotFoundError(profile) {
411
463
  code: "profile_not_found",
412
464
  message: `Profile "${profile}" was not found.`,
413
465
  why: "No saved CLI profile has that name.",
414
- hint: `Run npx @artifactshare/cli profiles list to see saved profiles, or npx @artifactshare/cli login --profile ${profile} to create it.`,
466
+ hint: `Run ${CLI_INVOCATION} profiles list to see saved profiles, or ${CLI_INVOCATION} login --profile ${profile} to create it.`,
415
467
  agentRecoverable: true,
416
468
  requiresHuman: false,
417
469
  recovery: { kind: "change_input" },
@@ -447,12 +499,12 @@ function unknownCommandError(command) {
447
499
  code: "unknown_command",
448
500
  message: `Unknown command: ${command}`,
449
501
  why: "The command is not part of Artifact Share CLI.",
450
- hint: "Run npx @artifactshare/cli --help.",
502
+ hint: `Run ${CLI_INVOCATION} --help.`,
451
503
  agentRecoverable: true,
452
504
  requiresHuman: false,
453
505
  recovery: {
454
506
  kind: "run_command",
455
- command: "npx @artifactshare/cli --help"
507
+ command: `${CLI_INVOCATION} --help`
456
508
  }
457
509
  });
458
510
  }
@@ -855,11 +907,12 @@ let insecureLocalhostDispatcher;
855
907
  function baseUrlOf(options) {
856
908
  return String(options.baseUrl ?? process.env.ARTIFACTSHARE_BASE_URL ?? "https://artifactshare.com").replace(/\/$/, "");
857
909
  }
858
- function requestConfig(options) {
910
+ async function requestConfig(options) {
859
911
  if (!insecureLocalhostEnabled(options)) return { init: {} };
860
912
  const baseUrl = baseUrlOf(options);
861
913
  const url = new URL(baseUrl);
862
914
  if (url.protocol !== "https:" || !isLocalHostname(url.hostname)) return { error: validationError("--insecure-localhost only works with local HTTPS base URLs.", "Use it only with https://localhost, https://127.0.0.1, or https://[::1].") };
915
+ const { Agent } = await import("undici");
863
916
  return { init: { dispatcher: insecureLocalhostDispatcher ??= new Agent({ connect: { rejectUnauthorized: false } }) } };
864
917
  }
865
918
  function insecureLocalhostEnabled(options) {
@@ -969,21 +1022,60 @@ function resolveDestination(options, config) {
969
1022
  code: "destination_required",
970
1023
  message: "A publish destination is required.",
971
1024
  why: "Non-interactive publish never guesses a project or home destination.",
972
- hint: "Retry with --project-id <id>, configure .artifactshare/config.json, or pass --home.",
1025
+ hint: "Retry with --project-id <id>, configure .artifactshare/config.local.json, or pass --home.",
973
1026
  agentRecoverable: true,
974
1027
  requiresHuman: false,
975
1028
  recovery: { kind: "change_input" }
976
1029
  }) };
977
1030
  }
978
1031
  const PROJECT_CONFIG_PATH = ".artifactshare/config.json";
979
- function projectConfigPath() {
980
- return resolve(process.cwd(), PROJECT_CONFIG_PATH);
1032
+ const PROJECT_CONFIG_LOCAL_PATH = ".artifactshare/config.local.json";
1033
+ function projectConfigLocalPath(cwd = process.cwd()) {
1034
+ return resolve(cwd, PROJECT_CONFIG_LOCAL_PATH);
1035
+ }
1036
+ function relativeProjectConfigPath(cwd, directory, filename) {
1037
+ const absolute = join(directory, filename);
1038
+ const rel = relative(cwd, absolute);
1039
+ return rel.startsWith("..") ? absolute : rel;
1040
+ }
1041
+ async function resolveProjectConfig(cwd = process.cwd()) {
1042
+ let current = resolve(cwd);
1043
+ const root = resolve(current, "/");
1044
+ while (true) {
1045
+ const localPath = join(current, PROJECT_CONFIG_LOCAL_PATH);
1046
+ const sharedPath = join(current, PROJECT_CONFIG_PATH);
1047
+ const localRaw = await readJsonFile(localPath);
1048
+ if (localRaw !== null) return {
1049
+ config: localRaw,
1050
+ raw: localRaw,
1051
+ kind: "local",
1052
+ path: relativeProjectConfigPath(cwd, current, PROJECT_CONFIG_LOCAL_PATH),
1053
+ directory: current
1054
+ };
1055
+ const sharedRaw = await readJsonFile(sharedPath);
1056
+ if (sharedRaw !== null) return {
1057
+ config: sharedRaw,
1058
+ raw: sharedRaw,
1059
+ kind: "shared",
1060
+ path: relativeProjectConfigPath(cwd, current, PROJECT_CONFIG_PATH),
1061
+ directory: current
1062
+ };
1063
+ if (current === root) break;
1064
+ current = dirname(current);
1065
+ }
1066
+ return {
1067
+ config: null,
1068
+ raw: null,
1069
+ kind: null,
1070
+ path: null,
1071
+ directory: null
1072
+ };
981
1073
  }
982
- async function readProjectConfig() {
983
- return await readJsonFile(projectConfigPath());
1074
+ async function readProjectConfigAtDirectory(directory, kind) {
1075
+ return await readJsonFile(join(directory, kind === "local" ? PROJECT_CONFIG_LOCAL_PATH : PROJECT_CONFIG_PATH));
984
1076
  }
985
- async function readRawProjectConfig() {
986
- return await readJsonFile(projectConfigPath());
1077
+ async function readRawLocalProjectConfig(cwd = process.cwd()) {
1078
+ return await readJsonFile(projectConfigLocalPath(cwd));
987
1079
  }
988
1080
  function configString(value) {
989
1081
  return nonEmpty(typeof value === "string" ? value : void 0) ?? null;
@@ -1157,6 +1249,75 @@ async function readPlaintextTokens() {
1157
1249
  function plaintextTokensPath(home) {
1158
1250
  return join(home, "tokens.json");
1159
1251
  }
1252
+ function pendingDeviceAuthPath(home) {
1253
+ return join(home, "pending-device-auth.json");
1254
+ }
1255
+ function pendingDeviceAuthKey(baseUrl, profile) {
1256
+ return `${baseUrl}:${profile}`;
1257
+ }
1258
+ async function readPendingDeviceAuth(baseUrl, profile) {
1259
+ const home = configHome();
1260
+ if (!home) return null;
1261
+ const raw = await readFile(pendingDeviceAuthPath(home), "utf8").catch(() => null);
1262
+ if (!raw) return null;
1263
+ try {
1264
+ const parsed = JSON.parse(raw);
1265
+ if (!isRecord(parsed)) return null;
1266
+ const entry = parsed[pendingDeviceAuthKey(baseUrl, profile)];
1267
+ return isPendingDeviceAuth(entry) ? entry : null;
1268
+ } catch {
1269
+ return null;
1270
+ }
1271
+ }
1272
+ async function writePendingDeviceAuth(pending) {
1273
+ const home = configHome();
1274
+ if (!home) return false;
1275
+ const path = pendingDeviceAuthPath(home);
1276
+ const existing = await readFile(path, "utf8").then((raw) => {
1277
+ try {
1278
+ const parsed = JSON.parse(raw);
1279
+ return isRecord(parsed) ? parsed : {};
1280
+ } catch {
1281
+ return {};
1282
+ }
1283
+ }).catch(() => ({}));
1284
+ const key = pendingDeviceAuthKey(pending.base_url, pending.profile);
1285
+ await mkdir(home, {
1286
+ recursive: true,
1287
+ mode: 448
1288
+ });
1289
+ await writeFile(path, `${JSON.stringify({
1290
+ ...existing,
1291
+ [key]: pending
1292
+ }, null, 2)}\n`, { mode: 384 });
1293
+ await chmod(path, 384);
1294
+ return true;
1295
+ }
1296
+ async function clearPendingDeviceAuth(baseUrl, profile) {
1297
+ const home = configHome();
1298
+ if (!home) return;
1299
+ const path = pendingDeviceAuthPath(home);
1300
+ const raw = await readFile(path, "utf8").catch(() => null);
1301
+ if (!raw) return;
1302
+ try {
1303
+ const parsed = JSON.parse(raw);
1304
+ if (!isRecord(parsed)) return;
1305
+ const key = pendingDeviceAuthKey(baseUrl, profile);
1306
+ if (!Object.hasOwn(parsed, key)) return;
1307
+ const { [key]: _removed, ...rest } = parsed;
1308
+ if (Object.keys(rest).length === 0) {
1309
+ await writeFile(path, "{}\n", { mode: 384 });
1310
+ return;
1311
+ }
1312
+ await writeFile(path, `${JSON.stringify(rest, null, 2)}\n`, { mode: 384 });
1313
+ } catch {
1314
+ return;
1315
+ }
1316
+ }
1317
+ function isPendingDeviceAuth(value) {
1318
+ if (!isRecord(value)) return false;
1319
+ return typeof value.base_url === "string" && typeof value.profile === "string" && 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";
1320
+ }
1160
1321
  function configHome() {
1161
1322
  const override = nonEmpty(process.env.ARTIFACTSHARE_CONFIG_HOME);
1162
1323
  if (override) return override;
@@ -1168,7 +1329,7 @@ function configHome() {
1168
1329
  }
1169
1330
  //#endregion
1170
1331
  //#region src/credentials.ts
1171
- async function resolveCredential(options, projectConfig = null) {
1332
+ async function resolveCredential(options, projectInput = null) {
1172
1333
  const envToken = nonEmpty(process.env.ARTIFACTSHARE_TOKEN);
1173
1334
  const optionToken = nonEmpty(options.token);
1174
1335
  const profile = nonEmpty(options.profile);
@@ -1189,18 +1350,36 @@ async function resolveCredential(options, projectConfig = null) {
1189
1350
  token: envToken
1190
1351
  };
1191
1352
  const globalConfig = await readGlobalConfig();
1192
- if (profile) return await resolveProfileCredential("profile", profile, options, globalConfig);
1193
- const projectProfile = nonEmpty(projectConfig?.default_profile);
1194
- if (projectProfile) return await resolveProfileCredential("project_config", projectProfile, options, globalConfig);
1353
+ if (profile) return await resolveProfileCredential("profile", profile, options, globalConfig, null, null);
1354
+ const project = normalizeProjectInput(projectInput);
1355
+ const projectProfile = nonEmpty(project.config?.default_profile);
1356
+ if (projectProfile) return await resolveProfileCredential(project.kind === "local" ? "local_config" : "project_config", projectProfile, options, globalConfig, project.path, project.kind);
1195
1357
  const globalProfile = nonEmpty(globalConfig?.default_profile);
1196
- if (globalProfile) return await resolveProfileCredential("global_profile", globalProfile, options, globalConfig);
1358
+ if (globalProfile) return await resolveProfileCredential("global_profile", globalProfile, options, globalConfig, null, null);
1197
1359
  return {
1198
1360
  ok: false,
1199
1361
  source: "none",
1200
- error: authRequiredError()
1362
+ error: authRequiredError(baseUrlOf(options))
1201
1363
  };
1202
1364
  }
1203
- async function resolveProfileCredential(source, profile, options, globalConfig) {
1365
+ function normalizeProjectInput(projectInput) {
1366
+ if (!projectInput) return {
1367
+ config: null,
1368
+ raw: null,
1369
+ kind: null,
1370
+ path: null,
1371
+ directory: null
1372
+ };
1373
+ if ("kind" in projectInput) return projectInput;
1374
+ return {
1375
+ config: projectInput,
1376
+ raw: projectInput,
1377
+ kind: "shared",
1378
+ path: null,
1379
+ directory: null
1380
+ };
1381
+ }
1382
+ async function resolveProfileCredential(source, profile, options, globalConfig, configPath, configKind) {
1204
1383
  const profileBaseUrl = nonEmpty(globalConfig?.profiles?.[profile]?.base_url);
1205
1384
  if (profileBaseUrl && !nonEmpty(options.baseUrl) && !nonEmpty(process.env.ARTIFACTSHARE_BASE_URL)) options.baseUrl = profileBaseUrl;
1206
1385
  const stored = await readProfileToken(profile, options);
@@ -1210,11 +1389,47 @@ async function resolveProfileCredential(source, profile, options, globalConfig)
1210
1389
  profile,
1211
1390
  token: stored.token
1212
1391
  };
1213
- return profileAuthRequired(source, profile, stored.reason);
1392
+ return profileAuthRequired(source, profile, stored.reason, options, globalConfig, configPath, configKind);
1214
1393
  }
1215
- function profileAuthRequired(source, profile, reason) {
1216
- const error = authRequiredError();
1394
+ async function profileAuthRequired(source, profile, reason, options, globalConfig, configPath, configKind) {
1395
+ const baseUrl = baseUrlOf(options);
1396
+ const url = tokensUrl(baseUrl);
1397
+ const error = authRequiredError(baseUrl);
1217
1398
  const why = reason === "unavailable" ? `No safe token store is available for profile "${profile}".` : `No saved credential was found for profile "${profile}".`;
1399
+ const alternative = await findAlternativeProfileWithToken(globalConfig, options, profile);
1400
+ const details = {
1401
+ ...authRecoveryDetails(baseUrl, `${CLI_INVOCATION} login --profile ${profile}`),
1402
+ credential_source: source,
1403
+ profile
1404
+ };
1405
+ if (configPath) {
1406
+ details.config_path = configPath;
1407
+ if (configKind) details.config_kind = configKind;
1408
+ }
1409
+ if (alternative) {
1410
+ const switchHint = profileSwitchHint(alternative);
1411
+ return {
1412
+ ok: false,
1413
+ source,
1414
+ profile,
1415
+ error: {
1416
+ ...error,
1417
+ why,
1418
+ hint: `${switchHint} Or in an interactive terminal run ${CLI_INVOCATION} login --profile ${profile}. In agents or CI, issue a token at ${url}, then set ${TOKEN_ENV_VAR}.`,
1419
+ agent_recoverable: true,
1420
+ requires_human: false,
1421
+ recovery: {
1422
+ kind: "run_command",
1423
+ command: `${CLI_INVOCATION} profiles use ${alternative}`
1424
+ },
1425
+ details: {
1426
+ ...details,
1427
+ alternative_profile: alternative,
1428
+ suggested_profile_command: `${CLI_INVOCATION} profiles use ${alternative}`
1429
+ }
1430
+ }
1431
+ };
1432
+ }
1218
1433
  return {
1219
1434
  ok: false,
1220
1435
  source,
@@ -1222,14 +1437,66 @@ function profileAuthRequired(source, profile, reason) {
1222
1437
  error: {
1223
1438
  ...error,
1224
1439
  why,
1225
- hint: `Run npx @artifactshare/cli login --profile ${profile}, or set ARTIFACTSHARE_TOKEN.`,
1226
- details: {
1227
- credential_source: source,
1228
- profile
1229
- }
1440
+ hint: `In an interactive terminal, run ${CLI_INVOCATION} login --profile ${profile}. In agents or CI, issue a token at ${url}, then set ${TOKEN_ENV_VAR}.`,
1441
+ details
1230
1442
  }
1231
1443
  };
1232
1444
  }
1445
+ function profileSwitchHint(profile) {
1446
+ return `Run with --profile ${profile}, init --profile ${profile}, or profiles use ${profile}.`;
1447
+ }
1448
+ async function findAlternativeProfileWithToken(globalConfig, options, excludeProfile) {
1449
+ const profiles = globalConfig?.profiles ?? {};
1450
+ const candidates = [];
1451
+ for (const name of Object.keys(profiles)) {
1452
+ if (name === excludeProfile) continue;
1453
+ const baseUrl = nonEmpty(profiles[name]?.base_url) ?? baseUrlOf(options);
1454
+ candidates.push({
1455
+ name,
1456
+ localDev: isLocalDevUrl(baseUrl)
1457
+ });
1458
+ }
1459
+ if (candidates.length === 0) return null;
1460
+ candidates.sort((left, right) => {
1461
+ if (left.localDev !== right.localDev) return left.localDev ? 1 : -1;
1462
+ return left.name.localeCompare(right.name);
1463
+ });
1464
+ for (const candidate of candidates) {
1465
+ const baseUrl = nonEmpty(profiles[candidate.name]?.base_url) ?? baseUrlOf(options);
1466
+ if ((await readProfileToken(candidate.name, {
1467
+ ...options,
1468
+ baseUrl
1469
+ })).ok) return candidate.name;
1470
+ }
1471
+ return null;
1472
+ }
1473
+ function isLocalDevUrl(baseUrl) {
1474
+ try {
1475
+ return isLocalHostname(new URL(baseUrl).hostname);
1476
+ } catch {
1477
+ return false;
1478
+ }
1479
+ }
1480
+ async function resolveEffectiveDefaultProfile(projectInput = null) {
1481
+ const project = normalizeProjectInput(projectInput);
1482
+ const projectProfile = nonEmpty(project.config?.default_profile);
1483
+ if (projectProfile) return {
1484
+ profile: projectProfile,
1485
+ source: project.kind === "local" ? "local" : "project",
1486
+ path: project.path
1487
+ };
1488
+ const globalProfile = nonEmpty((await readGlobalConfig())?.default_profile);
1489
+ if (globalProfile) return {
1490
+ profile: globalProfile,
1491
+ source: "global",
1492
+ path: null
1493
+ };
1494
+ return {
1495
+ profile: null,
1496
+ source: "none",
1497
+ path: null
1498
+ };
1499
+ }
1233
1500
  //#endregion
1234
1501
  //#region src/command-runners/artifacts-get.ts
1235
1502
  async function runArtifactsGet(parsed, mode) {
@@ -1241,9 +1508,9 @@ async function runArtifactsGet(parsed, mode) {
1241
1508
  if (offset.error) return writeFailure(command, offset.error, mode, 1);
1242
1509
  const include = parseIncludeOptions(parsed.options.include);
1243
1510
  if (include.error) return writeFailure(command, include.error, mode, 1);
1244
- const credential = await resolveCredential(parsed.options, await readProjectConfig());
1511
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1245
1512
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
1246
- const request = requestConfig(parsed.options);
1513
+ const request = await requestConfig(parsed.options);
1247
1514
  if (request.error) return writeFailure(command, request.error, mode, 1);
1248
1515
  const url = apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}`, baseUrlOf(parsed.options));
1249
1516
  if (offset.value !== void 0) url.searchParams.set("offset", offset.value);
@@ -1268,9 +1535,9 @@ async function runCommentsList(parsed, mode) {
1268
1535
  const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
1269
1536
  if (target.error) return writeFailure(command, target.error, mode, 1);
1270
1537
  const artifactId = target.artifactId;
1271
- const credential = await resolveCredential(parsed.options, await readProjectConfig());
1538
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1272
1539
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
1273
- const request = requestConfig(parsed.options);
1540
+ const request = await requestConfig(parsed.options);
1274
1541
  if (request.error) return writeFailure(command, request.error, mode, 1);
1275
1542
  const result = await apiGet(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, parsed.options, request.init, { artifactTarget: true });
1276
1543
  if (result.error) return writeFailure(command, result.error, mode, 1);
@@ -1294,9 +1561,9 @@ async function runCommentsPost(parsed, mode) {
1294
1561
  const quote = parsed.options.quote;
1295
1562
  if (quote !== void 0 && replyTo !== void 0) return writeFailure(command, validationError("Choose either --quote or --reply-to.", "A quote anchors a new thread; a reply joins an existing thread. Remove one and retry."), mode, 1);
1296
1563
  if (quote === void 0 && (parsed.options.quoteBefore !== void 0 || parsed.options.quoteAfter !== void 0)) return writeFailure(command, validationError("--quote-before and --quote-after require --quote.", "Add --quote <text>, or remove the context options."), mode, 1);
1297
- const credential = await resolveCredential(parsed.options, await readProjectConfig());
1564
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1298
1565
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
1299
- const request = requestConfig(parsed.options);
1566
+ const request = await requestConfig(parsed.options);
1300
1567
  if (request.error) return writeFailure(command, request.error, mode, 1);
1301
1568
  const result = await apiPost(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, {
1302
1569
  body,
@@ -1318,12 +1585,16 @@ async function runCommentsPost(parsed, mode) {
1318
1585
  }
1319
1586
  //#endregion
1320
1587
  //#region src/command-runners/doctor.ts
1321
- const LOGIN_COMMAND = "npx @artifactshare/cli login";
1322
- const REQUEST_ACCESS_COMMAND = "npx @artifactshare/cli request-access";
1588
+ const LOGIN_COMMAND = `${CLI_INVOCATION} login`;
1589
+ const REQUEST_ACCESS_COMMAND = `${CLI_INVOCATION} request-access`;
1323
1590
  function bearerTokenBlocksLogin(data) {
1324
1591
  return data.auth.credential_source === "env" || data.auth.credential_source === "token_option";
1325
1592
  }
1326
1593
  function resolveDoctorNextCommand(data) {
1594
+ if (data.config.local.code === "token_store_unsafe") {
1595
+ if (bearerTokenBlocksLogin(data)) return null;
1596
+ return LOGIN_COMMAND;
1597
+ }
1327
1598
  if (data.config.project.code === "token_store_unsafe") {
1328
1599
  if (bearerTokenBlocksLogin(data)) return null;
1329
1600
  return LOGIN_COMMAND;
@@ -1336,22 +1607,31 @@ function resolveDoctorNextCommand(data) {
1336
1607
  }
1337
1608
  return null;
1338
1609
  }
1610
+ function authRecovery(data, nextCommand) {
1611
+ const loginCommand = nextCommand?.startsWith(LOGIN_COMMAND) === true ? nextCommand : data.auth.profile ? `${LOGIN_COMMAND} --profile ${data.auth.profile}` : LOGIN_COMMAND;
1612
+ return authRecoveryDetails(data.base_url, loginCommand);
1613
+ }
1339
1614
  function doctorDataWithNextCommand(data) {
1340
- return {
1615
+ const nextCommand = resolveDoctorNextCommand(data);
1616
+ const next = {
1341
1617
  ...data,
1342
- next_command: resolveDoctorNextCommand(data)
1618
+ next_command: nextCommand
1343
1619
  };
1620
+ if (next.auth.code === "auth_required") next.auth = {
1621
+ ...next.auth,
1622
+ recovery: authRecovery(next, nextCommand)
1623
+ };
1624
+ return next;
1344
1625
  }
1345
1626
  async function runDoctor(parsed, mode) {
1346
1627
  const command = "doctor";
1347
- const rawProjectConfig = await readRawProjectConfig();
1348
- const config = rawProjectConfig;
1349
- const credential = await resolveCredential(parsed.options, config);
1350
- const destination = resolveDestination(parsed.options, config);
1628
+ const project = await resolveProjectConfig();
1629
+ const credential = await resolveCredential(parsed.options, project);
1630
+ const destination = resolveDestination(parsed.options, project.config);
1351
1631
  const data = {
1352
1632
  next_command: null,
1353
1633
  base_url: baseUrlOf(parsed.options),
1354
- config: await configDiagnostics(rawProjectConfig),
1634
+ config: await configDiagnostics(project),
1355
1635
  auth: {
1356
1636
  credential_source: credential.source,
1357
1637
  ...credential.profile ? { profile: credential.profile } : {},
@@ -1379,7 +1659,7 @@ async function runDoctor(parsed, mode) {
1379
1659
  data.auth.hint = credential.error.hint;
1380
1660
  return writeSuccess(command, doctorDataWithNextCommand(data), mode);
1381
1661
  }
1382
- const request = requestConfig(parsed.options);
1662
+ const request = await requestConfig(parsed.options);
1383
1663
  if (request.error) return writeFailure(command, request.error, mode, 1);
1384
1664
  const response = await fetch(apiUrl("/api/cli/doctor", baseUrlOf(parsed.options)), {
1385
1665
  headers: { Authorization: `Bearer ${credential.token}` },
@@ -1412,24 +1692,52 @@ async function runDoctor(parsed, mode) {
1412
1692
  }
1413
1693
  return writeSuccess(command, doctorDataWithNextCommand(data), mode);
1414
1694
  }
1415
- async function configDiagnostics(rawProjectConfig) {
1695
+ async function configDiagnostics(project) {
1416
1696
  const globalConfig = await readGlobalConfig();
1417
- const unsafeKey = Object.keys(rawProjectConfig ?? {}).find((key) => key.toLowerCase().includes("token"));
1697
+ const cwd = process.cwd();
1698
+ const directory = project.directory;
1699
+ const localRaw = directory ? await readProjectConfigAtDirectory(directory, "local") : null;
1700
+ const sharedRaw = directory ? await readProjectConfigAtDirectory(directory, "shared") : null;
1418
1701
  return {
1419
- project: {
1420
- present: rawProjectConfig !== null,
1421
- default_profile: configString(rawProjectConfig?.default_profile),
1422
- default_project_id: configString(rawProjectConfig?.default_project_id),
1423
- ...unsafeKey ? {
1424
- code: "token_store_unsafe",
1425
- hint: `Remove "${unsafeKey}" from ${PROJECT_CONFIG_PATH} and run npx @artifactshare/cli login instead; the working-directory config must never hold secrets.`
1426
- } : {}
1427
- },
1702
+ local: fileDiagnostics(localRaw, directory ? relativeProjectConfigPath(cwd, directory, PROJECT_CONFIG_LOCAL_PATH) : null),
1703
+ project: fileDiagnostics(sharedRaw, directory ? relativeProjectConfigPath(cwd, directory, PROJECT_CONFIG_PATH) : null),
1428
1704
  global: {
1429
1705
  present: globalConfig !== null,
1430
1706
  default_profile: configString(globalConfig?.default_profile),
1431
1707
  profile_count: Object.keys(globalConfig?.profiles ?? {}).length
1432
- }
1708
+ },
1709
+ effective: effectiveDiagnostics(project, globalConfig)
1710
+ };
1711
+ }
1712
+ function fileDiagnostics(raw, path) {
1713
+ const unsafeKey = Object.keys(raw ?? {}).find((key) => key.toLowerCase().includes("token"));
1714
+ return {
1715
+ present: raw !== null,
1716
+ path,
1717
+ default_profile: configString(raw?.default_profile),
1718
+ default_project_id: configString(raw?.default_project_id),
1719
+ ...unsafeKey ? {
1720
+ code: "token_store_unsafe",
1721
+ hint: `Remove "${unsafeKey}" from ${path ?? "the working-directory config"} and run ${CLI_INVOCATION} login instead; the working-directory config must never hold secrets.`
1722
+ } : {}
1723
+ };
1724
+ }
1725
+ function effectiveDiagnostics(project, globalConfig) {
1726
+ const projectProfile = configString(project.config?.default_profile);
1727
+ const projectProjectId = configString(project.config?.default_project_id);
1728
+ const globalProfile = configString(globalConfig?.default_profile);
1729
+ const defaultProfile = projectProfile ?? globalProfile;
1730
+ const defaultProfileSource = projectProfile ? project.kind === "local" ? "local" : "project" : globalProfile ? "global" : "none";
1731
+ const defaultProfilePath = defaultProfileSource === "local" || defaultProfileSource === "project" ? project.path : null;
1732
+ const defaultProjectId = projectProjectId;
1733
+ const defaultProjectIdSource = projectProjectId ? project.kind === "local" ? "local" : "project" : "none";
1734
+ return {
1735
+ default_profile: defaultProfile,
1736
+ default_profile_source: defaultProfileSource,
1737
+ default_profile_path: defaultProfilePath,
1738
+ default_project_id: defaultProjectId,
1739
+ default_project_id_source: defaultProjectIdSource,
1740
+ default_project_id_path: defaultProjectIdSource === "local" || defaultProjectIdSource === "project" ? project.path : null
1433
1741
  };
1434
1742
  }
1435
1743
  //#endregion
@@ -1600,7 +1908,7 @@ function artifactKindForFile(path) {
1600
1908
  //#endregion
1601
1909
  //#region src/command-runners/login.ts
1602
1910
  async function performDeviceLogin(profile, options, mode) {
1603
- const request = requestConfig(options);
1911
+ const request = await requestConfig(options);
1604
1912
  if (request.error) return {
1605
1913
  ok: false,
1606
1914
  error: request.error
@@ -1633,42 +1941,32 @@ async function performDeviceLogin(profile, options, mode) {
1633
1941
  error: token.error
1634
1942
  };
1635
1943
  const sessionExpiresAt = token.expires_in === void 0 ? null : new Date(Date.now() + token.expires_in * 1e3).toISOString();
1636
- const config = await readGlobalConfig() ?? {};
1637
- const whoamiResult = await apiGet("/api/cli/whoami", token.access_token, options, request.init);
1638
- if (whoamiResult.error) return {
1944
+ const stored = await verifyAndStoreProfileToken(profile, token.access_token, options, request.init);
1945
+ if (!stored.ok) return {
1639
1946
  ok: false,
1640
- error: whoamiResult.error
1641
- };
1642
- const whoami = whoamiProfile(whoamiResult.body);
1643
- const expectedEmail = config.profiles?.[profile]?.email;
1644
- if (expectedEmail && whoami.email && expectedEmail !== whoami.email) return {
1645
- ok: false,
1646
- error: authAccountMismatchError(profile, expectedEmail, whoami.email)
1947
+ error: stored.error
1647
1948
  };
1648
- const saved = await saveProfileToken(profile, token.access_token, options);
1649
- if (!saved.ok) return {
1650
- ok: false,
1651
- error: tokenStoreUnavailableError(profile)
1949
+ const effective = await resolveEffectiveDefaultProfile(await resolveProjectConfig());
1950
+ const data = {
1951
+ profile,
1952
+ status: "completed",
1953
+ credential_source: "profile",
1954
+ token_store: stored.data.token_store,
1955
+ user: stored.data.user,
1956
+ workspace: stored.data.workspace,
1957
+ verification_uri: code.verification_uri,
1958
+ verification_uri_complete: code.verification_uri_complete ?? null,
1959
+ user_code: code.user_code,
1960
+ expires_at: sessionExpiresAt,
1961
+ interval_seconds: code.interval
1652
1962
  };
1653
- await writeProfileConfig(profile, options, saved.store, whoami);
1963
+ if (effective.profile && effective.profile !== profile) {
1964
+ data.effective_default_profile = effective.profile;
1965
+ data.profile_switch_hint = `Saved credentials for "${profile}", but the current default profile is "${effective.profile}". Run with --profile ${profile}, init --profile ${profile}, or profiles use ${profile} before the next command.`;
1966
+ }
1654
1967
  return {
1655
1968
  ok: true,
1656
- data: {
1657
- profile,
1658
- status: "completed",
1659
- credential_source: "profile",
1660
- token_store: saved.store,
1661
- user: { email: whoami.email },
1662
- workspace: {
1663
- id: whoami.workspace_id,
1664
- hosted_domain: whoami.hosted_domain
1665
- },
1666
- verification_uri: code.verification_uri,
1667
- verification_uri_complete: code.verification_uri_complete ?? null,
1668
- user_code: code.user_code,
1669
- expires_at: sessionExpiresAt,
1670
- interval_seconds: code.interval
1671
- }
1969
+ data
1672
1970
  };
1673
1971
  }
1674
1972
  async function runLogin(parsed, mode) {
@@ -1688,10 +1986,48 @@ async function requestDeviceCode(options, init) {
1688
1986
  }).catch((error) => ({ networkError: error }));
1689
1987
  if ("networkError" in response) return { error: networkError(response.networkError) };
1690
1988
  const body = await readJson(response);
1691
- if (!response.ok) return { error: mapApiError(response.status, body) };
1989
+ if (!response.ok) return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
1692
1990
  if (!isDeviceCodeResponse(body)) return { error: validationError("Device login response was invalid.", "Retry login. If this repeats, report the response shape.", "service_error") };
1693
1991
  return body;
1694
1992
  }
1993
+ async function exchangeDeviceTokenOnce(options, deviceCode, init) {
1994
+ const response = await fetch(apiUrl("/api/auth/device/token", baseUrlOf(options)), {
1995
+ method: "POST",
1996
+ headers: { "content-type": "application/json" },
1997
+ body: JSON.stringify({
1998
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1999
+ device_code: deviceCode,
2000
+ client_id: DEVICE_CLIENT_ID
2001
+ }),
2002
+ ...init
2003
+ }).catch((error) => ({ networkError: error }));
2004
+ if ("networkError" in response) return { error: networkError(response.networkError) };
2005
+ const body = await readJson(response);
2006
+ if (response.ok && isDeviceTokenResponse(body)) return {
2007
+ status: "success",
2008
+ token: body
2009
+ };
2010
+ const authError = deviceTokenError(body);
2011
+ if (authError === "authorization_pending") return { status: "pending" };
2012
+ if (authError === "slow_down") return { status: "slow_down" };
2013
+ if (authError === "access_denied") return { status: "denied" };
2014
+ if (authError === "expired_token") return { status: "expired" };
2015
+ if (response.status === 429 || response.status >= 500) return { status: "retry_later" };
2016
+ return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
2017
+ }
2018
+ function pendingDeviceAuthFromCode(profile, options, code) {
2019
+ return {
2020
+ base_url: baseUrlOf(options),
2021
+ profile,
2022
+ device_code: code.device_code,
2023
+ verification_uri: code.verification_uri,
2024
+ verification_uri_complete: code.verification_uri_complete ?? null,
2025
+ user_code: code.user_code,
2026
+ expires_at: new Date(Date.now() + code.expires_in * 1e3).toISOString(),
2027
+ interval_seconds: code.interval,
2028
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
2029
+ };
2030
+ }
1695
2031
  async function pollForToken(options, code, init, profile, deadline) {
1696
2032
  let intervalMs = Math.max(code.interval, 1) * 1e3;
1697
2033
  let networkFailures = 0;
@@ -1723,21 +2059,56 @@ async function pollForToken(options, code, init, profile, deadline) {
1723
2059
  }
1724
2060
  if (authError === "access_denied") return { error: authDeniedError(profile) };
1725
2061
  if (authError === "expired_token") return { error: authExpiredError(profile) };
1726
- return { error: mapApiError(response.status, body) };
2062
+ return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
1727
2063
  }
1728
2064
  return { error: authExpiredError(profile) };
1729
2065
  }
2066
+ async function verifyAndStoreProfileToken(profile, token, options, init) {
2067
+ const config = await readGlobalConfig() ?? {};
2068
+ const whoamiResult = await apiGet("/api/cli/whoami", token, options, init);
2069
+ if (whoamiResult.error) return {
2070
+ ok: false,
2071
+ error: whoamiResult.error
2072
+ };
2073
+ const whoami = whoamiProfile(whoamiResult.body);
2074
+ const profiles = config.profiles ?? {};
2075
+ const expectedEmail = nonEmpty((Object.hasOwn(profiles, profile) ? profiles[profile] : void 0)?.email);
2076
+ if (expectedEmail && whoami.email !== expectedEmail) return {
2077
+ ok: false,
2078
+ error: authAccountMismatchError(profile, expectedEmail, whoami.email)
2079
+ };
2080
+ const saved = await saveProfileToken(profile, token, options);
2081
+ if (!saved.ok) return {
2082
+ ok: false,
2083
+ error: tokenStoreUnavailableError(profile)
2084
+ };
2085
+ await writeProfileConfig(profile, options, saved.store, whoami);
2086
+ return {
2087
+ ok: true,
2088
+ data: {
2089
+ profile,
2090
+ token_store: saved.store,
2091
+ user: { email: whoami.email },
2092
+ workspace: {
2093
+ id: whoami.workspace_id,
2094
+ hosted_domain: whoami.hosted_domain
2095
+ }
2096
+ }
2097
+ };
2098
+ }
1730
2099
  async function writeProfileConfig(profile, options, tokenStore, whoami) {
1731
2100
  const config = await readGlobalConfig() ?? {};
2101
+ const profiles = config.profiles ?? {};
2102
+ const currentProfile = Object.hasOwn(profiles, profile) ? profiles[profile] : void 0;
1732
2103
  await writeGlobalConfig({
1733
2104
  ...config,
1734
2105
  default_profile: nonEmpty(config.default_profile) ?? profile,
1735
2106
  profiles: {
1736
- ...config.profiles,
2107
+ ...profiles,
1737
2108
  [profile]: {
1738
- ...config.profiles?.[profile],
2109
+ ...currentProfile,
1739
2110
  base_url: baseUrlOf(options),
1740
- email: whoami.email,
2111
+ email: whoami.email ?? currentProfile?.email ?? null,
1741
2112
  workspace_id: whoami.workspace_id,
1742
2113
  token_store: tokenStore,
1743
2114
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
@@ -1769,14 +2140,25 @@ function whoamiProfile(body) {
1769
2140
  }
1770
2141
  //#endregion
1771
2142
  //#region src/command-runners/auto-login.ts
2143
+ const JSON_PENDING_AUTH_COMMANDS = new Set(["publish", "update"]);
1772
2144
  function isInteractiveTerminal(mode) {
1773
2145
  return !mode.json && process.stdin.isTTY === true;
1774
2146
  }
1775
2147
  function profileForAutoLogin(credential) {
1776
2148
  return credential.source === "none" ? "default" : credential.profile ?? "default";
1777
2149
  }
2150
+ function isPendingExpired(pending) {
2151
+ const expiresAt = Date.parse(pending.expires_at);
2152
+ return Number.isNaN(expiresAt) || expiresAt <= Date.now();
2153
+ }
2154
+ async function canAttemptProfileTokenSave(profile, options) {
2155
+ const stored = await readProfileToken(profile, options);
2156
+ return stored.ok || stored.reason !== "unavailable";
2157
+ }
1778
2158
  async function handleCredentialFailure(command, credential, options, mode, rerun, isRetry = false, deps = {}) {
1779
- if (credential.error.code !== "auth_required" || !isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
2159
+ if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
2160
+ if (mode.json && JSON_PENDING_AUTH_COMMANDS.has(command) && !isRetry) return handleJsonPendingAuth(command, credential, options, mode, rerun);
2161
+ if (!isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
1780
2162
  const performLogin = deps.performLogin ?? performDeviceLogin;
1781
2163
  const profile = profileForAutoLogin(credential);
1782
2164
  writeText("Not signed in. Starting device login to continue...\n");
@@ -1784,6 +2166,39 @@ async function handleCredentialFailure(command, credential, options, mode, rerun
1784
2166
  if (!loginResult.ok) return writeFailure(command, loginResult.error, mode, 1);
1785
2167
  return rerun();
1786
2168
  }
2169
+ async function handleJsonPendingAuth(command, credential, options, mode, rerun) {
2170
+ const profile = profileForAutoLogin(credential);
2171
+ const baseUrl = baseUrlOf(options);
2172
+ const request = await requestConfig(options);
2173
+ if (request.error) return writeFailure(command, request.error, mode, 1);
2174
+ if (!await canAttemptProfileTokenSave(profile, options)) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
2175
+ const existing = await readPendingDeviceAuth(baseUrl, profile);
2176
+ if (existing && !isPendingExpired(existing)) {
2177
+ const exchange = await exchangeDeviceTokenOnce(options, existing.device_code, request.init);
2178
+ if ("error" in exchange) {
2179
+ if (exchange.error.code !== "network_failed") await clearPendingDeviceAuth(baseUrl, profile);
2180
+ return writeFailure(command, exchange.error, mode, 1);
2181
+ }
2182
+ if (exchange.status === "success") {
2183
+ const stored = await verifyAndStoreProfileToken(profile, exchange.token.access_token, options, request.init);
2184
+ if (!stored.ok) return writeFailure(command, stored.error, mode, 1);
2185
+ await clearPendingDeviceAuth(baseUrl, profile);
2186
+ return rerun();
2187
+ }
2188
+ if (exchange.status === "denied") {
2189
+ await clearPendingDeviceAuth(baseUrl, profile);
2190
+ return writeFailure(command, authDeniedError(profile), mode, 1);
2191
+ }
2192
+ if (exchange.status === "expired") await clearPendingDeviceAuth(baseUrl, profile);
2193
+ else if (exchange.status === "retry_later") return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing), mode, 1);
2194
+ else return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing), mode, 1);
2195
+ } else if (existing) await clearPendingDeviceAuth(baseUrl, profile);
2196
+ const code = await requestDeviceCode(options, request.init);
2197
+ if ("error" in code) return writeFailure(command, credential.error, mode, 1);
2198
+ const pending = pendingDeviceAuthFromCode(profile, options, code);
2199
+ if (!await writePendingDeviceAuth(pending)) return writeFailure(command, credential.error, mode, 1);
2200
+ return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, pending), mode, 1);
2201
+ }
1787
2202
  //#endregion
1788
2203
  //#region src/command-runners/download.ts
1789
2204
  async function runDownload(parsed, mode, isRetry = false) {
@@ -1791,9 +2206,9 @@ async function runDownload(parsed, mode, isRetry = false) {
1791
2206
  const target = parseArtifactTarget(parsed.positionals[0], "download", "Pass an artifact ID or share URL to download.");
1792
2207
  if (target.error) return writeFailure(command, target.error, mode, 1);
1793
2208
  const artifactId = target.artifactId;
1794
- const credential = await resolveCredential(parsed.options, await readProjectConfig());
2209
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1795
2210
  if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
1796
- const request = requestConfig(parsed.options);
2211
+ const request = await requestConfig(parsed.options);
1797
2212
  if (request.error) return writeFailure(command, request.error, mode, 1);
1798
2213
  const baseUrl = baseUrlOf(parsed.options);
1799
2214
  const manifestUrl = apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/download`, baseUrl);
@@ -1864,40 +2279,113 @@ async function runDownload(parsed, mode, isRetry = false) {
1864
2279
  }, mode);
1865
2280
  }
1866
2281
  //#endregion
2282
+ //#region src/git-exclude.ts
2283
+ async function ensureGitExclude(cwd) {
2284
+ const git = await findGitDir(cwd);
2285
+ if (!git) return {
2286
+ applied: false,
2287
+ warning: null
2288
+ };
2289
+ const excludePath = join(git.gitDir, "info", "exclude");
2290
+ const excludeEntry = gitPattern(relative(git.workTree, resolve(cwd, PROJECT_CONFIG_LOCAL_PATH)));
2291
+ try {
2292
+ const existing = await readFile(excludePath, "utf8").catch(() => "");
2293
+ if (excludeLines(existing).includes(excludeEntry)) return {
2294
+ applied: false,
2295
+ warning: null
2296
+ };
2297
+ await mkdir(dirname(excludePath), { recursive: true });
2298
+ await appendFile(excludePath, `${existing.endsWith("\n") || existing.length === 0 ? "" : "\n"}${excludeEntry}\n`, "utf8");
2299
+ return {
2300
+ applied: true,
2301
+ warning: null
2302
+ };
2303
+ } catch {
2304
+ return {
2305
+ applied: false,
2306
+ warning: `Could not update ${excludePath}; keep ${PROJECT_CONFIG_LOCAL_PATH} out of version control manually.`
2307
+ };
2308
+ }
2309
+ }
2310
+ function excludeLines(text) {
2311
+ return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
2312
+ }
2313
+ async function findGitDir(start) {
2314
+ let current = resolve(start);
2315
+ const root = resolve(current, "/");
2316
+ while (true) {
2317
+ const gitDir = await resolveGitDir(join(current, ".git"));
2318
+ if (gitDir) return {
2319
+ gitDir,
2320
+ workTree: current
2321
+ };
2322
+ if (current === root) return null;
2323
+ current = dirname(current);
2324
+ }
2325
+ }
2326
+ async function resolveGitDir(gitPath) {
2327
+ const info = await stat(gitPath).catch(() => null);
2328
+ if (!info) return null;
2329
+ if (info.isDirectory()) return gitPath;
2330
+ if (!info.isFile()) return null;
2331
+ const text = await readFile(gitPath, "utf8").catch(() => null);
2332
+ if (!text) return null;
2333
+ const gitDir = text.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
2334
+ if (!gitDir) return null;
2335
+ const resolvedGitDir = resolve(dirname(gitPath), gitDir);
2336
+ const commonDir = await readFile(join(resolvedGitDir, "commondir"), "utf8").then((value) => value.trim()).catch(() => null);
2337
+ return commonDir ? resolve(resolvedGitDir, commonDir) : resolvedGitDir;
2338
+ }
2339
+ function gitPattern(path) {
2340
+ return path.split("\\").join("/");
2341
+ }
2342
+ //#endregion
1867
2343
  //#region src/command-runners/init.ts
1868
2344
  async function runInit(parsed, mode) {
1869
2345
  const command = "init";
1870
2346
  const profile = nonEmpty(parsed.options.profile);
1871
2347
  const projectId = nonEmpty(parsed.options.projectId);
1872
- const existing = await readRawProjectConfig() ?? {};
1873
- if (!profile && !projectId) return writeSuccess(command, initData(false, existing), mode);
2348
+ const resolved = await resolveProjectConfig();
2349
+ if (!profile && !projectId) return writeSuccess(command, initData(false, resolved.raw ?? {}, resolved), mode);
1874
2350
  if (profile) {
1875
2351
  if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
1876
2352
  const globalConfig = await readGlobalConfig();
1877
2353
  if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
1878
2354
  }
1879
2355
  const next = {
1880
- ...existing,
2356
+ ...await readRawLocalProjectConfig() ?? {},
1881
2357
  ...profile ? { default_profile: profile } : {},
1882
2358
  ...projectId ? { default_project_id: projectId } : {}
1883
2359
  };
1884
- const path = projectConfigPath();
2360
+ const path = projectConfigLocalPath();
1885
2361
  await mkdir(dirname(path), { recursive: true });
1886
2362
  await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
1887
- return writeSuccess(command, initData(true, next), mode);
1888
- }
1889
- function initData(written, config) {
2363
+ const gitExclude = await ensureGitExclude(process.cwd());
2364
+ const data = initData(true, next, resolved);
2365
+ delete data.read_path;
2366
+ if (gitExclude.warning) data.git_exclude_warning = gitExclude.warning;
2367
+ if (gitExclude.applied) data.git_exclude_applied = true;
2368
+ return writeSuccess(command, data, mode);
2369
+ }
2370
+ function initData(written, config, resolved) {
1890
2371
  return {
1891
- path: PROJECT_CONFIG_PATH,
2372
+ path: PROJECT_CONFIG_LOCAL_PATH,
1892
2373
  written,
1893
2374
  config: {
1894
2375
  default_profile: configString(config.default_profile),
1895
2376
  default_project_id: configString(config.default_project_id)
1896
- }
2377
+ },
2378
+ ...resolved.path ? { read_path: resolved.path } : {}
1897
2379
  };
1898
2380
  }
1899
2381
  //#endregion
1900
2382
  //#region src/command-runners/profiles.ts
2383
+ async function readStdinToken() {
2384
+ if (process.stdin.isTTY === true) return "";
2385
+ const chunks = [];
2386
+ for await (const chunk of process.stdin) chunks.push(chunk);
2387
+ return Buffer.concat(chunks).toString("utf8").trim();
2388
+ }
1901
2389
  async function runProfilesList(parsed, mode) {
1902
2390
  const command = "profiles list";
1903
2391
  if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
@@ -1924,12 +2412,12 @@ async function runProfilesList(parsed, mode) {
1924
2412
  default_profile: defaultProfile,
1925
2413
  profiles
1926
2414
  }, mode);
1927
- if (!mode.json && profiles.length === 0) writeText("No profiles yet. Run npx @artifactshare/cli login --profile default to create one.\n");
2415
+ if (!mode.json && profiles.length === 0) writeText(`No profiles yet. Run ${CLI_INVOCATION} login --profile default to create one.\n`);
1928
2416
  }
1929
2417
  async function runProfilesUse(parsed, mode) {
1930
2418
  const command = "profiles use";
1931
2419
  const name = nonEmpty(parsed.positionals[0]);
1932
- if (!name) return writeFailure(command, validationError("A profile name is required.", "Run npx @artifactshare/cli profiles use <name>."), mode, 1);
2420
+ if (!name) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles use <name>.`), mode, 1);
1933
2421
  if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
1934
2422
  const config = await readGlobalConfig() ?? {};
1935
2423
  if (!Object.hasOwn(config.profiles ?? {}, name)) return writeFailure(command, profileNotFoundError(name), mode, 1);
@@ -1943,6 +2431,32 @@ async function runProfilesUse(parsed, mode) {
1943
2431
  previous_default: previous
1944
2432
  }, mode);
1945
2433
  }
2434
+ async function runProfilesImportToken(parsed, mode) {
2435
+ const command = "profiles import-token";
2436
+ const profile = nonEmpty(parsed.options.profile);
2437
+ if (!profile) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles import-token --profile <name>.`), mode, 1);
2438
+ if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
2439
+ if (nonEmpty(parsed.options.token)) return writeFailure(command, validationError("Do not pass API tokens with --token to import-token.", "Pipe the token on standard input so it does not appear in process arguments."), mode, 1);
2440
+ if (parsed.positionals.length > 0) return writeFailure(command, validationError("Do not pass API tokens as positional arguments.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`), mode, 1);
2441
+ let token;
2442
+ try {
2443
+ token = await readStdinToken();
2444
+ } catch {
2445
+ return writeFailure(command, validationError("The token could not be read from standard input.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`, "service_error"), mode, 1);
2446
+ }
2447
+ if (!token) return writeFailure(command, validationError("A token is required on standard input.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`), mode, 1);
2448
+ const request = await requestConfig(parsed.options);
2449
+ if (request.error) return writeFailure(command, request.error, mode, 1);
2450
+ const stored = await verifyAndStoreProfileToken(profile, token, parsed.options, request.init);
2451
+ if (!stored.ok) return writeFailure(command, stored.error, mode, 1);
2452
+ return writeSuccess(command, {
2453
+ profile,
2454
+ token_store: stored.data.token_store,
2455
+ user: stored.data.user,
2456
+ workspace: stored.data.workspace,
2457
+ base_url: baseUrlOf(parsed.options)
2458
+ }, mode);
2459
+ }
1946
2460
  //#endregion
1947
2461
  //#region src/command-runners/projects.ts
1948
2462
  async function fetchProjects(token, options, init) {
@@ -1963,14 +2477,14 @@ async function fetchProjects(token, options, init) {
1963
2477
  }
1964
2478
  async function runProjectsList(parsed, mode) {
1965
2479
  const command = "projects list";
1966
- const config = await readProjectConfig();
1967
- const credential = await resolveCredential(parsed.options, config);
2480
+ const projectConfig = await resolveProjectConfig();
2481
+ const credential = await resolveCredential(parsed.options, projectConfig);
1968
2482
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
1969
- const request = requestConfig(parsed.options);
2483
+ const request = await requestConfig(parsed.options);
1970
2484
  if (request.error) return writeFailure(command, request.error, mode, 1);
1971
2485
  const result = await fetchProjects(credential.token, parsed.options, request.init);
1972
2486
  if (result.error) return writeFailure(command, result.error, mode, 1);
1973
- const defaultProjectId = configString(config?.default_project_id);
2487
+ const defaultProjectId = configString(projectConfig.config?.default_project_id);
1974
2488
  const projects = result.projects.map((project) => ({
1975
2489
  ...project,
1976
2490
  is_default: project.id === defaultProjectId
@@ -1993,8 +2507,8 @@ async function runPublish(parsed, mode, isRetry = false) {
1993
2507
  publishKey = (typeof parsed.options.key === "string" ? parsed.options.key : "").trim();
1994
2508
  if (publishKey.length === 0 || publishKey.length > MAX_PUBLISH_KEY_LENGTH) return writeFailure(command, validationError(`--key must be 1-${MAX_PUBLISH_KEY_LENGTH} characters after trimming.`, "Pass a short stable identifier, like a job name or PR number."), mode, 1);
1995
2509
  }
1996
- const config = await readProjectConfig();
1997
- const credential = await resolveCredential(parsed.options, config);
2510
+ const project = await resolveProjectConfig();
2511
+ const credential = await resolveCredential(parsed.options, project);
1998
2512
  if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runPublish(parsed, mode, true), isRetry);
1999
2513
  const baseUrl = baseUrlOf(parsed.options);
2000
2514
  const hasProjectFlag = "project" in parsed.options;
@@ -2006,12 +2520,12 @@ async function runPublish(parsed, mode, isRetry = false) {
2006
2520
  const conflict = destinationConflictError(parsed.options);
2007
2521
  if (conflict) return writeFailure(command, conflict, mode, 1);
2008
2522
  } else {
2009
- const earlyDestination = resolveDestination(parsed.options, config);
2523
+ const earlyDestination = resolveDestination(parsed.options, project.config);
2010
2524
  if (earlyDestination.error) return writeFailure(command, earlyDestination.error, mode, 1);
2011
2525
  }
2012
2526
  const fileStat = await stat(targetPath).catch(() => null);
2013
2527
  if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
2014
- const request = requestConfig(parsed.options);
2528
+ const request = await requestConfig(parsed.options);
2015
2529
  if (request.error) return writeFailure(command, request.error, mode, 1);
2016
2530
  if (hasProjectFlag && projectName) {
2017
2531
  const resolved = await resolveProjectIdByName(projectName, credential.token, parsed.options, request.init);
@@ -2022,7 +2536,7 @@ async function runPublish(parsed, mode, isRetry = false) {
2022
2536
  projectId: resolved.projectId
2023
2537
  };
2024
2538
  }
2025
- const destination = resolveDestination(destinationOptions, config);
2539
+ const destination = resolveDestination(destinationOptions, project.config);
2026
2540
  if (destination.error) return writeFailure(command, destination.error, mode, 1);
2027
2541
  const initialForm = new FormData();
2028
2542
  const grantEmails = arrayOption(parsed.options.grantEmail);
@@ -2089,9 +2603,9 @@ async function runRequestAccess(parsed, mode) {
2089
2603
  const command = "request-access";
2090
2604
  const note = parsed.options.note;
2091
2605
  if (note !== void 0 && note.length > NOTE_MAX) return writeFailure(command, validationError(`A note can be at most ${NOTE_MAX} characters.`, "Shorten --note and retry."), mode, 1);
2092
- const credential = await resolveCredential(parsed.options, await readProjectConfig());
2606
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2093
2607
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2094
- const request = requestConfig(parsed.options);
2608
+ const request = await requestConfig(parsed.options);
2095
2609
  if (request.error) return writeFailure(command, request.error, mode, 1);
2096
2610
  const result = await apiPost("/api/cli/request-access", credential.token, { note }, parsed.options, request.init);
2097
2611
  if (result.error) return writeFailure(command, result.error, mode, 1);
@@ -2113,9 +2627,9 @@ async function runResolve(parsed, mode) {
2113
2627
  const command = "resolve";
2114
2628
  const value = parsed.positionals[0]?.trim();
2115
2629
  if (!value) return writeFailure(command, validationError("Resolve value is required.", "Pass a URL, ID, title, or project name to resolve."), mode, 1);
2116
- const credential = await resolveCredential(parsed.options, await readProjectConfig());
2630
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2117
2631
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2118
- const request = requestConfig(parsed.options);
2632
+ const request = await requestConfig(parsed.options);
2119
2633
  if (request.error) return writeFailure(command, request.error, mode, 1);
2120
2634
  const url = apiUrl("/api/cli/resolve", baseUrlOf(parsed.options));
2121
2635
  url.searchParams.set("q", value);
@@ -2402,12 +2916,12 @@ async function runUpdate(parsed, mode, isRetry = false) {
2402
2916
  if (unsupportedOption) return writeFailure(command, validationError(`Update does not accept --${unsupportedOption}.`, "Update only adds a new version. Remove unsupported options and retry."), mode, 1);
2403
2917
  const artifactId = resolveArtifactId(artifactInput);
2404
2918
  if (!artifactId) return writeFailure(command, targetResolutionError(artifactInput, "update"), mode, 1);
2405
- const credential = await resolveCredential(parsed.options, await readProjectConfig());
2919
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2406
2920
  if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
2407
2921
  const fileStat = await stat(targetPath).catch(() => null);
2408
2922
  if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
2409
2923
  const baseUrl = baseUrlOf(parsed.options);
2410
- const request = requestConfig(parsed.options);
2924
+ const request = await requestConfig(parsed.options);
2411
2925
  if (request.error) return writeFailure(command, request.error, mode, 1);
2412
2926
  const upload = await prepareUploadPayload(targetPath, fileStat);
2413
2927
  if (upload.error) return writeFailure(command, upload.error, mode, 1);
@@ -2442,9 +2956,9 @@ async function runUpdate(parsed, mode, isRetry = false) {
2442
2956
  //#region src/command-runners/whoami.ts
2443
2957
  async function runWhoami(parsed, mode) {
2444
2958
  const command = "whoami";
2445
- const credential = await resolveCredential(parsed.options, await readProjectConfig());
2959
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2446
2960
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2447
- const request = requestConfig(parsed.options);
2961
+ const request = await requestConfig(parsed.options);
2448
2962
  if (request.error) return writeFailure(command, request.error, mode, 1);
2449
2963
  const whoami = await apiGet("/api/cli/whoami", credential.token, parsed.options, request.init);
2450
2964
  if (whoami.error) return writeFailure(command, whoami.error, mode, 1);
@@ -2503,6 +3017,11 @@ async function profilesUseRunner(ctx) {
2503
3017
  const parsed = parsedArgsFromContext("profiles use", ctx);
2504
3018
  return await runProfilesUse(parsed, outputMode(parsed.options));
2505
3019
  }
3020
+ async function profilesImportTokenRunner(ctx) {
3021
+ const parsed = parsedArgsFromContext("profiles import-token", ctx);
3022
+ if (hasOptionToken(ctx, "token")) parsed.options.token = "<redacted>";
3023
+ return await runProfilesImportToken(parsed, outputMode(parsed.options));
3024
+ }
2506
3025
  async function projectsListRunner(ctx) {
2507
3026
  const parsed = parsedArgsFromContext("projects list", ctx);
2508
3027
  return await runProjectsList(parsed, outputMode(parsed.options));
@@ -2534,9 +3053,16 @@ async function doctorRunner(ctx) {
2534
3053
  function parentCommandRunner(command) {
2535
3054
  return (ctx) => {
2536
3055
  const parsed = parsedArgsFromContext(command, ctx);
2537
- writeFailure(command, validationError("A subcommand is required.", `Run npx @artifactshare/cli ${command} <${(SUBCOMMANDS[command] ?? []).join(" | ")}>.`), outputMode(parsed.options), 1);
3056
+ writeFailure(command, validationError("A subcommand is required.", `Run ${CLI_INVOCATION} ${command} <${(SUBCOMMANDS[command] ?? []).join(" | ")}>.`), outputMode(parsed.options), 1);
2538
3057
  };
2539
3058
  }
3059
+ function hasOptionToken(ctx, name) {
3060
+ for (const token of ctx.tokens) {
3061
+ if (token.kind !== "option") continue;
3062
+ if ((token.name ?? token.rawName?.replace(/^--?/, "")) === name) return true;
3063
+ }
3064
+ return false;
3065
+ }
2540
3066
  //#endregion
2541
3067
  //#region src/index.ts
2542
3068
  async function main(rawArgv) {
@@ -2607,7 +3133,7 @@ const commonArgs = {
2607
3133
  token: {
2608
3134
  type: "string",
2609
3135
  toKebab: true,
2610
- description: "Bearer token (default: ARTIFACTSHARE_TOKEN)"
3136
+ description: `Bearer token (default: ${TOKEN_ENV_VAR})`
2611
3137
  },
2612
3138
  profile: {
2613
3139
  type: "string",
@@ -2630,27 +3156,31 @@ const entryCommand = define({
2630
3156
  description: "Artifact Share CLI",
2631
3157
  toKebab: true,
2632
3158
  args: commonArgs,
2633
- examples: `npx @artifactshare/cli publish <path> --project-id <id> --json
2634
- npx @artifactshare/cli update <artifact-id-or-url> <path> --json
2635
- npx @artifactshare/cli resolve <url-id-or-title> --json
2636
- npx @artifactshare/cli artifacts get <artifact-id-or-url> --json
2637
- npx @artifactshare/cli comments list <artifact-id-or-url> --json
2638
- npx @artifactshare/cli comments post <artifact-id-or-url> --body "<text>" --json
2639
- npx @artifactshare/cli download <artifact-id-or-url> --output ./artifact --json
2640
- npx @artifactshare/cli login --profile default
2641
- npx @artifactshare/cli profiles list --json
2642
- npx @artifactshare/cli profiles use <name> --json
2643
- npx @artifactshare/cli projects list --json
2644
- npx @artifactshare/cli skills install --tool codex --json
2645
- npx @artifactshare/cli skills list --json
2646
- npx @artifactshare/cli init --profile <name> --project-id <id> --json
2647
- npx @artifactshare/cli publish <path> --home --json
2648
- npx @artifactshare/cli request-access --json
2649
- npx @artifactshare/cli whoami --json
2650
- npx @artifactshare/cli doctor --json
3159
+ examples: `npx --yes @artifactshare/cli publish <path> --project-id <id> --json
3160
+ npx --yes @artifactshare/cli update <artifact-id-or-url> <path> --json
3161
+ npx --yes @artifactshare/cli resolve <url-id-or-title> --json
3162
+ npx --yes @artifactshare/cli artifacts get <artifact-id-or-url> --json
3163
+ npx --yes @artifactshare/cli comments list <artifact-id-or-url> --json
3164
+ npx --yes @artifactshare/cli comments post <artifact-id-or-url> --body "<text>" --json
3165
+ npx --yes @artifactshare/cli download <artifact-id-or-url> --output ./artifact --json
3166
+ npx --yes @artifactshare/cli login --profile default
3167
+ npx --yes @artifactshare/cli profiles list --json
3168
+ npx --yes @artifactshare/cli profiles use <name> --json
3169
+ npx --yes @artifactshare/cli projects list --json
3170
+ npx --yes @artifactshare/cli skills install --tool codex --json
3171
+ npx --yes @artifactshare/cli skills list --json
3172
+ npx --yes @artifactshare/cli init --profile <name> --project-id <id> --json
3173
+ npx --yes @artifactshare/cli publish <path> --home --json
3174
+ npx --yes @artifactshare/cli request-access --json
3175
+ npx --yes @artifactshare/cli whoami --json
3176
+ npx --yes @artifactshare/cli doctor --json
3177
+
3178
+ Authentication:
3179
+ Interactive terminal: run ${CLI_INVOCATION} login --profile default, then approve in your browser.
3180
+ Agents or CI: issue a token at ${DEFAULT_BASE_URL}/settings/tokens, then set ${TOKEN_ENV_VAR} or pass ${TOKEN_OPTION}.
2651
3181
 
2652
3182
  Common failures:
2653
- auth_required Set ARTIFACTSHARE_TOKEN or pass --token
3183
+ auth_required Use ${TOKEN_ENV_VAR} or ${TOKEN_OPTION}; tokens are issued at ${DEFAULT_BASE_URL}/settings/tokens
2654
3184
  destination_required Add --project-id, configure .artifactshare/config.json, or pass --home
2655
3185
  target_not_found Use an artifact ID, share URL, or sandbox URL
2656
3186
  upload_not_allowed Upload access is limited; run request-access to join the waitlist`,
@@ -2658,11 +3188,14 @@ Common failures:
2658
3188
  });
2659
3189
  const loginDefinition = define({
2660
3190
  name: "login",
2661
- description: "Sign in with device authorization and save a CLI profile.",
3191
+ description: "Sign in with browser device authorization and save a CLI profile.",
2662
3192
  toKebab: true,
2663
3193
  args: commonArgs,
2664
- examples: `npx @artifactshare/cli login --profile default
2665
- npx @artifactshare/cli login --profile client-a --json
3194
+ examples: `npx --yes @artifactshare/cli login --profile default
3195
+ npx --yes @artifactshare/cli login --profile client-a --json
3196
+
3197
+ login requires browser approval in an interactive terminal.
3198
+ For agents or CI, issue a token at ${DEFAULT_BASE_URL}/settings/tokens, then pass it to normal commands with ${TOKEN_ENV_VAR} or ${TOKEN_OPTION}; do not pass the token to login.
2666
3199
 
2667
3200
  Common failures:
2668
3201
  auth_denied The browser approval was denied
@@ -2711,7 +3244,7 @@ const publishDefinition = define({
2711
3244
  description: "Stable key for create-or-update: the first publish creates the artifact, repeats add versions. Not a secret; it appears in logs and JSON"
2712
3245
  }
2713
3246
  },
2714
- examples: `npx @artifactshare/cli publish report.html --project-id <id> --key nightly-report --json
3247
+ examples: `npx --yes @artifactshare/cli publish report.html --project-id <id> --key nightly-report --json
2715
3248
 
2716
3249
  Common failures:
2717
3250
  auth_required Set ARTIFACTSHARE_TOKEN before publish
@@ -2761,8 +3294,8 @@ const resolveDefinition = define({
2761
3294
  description: "Share URL, sandbox URL, ID, title, or project name"
2762
3295
  }
2763
3296
  },
2764
- examples: `npx @artifactshare/cli resolve "Weekly report" --json
2765
- npx @artifactshare/cli resolve https://artifactshare.com/a/abc123def4 --json
3297
+ examples: `npx --yes @artifactshare/cli resolve "Weekly report" --json
3298
+ npx --yes @artifactshare/cli resolve https://artifactshare.com/a/abc123def4 --json
2766
3299
 
2767
3300
  Use resolve before write commands when a user gives a title or project name.
2768
3301
  Pass the returned artifact id or project id to the next command.
@@ -2794,8 +3327,8 @@ const downloadDefinition = define({
2794
3327
  description: "Allow writing into an existing output directory"
2795
3328
  }
2796
3329
  },
2797
- examples: `npx @artifactshare/cli download abc123def4 --json
2798
- npx @artifactshare/cli download https://artifactshare.com/a/abc123def4 --output ./artifact --json
3330
+ examples: `npx --yes @artifactshare/cli download abc123def4 --json
3331
+ npx --yes @artifactshare/cli download https://artifactshare.com/a/abc123def4 --output ./artifact --json
2799
3332
 
2800
3333
  Use resolve first when a user gives a title or project name, then pass the id here.
2801
3334
  Download writes files to a directory so the result can be inspected or passed to update.
@@ -2834,9 +3367,9 @@ const artifactsDefinition = define({
2834
3367
  description: "Extra data to include: versions or comments"
2835
3368
  }
2836
3369
  },
2837
- examples: `npx @artifactshare/cli artifacts get abc123def4 --json
2838
- npx @artifactshare/cli artifacts get https://artifactshare.com/a/abc123def4 --include versions --include comments --json
2839
- npx @artifactshare/cli artifacts get abc123def4 --offset 200000 --json
3370
+ examples: `npx --yes @artifactshare/cli artifacts get abc123def4 --json
3371
+ npx --yes @artifactshare/cli artifacts get https://artifactshare.com/a/abc123def4 --include versions --include comments --json
3372
+ npx --yes @artifactshare/cli artifacts get abc123def4 --offset 200000 --json
2840
3373
 
2841
3374
  Use resolve first when a user gives a title or project name, then pass the id here.
2842
3375
  If truncated is true, call again with --offset set to next_offset before updating.
@@ -2847,7 +3380,7 @@ Common failures:
2847
3380
  unsupported_kind Use download for static sites or other multi-file artifacts
2848
3381
  validation_failed Check --offset and --include values`
2849
3382
  }), artifactsGetRunner) },
2850
- examples: `npx @artifactshare/cli artifacts get <artifact-id-or-url> --json
3383
+ examples: `npx --yes @artifactshare/cli artifacts get <artifact-id-or-url> --json
2851
3384
 
2852
3385
  Use artifacts get to read back Markdown or HTML before update.`,
2853
3386
  run: parentCommandRunner("artifacts")
@@ -2864,7 +3397,7 @@ const commentsListDefinition = define({
2864
3397
  description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
2865
3398
  }
2866
3399
  },
2867
- examples: `npx @artifactshare/cli comments list abc123def4 --json
3400
+ examples: `npx --yes @artifactshare/cli comments list abc123def4 --json
2868
3401
 
2869
3402
  Returns up to 50 threads (open threads first); has_more reports whether more exist.
2870
3403
  Each thread carries its messages, status, and quoted-text anchor when present.
@@ -2910,9 +3443,9 @@ const commentsPostDefinition = define({
2910
3443
  description: "Text just after the quote, to pick the right occurrence"
2911
3444
  }
2912
3445
  },
2913
- examples: `npx @artifactshare/cli comments post abc123def4 --body "Looks good" --json
2914
- npx @artifactshare/cli comments post abc123def4 --body "Done" --reply-to <thread-id> --json
2915
- npx @artifactshare/cli comments post abc123def4 --body "Fix this" --quote "exact text" --json
3446
+ examples: `npx --yes @artifactshare/cli comments post abc123def4 --body "Looks good" --json
3447
+ npx --yes @artifactshare/cli comments post abc123def4 --body "Done" --reply-to <thread-id> --json
3448
+ npx --yes @artifactshare/cli comments post abc123def4 --body "Fix this" --quote "exact text" --json
2916
3449
 
2917
3450
  Copy quote text from artifacts get so it matches the artifact exactly.
2918
3451
 
@@ -2933,8 +3466,8 @@ const commentsDefinition = define({
2933
3466
  list: lazyCommand(commentsListDefinition, commentsListRunner),
2934
3467
  post: lazyCommand(commentsPostDefinition, commentsPostRunner)
2935
3468
  },
2936
- examples: `npx @artifactshare/cli comments list <artifact-id-or-url> --json
2937
- npx @artifactshare/cli comments post <artifact-id-or-url> --body "<text>" --json`,
3469
+ examples: `npx --yes @artifactshare/cli comments list <artifact-id-or-url> --json
3470
+ npx --yes @artifactshare/cli comments post <artifact-id-or-url> --body "<text>" --json`,
2938
3471
  run: parentCommandRunner("comments")
2939
3472
  });
2940
3473
  const profilesListDefinition = define({
@@ -2942,7 +3475,7 @@ const profilesListDefinition = define({
2942
3475
  description: "List saved CLI profiles and the default profile.",
2943
3476
  toKebab: true,
2944
3477
  args: commonArgs,
2945
- examples: `npx @artifactshare/cli profiles list --json
3478
+ examples: `npx --yes @artifactshare/cli profiles list --json
2946
3479
 
2947
3480
  token_present shows whether a saved credential exists; token values are never printed.`
2948
3481
  });
@@ -2957,11 +3490,32 @@ const profilesUseDefinition = define({
2957
3490
  description: "Profile name to make the default"
2958
3491
  }
2959
3492
  },
2960
- examples: `npx @artifactshare/cli profiles use client-a --json
3493
+ examples: `npx --yes @artifactshare/cli profiles use client-a --json
2961
3494
 
2962
3495
  Common failures:
2963
3496
  profile_not_found Run profiles list to see saved profiles, or login --profile <name>`
2964
3497
  });
3498
+ const profilesImportTokenDefinition = define({
3499
+ name: "import-token",
3500
+ description: "Read an API token from standard input and save it to a CLI profile.",
3501
+ toKebab: true,
3502
+ args: {
3503
+ json: commonArgs.json,
3504
+ baseUrl: commonArgs.baseUrl,
3505
+ profile: commonArgs.profile,
3506
+ allowPlaintextTokenStore: commonArgs.allowPlaintextTokenStore,
3507
+ insecureLocalhost: commonArgs.insecureLocalhost
3508
+ },
3509
+ examples: `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile client-a --json
3510
+
3511
+ Reads the token from standard input only. Use this in agents or CI after issuing a token at ${DEFAULT_BASE_URL}/settings/tokens.
3512
+
3513
+ Common failures:
3514
+ validation_failed Pass --profile and pipe a non-empty token on standard input
3515
+ token_invalid The token is invalid or expired
3516
+ auth_account_mismatch The token belongs to a different account than the saved profile email
3517
+ token_store_unavailable Configure an OS credential store or use the explicit plaintext fallback`
3518
+ });
2965
3519
  const profilesDefinition = define({
2966
3520
  name: "profiles",
2967
3521
  description: "Manage saved CLI profiles.",
@@ -2969,10 +3523,12 @@ const profilesDefinition = define({
2969
3523
  args: commonArgs,
2970
3524
  subCommands: {
2971
3525
  list: lazyCommand(profilesListDefinition, profilesListRunner),
2972
- use: lazyCommand(profilesUseDefinition, profilesUseRunner)
3526
+ use: lazyCommand(profilesUseDefinition, profilesUseRunner),
3527
+ "import-token": lazyCommand(profilesImportTokenDefinition, profilesImportTokenRunner)
2973
3528
  },
2974
- examples: `npx @artifactshare/cli profiles list --json
2975
- npx @artifactshare/cli profiles use client-a --json`,
3529
+ examples: `npx --yes @artifactshare/cli profiles list --json
3530
+ npx --yes @artifactshare/cli profiles use client-a --json
3531
+ printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile client-a --json`,
2976
3532
  run: parentCommandRunner("profiles")
2977
3533
  });
2978
3534
  const projectsDefinition = define({
@@ -2985,12 +3541,12 @@ const projectsDefinition = define({
2985
3541
  description: "List projects you can publish into.",
2986
3542
  toKebab: true,
2987
3543
  args: commonArgs,
2988
- examples: `npx @artifactshare/cli projects list --json
3544
+ examples: `npx --yes @artifactshare/cli projects list --json
2989
3545
 
2990
3546
  is_default marks the working-directory default project from .artifactshare/config.json.
2991
3547
  Use a project id with publish --project-id or init --project-id.`
2992
3548
  }), projectsListRunner) },
2993
- examples: `npx @artifactshare/cli projects list --json`,
3549
+ examples: `npx --yes @artifactshare/cli projects list --json`,
2994
3550
  run: parentCommandRunner("projects")
2995
3551
  });
2996
3552
  const skillsToolArgs = {
@@ -3024,8 +3580,8 @@ const skillsInstallDefinition = define({
3024
3580
  description: "Overwrite an existing unmanaged file or reinstall the same version"
3025
3581
  }
3026
3582
  },
3027
- examples: `npx @artifactshare/cli skills install --tool codex --scope project --json
3028
- npx @artifactshare/cli skills install --tool claude --tool cursor --dry-run --json
3583
+ examples: `npx --yes @artifactshare/cli skills install --tool codex --scope project --json
3584
+ npx --yes @artifactshare/cli skills install --tool claude --tool cursor --dry-run --json
3029
3585
 
3030
3586
  Writes a managed SKILL.md (codex, claude) or Cursor rule (cursor).
3031
3587
  Files without the Artifact Share managed marker are never overwritten without --force.
@@ -3039,7 +3595,7 @@ const skillsListDefinition = define({
3039
3595
  description: "Show skill install status for each supported agent tool.",
3040
3596
  toKebab: true,
3041
3597
  args: commonArgs,
3042
- examples: `npx @artifactshare/cli skills list --json
3598
+ examples: `npx --yes @artifactshare/cli skills list --json
3043
3599
 
3044
3600
  Reports each tool and scope with detection, install state, and update availability.
3045
3601
  Runs locally; no network or authentication is used.`
@@ -3057,8 +3613,8 @@ const skillsUpdateDefinition = define({
3057
3613
  description: "Rewrite managed files even when the version already matches"
3058
3614
  }
3059
3615
  },
3060
- examples: `npx @artifactshare/cli skills update --json
3061
- npx @artifactshare/cli skills update --tool codex --scope user --json
3616
+ examples: `npx --yes @artifactshare/cli skills update --json
3617
+ npx --yes @artifactshare/cli skills update --tool codex --scope user --json
3062
3618
 
3063
3619
  Only files created by skills install (managed marker present) are updated.
3064
3620
 
@@ -3073,8 +3629,8 @@ const skillsRemoveDefinition = define({
3073
3629
  ...commonArgs,
3074
3630
  ...skillsToolArgs
3075
3631
  },
3076
- examples: `npx @artifactshare/cli skills remove --json
3077
- npx @artifactshare/cli skills remove --tool cursor --json
3632
+ examples: `npx --yes @artifactshare/cli skills remove --json
3633
+ npx --yes @artifactshare/cli skills remove --tool cursor --json
3078
3634
 
3079
3635
  Only files created by skills install are deleted; unmanaged files are skipped.`
3080
3636
  });
@@ -3089,8 +3645,8 @@ const skillsDefinition = define({
3089
3645
  update: lazyCommand(skillsUpdateDefinition, skillsUpdateRunner),
3090
3646
  remove: lazyCommand(skillsRemoveDefinition, skillsRemoveRunner)
3091
3647
  },
3092
- examples: `npx @artifactshare/cli skills install --tool codex --json
3093
- npx @artifactshare/cli skills list --json`,
3648
+ examples: `npx --yes @artifactshare/cli skills install --tool codex --json
3649
+ npx --yes @artifactshare/cli skills list --json`,
3094
3650
  run: parentCommandRunner("skills")
3095
3651
  });
3096
3652
  const initDefinition = define({
@@ -3105,8 +3661,8 @@ const initDefinition = define({
3105
3661
  description: "Default project for publish in this directory"
3106
3662
  }
3107
3663
  },
3108
- examples: `npx @artifactshare/cli init --profile client-a --project-id <id> --json
3109
- npx @artifactshare/cli init --json
3664
+ examples: `npx --yes @artifactshare/cli init --profile client-a --project-id <id> --json
3665
+ npx --yes @artifactshare/cli init --json
3110
3666
 
3111
3667
  Without flags, init reports the current config and writes nothing.
3112
3668
  Secrets are never written to .artifactshare/config.json.
@@ -3126,8 +3682,8 @@ const requestAccessDefinition = define({
3126
3682
  description: "Optional message for the Artifact Share team (max 2000 characters)"
3127
3683
  }
3128
3684
  },
3129
- examples: `npx @artifactshare/cli request-access --json
3130
- npx @artifactshare/cli request-access --note "Publishing weekly reports for my team" --json
3685
+ examples: `npx --yes @artifactshare/cli request-access --json
3686
+ npx --yes @artifactshare/cli request-access --note "Publishing weekly reports for my team" --json
3131
3687
 
3132
3688
  Joining the waitlist does not enable publishing immediately; an operator opens it.
3133
3689
  Re-running updates your note without creating a duplicate entry.