@artifactshare/cli 0.11.2 → 0.11.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/CHANGELOG.md CHANGED
@@ -5,6 +5,11 @@ For user-facing announcements, see https://artifactshare.com/updates?product=cli
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ ## 0.11.3 - 2026-08-20
9
+
10
+ - Support Windows Credential Manager for saved profiles, resolve Windows config homes without `HOME`, and expose token-store diagnostics from `doctor --json`. The explicit plaintext fallback is now limited to POSIX systems with mode `0600` instead of implying Windows protection from ignored mode bits.
11
+ - `profiles import-token` detects workspace-issued bot tokens (`asb_` prefix), imports them as rotating refresh credentials (the first refresh consumes the displayed token; the rotated credential is stored before success is reported), persists `kind: "bot"` in the profile, and adds `--force` to replace an existing profile credential (no-op for API tokens). Rejected bot tokens report `bot_token_invalid`; runtime 401s on bot profiles now point to an admin reissue instead of login/preset/API-token recovery. `profiles list` and `doctor` surface bot profiles.
12
+
8
13
  ## 0.11.2 - 2026-08-12
9
14
 
10
15
  - Direct agents with a user present to project-scoped browser login, and reserve API-token guidance for unattended CI or scripts without browser approval.
package/README.md CHANGED
@@ -45,7 +45,11 @@ runs add versions to the same file.
45
45
 
46
46
  - **Interactive**: run `npx --yes @artifactshare/cli login`, or use `login --preset agent` to authorize a profile for one selected project with restricted agent operations. Running `share`, `update`, or `download` directly also starts sign-in when unauthenticated (the CLI prints a link and code to open in your browser). Profiles created by `login` renew expired CLI sessions automatically during normal use.
47
47
  - **CI / non-interactive**: issue a token at `https://artifactshare.com/settings/tokens`, then set `ARTIFACTSHARE_TOKEN` (or pass `--token`). Without a token, non-interactive runs fail with `error.code: "auth_required"` instead of hanging.
48
- - Multiple accounts: keep one local profile per account (`profiles list` / `profiles use <name>`). In non-interactive agents, pipe an issued token into `profiles import-token --profile <name> --json` to create a saved API-token profile without browser login; API-token profiles are not renewed by the CLI. Use `logout --profile <name>` to revoke a device-login credential before removing it locally while keeping profile metadata, or `profiles delete <name>` to remove the profile entry too. API-token profiles are only removed locally.
48
+ - Multiple accounts: keep one local profile per account (`profiles list` / `profiles use <name>`). In non-interactive agents, pipe an issued token into `profiles import-token --profile <name> --json` to create a saved API-token profile without browser login; API-token profiles are not renewed by the CLI. Workspace-issued bot tokens (`asb_` prefix) are imported the same way: the CLI detects the prefix, performs the first rotating refresh (which consumes the displayed token), and stores the rotated credential; replacing an existing profile credential with a bot token requires `--force` (a no-op for API tokens), and a rejected bot token reports `bot_token_invalid` (recovery is an admin reissue). Use `logout --profile <name>` to revoke a device-login credential before removing it locally while keeping profile metadata, or `profiles delete <name>` to remove the profile entry too. API-token profiles are only removed locally.
49
+
50
+ Successful `share --json` output may include `data.warnings`. Surface each
51
+ warning to the user. `slack_reauthorization_required` means the destination
52
+ project's Slack channel must be reauthorized.
49
53
 
50
54
  ## Commands
51
55
 
@@ -64,7 +68,7 @@ runs add versions to the same file.
64
68
  | `projects list / create / edit` | List, create, and edit project destinations and audience |
65
69
  | `move <target>` | Move an existing file into a project or back home; `edit` is preferred for new automation |
66
70
  | `login` / `logout` / `whoami` | Sign in, revoke a device-login credential before removing it locally, and check who you are |
67
- | `doctor` | Diagnose auth, destination, network, and upload readiness — tells you the next command to run |
71
+ | `doctor` | Diagnose token storage, auth, destination, network, and upload readiness — tells you the next command to run |
68
72
  | `changelog` | Show the installed version, this release's notes, and the public updates page |
69
73
  | `profiles list / use / import-token / delete` | Switch between local account profiles, import an issued token from stdin, and delete profile entries |
70
74
  | `init` | Set up this directory: detect Claude Code, Codex, or Cursor and install the skill in user scope, then show next steps; or save defaults with `--profile` / `--project-id` |
@@ -74,6 +78,14 @@ Public command paths covered by this reference:
74
78
 
75
79
  `append`, `artifacts`, `artifacts get`, `artifacts list`, `changelog`, `comments`, `comments delete`, `comments edit`, `comments list`, `comments post`, `comments reopen`, `comments resolve`, `config`, `config get`, `config set`, `config unset`, `delete`, `doctor`, `download`, `edit`, `init`, `login`, `logout`, `move`, `open`, `profiles`, `profiles delete`, `profiles import-token`, `profiles list`, `profiles use`, `projects`, `projects create`, `projects edit`, `projects list`, `resolve`, `share`, `skills`, `skills ensure`, `skills install`, `skills list`, `skills remove`, `skills update`, `update`, `whoami`.
76
80
 
81
+ Saved credentials use macOS Keychain, Linux Secret Service, or Windows
82
+ Credential Manager. If no native store is available, the explicit
83
+ `--allow-plaintext-token-store` fallback writes under the resolved user config
84
+ directory with mode `0600` on POSIX systems. It is unavailable on Windows,
85
+ where saved profiles require Credential Manager. Run `doctor --json` to inspect
86
+ the resolved config home, available native store, and plaintext credential
87
+ count.
88
+
77
89
  ## Where shared files are delivered
78
90
 
79
91
  Posting to a project delivers to the audience defined by that project. With no destination, `share` posts to home. Choose the home audience by purpose:
package/dist/index.js CHANGED
@@ -5,10 +5,10 @@ import { createReadStream, realpathSync } from "node:fs";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { spawn } from "node:child_process";
7
7
  import { appendFile, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
8
+ import { arch, homedir, platform } from "node:os";
8
9
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
9
10
  import { createHash, randomUUID } from "node:crypto";
10
11
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
11
- import { arch, homedir, platform } from "node:os";
12
12
  import { Blob } from "node:buffer";
13
13
  //#region src/constants.ts
14
14
  const DEFAULT_BASE_URL = "https://artifactshare.com";
@@ -178,7 +178,10 @@ function mapApiError(status, body, options = {}) {
178
178
  if (!options.authenticated) return authRequiredError(options.baseUrl ?? "https://artifactshare.com");
179
179
  const source = options.credentialSource;
180
180
  const profile = options.profile;
181
- if (typeof profile === "string" && profile.length > 0 && isProfileCredentialSource(source) && options.profileCredentialKind !== "api_token") return profileReauthRequiredError(options.baseUrl ?? "https://artifactshare.com", source, profile);
181
+ if (typeof profile === "string" && profile.length > 0 && isProfileCredentialSource(source) && options.profileCredentialKind !== "api_token") {
182
+ if (options.botProfile) return botReauthRequiredError(profile);
183
+ return profileReauthRequiredError(options.baseUrl ?? "https://artifactshare.com", source, profile);
184
+ }
182
185
  return tokenInvalidError();
183
186
  }
184
187
  if (apiCode === "upload-not-allowed") return cliError({
@@ -219,15 +222,20 @@ function mapApiError(status, body, options = {}) {
219
222
  requiresHuman: true,
220
223
  recovery: { kind: "ask_human" }
221
224
  });
222
- if (apiCode === "quota-exceeded") return cliError({
223
- code: "storage_limit_exceeded",
224
- message: "Storage quota is exceeded.",
225
- why: "The workspace does not have enough remaining storage for this upload.",
226
- hint: "Reduce the artifact size or ask an administrator to increase storage.",
227
- agentRecoverable: false,
228
- requiresHuman: true,
229
- recovery: { kind: "ask_human" }
230
- });
225
+ if (apiCode === "quota-exceeded") {
226
+ const apiDetails = typeof body?.error === "object" && isRecord(body.error.details) ? body.error.details : void 0;
227
+ const upgradeRequest = isRecord(apiDetails?.upgrade_request) ? apiDetails.upgrade_request : void 0;
228
+ return cliError({
229
+ code: "storage_limit_exceeded",
230
+ message: "Storage quota is exceeded.",
231
+ why: "The workspace does not have enough remaining storage for this upload.",
232
+ hint: "Reduce the artifact size or ask an administrator to increase storage.",
233
+ agentRecoverable: false,
234
+ requiresHuman: true,
235
+ recovery: { kind: "ask_human" },
236
+ ...upgradeRequest ? { details: { upgrade_request: upgradeRequest } } : {}
237
+ });
238
+ }
231
239
  if (apiCode !== null && ["too-large", "file-too-large"].includes(apiCode)) return cliError({
232
240
  code: "file_too_large",
233
241
  message: apiMessage ?? "The upload is too large.",
@@ -366,15 +374,20 @@ function mapApiError(status, body, options = {}) {
366
374
  ...currentVersionId ? { details: { current_version_id: currentVersionId } } : {}
367
375
  });
368
376
  }
369
- if (apiCode === "project-limit-reached") return cliError({
370
- code: "project_limit_reached",
371
- message: apiMessage ?? "You've reached your plan's project limit. Upgrade your plan or archive existing projects.",
372
- why: "The workspace already has the maximum number of active projects allowed by its plan.",
373
- hint: "Archive an existing project, upgrade the workspace plan, or choose a different project.",
374
- agentRecoverable: false,
375
- requiresHuman: true,
376
- recovery: { kind: "change_input" }
377
- });
377
+ if (apiCode === "project-limit-reached") {
378
+ const apiDetails = typeof body?.error === "object" && isRecord(body.error.details) ? body.error.details : void 0;
379
+ const upgradeRequest = isRecord(apiDetails?.upgrade_request) ? apiDetails.upgrade_request : void 0;
380
+ return cliError({
381
+ code: "project_limit_reached",
382
+ message: apiMessage ?? "You've reached your plan's project limit. Upgrade your plan or archive existing projects.",
383
+ why: "The workspace already has the maximum number of active projects allowed by its plan.",
384
+ hint: "Archive an existing project, upgrade the workspace plan, or choose a different project.",
385
+ agentRecoverable: false,
386
+ requiresHuman: true,
387
+ recovery: { kind: "change_input" },
388
+ ...upgradeRequest ? { details: { upgrade_request: upgradeRequest } } : {}
389
+ });
390
+ }
378
391
  if (apiCode === "forbidden" || status === 403) return cliError({
379
392
  code: "forbidden",
380
393
  message: apiMessage ?? "You do not have permission to do that.",
@@ -559,6 +572,33 @@ function authRequiredError(baseUrl) {
559
572
  details: authRecoveryDetails(baseUrl)
560
573
  });
561
574
  }
575
+ function botReauthRequiredError(profile) {
576
+ return cliError({
577
+ code: "auth_required",
578
+ message: "The bot credential is no longer valid.",
579
+ why: `The saved bot credential for profile "${profile}" is expired, was superseded by a reissue, or the bot was stopped.`,
580
+ hint: `If a workspace administrator already reissued the bot token, import it: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --force. Otherwise ask a workspace administrator to reissue the bot token.`,
581
+ agentRecoverable: false,
582
+ requiresHuman: true,
583
+ recovery: { kind: "ask_human" },
584
+ details: {
585
+ profile,
586
+ reauth_reason: "bot_credential_invalid"
587
+ }
588
+ });
589
+ }
590
+ function botTokenInvalidError(profile) {
591
+ return cliError({
592
+ code: "bot_token_invalid",
593
+ message: "The bot token was rejected.",
594
+ why: "The token is revoked (a newer reissue supersedes it), expired, or the bot was stopped.",
595
+ hint: "Ask a workspace administrator to reissue the bot token, then import the newly displayed token.",
596
+ agentRecoverable: false,
597
+ requiresHuman: true,
598
+ recovery: { kind: "ask_human" },
599
+ details: { profile }
600
+ });
601
+ }
562
602
  function profileReauthRequiredError(baseUrl, source, profile) {
563
603
  const loginCommand = `${CLI_INVOCATION} login --profile ${profile}`;
564
604
  return cliError({
@@ -677,16 +717,38 @@ function profileNotFoundError(profile) {
677
717
  details: { profile }
678
718
  });
679
719
  }
680
- function tokenStoreUnavailableError(profile) {
720
+ function tokenStoreUnavailableError(profile, cause = "credential_store_unavailable_or_failed", platform = process.platform) {
721
+ const hint = cause === "config_write_failed" ? "Check that the resolved configuration directory is private and writable, then retry." : cause === "store_operation_failed" ? "Retry the credential operation. If it continues to fail, check access to the configured credential store and configuration directory." : platform === "win32" ? "Windows requires Credential Manager for saved profiles. Check that Windows PowerShell 5.1 and Credential Manager are available, then retry." : `Configure an OS credential store, or rerun login with --allow-plaintext-token-store only if this machine is trusted.`;
722
+ const retryable = cause === "store_operation_failed" || cause === "config_write_failed";
681
723
  return cliError({
682
724
  code: "token_store_unavailable",
683
725
  message: "No safe token store is available.",
684
- why: "Artifact Share could not find an OS credential store for this environment.",
685
- hint: `Configure an OS credential store, or rerun login with --allow-plaintext-token-store only if this machine is trusted.`,
686
- agentRecoverable: false,
687
- requiresHuman: true,
688
- recovery: { kind: "ask_human" },
689
- ...profile ? { details: { profile } } : {}
726
+ why: "Artifact Share could not use an OS credential store for this environment.",
727
+ hint,
728
+ agentRecoverable: retryable,
729
+ requiresHuman: !retryable,
730
+ recovery: retryable ? { kind: "retry_later" } : { kind: "ask_human" },
731
+ details: {
732
+ cause,
733
+ platform,
734
+ ...profile ? { profile } : {}
735
+ }
736
+ });
737
+ }
738
+ function configHomeUnavailableError(profile) {
739
+ return cliError({
740
+ code: "config_home_unavailable",
741
+ message: "The user configuration directory could not be resolved.",
742
+ why: "Artifact Share could not resolve a home directory for profile configuration or the plaintext token fallback.",
743
+ hint: "Set ARTIFACTSHARE_CONFIG_HOME to a private directory owned by the current user, then retry.",
744
+ agentRecoverable: true,
745
+ requiresHuman: false,
746
+ recovery: { kind: "change_input" },
747
+ details: {
748
+ cause: "config_home_unresolved",
749
+ platform: process.platform,
750
+ ...profile ? { profile } : {}
751
+ }
690
752
  });
691
753
  }
692
754
  function skillUpdateConflictError(path) {
@@ -1079,7 +1141,11 @@ function writeFailure(command, error, mode, exitCode) {
1079
1141
  error
1080
1142
  };
1081
1143
  if (mode.json) process.stderr.write(`${JSON.stringify(payload, null, 2)}\n`);
1082
- else process.stderr.write(`Error: ${error.message}\nWhy: ${error.why}\nHint: ${error.hint}\n`);
1144
+ else {
1145
+ const upgradeRequest = isRecord(error.details?.upgrade_request) ? error.details.upgrade_request : null;
1146
+ const upgradeHint = upgradeRequest?.kind === "contact" && typeof upgradeRequest.request_message === "string" ? upgradeRequest.request_message : upgradeRequest?.kind === "billing" && typeof upgradeRequest.upgrade_url === "string" ? upgradeRequest.upgrade_url : upgradeRequest?.kind === "support" && typeof upgradeRequest.support_url === "string" ? upgradeRequest.support_url : null;
1147
+ process.stderr.write(`Error: ${error.message}\nWhy: ${error.why}\nHint: ${error.hint}${upgradeHint ? `\n${upgradeHint}` : ""}\n`);
1148
+ }
1083
1149
  process.exitCode = exitCode;
1084
1150
  }
1085
1151
  function writeText(text) {
@@ -1101,7 +1167,9 @@ function humanSuccess(command, data) {
1101
1167
  `Visibility: ${fields.visibility}`,
1102
1168
  ""
1103
1169
  ].join("\n");
1104
- return suffix ? `${output}${suffix}` : output;
1170
+ const warnings = shareWarnings(data);
1171
+ const withWarnings = warnings.length ? `${output}${warnings.map((message) => `Warning: ${message}`).join("\n")}\n` : output;
1172
+ return suffix ? `${withWarnings}${suffix}` : withWarnings;
1105
1173
  }
1106
1174
  if (command === "doctor") return doctorHumanOutput(data);
1107
1175
  if (command === "open") return openHumanOutput(data);
@@ -1111,6 +1179,10 @@ function humanSuccess(command, data) {
1111
1179
  const output = `${JSON.stringify(data, null, 2)}\n`;
1112
1180
  return suffix ? `${output}${suffix}` : output;
1113
1181
  }
1182
+ function shareWarnings(data) {
1183
+ if (!isRecord(data) || !Array.isArray(data.warnings)) return [];
1184
+ return data.warnings.flatMap((warning) => isRecord(warning) && warning.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [warning.message] : []);
1185
+ }
1114
1186
  function skillAutoUpdateHumanOutput(data) {
1115
1187
  if (!isRecord(data)) return "";
1116
1188
  const skills = data.skills;
@@ -1723,9 +1795,16 @@ async function readProfileToken(profile, options) {
1723
1795
  if (plaintext.reason === "legacy") return plaintext;
1724
1796
  return {
1725
1797
  ok: false,
1726
- reason: native || options.allowPlaintextTokenStore ? "missing" : "unavailable"
1798
+ reason: native || options.allowPlaintextTokenStore && plaintextStoreWritable() ? "missing" : "unavailable"
1727
1799
  };
1728
1800
  }
1801
+ async function probeTokenStoreWritable(profile, options, { ignoreExistingEntry = false, platform = process.platform } = {}) {
1802
+ if (await nativeStore()) return true;
1803
+ if (options.allowPlaintextTokenStore) return plaintextStoreWritable(platform);
1804
+ if (ignoreExistingEntry) return false;
1805
+ if (!plaintextFallbackSupported(platform)) return false;
1806
+ return await readPlaintextToken(accountName(profile, baseUrlOf(options))) !== null;
1807
+ }
1729
1808
  async function saveProfileSessionCredential(profile, credential, options) {
1730
1809
  return await saveProfileCredential(profile, credential, options);
1731
1810
  }
@@ -1736,10 +1815,13 @@ async function saveProfileCredential(profile, credential, options) {
1736
1815
  const account = accountName(profile, baseUrlOf(options));
1737
1816
  const value = JSON.stringify(credential);
1738
1817
  const native = await nativeStore();
1739
- if (native && await native.write(account, value)) return {
1740
- ok: true,
1741
- store: native.kind
1742
- };
1818
+ if (native && await native.write(account, value)) {
1819
+ if (process.platform === "win32") await deletePlaintextTokenAccount(account).catch(() => false);
1820
+ return {
1821
+ ok: true,
1822
+ store: native.kind
1823
+ };
1824
+ }
1743
1825
  const hasPlaintextEntry = await readPlaintextToken(account) !== null;
1744
1826
  if ((options.allowPlaintextTokenStore || hasPlaintextEntry) && await writePlaintextToken(account, value)) return {
1745
1827
  ok: true,
@@ -1849,18 +1931,19 @@ function accountName(profile, baseUrl) {
1849
1931
  let nativeStorePromise;
1850
1932
  function nativeStore() {
1851
1933
  if (process.env.ARTIFACTSHARE_DISABLE_NATIVE_TOKEN_STORE === "1") return Promise.resolve(null);
1852
- return nativeStorePromise ??= detectNativeStore();
1934
+ return nativeStorePromise ??= detectNativeStore(process.platform);
1853
1935
  }
1854
- async function detectNativeStore() {
1855
- if (process.platform === "darwin") return macosKeychain();
1856
- if (process.platform === "linux") return await linuxSecretService();
1936
+ async function detectNativeStore(platform, run = spawnFile) {
1937
+ if (platform === "darwin") return macosKeychain(run);
1938
+ if (platform === "linux") return await linuxSecretService(run);
1939
+ if (platform === "win32") return await windowsCredentialManager(run);
1857
1940
  return null;
1858
1941
  }
1859
- function macosKeychain() {
1942
+ function macosKeychain(run) {
1860
1943
  return {
1861
1944
  kind: "macos_keychain",
1862
1945
  read: async (account) => {
1863
- const result = await spawnFile("security", [
1946
+ const result = await run("security", [
1864
1947
  "find-generic-password",
1865
1948
  "-s",
1866
1949
  SERVICE,
@@ -1871,7 +1954,7 @@ function macosKeychain() {
1871
1954
  return result.status === 0 ? result.stdout.trim() || null : null;
1872
1955
  },
1873
1956
  write: async (account, token) => {
1874
- return (await spawnFile("security", ["-i"], `${[
1957
+ return (await run("security", ["-i"], `${[
1875
1958
  "add-generic-password",
1876
1959
  "-U",
1877
1960
  "-s",
@@ -1883,7 +1966,7 @@ function macosKeychain() {
1883
1966
  ].join(" ")}\n`)).status === 0;
1884
1967
  },
1885
1968
  delete: async (account) => {
1886
- return (await spawnFile("security", [
1969
+ return (await run("security", [
1887
1970
  "delete-generic-password",
1888
1971
  "-s",
1889
1972
  SERVICE,
@@ -1896,12 +1979,12 @@ function macosKeychain() {
1896
1979
  function securityQuote(value) {
1897
1980
  return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
1898
1981
  }
1899
- async function linuxSecretService() {
1900
- if ((await spawnFile("secret-tool", ["--version"])).status !== 0) return null;
1982
+ async function linuxSecretService(run) {
1983
+ if ((await run("secret-tool", ["--version"])).status !== 0) return null;
1901
1984
  return {
1902
1985
  kind: "linux_secret_service",
1903
1986
  read: async (account) => {
1904
- const result = await spawnFile("secret-tool", [
1987
+ const result = await run("secret-tool", [
1905
1988
  "lookup",
1906
1989
  "service",
1907
1990
  SERVICE,
@@ -1911,7 +1994,7 @@ async function linuxSecretService() {
1911
1994
  return result.status === 0 ? result.stdout.trim() || null : null;
1912
1995
  },
1913
1996
  write: async (account, token) => {
1914
- return (await spawnFile("secret-tool", [
1997
+ return (await run("secret-tool", [
1915
1998
  "store",
1916
1999
  "--label",
1917
2000
  `Artifact Share ${account}`,
@@ -1922,7 +2005,7 @@ async function linuxSecretService() {
1922
2005
  ], token)).status === 0;
1923
2006
  },
1924
2007
  delete: async (account) => {
1925
- return (await spawnFile("secret-tool", [
2008
+ return (await run("secret-tool", [
1926
2009
  "clear",
1927
2010
  "service",
1928
2011
  SERVICE,
@@ -1932,6 +2015,274 @@ async function linuxSecretService() {
1932
2015
  }
1933
2016
  };
1934
2017
  }
2018
+ const WINDOWS_CREDENTIAL_SCRIPT = String.raw`
2019
+ $ErrorActionPreference = 'Stop'
2020
+ Add-Type -TypeDefinition @'
2021
+ using System;
2022
+ using System.ComponentModel;
2023
+ using System.Runtime.InteropServices;
2024
+
2025
+ public static class ArtifactShareCredentialManager {
2026
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
2027
+ private struct Credential {
2028
+ public UInt32 Flags;
2029
+ public UInt32 Type;
2030
+ public string TargetName;
2031
+ public string Comment;
2032
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
2033
+ public UInt32 CredentialBlobSize;
2034
+ public IntPtr CredentialBlob;
2035
+ public UInt32 Persist;
2036
+ public UInt32 AttributeCount;
2037
+ public IntPtr Attributes;
2038
+ public string TargetAlias;
2039
+ public string UserName;
2040
+ }
2041
+
2042
+ [DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
2043
+ private static extern bool CredRead(string target, UInt32 type, UInt32 flags, out IntPtr credential);
2044
+
2045
+ [DllImport("advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)]
2046
+ private static extern bool CredWrite(ref Credential credential, UInt32 flags);
2047
+
2048
+ [DllImport("advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode, SetLastError = true)]
2049
+ private static extern bool CredDelete(string target, UInt32 type, UInt32 flags);
2050
+
2051
+ [DllImport("advapi32.dll", EntryPoint = "CredFree")]
2052
+ private static extern void CredFree(IntPtr credential);
2053
+
2054
+ private const UInt32 Generic = 1;
2055
+ private const UInt32 PersistLocalMachine = 2;
2056
+ private const int ErrorNotFound = 1168;
2057
+
2058
+ public static bool Probe() { return true; }
2059
+
2060
+ public static byte[] Read(string target) {
2061
+ IntPtr pointer;
2062
+ if (!CredRead(target, Generic, 0, out pointer)) {
2063
+ int error = Marshal.GetLastWin32Error();
2064
+ if (error == ErrorNotFound) return null;
2065
+ throw new Win32Exception(error);
2066
+ }
2067
+ try {
2068
+ Credential credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
2069
+ byte[] value = new byte[credential.CredentialBlobSize];
2070
+ if (value.Length > 0) Marshal.Copy(credential.CredentialBlob, value, 0, value.Length);
2071
+ return value;
2072
+ } finally {
2073
+ CredFree(pointer);
2074
+ }
2075
+ }
2076
+
2077
+ public static void Write(string target, byte[] value) {
2078
+ IntPtr blob = Marshal.AllocHGlobal(value.Length);
2079
+ try {
2080
+ if (value.Length > 0) Marshal.Copy(value, 0, blob, value.Length);
2081
+ Credential credential = new Credential {
2082
+ Type = Generic,
2083
+ TargetName = target,
2084
+ CredentialBlobSize = (UInt32)value.Length,
2085
+ CredentialBlob = blob,
2086
+ Persist = PersistLocalMachine,
2087
+ UserName = Environment.UserName
2088
+ };
2089
+ if (!CredWrite(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
2090
+ } finally {
2091
+ Marshal.FreeHGlobal(blob);
2092
+ }
2093
+ }
2094
+
2095
+ public static void Delete(string target) {
2096
+ if (!CredDelete(target, Generic, 0)) {
2097
+ int error = Marshal.GetLastWin32Error();
2098
+ if (error != ErrorNotFound) throw new Win32Exception(error);
2099
+ }
2100
+ }
2101
+ }
2102
+ '@
2103
+
2104
+ $requestJson = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd()))
2105
+ $request = $requestJson | ConvertFrom-Json
2106
+ $target = 'artifactshare-cli:' + [string]$request.account
2107
+ $chunkSize = 2400
2108
+ $chunkMarker = 'artifactshare-chunks-v1:'
2109
+ $deletingMarker = 'artifactshare-chunks-deleting-v1:'
2110
+ $cleanupMarker = 'artifactshare-chunks-cleanup-v1:'
2111
+
2112
+ function Get-ChunkManifest([byte[]]$bytes, [string]$marker = $chunkMarker) {
2113
+ if ($null -eq $bytes) { return $null }
2114
+ $text = [Text.Encoding]::UTF8.GetString($bytes)
2115
+ if (-not $text.StartsWith($marker)) { return $null }
2116
+ $parts = $text.Substring($marker.Length).Split(':')
2117
+ $count = 0
2118
+ if ($parts.Length -ne 2 -or -not [int]::TryParse($parts[1], [ref]$count) -or $count -lt 1) {
2119
+ throw 'Invalid chunked credential manifest.'
2120
+ }
2121
+ return [PSCustomObject]@{ Version = $parts[0]; Count = $count }
2122
+ }
2123
+
2124
+ function Get-CleanupManifest([byte[]]$bytes) {
2125
+ if ($null -eq $bytes) { return $null }
2126
+ $text = [Text.Encoding]::UTF8.GetString($bytes)
2127
+ if (-not $text.StartsWith($cleanupMarker)) { return $null }
2128
+ $parts = $text.Substring($cleanupMarker.Length).Split(':')
2129
+ $activeCount = 0
2130
+ $staleCount = 0
2131
+ if (
2132
+ $parts.Length -ne 4 -or
2133
+ -not [int]::TryParse($parts[1], [ref]$activeCount) -or
2134
+ -not [int]::TryParse($parts[3], [ref]$staleCount) -or
2135
+ $activeCount -lt 1 -or
2136
+ $staleCount -lt 1
2137
+ ) {
2138
+ throw 'Invalid credential cleanup manifest.'
2139
+ }
2140
+ return [PSCustomObject]@{
2141
+ Active = [PSCustomObject]@{ Version = $parts[0]; Count = $activeCount }
2142
+ Stale = [PSCustomObject]@{ Version = $parts[2]; Count = $staleCount }
2143
+ }
2144
+ }
2145
+
2146
+ function Remove-CredentialChunks($manifest) {
2147
+ if ($null -eq $manifest) { return }
2148
+ for ($index = 0; $index -lt $manifest.Count; $index++) {
2149
+ [ArtifactShareCredentialManager]::Delete(($target + ':chunk:' + $manifest.Version + ':' + $index))
2150
+ }
2151
+ }
2152
+
2153
+ switch ([string]$request.operation) {
2154
+ 'probe' { [void][ArtifactShareCredentialManager]::Probe() }
2155
+ 'read' {
2156
+ $bytes = [ArtifactShareCredentialManager]::Read($target)
2157
+ $deletingManifest = Get-ChunkManifest $bytes $deletingMarker
2158
+ if ($null -ne $deletingManifest) { break }
2159
+ $cleanupManifest = Get-CleanupManifest($bytes)
2160
+ $manifest = if ($null -ne $cleanupManifest) {
2161
+ $cleanupManifest.Active
2162
+ } else {
2163
+ Get-ChunkManifest($bytes)
2164
+ }
2165
+ if ($null -ne $manifest) {
2166
+ $stream = New-Object IO.MemoryStream
2167
+ try {
2168
+ for ($index = 0; $index -lt $manifest.Count; $index++) {
2169
+ $chunkTarget = $target + ':chunk:' + $manifest.Version + ':' + $index
2170
+ $chunk = [ArtifactShareCredentialManager]::Read($chunkTarget)
2171
+ if ($null -eq $chunk) { throw 'Credential chunk is missing.' }
2172
+ $stream.Write($chunk, 0, $chunk.Length)
2173
+ }
2174
+ $bytes = $stream.ToArray()
2175
+ } finally {
2176
+ $stream.Dispose()
2177
+ }
2178
+ }
2179
+ if ($null -ne $bytes) { [Console]::Out.Write([Convert]::ToBase64String($bytes)) }
2180
+ }
2181
+ 'write' {
2182
+ $oldBytes = [ArtifactShareCredentialManager]::Read($target)
2183
+ $pendingCleanup = Get-CleanupManifest($oldBytes)
2184
+ if ($null -ne $pendingCleanup) {
2185
+ Remove-CredentialChunks($pendingCleanup.Stale)
2186
+ $oldManifest = $pendingCleanup.Active
2187
+ $oldBytes = [Text.Encoding]::UTF8.GetBytes(($chunkMarker + $oldManifest.Version + ':' + $oldManifest.Count))
2188
+ [ArtifactShareCredentialManager]::Write($target, $oldBytes)
2189
+ } else {
2190
+ $oldManifest = Get-ChunkManifest($oldBytes)
2191
+ }
2192
+ if ($null -eq $oldManifest) {
2193
+ $oldManifest = Get-ChunkManifest $oldBytes $deletingMarker
2194
+ if ($null -ne $oldManifest) {
2195
+ Remove-CredentialChunks($oldManifest)
2196
+ $oldManifest = $null
2197
+ }
2198
+ }
2199
+ $bytes = [Text.Encoding]::UTF8.GetBytes([string]$request.value)
2200
+ if ($bytes.Length -le $chunkSize -and $null -eq $oldManifest) {
2201
+ [ArtifactShareCredentialManager]::Write($target, $bytes)
2202
+ } else {
2203
+ $version = [Guid]::NewGuid().ToString('N')
2204
+ $count = [int][Math]::Ceiling($bytes.Length / $chunkSize)
2205
+ $written = 0
2206
+ try {
2207
+ for ($index = 0; $index -lt $count; $index++) {
2208
+ $offset = [int]($index * $chunkSize)
2209
+ $length = [int][Math]::Min($chunkSize, $bytes.Length - $offset)
2210
+ $chunk = New-Object byte[] $length
2211
+ [Array]::Copy($bytes, $offset, $chunk, 0, $length)
2212
+ $chunkTarget = $target + ':chunk:' + $version + ':' + $index
2213
+ [ArtifactShareCredentialManager]::Write($chunkTarget, $chunk)
2214
+ $written++
2215
+ }
2216
+ $manifestBytes = [Text.Encoding]::UTF8.GetBytes(($chunkMarker + $version + ':' + $count))
2217
+ if ($null -ne $oldManifest) {
2218
+ $cleanupBytes = [Text.Encoding]::UTF8.GetBytes(
2219
+ ($cleanupMarker + $version + ':' + $count + ':' + $oldManifest.Version + ':' + $oldManifest.Count)
2220
+ )
2221
+ [ArtifactShareCredentialManager]::Write($target, $cleanupBytes)
2222
+ $written = 0
2223
+ Remove-CredentialChunks($oldManifest)
2224
+ }
2225
+ [ArtifactShareCredentialManager]::Write($target, $manifestBytes)
2226
+ } catch {
2227
+ for ($index = 0; $index -lt $written; $index++) {
2228
+ [ArtifactShareCredentialManager]::Delete(($target + ':chunk:' + $version + ':' + $index))
2229
+ }
2230
+ throw
2231
+ }
2232
+ }
2233
+ }
2234
+ 'delete' {
2235
+ $bytes = [ArtifactShareCredentialManager]::Read($target)
2236
+ $pendingCleanup = Get-CleanupManifest($bytes)
2237
+ if ($null -ne $pendingCleanup) {
2238
+ Remove-CredentialChunks($pendingCleanup.Stale)
2239
+ $manifest = $pendingCleanup.Active
2240
+ } else {
2241
+ $manifest = Get-ChunkManifest($bytes)
2242
+ }
2243
+ if ($null -eq $manifest) {
2244
+ $manifest = Get-ChunkManifest $bytes $deletingMarker
2245
+ }
2246
+ if ($null -ne $manifest) {
2247
+ $deletingBytes = [Text.Encoding]::UTF8.GetBytes(($deletingMarker + $manifest.Version + ':' + $manifest.Count))
2248
+ [ArtifactShareCredentialManager]::Write($target, $deletingBytes)
2249
+ Remove-CredentialChunks($manifest)
2250
+ }
2251
+ [ArtifactShareCredentialManager]::Delete($target)
2252
+ }
2253
+ default { throw 'Unknown credential operation.' }
2254
+ }
2255
+ `;
2256
+ const WINDOWS_CREDENTIAL_COMMAND = Buffer.from(WINDOWS_CREDENTIAL_SCRIPT, "utf16le").toString("base64");
2257
+ async function runWindowsCredentialOperation(run, operation, account = "", value) {
2258
+ return await run("powershell.exe", [
2259
+ "-NoProfile",
2260
+ "-NonInteractive",
2261
+ "-EncodedCommand",
2262
+ WINDOWS_CREDENTIAL_COMMAND
2263
+ ], Buffer.from(JSON.stringify({
2264
+ operation,
2265
+ account,
2266
+ ...value === void 0 ? {} : { value }
2267
+ }), "utf8").toString("base64"));
2268
+ }
2269
+ async function windowsCredentialManager(run) {
2270
+ if ((await runWindowsCredentialOperation(run, "probe")).status !== 0) return null;
2271
+ return {
2272
+ kind: "windows_credential_manager",
2273
+ read: async (account) => {
2274
+ const result = await runWindowsCredentialOperation(run, "read", account);
2275
+ if (result.status !== 0 || !result.stdout) return null;
2276
+ return Buffer.from(result.stdout, "base64").toString("utf8");
2277
+ },
2278
+ write: async (account, token) => {
2279
+ return (await runWindowsCredentialOperation(run, "write", account, token)).status === 0;
2280
+ },
2281
+ delete: async (account) => {
2282
+ return (await runWindowsCredentialOperation(run, "delete", account)).status === 0;
2283
+ }
2284
+ };
2285
+ }
1935
2286
  async function deletePlaintextTokenAccount(account) {
1936
2287
  const tokens = await readPlaintextTokens();
1937
2288
  if (!tokens || !Object.hasOwn(tokens, account)) return false;
@@ -1955,6 +2306,7 @@ async function readPlaintextToken(account) {
1955
2306
  async function writePlaintextToken(account, token) {
1956
2307
  const home = configHome();
1957
2308
  if (!home) return false;
2309
+ if (!plaintextFallbackSupported()) return false;
1958
2310
  const tokens = await readPlaintextTokens() ?? {};
1959
2311
  tokens[account] = token;
1960
2312
  await mkdir(home, {
@@ -2050,15 +2402,42 @@ function isPendingDeviceAuth(value) {
2050
2402
  if (!isRecord(value)) return false;
2051
2403
  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";
2052
2404
  }
2053
- function configHome() {
2054
- const override = nonEmpty(process.env.ARTIFACTSHARE_CONFIG_HOME);
2405
+ function resolveConfigHome(env, fallbackHome = homedir, platform = process.platform) {
2406
+ const override = nonEmpty(env.ARTIFACTSHARE_CONFIG_HOME);
2055
2407
  if (override) return override;
2056
- const xdgConfigHome = nonEmpty(process.env.XDG_CONFIG_HOME);
2408
+ const xdgConfigHome = nonEmpty(env.XDG_CONFIG_HOME);
2057
2409
  if (xdgConfigHome) return join(xdgConfigHome, "artifactshare");
2058
- const home = nonEmpty(process.env.HOME);
2410
+ const home = platform === "win32" ? nonEmpty(env.USERPROFILE) ?? nonEmpty(env.HOME) : nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE);
2059
2411
  if (home) return join(home, ".config/artifactshare");
2412
+ try {
2413
+ const detectedHome = nonEmpty(fallbackHome());
2414
+ if (detectedHome) return join(detectedHome, ".config/artifactshare");
2415
+ } catch {}
2060
2416
  return null;
2061
2417
  }
2418
+ function configHome() {
2419
+ return resolveConfigHome(process.env);
2420
+ }
2421
+ function plaintextFallbackSupported(platform = process.platform) {
2422
+ return platform !== "win32";
2423
+ }
2424
+ function plaintextStoreWritable(platform = process.platform) {
2425
+ if (!configHome()) return false;
2426
+ return plaintextFallbackSupported(platform);
2427
+ }
2428
+ async function tokenStoreDiagnostics() {
2429
+ const home = configHome();
2430
+ const native = await nativeStore();
2431
+ const plaintext = await readPlaintextTokens();
2432
+ const plaintextCredentials = plaintext ? Object.values(plaintext).filter((value) => typeof value === "string" && value.length > 0).length : 0;
2433
+ const plaintextProtection = home && process.platform !== "win32" ? "mode_0600" : "unavailable";
2434
+ return {
2435
+ config_home: home,
2436
+ native_store: native?.kind ?? "none",
2437
+ plaintext_credentials: plaintextCredentials,
2438
+ plaintext_protection: plaintextProtection
2439
+ };
2440
+ }
2062
2441
  //#endregion
2063
2442
  //#region src/credentials.ts
2064
2443
  async function resolveCredential(options, projectInput = null) {
@@ -2121,6 +2500,7 @@ async function resolveProfileCredential(source, profile, options, globalConfig,
2121
2500
  profile,
2122
2501
  token: stored.token,
2123
2502
  profileCredentialKind: stored.credential.kind,
2503
+ botProfile: globalConfig?.profiles?.[profile]?.kind === "bot",
2124
2504
  ...stored.credential.kind === "session" ? { refreshToken: stored.credential.refresh_token } : {}
2125
2505
  };
2126
2506
  return profileAuthRequired(source, profile, stored.reason, options, globalConfig, configPath, configKind);
@@ -2515,7 +2895,7 @@ async function writeProfileConfig(profile, options, tokenStore, whoami) {
2515
2895
  profiles: {
2516
2896
  ...profiles,
2517
2897
  [profile]: {
2518
- ...currentProfile,
2898
+ ...currentProfile ? Object.fromEntries(Object.entries(currentProfile).filter(([key]) => key !== "kind")) : {},
2519
2899
  base_url: baseUrlOf(options),
2520
2900
  email: whoami.email ?? currentProfile?.email ?? null,
2521
2901
  workspace_id: whoami.workspace_id,
@@ -2590,6 +2970,10 @@ async function canAttemptProfileTokenSave(profile, options) {
2590
2970
  }
2591
2971
  async function handleCredentialFailure(command, credential, options, mode, rerun, isRetry = false, deps = {}) {
2592
2972
  if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
2973
+ const failedProfile = profileForAutoLogin(credential);
2974
+ if (failedProfile) {
2975
+ if ((await readGlobalConfig())?.profiles?.[failedProfile]?.kind === "bot") return writeFailure(command, botReauthRequiredError(failedProfile), mode, 1);
2976
+ }
2593
2977
  if (mode.json && JSON_PENDING_AUTH_COMMANDS.has(command) && !isRetry) return handleJsonPendingAuth(command, credential, options, mode, rerun);
2594
2978
  if (!isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
2595
2979
  const performLogin = deps.performLogin ?? performDeviceLogin;
@@ -2640,6 +3024,10 @@ async function runAuthenticatedApi(credential, options, request) {
2640
3024
  async function refreshStoredProfileSession(profile, refreshToken, options) {
2641
3025
  const stored = await readProfileToken(profile, options);
2642
3026
  if (!stored.ok || stored.credential.kind !== "session") return { ok: false };
3027
+ if (!await probeTokenStoreWritable(profile, options)) return {
3028
+ ok: false,
3029
+ error: tokenStoreUnavailableError(profile, "native_store_unavailable")
3030
+ };
2643
3031
  const rotationRequestId = stored.credential.pending_rotation_id ?? randomUUID();
2644
3032
  if (!stored.credential.pending_rotation_id) {
2645
3033
  if (!(await saveProfileSessionCredential(profile, {
@@ -2647,7 +3035,7 @@ async function refreshStoredProfileSession(profile, refreshToken, options) {
2647
3035
  pending_rotation_id: rotationRequestId
2648
3036
  }, options)).ok) return {
2649
3037
  ok: false,
2650
- error: tokenStoreUnavailableError(profile)
3038
+ error: tokenStoreUnavailableError(profile, "store_operation_failed")
2651
3039
  };
2652
3040
  }
2653
3041
  const request = await requestConfig(options);
@@ -2684,7 +3072,7 @@ async function refreshStoredProfileSession(profile, refreshToken, options) {
2684
3072
  expires_at: body.expires_at
2685
3073
  }, options)).ok) return {
2686
3074
  ok: false,
2687
- error: tokenStoreUnavailableError(profile)
3075
+ error: tokenStoreUnavailableError(profile, "store_operation_failed")
2688
3076
  };
2689
3077
  return {
2690
3078
  ok: true,
@@ -2697,7 +3085,8 @@ async function handleJsonPendingAuth(command, credential, options, mode, rerun)
2697
3085
  const baseUrl = baseUrlOf(options);
2698
3086
  const request = await requestConfig(options);
2699
3087
  if (request.error) return writeFailure(command, request.error, mode, 1);
2700
- if (!await canAttemptProfileTokenSave(profile, options)) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
3088
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
3089
+ if (!await canAttemptProfileTokenSave(profile, options)) return writeFailure(command, tokenStoreUnavailableError(profile, "native_store_unavailable"), mode, 1);
2701
3090
  const existing = await readPendingDeviceAuth(baseUrl, profile);
2702
3091
  if (existing && !isPendingExpired(existing)) {
2703
3092
  const exchange = await exchangeDeviceTokenOnce(options, existing.device_code, request.init);
@@ -2782,7 +3171,8 @@ async function fetchArtifact(parsed, target, credential) {
2782
3171
  baseUrl: baseUrlOf(parsed.options),
2783
3172
  credentialSource: credential.source,
2784
3173
  profile: credential.profile,
2785
- profileCredentialKind: credential.profileCredentialKind
3174
+ profileCredentialKind: credential.profileCredentialKind,
3175
+ botProfile: credential.botProfile
2786
3176
  }) };
2787
3177
  if (!artifactGetSuccessFields(body)) return { error: serviceError("Artifact read succeeded but the response did not include source metadata.") };
2788
3178
  return { data: body };
@@ -2817,7 +3207,8 @@ async function runArtifactsList(parsed, mode) {
2817
3207
  baseUrl: baseUrlOf(parsed.options),
2818
3208
  credentialSource: current.source,
2819
3209
  profile: current.profile,
2820
- profileCredentialKind: current.profileCredentialKind
3210
+ profileCredentialKind: current.profileCredentialKind,
3211
+ botProfile: current.botProfile
2821
3212
  }) };
2822
3213
  return { data: body };
2823
3214
  });
@@ -3329,7 +3720,8 @@ async function runCommentsList(parsed, mode) {
3329
3720
  artifactTarget: true,
3330
3721
  credentialSource: current.source,
3331
3722
  profile: current.profile,
3332
- profileCredentialKind: current.profileCredentialKind
3723
+ profileCredentialKind: current.profileCredentialKind,
3724
+ botProfile: current.botProfile
3333
3725
  });
3334
3726
  return comments.error ? { error: comments.error } : { data: comments.body };
3335
3727
  });
@@ -3371,7 +3763,8 @@ async function runCommentsPost(parsed, mode) {
3371
3763
  artifactTarget: true,
3372
3764
  credentialSource: current.source,
3373
3765
  profile: current.profile,
3374
- profileCredentialKind: current.profileCredentialKind
3766
+ profileCredentialKind: current.profileCredentialKind,
3767
+ botProfile: current.botProfile
3375
3768
  });
3376
3769
  return posted.error ? { error: posted.error } : { data: posted.body };
3377
3770
  });
@@ -3477,7 +3870,8 @@ async function postCommentAction(parsed, command, artifactId, payload, mode) {
3477
3870
  artifactTarget: true,
3478
3871
  credentialSource: current.source,
3479
3872
  profile: current.profile,
3480
- profileCredentialKind: current.profileCredentialKind
3873
+ profileCredentialKind: current.profileCredentialKind,
3874
+ botProfile: current.botProfile
3481
3875
  });
3482
3876
  return action.error ? { error: action.error } : { data: action.body };
3483
3877
  });
@@ -3512,7 +3906,8 @@ async function runDelete(parsed, mode) {
3512
3906
  artifactTarget: true,
3513
3907
  credentialSource: current.source,
3514
3908
  profile: current.profile,
3515
- profileCredentialKind: current.profileCredentialKind
3909
+ profileCredentialKind: current.profileCredentialKind,
3910
+ botProfile: current.botProfile
3516
3911
  });
3517
3912
  return deleted.error ? { error: deleted.error } : { data: deleted.body };
3518
3913
  });
@@ -3564,11 +3959,13 @@ async function runDoctor(parsed, mode) {
3564
3959
  const data = {
3565
3960
  next_command: null,
3566
3961
  base_url: baseUrlOf(parsed.options),
3962
+ token_store: await tokenStoreDiagnostics(),
3567
3963
  config: await configDiagnostics(project),
3568
3964
  skills: await skillDiagnostics(),
3569
3965
  auth: {
3570
3966
  credential_source: credential.source,
3571
3967
  ...credential.profile ? { profile: credential.profile } : {},
3968
+ ...credential.ok && credential.botProfile ? { profile_kind: "bot" } : {},
3572
3969
  token_present: credential.ok,
3573
3970
  ok: false
3574
3971
  },
@@ -3610,7 +4007,8 @@ async function runDoctor(parsed, mode) {
3610
4007
  baseUrl: baseUrlOf(parsed.options),
3611
4008
  credentialSource: current.source,
3612
4009
  profile: current.profile,
3613
- profileCredentialKind: current.profileCredentialKind
4010
+ profileCredentialKind: current.profileCredentialKind,
4011
+ botProfile: current.botProfile
3614
4012
  }) };
3615
4013
  return { data: {
3616
4014
  kind: "body",
@@ -4002,7 +4400,8 @@ async function runDownload(parsed, mode, isRetry = false) {
4002
4400
  baseUrl,
4003
4401
  credentialSource: credential.source,
4004
4402
  profile: credential.profile,
4005
- profileCredentialKind: credential.profileCredentialKind
4403
+ profileCredentialKind: credential.profileCredentialKind,
4404
+ botProfile: credential.botProfile
4006
4405
  }), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
4007
4406
  if (!downloadManifestFields(body)) return writeFailure(command, serviceError("Download manifest succeeded but the response did not include file metadata."), mode, 1);
4008
4407
  const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force));
@@ -4022,7 +4421,8 @@ async function runDownload(parsed, mode, isRetry = false) {
4022
4421
  baseUrl,
4023
4422
  credentialSource: credential.source,
4024
4423
  profile: credential.profile,
4025
- profileCredentialKind: credential.profileCredentialKind
4424
+ profileCredentialKind: credential.profileCredentialKind,
4425
+ botProfile: credential.botProfile
4026
4426
  }), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
4027
4427
  const bytes = Buffer.from(await fileResponse.arrayBuffer());
4028
4428
  const verified = verifyDownloadedBytes(file, bytes);
@@ -4087,7 +4487,8 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
4087
4487
  artifactTarget: true,
4088
4488
  credentialSource: credential.source,
4089
4489
  profile: credential.profile,
4090
- profileCredentialKind: credential.profileCredentialKind
4490
+ profileCredentialKind: credential.profileCredentialKind,
4491
+ botProfile: credential.botProfile
4091
4492
  }), credential, parsed.options, isRetry);
4092
4493
  if (!refreshed.ok) return response;
4093
4494
  credential = {
@@ -4115,7 +4516,8 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
4115
4516
  artifactTarget: true,
4116
4517
  credentialSource: credential.source,
4117
4518
  profile: credential.profile,
4118
- profileCredentialKind: credential.profileCredentialKind
4519
+ profileCredentialKind: credential.profileCredentialKind,
4520
+ botProfile: credential.botProfile
4119
4521
  }),
4120
4522
  authFailure: response.status === 401
4121
4523
  };
@@ -4285,7 +4687,8 @@ async function runEdit(parsed, mode) {
4285
4687
  editSettings: true,
4286
4688
  credentialSource: current.source,
4287
4689
  profile: current.profile,
4288
- profileCredentialKind: current.profileCredentialKind
4690
+ profileCredentialKind: current.profileCredentialKind,
4691
+ botProfile: current.botProfile
4289
4692
  });
4290
4693
  return edited.error ? { error: edited.error } : { data: edited.body };
4291
4694
  });
@@ -4495,7 +4898,7 @@ async function runInitConfig(parsed, mode, profile, projectId) {
4495
4898
  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);
4496
4899
  const resolved = await resolveProjectConfig();
4497
4900
  if (profile) {
4498
- if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
4901
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
4499
4902
  const globalConfig = await readGlobalConfig();
4500
4903
  if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
4501
4904
  }
@@ -4546,7 +4949,7 @@ function optionsForProfileEntry(rawEntry, options) {
4546
4949
  async function runLogout(parsed, mode) {
4547
4950
  const command = "logout";
4548
4951
  const explicitProfile = nonEmpty(parsed.options.profile);
4549
- if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
4952
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(explicitProfile), mode, 1);
4550
4953
  const config = await readGlobalConfig() ?? {};
4551
4954
  let profile;
4552
4955
  if (explicitProfile) {
@@ -4573,7 +4976,7 @@ async function runLogout(parsed, mode) {
4573
4976
  if (!revoked.response.ok && revoked.response.status !== 401) return writeFailure(command, mapApiError(revoked.response.status, revoked.body, { baseUrl: baseUrlOf(profileOptions) }), mode, 1);
4574
4977
  }
4575
4978
  const deleted = await deleteCredentialForProfileEntry(profile, rawEntry, parsed.options);
4576
- if (!deleted.ok) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
4979
+ if (!deleted.ok) return writeFailure(command, tokenStoreUnavailableError(profile, "store_operation_failed"), mode, 1);
4577
4980
  return writeSuccess(command, {
4578
4981
  profile,
4579
4982
  credential_removed: deleted.credential_removed,
@@ -4600,7 +5003,8 @@ async function runMove(parsed, mode) {
4600
5003
  artifactTarget: true,
4601
5004
  credentialSource: current.source,
4602
5005
  profile: current.profile,
4603
- profileCredentialKind: current.profileCredentialKind
5006
+ profileCredentialKind: current.profileCredentialKind,
5007
+ botProfile: current.botProfile
4604
5008
  });
4605
5009
  return moved.error ? { error: moved.error } : { data: moved.body };
4606
5010
  });
@@ -4659,7 +5063,7 @@ async function readStdinToken() {
4659
5063
  }
4660
5064
  async function runProfilesList(parsed, mode) {
4661
5065
  const command = "profiles list";
4662
- if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
5066
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(), mode, 1);
4663
5067
  const config = await readGlobalConfig() ?? {};
4664
5068
  const defaultProfile = nonEmpty(config.default_profile) ?? null;
4665
5069
  const profiles = await Promise.all(Object.entries(config.profiles ?? {}).map(async ([name, rawEntry]) => {
@@ -4676,7 +5080,8 @@ async function runProfilesList(parsed, mode) {
4676
5080
  token_store: entry.token_store ?? null,
4677
5081
  updated_at: nonEmpty(entry.updated_at) ?? null,
4678
5082
  is_default: name === defaultProfile,
4679
- token_present: stored.ok
5083
+ token_present: stored.ok,
5084
+ ...entry.kind === "bot" ? { kind: "bot" } : {}
4680
5085
  };
4681
5086
  }));
4682
5087
  writeSuccess(command, {
@@ -4689,7 +5094,7 @@ async function runProfilesUse(parsed, mode) {
4689
5094
  const command = "profiles use";
4690
5095
  const name = nonEmpty(parsed.positionals[0]);
4691
5096
  if (!name) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles use <name>.`), mode, 1);
4692
- if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
5097
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(name), mode, 1);
4693
5098
  const config = await readGlobalConfig() ?? {};
4694
5099
  if (!Object.hasOwn(config.profiles ?? {}, name)) return writeFailure(command, profileNotFoundError(name), mode, 1);
4695
5100
  const previous = nonEmpty(config.default_profile) ?? null;
@@ -4706,7 +5111,7 @@ async function runProfilesImportToken(parsed, mode) {
4706
5111
  const command = "profiles import-token";
4707
5112
  const profile = nonEmpty(parsed.options.profile);
4708
5113
  if (!profile) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles import-token --profile <name>.`), mode, 1);
4709
- if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
5114
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
4710
5115
  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);
4711
5116
  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);
4712
5117
  let token;
@@ -4716,6 +5121,7 @@ async function runProfilesImportToken(parsed, mode) {
4716
5121
  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);
4717
5122
  }
4718
5123
  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);
5124
+ if (token.startsWith("asb_")) return await importBotTokenProfile(command, profile, token, parsed, mode);
4719
5125
  const request = await requestConfig(parsed.options);
4720
5126
  if (request.error) return writeFailure(command, request.error, mode, 1);
4721
5127
  const stored = await verifyAndStoreApiTokenProfile(profile, token, parsed.options, request.init);
@@ -4732,12 +5138,12 @@ async function runProfilesDelete(parsed, mode) {
4732
5138
  const command = "profiles delete";
4733
5139
  const name = nonEmpty(parsed.positionals[0]);
4734
5140
  if (!name) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles delete <name>.`), mode, 1);
4735
- if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
5141
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(name), mode, 1);
4736
5142
  const config = await readGlobalConfig() ?? {};
4737
5143
  if (!Object.hasOwn(config.profiles ?? {}, name)) return writeFailure(command, profileNotFoundError(name), mode, 1);
4738
5144
  const rawEntry = config.profiles?.[name];
4739
5145
  const deleted = await deleteCredentialForProfileEntry(name, rawEntry, parsed.options);
4740
- if (!deleted.ok) return writeFailure(command, tokenStoreUnavailableError(name), mode, 1);
5146
+ if (!deleted.ok) return writeFailure(command, tokenStoreUnavailableError(name, "store_operation_failed"), mode, 1);
4741
5147
  const previousDefault = nonEmpty(config.default_profile) ?? null;
4742
5148
  const { [name]: _removed, ...restProfiles } = config.profiles ?? {};
4743
5149
  const defaultProfile = config.default_profile === name ? null : config.default_profile ?? null;
@@ -4755,6 +5161,94 @@ async function runProfilesDelete(parsed, mode) {
4755
5161
  default_profile: defaultProfile
4756
5162
  }, mode);
4757
5163
  }
5164
+ async function importBotTokenProfile(command, profile, token, parsed, mode) {
5165
+ const config = await readGlobalConfig() ?? {};
5166
+ const entry = isRecord(config.profiles?.[profile]) ? config.profiles?.[profile] : void 0;
5167
+ if (entry && parsed.options.force !== true) {
5168
+ if ((await readProfileToken(profile, {
5169
+ ...parsed.options,
5170
+ baseUrl: nonEmpty(entry.base_url) ?? baseUrlOf(parsed.options)
5171
+ })).ok) return writeFailure(command, validationError(`Profile "${profile}" already has a stored credential.`, `Re-run with --force to replace it: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --force`), mode, 1);
5172
+ }
5173
+ const request = await requestConfig(parsed.options);
5174
+ if (request.error) return writeFailure(command, request.error, mode, 1);
5175
+ const forcedReplace = Boolean(entry && parsed.options.force === true);
5176
+ if (!await probeTokenStoreWritable(profile, parsed.options, { ignoreExistingEntry: forcedReplace })) return writeFailure(command, tokenStoreUnavailableError(profile, "native_store_unavailable"), mode, 1);
5177
+ if (forcedReplace && entry) {
5178
+ if (!(await deleteCredentialForProfileEntry(profile, entry, parsed.options)).ok) return writeFailure(command, validationError(`The existing credential for profile "${profile}" could not be removed, so the forced import was aborted before consuming the token.`, "Fix the credential store (or remove the credential with logout --profile), then re-run the import; the bot token is still unconsumed."), mode, 1);
5179
+ }
5180
+ let configWritable = false;
5181
+ try {
5182
+ configWritable = await writeGlobalConfig(config);
5183
+ } catch {
5184
+ configWritable = false;
5185
+ }
5186
+ if (!configWritable) return writeFailure(command, tokenStoreUnavailableError(profile, "config_write_failed"), mode, 1);
5187
+ const rotationRequestId = randomUUID();
5188
+ let result = await apiPostPublic("/api/cli/auth/refresh", {
5189
+ refresh_token: token,
5190
+ rotation_request_id: rotationRequestId
5191
+ }, parsed.options, request.init);
5192
+ for (let retry = 0; result.error && retry < 2; retry += 1) result = await apiPostPublic("/api/cli/auth/refresh", {
5193
+ refresh_token: token,
5194
+ rotation_request_id: rotationRequestId
5195
+ }, parsed.options, request.init);
5196
+ if (result.error) return writeFailure(command, result.error, mode, 1);
5197
+ const { response, body } = result;
5198
+ if (!response.ok) {
5199
+ if (response.status === 401) return writeFailure(command, botTokenInvalidError(profile), mode, 1);
5200
+ return writeFailure(command, mapApiError(response.status, body, { baseUrl: baseUrlOf(parsed.options) }), mode, 1);
5201
+ }
5202
+ if (typeof body?.access_token !== "string" || body.access_token.length === 0 || typeof body.expires_at !== "string" || typeof body.refresh_token !== "string" || !body.refresh_token || typeof body.refresh_token_expires_at !== "string") return writeFailure(command, validationError("The refresh response was invalid.", "Ask a workspace administrator to reissue the bot token, then retry with the new token.", "service_error"), mode, 1);
5203
+ const saved = await saveProfileSessionCredential(profile, {
5204
+ kind: "session",
5205
+ session_token: body.access_token,
5206
+ refresh_token: body.refresh_token,
5207
+ expires_at: body.expires_at
5208
+ }, parsed.options);
5209
+ if (!saved.ok) return writeFailure(command, validationError("The rotated bot credential could not be stored; the imported token is now consumed and lost.", "Fix the token store, ask a workspace administrator to reissue the bot token, and import the new token.", "token_store_unavailable"), mode, 1);
5210
+ const whoamiResult = await apiGet("/api/cli/whoami", body.access_token, parsed.options, request.init, {
5211
+ authenticated: true,
5212
+ baseUrl: baseUrlOf(parsed.options)
5213
+ });
5214
+ const whoami = whoamiResult.error ? null : whoamiProfile(whoamiResult.body);
5215
+ const latest = await readGlobalConfig() ?? {};
5216
+ const profiles = latest.profiles ?? {};
5217
+ let configSaved = false;
5218
+ try {
5219
+ configSaved = await writeGlobalConfig({
5220
+ ...latest,
5221
+ default_profile: nonEmpty(latest.default_profile) ?? profile,
5222
+ profiles: {
5223
+ ...profiles,
5224
+ [profile]: {
5225
+ ...isRecord(profiles[profile]) ? profiles[profile] : {},
5226
+ kind: "bot",
5227
+ base_url: baseUrlOf(parsed.options),
5228
+ email: whoami?.email ?? null,
5229
+ workspace_id: whoami?.workspace_id ?? null,
5230
+ token_store: saved.store,
5231
+ preset: "agent",
5232
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
5233
+ }
5234
+ }
5235
+ });
5236
+ } catch {
5237
+ configSaved = false;
5238
+ }
5239
+ if (!configSaved) return writeFailure(command, validationError(`The rotated bot credential was stored, but the profile configuration for "${profile}" could not be written.`, "Without the config entry the profile loses its bot marker and later auth may attempt a human device login. Fix the config directory (disk space / permissions), then ask a workspace administrator to reissue the bot token and import it again.", "service_error"), mode, 1);
5240
+ return writeSuccess(command, {
5241
+ profile,
5242
+ token_store: saved.store,
5243
+ user: { email: whoami?.email ?? null },
5244
+ workspace: {
5245
+ id: whoami?.workspace_id ?? null,
5246
+ hosted_domain: whoami?.hosted_domain ?? null
5247
+ },
5248
+ base_url: baseUrlOf(parsed.options),
5249
+ kind: "bot"
5250
+ }, mode);
5251
+ }
4758
5252
  //#endregion
4759
5253
  //#region src/command-runners/projects.ts
4760
5254
  async function fetchProjects(token, options, init, errorOptions = {}) {
@@ -4784,7 +5278,8 @@ async function runProjectsList(parsed, mode) {
4784
5278
  const fetched = await fetchProjects(current.token, parsed.options, request.init, {
4785
5279
  credentialSource: current.source,
4786
5280
  profile: current.profile,
4787
- profileCredentialKind: current.profileCredentialKind
5281
+ profileCredentialKind: current.profileCredentialKind,
5282
+ botProfile: current.botProfile
4788
5283
  });
4789
5284
  return fetched.error ? { error: fetched.error } : { data: fetched.projects };
4790
5285
  });
@@ -4821,7 +5316,8 @@ async function runProjectsCreate(parsed, mode) {
4821
5316
  }, parsed.options, request.init, {
4822
5317
  credentialSource: current.source,
4823
5318
  profile: current.profile,
4824
- profileCredentialKind: current.profileCredentialKind
5319
+ profileCredentialKind: current.profileCredentialKind,
5320
+ botProfile: current.botProfile
4825
5321
  });
4826
5322
  return created.error ? { error: created.error } : { data: created.body };
4827
5323
  });
@@ -4855,7 +5351,8 @@ async function runProjectsEdit(parsed, mode) {
4855
5351
  projectTarget: true,
4856
5352
  credentialSource: current.source,
4857
5353
  profile: current.profile,
4858
- profileCredentialKind: current.profileCredentialKind
5354
+ profileCredentialKind: current.profileCredentialKind,
5355
+ botProfile: current.botProfile
4859
5356
  });
4860
5357
  return edited.error ? { error: edited.error } : { data: edited.body };
4861
5358
  });
@@ -4967,7 +5464,8 @@ async function runShare(parsed, mode, isRetry = false) {
4967
5464
  baseUrl,
4968
5465
  credentialSource: credential.source,
4969
5466
  profile: credential.profile,
4970
- profileCredentialKind: credential.profileCredentialKind
5467
+ profileCredentialKind: credential.profileCredentialKind,
5468
+ botProfile: credential.botProfile
4971
5469
  });
4972
5470
  if (resolved.error) return handleAuthenticatedCredentialFailure(command, resolved.error, credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
4973
5471
  const { project: _project, ...rest } = parsed.options;
@@ -5010,14 +5508,21 @@ async function runShare(parsed, mode, isRetry = false) {
5010
5508
  baseUrl,
5011
5509
  credentialSource: credential.source,
5012
5510
  profile: credential.profile,
5013
- profileCredentialKind: credential.profileCredentialKind
5511
+ profileCredentialKind: credential.profileCredentialKind,
5512
+ botProfile: credential.botProfile
5014
5513
  }), credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
5015
5514
  const id = body?.id ?? null;
5515
+ const url = body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null);
5516
+ const artifactKind = body?.artifactKind ?? upload.payload.kind;
5517
+ const warnings = Array.isArray(body?.warnings) ? body.warnings.flatMap((warning) => warning?.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [{
5518
+ code: "slack_reauthorization_required",
5519
+ message: warning.message
5520
+ }] : []) : [];
5016
5521
  return writeSuccess(command, {
5017
5522
  artifact: {
5018
5523
  id,
5019
- url: body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
5020
- kind: body?.artifactKind ?? upload.payload.kind
5524
+ url,
5525
+ kind: artifactKind
5021
5526
  },
5022
5527
  version: { id: body?.versionId ?? null },
5023
5528
  result: { created: body?.created ?? true },
@@ -5030,7 +5535,8 @@ async function runShare(parsed, mode, isRetry = false) {
5030
5535
  visibility: body?.visibility ?? requestedVisibility,
5031
5536
  grant_emails: grantEmails,
5032
5537
  link_expires_at: body?.link_expires_at ?? null
5033
- }
5538
+ },
5539
+ ...warnings.length > 0 ? { warnings } : {}
5034
5540
  }, mode);
5035
5541
  }
5036
5542
  async function resolveProjectIdByName(projectName, token, options, init, errorOptions) {
@@ -5072,7 +5578,8 @@ async function runResolve(parsed, mode) {
5072
5578
  baseUrl: baseUrlOf(parsed.options),
5073
5579
  credentialSource: current.source,
5074
5580
  profile: current.profile,
5075
- profileCredentialKind: current.profileCredentialKind
5581
+ profileCredentialKind: current.profileCredentialKind,
5582
+ botProfile: current.botProfile
5076
5583
  }) };
5077
5584
  return { data: body };
5078
5585
  });
@@ -5118,7 +5625,8 @@ async function runUpdate(parsed, mode, isRetry = false) {
5118
5625
  baseUrl,
5119
5626
  credentialSource: credential.source,
5120
5627
  profile: credential.profile,
5121
- profileCredentialKind: credential.profileCredentialKind
5628
+ profileCredentialKind: credential.profileCredentialKind,
5629
+ botProfile: credential.botProfile
5122
5630
  }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
5123
5631
  const id = body?.id ?? artifactId;
5124
5632
  const result = {
@@ -5174,7 +5682,8 @@ async function runAppend(parsed, mode, isRetry = false) {
5174
5682
  baseUrl: baseUrlOf(parsed.options),
5175
5683
  credentialSource: credential.source,
5176
5684
  profile: credential.profile,
5177
- profileCredentialKind: credential.profileCredentialKind
5685
+ profileCredentialKind: credential.profileCredentialKind,
5686
+ botProfile: credential.botProfile
5178
5687
  }), credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
5179
5688
  const success = {
5180
5689
  artifact: {
@@ -5200,7 +5709,8 @@ async function runWhoami(parsed, mode) {
5200
5709
  const result = await apiGet("/api/cli/whoami", current.token, parsed.options, request.init, {
5201
5710
  credentialSource: current.source,
5202
5711
  profile: current.profile,
5203
- profileCredentialKind: current.profileCredentialKind
5712
+ profileCredentialKind: current.profileCredentialKind,
5713
+ botProfile: current.botProfile
5204
5714
  });
5205
5715
  return result.error ? { error: result.error } : { data: result.body };
5206
5716
  });
@@ -5714,7 +6224,7 @@ const commonArgs = {
5714
6224
  allowPlaintextTokenStore: {
5715
6225
  type: "boolean",
5716
6226
  toKebab: true,
5717
- description: "Allow a 0600 file token store when no OS credential store is available"
6227
+ description: "Allow a plaintext token file (0600 on POSIX; unavailable on Windows)"
5718
6228
  },
5719
6229
  insecureLocalhost: {
5720
6230
  type: "boolean",
@@ -6466,22 +6976,30 @@ Common failures:
6466
6976
  });
6467
6977
  const profilesImportTokenDefinition = define({
6468
6978
  name: "import-token",
6469
- description: "Read an API token from standard input and save it to a CLI profile.",
6979
+ description: "Read an API token or bot token from standard input and save it to a CLI profile.",
6470
6980
  toKebab: true,
6471
6981
  args: {
6472
6982
  json: commonArgs.json,
6473
6983
  baseUrl: commonArgs.baseUrl,
6474
6984
  profile: commonArgs.profile,
6475
6985
  allowPlaintextTokenStore: commonArgs.allowPlaintextTokenStore,
6476
- insecureLocalhost: commonArgs.insecureLocalhost
6986
+ insecureLocalhost: commonArgs.insecureLocalhost,
6987
+ force: {
6988
+ type: "boolean",
6989
+ toKebab: true,
6990
+ description: "Replace an existing profile credential when importing a bot token (no-op for API tokens)"
6991
+ }
6477
6992
  },
6478
6993
  examples: `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile client-a --json
6479
6994
 
6480
6995
  Reads the token from standard input only. Use this in unattended CI or scripts without browser approval after issuing a token at ${DEFAULT_BASE_URL}/settings/tokens.
6481
6996
 
6997
+ Bot tokens (asb_ prefix, issued once by a workspace admin) are detected by prefix and imported as rotating refresh credentials; the first refresh consumes the displayed token, so the rotated credential is stored before success is reported. Importing a bot token over an existing profile credential requires --force (--force is a no-op for API tokens). A stored bot credential cannot be re-imported; recovery is an admin reissue.
6998
+
6482
6999
  Common failures:
6483
- validation_failed Pass --profile and pipe a non-empty token on standard input
7000
+ validation_failed Pass --profile and pipe a non-empty token on standard input; bot-token overwrite needs --force
6484
7001
  token_invalid The token is invalid or expired
7002
+ bot_token_invalid The bot token was revoked, superseded by a reissue, or the bot was stopped; ask an admin to reissue
6485
7003
  auth_account_mismatch The token belongs to a different account than the saved profile email
6486
7004
  token_store_unavailable Configure an OS credential store or use the explicit plaintext fallback`
6487
7005
  });
@@ -6890,7 +7408,7 @@ const whoamiDefinition = define({
6890
7408
  });
6891
7409
  const doctorDefinition = define({
6892
7410
  name: "doctor",
6893
- description: "Check authentication, destination, network, and upload access.",
7411
+ description: "Check token storage, authentication, destination, network, and upload access.",
6894
7412
  toKebab: true,
6895
7413
  args: commonArgs
6896
7414
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@artifactshare/cli",
3
- "version": "0.11.2",
3
+ "version": "0.11.3",
4
4
  "description": "Upload and share HTML, Markdown, folders, and static sites from terminals, AI agents, automation, and CI.",
5
5
  "homepage": "https://artifactshare.com/connect",
6
6
  "repository": {
@@ -80,10 +80,15 @@ contain `$`, spaces, `*`, or `?`; use single quotes such as
80
80
  - To keep using an issued token as a named profile without TTY or browser
81
81
  login, pipe it on standard input:
82
82
  `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile <name> --json`.
83
+ Bot tokens (`asb_` prefix, issued by a workspace admin) use the same command; the first
84
+ refresh consumes the displayed token, overwriting an existing profile credential requires
85
+ `--force`, and a revoked or superseded bot token fails with `bot_token_invalid` (ask the
86
+ admin to reissue).
83
87
  Imported API-token profiles are not renewed by the CLI.
84
88
  Use `--allow-plaintext-token-store` only on a trusted machine without a native token store.
85
- - Check the current state with `whoami --json`, or `doctor --json` for
86
- authentication, destination, network, upload access, and skill update status.
89
+ That fallback is mode `0600` on POSIX and unavailable on Windows, where saved profiles require Credential Manager.
90
+ - Check the current state with `whoami --json`, or `doctor --json` for token
91
+ storage, authentication, destination, network, upload access, and skill update status.
87
92
 
88
93
  ## Share
89
94
 
@@ -99,6 +104,9 @@ npx --yes @artifactshare/cli share ./site-dir --project-id <id> --json
99
104
  ```
100
105
 
101
106
  - `share` accepts a single `.html` / `.md` file or a static-site directory.
107
+ If a successful result contains `data.warnings`, tell the user each warning
108
+ explicitly. `slack_reauthorization_required` means project Slack
109
+ notifications are not being delivered until the channel is reauthorized.
102
110
  In JSON output, give the user `data.artifact.url`; the artifact ID is
103
111
  `data.artifact.id`.
104
112
  Do not rerun `share` just to inspect the JSON shape: without `--key`, each
@@ -50,12 +50,15 @@ contain `$`, spaces, `*`, or `?`; use single quotes such as
50
50
  both to use the workspace default on share or preserve the current expiry on
51
51
  edit. Results expose `link_expires_at` as a UTC timestamp or `null`.
52
52
  - For an agent with a user present, use `login --preset agent --profile <name> --json` and let the user select one project during browser approval. In unattended CI or scripts without browser approval, ask the user to issue an API token at `https://artifactshare.com/settings/tokens`, then run normal commands with `ARTIFACTSHARE_TOKEN` or `--token`; do not pass API tokens to `login`.
53
- - To save that token as a named profile without TTY or browser login, pipe it on standard input: `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile <name> --json`. Imported API-token profiles are not renewed by the CLI. Add `--allow-plaintext-token-store` only on a trusted machine without a native token store.
53
+ - To save that token as a named profile without TTY or browser login, pipe it on standard input: `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile <name> --json`. Imported API-token profiles are not renewed by the CLI. Bot tokens (`asb_` prefix) import through the same command as rotating refresh credentials; overwriting an existing profile credential needs `--force`, and a rejected bot token reports `bot_token_invalid` (recovery is an admin reissue). Add `--allow-plaintext-token-store` only on a trusted machine without a native token store. That fallback is mode `0600` on POSIX and unavailable on Windows, where saved profiles require Credential Manager.
54
54
  - Use `login --profile <name> --json` when a user is present for browser approval. The pending event on stderr includes `browser_open`. Profiles created by `login` renew expired CLI sessions automatically.
55
55
  - Use `logout --profile <name> --json` to revoke a device-login credential before removing it locally; this keeps profile metadata. API-token profiles are removed locally only and their server token is not revoked.
56
56
  - Switch profiles with `profiles use <name> --json`; list with `profiles list --json`; remove a profile entry and its credential with `profiles delete <name> --json`.
57
57
  - When the user gives an Artifact Share URL, start with `open <artifact-id-or-url> --json`. It ensures this rule is installed or updated, then reads single-file artifacts or returns a `download` next command for static sites and multi-file artifacts.
58
58
  - Share with `share <path> --json`. In JSON output, give the user `data.artifact.url`; the artifact ID is `data.artifact.id`. Do not rerun `share` just to inspect the JSON shape: without `--key`, each successful run creates a new artifact. Posting to a project delivers to the audience defined by that project. Pick it with `--project-id <id>` or `--project <name>` (by exact name), or use the saved default. With no destination, share posts to home. Choose `home_audience` by purpose: use `config set home_audience private --scope user --json` for a personal safe default in this CLI environment, use `--scope repository` only for a policy agreed by all participants, and use `--visibility private|workspace|link` for one home post. For link sharing, pass exactly one of `--link-expires-at <RFC3339 UTC>` or `--no-link-expiry`; omit both to use the workspace default. Confirm the resolved audience with `config get home_audience --scope effective --json`; `--grant-email` does not change the resolved default.
59
+ - If a successful `share` result contains `data.warnings`, tell the user each
60
+ warning explicitly. `slack_reauthorization_required` means project Slack
61
+ notifications are not being delivered until the channel is reauthorized.
59
62
  - For new projects, pass `projects create <name> --visibility private|workspace`; persistent project defaults are documented in `projects create --help`. The complete `config --help` reference covers the canonical `home_audience`, user/repository/effective scopes, and resolution. `default_artifact_visibility` is a compatibility alias; `default_project_visibility` is the advanced project-creation default. Home resolution checks repository then user settings, including the alias at each scope, then product default `workspace`. Keyless `config get --json` returns only `home_audience`; pass an explicit key for either other setting. These settings do not change update, edit, Web, or MCP defaults.
60
63
  - For repeat jobs with a stable caller-owned name, use `share <path> --key <key> --json`: the first run creates the artifact, later runs add versions to the same artifact.
61
64
  - To keep an existing share URL, do not use `share --artifact-id`; add a version with `update <artifact-id-or-url> <path> --json`. `update` does not change title, visibility, viewers, or placement.
@@ -76,5 +79,5 @@ contain `$`, spaces, `*`, or `?`; use single quotes such as
76
79
  - Manage projects: `projects list --json`, `projects create <name> --json` (uses `default_project_visibility` when saved, otherwise `workspace`; pass `--visibility private` for a confidential project), `projects edit <id>` for name, description, visibility, audience (`--add-email`/`--remove-email`), and archive state (`--archive`/`--unarchive`).
77
80
  - Save a default project with `init --project-id <id> --json`. Preview setup with `init --dry-run --json`.
78
81
  - Manage skills: `skills ensure --tool auto --json` detects Claude Code, Codex, or Cursor and installs or updates user-scope skills; Cursor project scope needs `skills install --tool cursor --scope project --json`. Use `skills install --tool cursor --scope user --json` for the Cursor user-scope skill explicitly. Project scope is opt-in via `skills install --tool <tool> --scope project --json`. `skills update --json` updates installed managed skills; `--force` overwrites unmanaged files on install.
79
- - Check the current state with `whoami --json` or `doctor --json` for authentication, destination, network, upload access, and skill update status.
82
+ - Check the current state with `whoami --json` or `doctor --json` for token storage, authentication, destination, network, upload access, and skill update status.
80
83
  - First-time setup: `npx --yes @artifactshare/cli init --json` detects Claude Code, Codex, or Cursor, installs or updates user-scope skills, and reports the next steps (sign in, then share). For Cursor project scope, run `skills install --tool cursor --scope project --json` explicitly.