@artifactshare/cli 0.1.7 → 0.1.8

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
@@ -3,10 +3,10 @@ import { appendFile, chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm
3
3
  import { cli, define, lazy } from "gunshi";
4
4
  import { spawn } from "node:child_process";
5
5
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
6
+ import { setTimeout } from "node:timers/promises";
6
7
  import { homedir } from "node:os";
7
8
  import { createReadStream } from "node:fs";
8
9
  import { createHash } from "node:crypto";
9
- import { setTimeout } from "node:timers/promises";
10
10
  //#region src/constants.ts
11
11
  const DEFAULT_BASE_URL = "https://artifactshare.com";
12
12
  const DEVICE_CLIENT_ID = "artifactshare-cli";
@@ -128,6 +128,11 @@ function agentDownloadCommand(target) {
128
128
  return `${CLI_INVOCATION} download ${target} --output ${AGENT_DOWNLOAD_OUTPUT} --json`;
129
129
  }
130
130
  //#endregion
131
+ //#region src/types.ts
132
+ function isProfileCredentialSource(source) {
133
+ return source === "profile" || source === "local_config" || source === "project_config" || source === "global_profile";
134
+ }
135
+ //#endregion
131
136
  //#region src/errors.ts
132
137
  const REQUEST_ACCESS_COMMAND$1 = `${CLI_INVOCATION} request-access --json`;
133
138
  const PROJECTS_LIST_COMMAND = `${CLI_INVOCATION} projects list --json`;
@@ -144,7 +149,13 @@ function apiError(body) {
144
149
  }
145
150
  function mapApiError(status, body, options = {}) {
146
151
  const { code: apiCode, message: apiMessage } = apiError(body);
147
- if (status === 401) return options.authenticated ? tokenInvalidError() : authRequiredError(options.baseUrl ?? "https://artifactshare.com");
152
+ if (status === 401) {
153
+ if (!options.authenticated) return authRequiredError(options.baseUrl ?? "https://artifactshare.com");
154
+ const source = options.credentialSource;
155
+ const profile = options.profile;
156
+ if (typeof profile === "string" && profile.length > 0 && isProfileCredentialSource(source)) return profileReauthRequiredError(options.baseUrl ?? "https://artifactshare.com", source, profile);
157
+ return tokenInvalidError();
158
+ }
148
159
  if (apiCode === "upload-not-allowed") return cliError({
149
160
  code: "upload_not_allowed",
150
161
  message: "This account cannot publish yet.",
@@ -473,6 +484,24 @@ function authRequiredError(baseUrl) {
473
484
  details: authRecoveryDetails(baseUrl)
474
485
  });
475
486
  }
487
+ function profileReauthRequiredError(baseUrl, source, profile) {
488
+ const loginCommand = `${CLI_INVOCATION} login --profile ${profile}`;
489
+ return cliError({
490
+ code: "auth_required",
491
+ message: "Login is required.",
492
+ why: `The saved credential for profile "${profile}" is invalid or expired.`,
493
+ hint: `In an interactive terminal, run ${loginCommand}. In agents or CI, issue a token at ${tokensUrl(baseUrl)}, then set ${TOKEN_ENV_VAR} or pass ${TOKEN_OPTION}.`,
494
+ agentRecoverable: false,
495
+ requiresHuman: true,
496
+ recovery: { kind: "ask_human" },
497
+ details: {
498
+ ...authRecoveryDetails(baseUrl, loginCommand),
499
+ credential_source: source,
500
+ reauth_reason: "profile_token_invalid_or_expired",
501
+ profile
502
+ }
503
+ });
504
+ }
476
505
  function deviceAuthErrorDetails(pending) {
477
506
  const openUrl = pending.verification_uri_complete ?? pending.verification_uri;
478
507
  return {
@@ -486,7 +515,7 @@ function deviceAuthErrorDetails(pending) {
486
515
  retry_hint: "After approval in the browser, rerun the same command to continue."
487
516
  };
488
517
  }
489
- function authRequiredWithDeviceAuthError(baseUrl, pending) {
518
+ function authRequiredWithDeviceAuthError(baseUrl, pending, extraDetails = {}) {
490
519
  const device = deviceAuthErrorDetails(pending);
491
520
  const openUrl = pending.verification_uri_complete ?? pending.verification_uri;
492
521
  return cliError({
@@ -499,6 +528,7 @@ function authRequiredWithDeviceAuthError(baseUrl, pending) {
499
528
  recovery: { kind: "ask_human" },
500
529
  details: {
501
530
  ...authRecoveryDetails(baseUrl, `${CLI_INVOCATION} login --profile ${pending.profile}`),
531
+ ...extraDetails,
502
532
  ...device
503
533
  }
504
534
  });
@@ -1132,6 +1162,7 @@ async function apiRequest(path, options, init, errorOptions) {
1132
1162
  const body = await readJson(response);
1133
1163
  if (!response.ok) return { error: mapApiError(response.status, body, {
1134
1164
  authenticated: true,
1165
+ baseUrl: baseUrlOf(options),
1135
1166
  ...errorOptions
1136
1167
  }) };
1137
1168
  return { body };
@@ -1554,7 +1585,7 @@ async function resolveProfileCredential(source, profile, options, globalConfig,
1554
1585
  const stored = await readProfileToken(profile, options);
1555
1586
  if (stored.ok) return {
1556
1587
  ok: true,
1557
- source: "profile",
1588
+ source,
1558
1589
  profile,
1559
1590
  token: stored.token
1560
1591
  };
@@ -1667,1225 +1698,1294 @@ async function resolveEffectiveDefaultProfile(projectInput = null) {
1667
1698
  };
1668
1699
  }
1669
1700
  //#endregion
1670
- //#region src/command-runners/artifacts-get.ts
1671
- async function runArtifactsGet(parsed, mode) {
1672
- const command = "artifacts get";
1673
- const result = await readArtifact(parsed, command);
1674
- if (result.error) return writeFailure(command, result.error, mode, 1);
1701
+ //#region src/command-runners/login.ts
1702
+ async function performDeviceLogin(profile, options, mode) {
1703
+ const request = await requestConfig(options);
1704
+ if (request.error) return {
1705
+ ok: false,
1706
+ error: request.error
1707
+ };
1708
+ const code = await requestDeviceCode(options, request.init);
1709
+ if ("error" in code) return {
1710
+ ok: false,
1711
+ error: code.error
1712
+ };
1713
+ const deadline = Date.now() + code.expires_in * 1e3;
1714
+ if (mode.json) writeEvent({
1715
+ status: "pending",
1716
+ verification_uri: code.verification_uri,
1717
+ verification_uri_complete: code.verification_uri_complete ?? null,
1718
+ user_code: code.user_code,
1719
+ expires_at: new Date(deadline).toISOString(),
1720
+ interval_seconds: code.interval
1721
+ });
1722
+ else writeText([
1723
+ "Open this URL in a browser to sign in:",
1724
+ code.verification_uri_complete ?? code.verification_uri,
1725
+ "",
1726
+ `Code: ${code.user_code}`,
1727
+ `Waiting for approval for profile "${profile}"...`,
1728
+ ""
1729
+ ].join("\n"));
1730
+ const token = await pollForToken(options, code, request.init, profile, deadline);
1731
+ if ("error" in token) return {
1732
+ ok: false,
1733
+ error: token.error
1734
+ };
1735
+ const sessionExpiresAt = token.expires_in === void 0 ? null : new Date(Date.now() + token.expires_in * 1e3).toISOString();
1736
+ const stored = await verifyAndStoreProfileToken(profile, token.access_token, options, request.init);
1737
+ if (!stored.ok) return {
1738
+ ok: false,
1739
+ error: stored.error
1740
+ };
1741
+ const effective = await resolveEffectiveDefaultProfile(await resolveProjectConfig());
1742
+ const data = {
1743
+ profile,
1744
+ status: "completed",
1745
+ credential_source: "profile",
1746
+ token_store: stored.data.token_store,
1747
+ user: stored.data.user,
1748
+ workspace: stored.data.workspace,
1749
+ verification_uri: code.verification_uri,
1750
+ verification_uri_complete: code.verification_uri_complete ?? null,
1751
+ user_code: code.user_code,
1752
+ expires_at: sessionExpiresAt,
1753
+ interval_seconds: code.interval
1754
+ };
1755
+ if (effective.profile && effective.profile !== profile) {
1756
+ data.effective_default_profile = effective.profile;
1757
+ 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.`;
1758
+ }
1759
+ return {
1760
+ ok: true,
1761
+ data
1762
+ };
1763
+ }
1764
+ async function runLogin(parsed, mode) {
1765
+ const command = "login";
1766
+ const profile = nonEmpty(parsed.options.profile) ?? "default";
1767
+ if (nonEmpty(process.env.ARTIFACTSHARE_TOKEN) || nonEmpty(parsed.options.token)) return writeFailure(command, validationError("Login cannot run with a bearer token already selected.", "Unset ARTIFACTSHARE_TOKEN and remove --token before running login."), mode, 1);
1768
+ const result = await performDeviceLogin(profile, parsed.options, mode);
1769
+ if (!result.ok) return writeFailure(command, result.error, mode, 1);
1675
1770
  return writeSuccess(command, result.data, mode);
1676
1771
  }
1677
- async function readArtifact(parsed, command) {
1678
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to read.");
1679
- if (target.error) return { error: target.error };
1680
- const artifactId = target.artifactId;
1681
- const offset = parseOffsetOption(parsed.options.offset);
1682
- if (offset.error) return { error: offset.error };
1683
- const include = parseIncludeOptions(parsed.options.include);
1684
- if (include.error) return { error: include.error };
1685
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1686
- if (!credential.ok) return { error: credential.error };
1687
- const request = await requestConfig(parsed.options);
1688
- if (request.error) return { error: request.error };
1689
- const url = apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}`, baseUrlOf(parsed.options));
1690
- if (offset.value !== void 0) url.searchParams.set("offset", offset.value);
1691
- for (const item of include.values) url.searchParams.append("include", item);
1692
- const response = await fetch(url, {
1693
- headers: { Authorization: `Bearer ${credential.token}` },
1694
- ...request.init
1772
+ async function requestDeviceCode(options, init) {
1773
+ const response = await fetch(apiUrl("/api/auth/device/code", baseUrlOf(options)), {
1774
+ method: "POST",
1775
+ headers: { "content-type": "application/json" },
1776
+ body: JSON.stringify({ client_id: DEVICE_CLIENT_ID }),
1777
+ ...init
1695
1778
  }).catch((error) => ({ networkError: error }));
1696
1779
  if ("networkError" in response) return { error: networkError(response.networkError) };
1697
1780
  const body = await readJson(response);
1698
- if (!response.ok) return { error: mapApiError(response.status, body, {
1699
- authenticated: true,
1700
- artifactTarget: true
1701
- }) };
1702
- if (!artifactGetSuccessFields(body)) return { error: serviceError("Artifact read succeeded but the response did not include source metadata.") };
1703
- return { data: body };
1781
+ if (!response.ok) return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
1782
+ if (!isDeviceCodeResponse(body)) return { error: validationError("Device login response was invalid.", "Retry login. If this repeats, report the response shape.", "service_error") };
1783
+ return body;
1704
1784
  }
1705
- async function runArtifactsList(parsed, mode) {
1706
- const command = "artifacts list";
1707
- const hasProjectId = parsed.options.projectId !== void 0;
1708
- const projectId = parsed.options.projectId?.trim() ?? "";
1709
- const home = Boolean(parsed.options.home);
1710
- if (hasProjectId && !projectId) return writeFailure(command, validationError("--project-id must not be empty.", "Pass --project-id <id>, use --home, or omit the destination filter."), mode, 1);
1711
- if (hasProjectIdHomeConflict(parsed.options)) return writeFailure(command, validationError("Artifact list destination is ambiguous.", "Choose only one destination filter: --project-id <id> or --home.", "destination_conflict"), mode, 1);
1712
- const query = parsed.options.query?.trim();
1713
- if (parsed.options.query !== void 0 && !query) return writeFailure(command, validationError("--query must not be empty.", "Pass --query <text> or omit --query."), mode, 1);
1714
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1715
- if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
1716
- const request = await requestConfig(parsed.options);
1717
- if (request.error) return writeFailure(command, request.error, mode, 1);
1718
- const url = apiUrl("/api/cli/artifacts", baseUrlOf(parsed.options));
1719
- if (home) url.searchParams.set("project_id", "");
1720
- else if (projectId) url.searchParams.set("project_id", projectId);
1721
- if (query) url.searchParams.set("query", query);
1722
- const response = await fetch(url, {
1723
- headers: { Authorization: `Bearer ${credential.token}` },
1724
- ...request.init
1785
+ async function exchangeDeviceTokenOnce(options, deviceCode, init) {
1786
+ const response = await fetch(apiUrl("/api/auth/device/token", baseUrlOf(options)), {
1787
+ method: "POST",
1788
+ headers: { "content-type": "application/json" },
1789
+ body: JSON.stringify({
1790
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1791
+ device_code: deviceCode,
1792
+ client_id: DEVICE_CLIENT_ID
1793
+ }),
1794
+ ...init
1725
1795
  }).catch((error) => ({ networkError: error }));
1726
- if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
1796
+ if ("networkError" in response) return { error: networkError(response.networkError) };
1727
1797
  const body = await readJson(response);
1728
- if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
1729
- if (!artifactsListSuccessFields(body)) return writeFailure(command, serviceError("Artifact list succeeded but the response did not include list metadata."), mode, 1);
1730
- return writeSuccess(command, body, mode);
1731
- }
1732
- //#endregion
1733
- //#region src/command-runners/skills.ts
1734
- const SKILL_TOOLS = [
1735
- "codex",
1736
- "claude",
1737
- "cursor"
1738
- ];
1739
- const SKILL_FILE_PATH = join("skills", "artifactshare", "SKILL.md");
1740
- const TOOL_CONFIG = {
1741
- codex: {
1742
- relativePath: join(".agents", SKILL_FILE_PATH),
1743
- scopes: ["project", "user"],
1744
- detectDirs: [".codex", ".agents"],
1745
- bundledFile: "SKILL.md",
1746
- pruneDirs: ["artifactshare", "skills"]
1747
- },
1748
- claude: {
1749
- relativePath: join(".claude", SKILL_FILE_PATH),
1750
- scopes: ["project", "user"],
1751
- detectDirs: [".claude"],
1752
- bundledFile: "SKILL.md",
1753
- pruneDirs: ["artifactshare", "skills"]
1754
- },
1755
- cursor: {
1756
- relativePath: join(".cursor", "rules", "artifactshare.mdc"),
1757
- scopes: ["project"],
1758
- detectDirs: [".cursor"],
1759
- bundledFile: "artifactshare.mdc",
1760
- pruneDirs: []
1761
- }
1762
- };
1763
- function skillTarget(tool, scope) {
1764
- const relative = TOOL_CONFIG[tool].relativePath;
1765
- const path = scope === "project" ? relative : join(homedir(), relative);
1766
- return {
1767
- tool,
1768
- scope,
1769
- path,
1770
- absolutePath: resolve(path)
1771
- };
1772
- }
1773
- function allTargets() {
1774
- return SKILL_TOOLS.flatMap((tool) => TOOL_CONFIG[tool].scopes.map((scope) => skillTarget(tool, scope)));
1775
- }
1776
- function managedState(content) {
1777
- if (content === null) return { kind: "missing" };
1778
- if (!content.includes("artifactshare-skill")) return { kind: "unmanaged" };
1779
- const block = content.match(/<!--\s*artifactshare-skill([\s\S]*?)-->/)?.[1];
1780
- const version = block?.match(/(?:^|\n)\s*version:\s*(\d+)\s*(?:\n|$)/)?.[1];
1781
- const managed = block !== void 0 && /(?:^|\n)\s*managed:\s*true\s*(?:\n|$)/.test(block);
1782
- if (version === void 0 || !managed) return { kind: "broken" };
1783
- return {
1784
- kind: "managed",
1785
- version: Number(version)
1798
+ if (response.ok && isDeviceTokenResponse(body)) return {
1799
+ status: "success",
1800
+ token: body
1786
1801
  };
1802
+ const authError = deviceTokenError(body);
1803
+ if (authError === "authorization_pending") return { status: "pending" };
1804
+ if (authError === "slow_down") return { status: "slow_down" };
1805
+ if (authError === "access_denied") return { status: "denied" };
1806
+ if (authError === "expired_token") return { status: "expired" };
1807
+ if (response.status === 429 || response.status >= 500) return { status: "retry_later" };
1808
+ return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
1787
1809
  }
1788
- async function readTarget(target) {
1789
- return managedState(await readFile(target.absolutePath, "utf8").catch(() => null));
1790
- }
1791
- async function loadBundledSkills() {
1792
- const byFile = /* @__PURE__ */ new Map();
1793
- const contents = {};
1794
- let version;
1795
- for (const tool of SKILL_TOOLS) {
1796
- const file = TOOL_CONFIG[tool].bundledFile;
1797
- let content = byFile.get(file);
1798
- if (content === void 0) {
1799
- content = await readFile(new URL(`../skills/artifactshare/${file}`, import.meta.url), "utf8");
1800
- const state = managedState(content);
1801
- if (state.kind !== "managed" || (version ?? state.version) !== state.version) throw new Error(`The bundled ${file} has a missing or mismatched managed marker.`);
1802
- version = state.version;
1803
- byFile.set(file, content);
1804
- }
1805
- contents[tool] = content;
1806
- }
1810
+ function pendingDeviceAuthFromCode(profile, options, code) {
1807
1811
  return {
1808
- contents,
1809
- version
1812
+ base_url: baseUrlOf(options),
1813
+ profile,
1814
+ device_code: code.device_code,
1815
+ verification_uri: code.verification_uri,
1816
+ verification_uri_complete: code.verification_uri_complete ?? null,
1817
+ user_code: code.user_code,
1818
+ expires_at: new Date(Date.now() + code.expires_in * 1e3).toISOString(),
1819
+ interval_seconds: code.interval,
1820
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1810
1821
  };
1811
1822
  }
1812
- function parseTools(value, options = {}) {
1813
- const raws = arrayOption(value);
1814
- const tools = [];
1815
- for (const raw of raws) for (const item of raw.split(",")) {
1816
- const trimmed = item.trim();
1817
- if (!trimmed) continue;
1818
- if (trimmed === "auto") {
1819
- if (!options.allowAuto) return { error: validationError(`Unknown --tool value: ${trimmed}`, "Pass --tool codex, --tool claude, or --tool cursor.") };
1820
- tools.push(trimmed);
1823
+ async function pollForToken(options, code, init, profile, deadline) {
1824
+ let intervalMs = Math.max(code.interval, 1) * 1e3;
1825
+ let networkFailures = 0;
1826
+ while (Date.now() < deadline) {
1827
+ await setTimeout(intervalMs);
1828
+ const response = await fetch(apiUrl("/api/auth/device/token", baseUrlOf(options)), {
1829
+ method: "POST",
1830
+ headers: { "content-type": "application/json" },
1831
+ body: JSON.stringify({
1832
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1833
+ device_code: code.device_code,
1834
+ client_id: DEVICE_CLIENT_ID
1835
+ }),
1836
+ ...init
1837
+ }).catch((error) => ({ networkError: error }));
1838
+ if ("networkError" in response) {
1839
+ networkFailures += 1;
1840
+ if (networkFailures >= 5) return { error: networkError(response.networkError) };
1821
1841
  continue;
1822
1842
  }
1823
- if (!SKILL_TOOLS.includes(trimmed)) return { error: validationError(`Unknown --tool value: ${trimmed}`, "Pass --tool codex, --tool claude, or --tool cursor.") };
1824
- tools.push(trimmed);
1843
+ networkFailures = 0;
1844
+ const body = await readJson(response);
1845
+ if (response.ok && isDeviceTokenResponse(body)) return body;
1846
+ const authError = deviceTokenError(body);
1847
+ if (authError === "authorization_pending") continue;
1848
+ if (authError === "slow_down") {
1849
+ intervalMs += 5e3;
1850
+ continue;
1851
+ }
1852
+ if (authError === "access_denied") return { error: authDeniedError(profile) };
1853
+ if (authError === "expired_token") return { error: authExpiredError(profile) };
1854
+ return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
1825
1855
  }
1826
- if (raws.length > 0 && tools.length === 0) return { error: validationError("--tool has no value.", "Pass --tool codex, --tool claude, or --tool cursor.") };
1827
- const unique = [...new Set(tools)];
1828
- const auto = unique.includes("auto");
1829
- if (auto && unique.length > 1) return { error: validationError("--tool auto cannot be combined with explicit tools.", "Pass --tool auto by itself, or pass --tool codex, --tool claude, or --tool cursor.") };
1856
+ return { error: authExpiredError(profile) };
1857
+ }
1858
+ async function verifyAndStoreProfileToken(profile, token, options, init) {
1859
+ const config = await readGlobalConfig() ?? {};
1860
+ const whoamiResult = await apiGet("/api/cli/whoami", token, options, init);
1861
+ if (whoamiResult.error) return {
1862
+ ok: false,
1863
+ error: whoamiResult.error
1864
+ };
1865
+ const whoami = whoamiProfile(whoamiResult.body);
1866
+ const profiles = config.profiles ?? {};
1867
+ const expectedEmail = nonEmpty((Object.hasOwn(profiles, profile) ? profiles[profile] : void 0)?.email);
1868
+ if (expectedEmail && whoami.email !== expectedEmail) return {
1869
+ ok: false,
1870
+ error: authAccountMismatchError(profile, expectedEmail, whoami.email)
1871
+ };
1872
+ const saved = await saveProfileToken(profile, token, options);
1873
+ if (!saved.ok) return {
1874
+ ok: false,
1875
+ error: tokenStoreUnavailableError(profile)
1876
+ };
1877
+ await writeProfileConfig(profile, options, saved.store, whoami);
1830
1878
  return {
1831
- tools: unique.filter((tool) => tool !== "auto"),
1832
- auto
1879
+ ok: true,
1880
+ data: {
1881
+ profile,
1882
+ token_store: saved.store,
1883
+ user: { email: whoami.email },
1884
+ workspace: {
1885
+ id: whoami.workspace_id,
1886
+ hosted_domain: whoami.hosted_domain
1887
+ }
1888
+ }
1833
1889
  };
1834
1890
  }
1835
- function parseScope(value) {
1836
- const trimmed = nonEmpty(value);
1837
- if (trimmed === void 0) return { scope: void 0 };
1838
- if (trimmed === "project" || trimmed === "user") return { scope: trimmed };
1839
- return { error: validationError(`Unknown --scope value: ${trimmed}`, "Pass --scope project or --scope user.") };
1891
+ async function writeProfileConfig(profile, options, tokenStore, whoami) {
1892
+ const config = await readGlobalConfig() ?? {};
1893
+ const profiles = config.profiles ?? {};
1894
+ const currentProfile = Object.hasOwn(profiles, profile) ? profiles[profile] : void 0;
1895
+ await writeGlobalConfig({
1896
+ ...config,
1897
+ default_profile: nonEmpty(config.default_profile) ?? profile,
1898
+ profiles: {
1899
+ ...profiles,
1900
+ [profile]: {
1901
+ ...currentProfile,
1902
+ base_url: baseUrlOf(options),
1903
+ email: whoami.email ?? currentProfile?.email ?? null,
1904
+ workspace_id: whoami.workspace_id,
1905
+ token_store: tokenStore,
1906
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
1907
+ }
1908
+ }
1909
+ });
1840
1910
  }
1841
- function parseFilters(parsed, options = {}) {
1842
- const tools = parseTools(parsed.options.tool, options);
1843
- if (tools.error) return { error: tools.error };
1844
- const scope = parseScope(parsed.options.scope);
1845
- if (scope.error) return { error: scope.error };
1846
- if (tools.auto && scope.scope === "user") return { error: validationError("--tool auto supports project scope only.", "Use --tool auto --scope project, or pass an explicit --tool for user scope.") };
1847
- const unsupported = scope.scope === void 0 ? void 0 : tools.tools.find((tool) => !TOOL_CONFIG[tool].scopes.includes(scope.scope));
1848
- if (unsupported) return { error: validationError(`The ${unsupported} tool does not support --scope ${scope.scope}.`, `Use --tool ${unsupported} --scope project.`) };
1911
+ function isDeviceCodeResponse(body) {
1912
+ if (!isRecord(body)) return false;
1913
+ return typeof body.device_code === "string" && typeof body.user_code === "string" && typeof body.verification_uri === "string" && (typeof body.verification_uri_complete === "string" || body.verification_uri_complete === void 0) && typeof body.expires_in === "number" && typeof body.interval === "number";
1914
+ }
1915
+ function isDeviceTokenResponse(body) {
1916
+ if (!isRecord(body)) return false;
1917
+ return typeof body.access_token === "string" && typeof body.token_type === "string" && body.token_type.toLowerCase() === "bearer" && (typeof body.expires_in === "number" || body.expires_in === void 0);
1918
+ }
1919
+ function deviceTokenError(body) {
1920
+ if (!isRecord(body)) return null;
1921
+ return typeof body.error === "string" ? body.error : null;
1922
+ }
1923
+ function whoamiProfile(body) {
1924
+ const record = isRecord(body) ? body : null;
1925
+ const user = record && isRecord(record.user) ? record.user : null;
1926
+ const workspace = record && isRecord(record.workspace) ? record.workspace : null;
1849
1927
  return {
1850
- tools: tools.tools,
1851
- auto: tools.auto,
1852
- scope: scope.scope
1928
+ email: typeof user?.email === "string" ? user.email : null,
1929
+ workspace_id: typeof workspace?.id === "string" ? workspace.id : null,
1930
+ hosted_domain: typeof workspace?.hosted_domain === "string" ? workspace.hosted_domain : null
1853
1931
  };
1854
1932
  }
1855
- function filteredTargets(tools, scope) {
1856
- return allTargets().filter((target) => (tools.length === 0 || tools.includes(target.tool)) && (scope === void 0 || target.scope === scope));
1933
+ //#endregion
1934
+ //#region src/command-runners/auto-login.ts
1935
+ const JSON_PENDING_AUTH_COMMANDS = new Set([
1936
+ "publish",
1937
+ "update",
1938
+ "download",
1939
+ "artifacts get"
1940
+ ]);
1941
+ function isInteractiveTerminal(mode) {
1942
+ return !mode.json && process.stdin.isTTY === true;
1857
1943
  }
1858
- function detectionBase(scope) {
1859
- return scope === "project" ? process.cwd() : homedir();
1944
+ function profileForAutoLogin(credential) {
1945
+ return credential.source === "none" ? "default" : credential.profile ?? "default";
1860
1946
  }
1861
- async function isToolDetected(tool, scope) {
1862
- const base = detectionBase(scope);
1863
- for (const dir of TOOL_CONFIG[tool].detectDirs) if ((await stat(join(base, dir)).catch(() => null))?.isDirectory()) return true;
1864
- return false;
1947
+ function isPendingExpired(pending) {
1948
+ const expiresAt = Date.parse(pending.expires_at);
1949
+ return Number.isNaN(expiresAt) || expiresAt <= Date.now();
1865
1950
  }
1866
- async function autoTargets(scope) {
1867
- const targetScope = scope ?? "project";
1868
- const autoOrder = [
1869
- "claude",
1870
- "codex",
1871
- "cursor"
1872
- ];
1873
- const detected = /* @__PURE__ */ new Set();
1874
- for (const tool of autoOrder) if (TOOL_CONFIG[tool].scopes.includes(targetScope) && await isToolDetected(tool, targetScope)) detected.add(tool);
1875
- return (detected.size > 0 ? [...detected] : ["codex", "claude"]).filter((tool) => TOOL_CONFIG[tool].scopes.includes(targetScope)).map((tool) => skillTarget(tool, targetScope));
1951
+ function authRequiredExtraDetails(error) {
1952
+ const credentialSource = error.details?.credential_source;
1953
+ return typeof credentialSource === "string" ? { credential_source: credentialSource } : {};
1876
1954
  }
1877
- async function applyAction({ target, action, content }) {
1878
- if (content !== void 0) {
1879
- await mkdir(dirname(target.absolutePath), { recursive: true });
1880
- await writeFile(target.absolutePath, content);
1881
- return;
1882
- }
1883
- if (action === "removed") {
1884
- await rm(target.absolutePath, { force: true });
1885
- await cleanupSkillDirs(target);
1886
- }
1955
+ function interactiveLoginMessage(credential) {
1956
+ if (isProfileCredentialSource(credential.source) && credential.error.details?.reauth_reason === "profile_token_invalid_or_expired") return "Profile token expired. Starting device login to refresh...\n";
1957
+ return "Not signed in. Starting device login to continue...\n";
1887
1958
  }
1888
- async function cleanupSkillDirs(target) {
1889
- let dir = dirname(target.absolutePath);
1890
- for (const expected of TOOL_CONFIG[target.tool].pruneDirs) {
1891
- if (basename(dir) !== expected) return;
1892
- try {
1893
- await rmdir(dir);
1894
- } catch {
1895
- return;
1896
- }
1897
- dir = dirname(dir);
1898
- }
1959
+ async function canAttemptProfileTokenSave(profile, options) {
1960
+ const stored = await readProfileToken(profile, options);
1961
+ return stored.ok || stored.reason !== "unavailable";
1899
1962
  }
1900
- async function finishActions(command, planned, dryRun, mode) {
1901
- if (!dryRun) try {
1902
- for (const item of planned) await applyAction(item);
1903
- } catch (error) {
1904
- writeFailure(command, unexpectedError(error), mode, 1);
1905
- return;
1906
- }
1907
- return {
1908
- dry_run: dryRun,
1909
- targets: planned.map(({ target, action }) => ({
1910
- tool: target.tool,
1911
- scope: target.scope,
1912
- path: target.path,
1913
- action
1914
- }))
1915
- };
1963
+ async function handleCredentialFailure(command, credential, options, mode, rerun, isRetry = false, deps = {}) {
1964
+ if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
1965
+ if (mode.json && JSON_PENDING_AUTH_COMMANDS.has(command) && !isRetry) return handleJsonPendingAuth(command, credential, options, mode, rerun);
1966
+ if (!isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
1967
+ const performLogin = deps.performLogin ?? performDeviceLogin;
1968
+ const profile = profileForAutoLogin(credential);
1969
+ writeText(interactiveLoginMessage(credential));
1970
+ const loginResult = await performLogin(profile, options, mode);
1971
+ if (!loginResult.ok) return writeFailure(command, loginResult.error, mode, 1);
1972
+ return rerun();
1916
1973
  }
1917
- async function runActions(command, planned, dryRun, mode) {
1918
- const data = await finishActions(command, planned, dryRun, mode);
1919
- if (data) writeSuccess(command, data, mode);
1974
+ async function handleAuthenticatedCredentialFailure(command, error, credential, options, mode, rerun, isRetry = false) {
1975
+ if (error.code !== "auth_required") return writeFailure(command, error, mode, 1);
1976
+ return await handleCredentialFailure(command, {
1977
+ ok: false,
1978
+ source: credential.source,
1979
+ ...credential.profile ? { profile: credential.profile } : {},
1980
+ error
1981
+ }, options, mode, rerun, isRetry);
1920
1982
  }
1921
- async function bundledOrFailure(command, mode) {
1922
- try {
1923
- return await loadBundledSkills();
1924
- } catch (error) {
1925
- writeFailure(command, unexpectedError(error), mode, 1);
1926
- return;
1983
+ async function handleJsonPendingAuth(command, credential, options, mode, rerun) {
1984
+ const profile = profileForAutoLogin(credential);
1985
+ const extraDetails = authRequiredExtraDetails(credential.error);
1986
+ const baseUrl = baseUrlOf(options);
1987
+ const request = await requestConfig(options);
1988
+ if (request.error) return writeFailure(command, request.error, mode, 1);
1989
+ if (!await canAttemptProfileTokenSave(profile, options)) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
1990
+ const existing = await readPendingDeviceAuth(baseUrl, profile);
1991
+ if (existing && !isPendingExpired(existing)) {
1992
+ const exchange = await exchangeDeviceTokenOnce(options, existing.device_code, request.init);
1993
+ if ("error" in exchange) {
1994
+ if (exchange.error.code !== "network_failed") await clearPendingDeviceAuth(baseUrl, profile);
1995
+ return writeFailure(command, exchange.error, mode, 1);
1996
+ }
1997
+ if (exchange.status === "success") {
1998
+ const stored = await verifyAndStoreProfileToken(profile, exchange.token.access_token, options, request.init);
1999
+ if (!stored.ok) return writeFailure(command, stored.error, mode, 1);
2000
+ await clearPendingDeviceAuth(baseUrl, profile);
2001
+ return rerun();
2002
+ }
2003
+ if (exchange.status === "denied") {
2004
+ await clearPendingDeviceAuth(baseUrl, profile);
2005
+ return writeFailure(command, authDeniedError(profile), mode, 1);
2006
+ }
2007
+ if (exchange.status === "expired") await clearPendingDeviceAuth(baseUrl, profile);
2008
+ else if (exchange.status === "retry_later") return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing, extraDetails), mode, 1);
2009
+ else return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing, extraDetails), mode, 1);
2010
+ } else if (existing) await clearPendingDeviceAuth(baseUrl, profile);
2011
+ const code = await requestDeviceCode(options, request.init);
2012
+ if ("error" in code) return writeFailure(command, credential.error, mode, 1);
2013
+ const pending = pendingDeviceAuthFromCode(profile, options, code);
2014
+ if (!await writePendingDeviceAuth(pending)) return writeFailure(command, credential.error, mode, 1);
2015
+ return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, pending, extraDetails), mode, 1);
2016
+ }
2017
+ //#endregion
2018
+ //#region src/command-runners/artifacts-get.ts
2019
+ async function runArtifactsGet(parsed, mode, isRetry = false) {
2020
+ const command = "artifacts get";
2021
+ const target = parseArtifactReadTarget(parsed, command);
2022
+ if (target.error) return writeFailure(command, target.error, mode, 1);
2023
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2024
+ if (!credential.ok) {
2025
+ if (!mode.json) return writeFailure(command, credential.error, mode, 1);
2026
+ return handleCredentialFailure(command, credential, parsed.options, mode, () => runArtifactsGet(parsed, mode, true), isRetry);
1927
2027
  }
2028
+ const result = await fetchArtifact(parsed, target.value, credential);
2029
+ if (result.error) return handleAuthenticatedCredentialFailure(command, result.error, credential, parsed.options, mode, () => runArtifactsGet(parsed, mode, true), isRetry);
2030
+ return writeSuccess(command, result.data, mode);
1928
2031
  }
1929
- async function runSkillsInstall(parsed, mode) {
1930
- const command = "skills install";
1931
- const filters = parseFilters(parsed);
1932
- if (filters.error) return writeFailure(command, filters.error, mode, 1);
1933
- const { tools } = filters;
1934
- if (tools.length === 0) return writeFailure(command, validationError("--tool is required.", "Pass --tool codex, --tool claude, or --tool cursor; repeat for multiple tools."), mode, 1);
1935
- const scope = filters.scope ?? "project";
1936
- const force = parsed.options.force === true;
1937
- const bundled = await bundledOrFailure(command, mode);
1938
- if (!bundled) return;
1939
- const planned = [];
1940
- for (const tool of tools) {
1941
- const target = skillTarget(tool, scope);
1942
- const state = await readTarget(target);
1943
- if ((state.kind === "unmanaged" || state.kind === "broken") && !force) return writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
1944
- if (state.kind === "managed" && state.version === bundled.version && !force) {
1945
- planned.push({
1946
- target,
1947
- action: "unchanged"
1948
- });
1949
- continue;
1950
- }
1951
- planned.push({
1952
- target,
1953
- action: state.kind === "missing" ? "installed" : "updated",
1954
- content: bundled.contents[tool]
1955
- });
1956
- }
1957
- await runActions(command, planned, parsed.options.dryRun === true, mode);
1958
- }
1959
- async function ensureSkills(parsed, mode, options = {}) {
1960
- const command = options.command ?? "skills ensure";
1961
- const filters = parseFilters(parsed, { allowAuto: true });
1962
- if (filters.error) {
1963
- writeFailure(command, filters.error, mode, 1);
1964
- return;
1965
- }
1966
- if (filters.tools.length === 0 && !filters.auto) {
1967
- writeFailure(command, validationError("--tool is required.", "Pass --tool auto, --tool codex, --tool claude, or --tool cursor; repeat explicit tools for multiple targets."), mode, 1);
1968
- return;
1969
- }
1970
- const bundled = await bundledOrFailure(command, mode);
1971
- if (!bundled) return void 0;
1972
- const targets = filters.auto ? await autoTargets(filters.scope) : filteredTargets(filters.tools, filters.scope ?? "project");
1973
- const planned = [];
1974
- for (const target of targets) {
1975
- const state = await readTarget(target);
1976
- if (state.kind === "unmanaged" || state.kind === "broken") {
1977
- writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
1978
- return;
1979
- }
1980
- const unchanged = state.kind === "managed" && state.version === bundled.version;
1981
- planned.push(unchanged ? {
1982
- target,
1983
- action: "unchanged"
1984
- } : {
1985
- target,
1986
- action: state.kind === "missing" ? "installed" : "updated",
1987
- content: bundled.contents[target.tool]
1988
- });
1989
- }
1990
- return finishActions(command, planned, parsed.options.dryRun === true, mode);
1991
- }
1992
- async function runSkillsEnsure(parsed, mode) {
1993
- const data = await ensureSkills(parsed, mode);
1994
- if (data) writeSuccess("skills ensure", data, mode);
1995
- }
1996
- async function runSkillsList(parsed, mode) {
1997
- const bundled = await bundledOrFailure("skills list", mode);
1998
- if (!bundled) return;
1999
- const targets = [];
2000
- for (const target of allTargets()) {
2001
- const state = await readTarget(target);
2002
- targets.push({
2003
- tool: target.tool,
2004
- scope: target.scope,
2005
- path: target.path,
2006
- detected: await isToolDetected(target.tool, target.scope),
2007
- installed: state.kind !== "missing",
2008
- managed: state.kind === "managed",
2009
- installed_version: state.kind === "managed" ? state.version : null,
2010
- update_available: state.kind === "managed" && state.version !== bundled.version
2011
- });
2012
- }
2013
- return writeSuccess("skills list", {
2014
- bundled_version: bundled.version,
2015
- targets
2016
- }, mode);
2017
- }
2018
- async function runSkillsUpdate(parsed, mode) {
2019
- const command = "skills update";
2020
- const filters = parseFilters(parsed);
2021
- if (filters.error) return writeFailure(command, filters.error, mode, 1);
2022
- const force = parsed.options.force === true;
2023
- const bundled = await bundledOrFailure(command, mode);
2024
- if (!bundled) return;
2025
- const planned = [];
2026
- for (const target of filteredTargets(filters.tools, filters.scope)) {
2027
- const state = await readTarget(target);
2028
- if (state.kind === "broken") return writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
2029
- if (state.kind === "missing") planned.push({
2030
- target,
2031
- action: "not_installed"
2032
- });
2033
- else if (state.kind === "unmanaged") planned.push({
2034
- target,
2035
- action: "skipped_unmanaged"
2036
- });
2037
- else if (state.version !== bundled.version || force) planned.push({
2038
- target,
2039
- action: "updated",
2040
- content: bundled.contents[target.tool]
2041
- });
2042
- else planned.push({
2043
- target,
2044
- action: "unchanged"
2045
- });
2046
- }
2047
- await runActions(command, planned, parsed.options.dryRun === true, mode);
2048
- }
2049
- async function runSkillsRemove(parsed, mode) {
2050
- const command = "skills remove";
2051
- const filters = parseFilters(parsed);
2052
- if (filters.error) return writeFailure(command, filters.error, mode, 1);
2053
- const planned = [];
2054
- for (const target of filteredTargets(filters.tools, filters.scope)) {
2055
- const state = await readTarget(target);
2056
- const action = state.kind === "missing" ? "not_installed" : state.kind === "managed" ? "removed" : "skipped_unmanaged";
2057
- planned.push({
2058
- target,
2059
- action
2060
- });
2061
- }
2062
- await runActions(command, planned, parsed.options.dryRun === true, mode);
2063
- }
2064
- //#endregion
2065
- //#region src/command-runners/agent.ts
2066
- async function runAgentOpen(parsed, mode) {
2067
- const command = "agent open";
2068
- const skills = await ensureSkills({
2069
- ...parsed,
2070
- options: {
2071
- ...parsed.options,
2072
- tool: "auto",
2073
- scope: "project"
2074
- }
2075
- }, mode, { command });
2076
- if (!skills) return;
2077
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to read.");
2078
- if (target.error) return writeFailure(command, target.error, mode, 1);
2079
- const result = await readArtifact(parsed, command);
2080
- if (result.error) {
2081
- if (result.error.code === "unsupported_kind") return writeSuccess(command, {
2082
- skills,
2083
- open: {
2084
- kind: "download_required",
2085
- next_command: agentDownloadCommand(target.artifactId)
2086
- }
2087
- }, mode);
2088
- return writeFailure(command, result.error, mode, 1);
2089
- }
2090
- return writeSuccess(command, {
2091
- skills,
2092
- open: {
2093
- kind: "read",
2094
- artifact: result.data
2095
- }
2096
- }, mode);
2097
- }
2098
- //#endregion
2099
- //#region src/command-runners/comments.ts
2100
- async function runCommentsList(parsed, mode) {
2101
- const command = "comments list";
2102
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2103
- if (target.error) return writeFailure(command, target.error, mode, 1);
2104
- const artifactId = target.artifactId;
2032
+ async function readArtifact(parsed, command) {
2033
+ const target = parseArtifactReadTarget(parsed, command);
2034
+ if (target.error) return { error: target.error };
2105
2035
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2106
- if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2107
- const request = await requestConfig(parsed.options);
2108
- if (request.error) return writeFailure(command, request.error, mode, 1);
2109
- const result = await apiGet(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, parsed.options, request.init, { artifactTarget: true });
2110
- if (result.error) return writeFailure(command, result.error, mode, 1);
2111
- const comments = Array.isArray(result.body?.comments) ? result.body.comments : [];
2112
- writeSuccess(command, {
2113
- artifact_id: artifactId,
2114
- share_url: configString(result.body?.share_url),
2115
- comments,
2116
- has_more: result.body?.has_more === true
2117
- }, mode);
2118
- if (!mode.json && comments.length === 0) writeText("No comments yet.\n");
2036
+ if (!credential.ok) return { error: credential.error };
2037
+ return await fetchArtifact(parsed, target.value, credential);
2119
2038
  }
2120
- async function runCommentsPost(parsed, mode) {
2121
- const command = "comments post";
2122
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2123
- if (target.error) return writeFailure(command, target.error, mode, 1);
2039
+ function parseArtifactReadTarget(parsed, command) {
2040
+ const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to read.");
2041
+ if (target.error) return { error: target.error };
2124
2042
  const artifactId = target.artifactId;
2125
- const body = parsed.options.body;
2126
- if (!body || !body.trim()) return writeFailure(command, validationError("A comment body is required.", "Retry with --body <text>."), mode, 1);
2127
- const replyTo = parsed.options.replyTo;
2128
- const quote = parsed.options.quote;
2129
- 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);
2130
- 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);
2131
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2132
- if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2133
- const request = await requestConfig(parsed.options);
2134
- if (request.error) return writeFailure(command, request.error, mode, 1);
2135
- const result = await apiPost(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, {
2136
- body,
2137
- reply_to: replyTo,
2138
- quote,
2139
- quote_before: parsed.options.quoteBefore,
2140
- quote_after: parsed.options.quoteAfter
2141
- }, parsed.options, request.init, { artifactTarget: true });
2142
- if (result.error) return writeFailure(command, result.error, mode, 1);
2143
- const threadId = configString(result.body?.thread_id);
2144
- if (!threadId) return writeFailure(command, serviceError("Comment was saved but the response had no thread id."), mode, 1);
2145
- writeSuccess(command, {
2146
- artifact_id: artifactId,
2147
- share_url: configString(result.body?.share_url),
2148
- thread_id: threadId,
2149
- reply: result.body?.reply === true,
2150
- thread: result.body?.thread ?? null
2151
- }, mode);
2152
- }
2153
- async function runCommentsEdit(parsed, mode) {
2154
- const command = "comments edit";
2155
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2156
- if (target.error) return writeFailure(command, target.error, mode, 1);
2157
- const messageId = requiredOption(parsed.options.messageId, "--message-id is required.", "Run comments list and retry with a listed message_id.");
2158
- if (messageId.error) return writeFailure(command, messageId.error, mode, 1);
2159
- const body = requiredOption(parsed.options.body, "--body is required.", "Pass --body <text> with the updated comment.");
2160
- if (body.error) return writeFailure(command, body.error, mode, 1);
2161
- const result = await postCommentAction(parsed, command, target.artifactId, {
2162
- action: "edit",
2163
- message_id: messageId.value,
2164
- body: body.value
2165
- }, mode);
2166
- if (!result) return;
2167
- const threadId = configString(result.thread_id);
2168
- if (!threadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
2169
- writeSuccess(command, {
2170
- artifact_id: target.artifactId,
2171
- share_url: configString(result.share_url),
2172
- thread_id: threadId,
2173
- thread: result.thread
2174
- }, mode);
2175
- }
2176
- async function runCommentsResolve(parsed, mode) {
2177
- return await runCommentsStatus(parsed, mode, "comments resolve", "resolve");
2178
- }
2179
- async function runCommentsReopen(parsed, mode) {
2180
- return await runCommentsStatus(parsed, mode, "comments reopen", "reopen");
2181
- }
2182
- async function runCommentsDelete(parsed, mode) {
2183
- const command = "comments delete";
2184
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2185
- if (target.error) return writeFailure(command, target.error, mode, 1);
2186
- const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
2187
- if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
2188
- const payload = {
2189
- action: "delete",
2190
- thread_id: threadId.value
2191
- };
2192
- if (parsed.options.messageId !== void 0) {
2193
- if (!parsed.options.messageId.trim()) return writeFailure(command, validationError("--message-id cannot be empty.", "Run comments list and retry with a listed message_id."), mode, 1);
2194
- payload.message_id = parsed.options.messageId.trim();
2195
- }
2196
- const result = await postCommentAction(parsed, command, target.artifactId, payload, mode);
2197
- if (!result) return;
2198
- const responseThreadId = configString(result.thread_id);
2199
- if (!responseThreadId || result.deleted !== true) return writeFailure(command, serviceError("Comment was deleted but the response was incomplete."), mode, 1);
2200
- writeSuccess(command, {
2201
- artifact_id: target.artifactId,
2202
- share_url: configString(result.share_url),
2203
- thread_id: responseThreadId,
2204
- deleted: true,
2205
- thread_deleted: result.thread_deleted === true,
2206
- ...result.thread !== void 0 ? { thread: result.thread } : {}
2207
- }, mode);
2208
- }
2209
- async function runCommentsStatus(parsed, mode, command, action) {
2210
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2211
- if (target.error) return writeFailure(command, target.error, mode, 1);
2212
- const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
2213
- if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
2214
- const result = await postCommentAction(parsed, command, target.artifactId, {
2215
- action,
2216
- thread_id: threadId.value
2217
- }, mode);
2218
- if (!result) return;
2219
- const responseThreadId = configString(result.thread_id);
2220
- if (!responseThreadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
2221
- writeSuccess(command, {
2222
- artifact_id: target.artifactId,
2223
- share_url: configString(result.share_url),
2224
- thread_id: responseThreadId,
2225
- thread: result.thread
2226
- }, mode);
2043
+ const offset = parseOffsetOption(parsed.options.offset);
2044
+ if (offset.error) return { error: offset.error };
2045
+ const include = parseIncludeOptions(parsed.options.include);
2046
+ if (include.error) return { error: include.error };
2047
+ return { value: {
2048
+ artifactId,
2049
+ include: include.values,
2050
+ offset: offset.value
2051
+ } };
2227
2052
  }
2228
- async function postCommentAction(parsed, command, artifactId, payload, mode) {
2229
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2230
- if (!credential.ok) {
2231
- writeFailure(command, credential.error, mode, 1);
2232
- return null;
2233
- }
2053
+ async function fetchArtifact(parsed, target, credential) {
2234
2054
  const request = await requestConfig(parsed.options);
2235
- if (request.error) {
2236
- writeFailure(command, request.error, mode, 1);
2237
- return null;
2238
- }
2239
- const result = await apiPost(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, payload, parsed.options, request.init, { artifactTarget: true });
2240
- if (result.error) {
2241
- writeFailure(command, result.error, mode, 1);
2242
- return null;
2243
- }
2244
- if (result.body === null) {
2245
- writeFailure(command, serviceError("Comment was changed but the response was empty."), mode, 1);
2246
- return null;
2247
- }
2248
- return result.body;
2249
- }
2250
- function requiredOption(value, message, hint) {
2251
- if (!value || !value.trim()) return { error: validationError(message, hint) };
2252
- return { value: value.trim() };
2055
+ if (request.error) return { error: request.error };
2056
+ const url = apiUrl(`/api/cli/artifacts/${encodeURIComponent(target.artifactId)}`, baseUrlOf(parsed.options));
2057
+ if (target.offset !== void 0) url.searchParams.set("offset", target.offset);
2058
+ for (const item of target.include) url.searchParams.append("include", item);
2059
+ const response = await fetch(url, {
2060
+ headers: { Authorization: `Bearer ${credential.token}` },
2061
+ ...request.init
2062
+ }).catch((error) => ({ networkError: error }));
2063
+ if ("networkError" in response) return { error: networkError(response.networkError) };
2064
+ const body = await readJson(response);
2065
+ if (!response.ok) return { error: mapApiError(response.status, body, {
2066
+ authenticated: true,
2067
+ artifactTarget: true,
2068
+ baseUrl: baseUrlOf(parsed.options),
2069
+ credentialSource: credential.source,
2070
+ profile: credential.profile
2071
+ }) };
2072
+ if (!artifactGetSuccessFields(body)) return { error: serviceError("Artifact read succeeded but the response did not include source metadata.") };
2073
+ return { data: body };
2253
2074
  }
2254
- //#endregion
2255
- //#region src/command-runners/delete.ts
2256
- async function runDelete(parsed, mode) {
2257
- const command = "delete";
2258
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to delete.");
2259
- if (target.error) return writeFailure(command, target.error, mode, 1);
2260
- const artifactId = target.artifactId;
2075
+ async function runArtifactsList(parsed, mode) {
2076
+ const command = "artifacts list";
2077
+ const hasProjectId = parsed.options.projectId !== void 0;
2078
+ const projectId = parsed.options.projectId?.trim() ?? "";
2079
+ const home = Boolean(parsed.options.home);
2080
+ if (hasProjectId && !projectId) return writeFailure(command, validationError("--project-id must not be empty.", "Pass --project-id <id>, use --home, or omit the destination filter."), mode, 1);
2081
+ if (hasProjectIdHomeConflict(parsed.options)) return writeFailure(command, validationError("Artifact list destination is ambiguous.", "Choose only one destination filter: --project-id <id> or --home.", "destination_conflict"), mode, 1);
2082
+ const query = parsed.options.query?.trim();
2083
+ if (parsed.options.query !== void 0 && !query) return writeFailure(command, validationError("--query must not be empty.", "Pass --query <text> or omit --query."), mode, 1);
2261
2084
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2262
2085
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2263
2086
  const request = await requestConfig(parsed.options);
2264
2087
  if (request.error) return writeFailure(command, request.error, mode, 1);
2265
- const result = await apiDelete(`/api/cli/artifacts/${encodeURIComponent(artifactId)}`, credential.token, parsed.options, request.init, {
2088
+ const url = apiUrl("/api/cli/artifacts", baseUrlOf(parsed.options));
2089
+ if (home) url.searchParams.set("project_id", "");
2090
+ else if (projectId) url.searchParams.set("project_id", projectId);
2091
+ if (query) url.searchParams.set("query", query);
2092
+ const response = await fetch(url, {
2093
+ headers: { Authorization: `Bearer ${credential.token}` },
2094
+ ...request.init
2095
+ }).catch((error) => ({ networkError: error }));
2096
+ if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
2097
+ const body = await readJson(response);
2098
+ if (!response.ok) return writeFailure(command, mapApiError(response.status, body, {
2266
2099
  authenticated: true,
2267
- artifactTarget: true
2268
- });
2269
- if (result.error) return writeFailure(command, result.error, mode, 1);
2270
- const body = result.body;
2271
- if (!deleteSuccessFields(body)) return writeFailure(command, serviceError("Delete succeeded but the response did not include deletion metadata."), mode, 1);
2100
+ baseUrl: baseUrlOf(parsed.options),
2101
+ credentialSource: credential.source,
2102
+ profile: credential.profile
2103
+ }), mode, 1);
2104
+ if (!artifactsListSuccessFields(body)) return writeFailure(command, serviceError("Artifact list succeeded but the response did not include list metadata."), mode, 1);
2272
2105
  return writeSuccess(command, body, mode);
2273
2106
  }
2274
2107
  //#endregion
2275
- //#region src/command-runners/doctor.ts
2276
- const LOGIN_COMMAND = `${CLI_INVOCATION} login`;
2277
- const REQUEST_ACCESS_COMMAND = `${CLI_INVOCATION} request-access`;
2278
- function bearerTokenBlocksLogin(data) {
2279
- return data.auth.credential_source === "env" || data.auth.credential_source === "token_option";
2280
- }
2281
- function resolveDoctorNextCommand(data) {
2282
- if (data.config.local.code === "token_store_unsafe") {
2283
- if (bearerTokenBlocksLogin(data)) return null;
2284
- return LOGIN_COMMAND;
2108
+ //#region src/command-runners/skills.ts
2109
+ const SKILL_TOOLS = [
2110
+ "codex",
2111
+ "claude",
2112
+ "cursor"
2113
+ ];
2114
+ const SKILL_FILE_PATH = join("skills", "artifactshare", "SKILL.md");
2115
+ const TOOL_CONFIG = {
2116
+ codex: {
2117
+ relativePath: join(".agents", SKILL_FILE_PATH),
2118
+ scopes: ["project", "user"],
2119
+ detectDirs: [".codex", ".agents"],
2120
+ bundledFile: "SKILL.md",
2121
+ pruneDirs: ["artifactshare", "skills"]
2122
+ },
2123
+ claude: {
2124
+ relativePath: join(".claude", SKILL_FILE_PATH),
2125
+ scopes: ["project", "user"],
2126
+ detectDirs: [".claude"],
2127
+ bundledFile: "SKILL.md",
2128
+ pruneDirs: ["artifactshare", "skills"]
2129
+ },
2130
+ cursor: {
2131
+ relativePath: join(".cursor", "rules", "artifactshare.mdc"),
2132
+ scopes: ["project"],
2133
+ detectDirs: [".cursor"],
2134
+ bundledFile: "artifactshare.mdc",
2135
+ pruneDirs: []
2285
2136
  }
2286
- if (data.config.project.code === "token_store_unsafe") {
2287
- if (bearerTokenBlocksLogin(data)) return null;
2288
- return LOGIN_COMMAND;
2137
+ };
2138
+ function skillTarget(tool, scope) {
2139
+ const relative = TOOL_CONFIG[tool].relativePath;
2140
+ const path = scope === "project" ? relative : join(homedir(), relative);
2141
+ return {
2142
+ tool,
2143
+ scope,
2144
+ path,
2145
+ absolutePath: resolve(path)
2146
+ };
2147
+ }
2148
+ function allTargets() {
2149
+ return SKILL_TOOLS.flatMap((tool) => TOOL_CONFIG[tool].scopes.map((scope) => skillTarget(tool, scope)));
2150
+ }
2151
+ function managedState(content) {
2152
+ if (content === null) return { kind: "missing" };
2153
+ if (!content.includes("artifactshare-skill")) return { kind: "unmanaged" };
2154
+ const block = content.match(/<!--\s*artifactshare-skill([\s\S]*?)-->/)?.[1];
2155
+ const version = block?.match(/(?:^|\n)\s*version:\s*(\d+)\s*(?:\n|$)/)?.[1];
2156
+ const managed = block !== void 0 && /(?:^|\n)\s*managed:\s*true\s*(?:\n|$)/.test(block);
2157
+ if (version === void 0 || !managed) return { kind: "broken" };
2158
+ return {
2159
+ kind: "managed",
2160
+ version: Number(version)
2161
+ };
2162
+ }
2163
+ async function readTarget(target) {
2164
+ return managedState(await readFile(target.absolutePath, "utf8").catch(() => null));
2165
+ }
2166
+ async function loadBundledSkills() {
2167
+ const byFile = /* @__PURE__ */ new Map();
2168
+ const contents = {};
2169
+ let version;
2170
+ for (const tool of SKILL_TOOLS) {
2171
+ const file = TOOL_CONFIG[tool].bundledFile;
2172
+ let content = byFile.get(file);
2173
+ if (content === void 0) {
2174
+ content = await readFile(new URL(`../skills/artifactshare/${file}`, import.meta.url), "utf8");
2175
+ const state = managedState(content);
2176
+ if (state.kind !== "managed" || (version ?? state.version) !== state.version) throw new Error(`The bundled ${file} has a missing or mismatched managed marker.`);
2177
+ version = state.version;
2178
+ byFile.set(file, content);
2179
+ }
2180
+ contents[tool] = content;
2289
2181
  }
2290
- if ((data.auth.code === "auth_required" || data.auth.code === "token_invalid") && !bearerTokenBlocksLogin(data)) return data.auth.profile ? `${LOGIN_COMMAND} --profile ${data.auth.profile}` : LOGIN_COMMAND;
2291
- if (!data.network.ok) return null;
2292
- if (data.upload.checked && !data.upload.ok) {
2293
- if (data.upload.code === "upload-not-allowed") return REQUEST_ACCESS_COMMAND;
2294
- return null;
2182
+ return {
2183
+ contents,
2184
+ version
2185
+ };
2186
+ }
2187
+ function parseTools(value, options = {}) {
2188
+ const raws = arrayOption(value);
2189
+ const tools = [];
2190
+ for (const raw of raws) for (const item of raw.split(",")) {
2191
+ const trimmed = item.trim();
2192
+ if (!trimmed) continue;
2193
+ if (trimmed === "auto") {
2194
+ if (!options.allowAuto) return { error: validationError(`Unknown --tool value: ${trimmed}`, "Pass --tool codex, --tool claude, or --tool cursor.") };
2195
+ tools.push(trimmed);
2196
+ continue;
2197
+ }
2198
+ if (!SKILL_TOOLS.includes(trimmed)) return { error: validationError(`Unknown --tool value: ${trimmed}`, "Pass --tool codex, --tool claude, or --tool cursor.") };
2199
+ tools.push(trimmed);
2295
2200
  }
2296
- return null;
2201
+ if (raws.length > 0 && tools.length === 0) return { error: validationError("--tool has no value.", "Pass --tool codex, --tool claude, or --tool cursor.") };
2202
+ const unique = [...new Set(tools)];
2203
+ const auto = unique.includes("auto");
2204
+ if (auto && unique.length > 1) return { error: validationError("--tool auto cannot be combined with explicit tools.", "Pass --tool auto by itself, or pass --tool codex, --tool claude, or --tool cursor.") };
2205
+ return {
2206
+ tools: unique.filter((tool) => tool !== "auto"),
2207
+ auto
2208
+ };
2297
2209
  }
2298
- function authRecovery(data, nextCommand) {
2299
- const loginCommand = nextCommand?.startsWith(LOGIN_COMMAND) === true ? nextCommand : data.auth.profile ? `${LOGIN_COMMAND} --profile ${data.auth.profile}` : LOGIN_COMMAND;
2300
- return authRecoveryDetails(data.base_url, loginCommand);
2210
+ function parseScope(value) {
2211
+ const trimmed = nonEmpty(value);
2212
+ if (trimmed === void 0) return { scope: void 0 };
2213
+ if (trimmed === "project" || trimmed === "user") return { scope: trimmed };
2214
+ return { error: validationError(`Unknown --scope value: ${trimmed}`, "Pass --scope project or --scope user.") };
2301
2215
  }
2302
- function doctorDataWithNextCommand(data) {
2303
- const nextCommand = resolveDoctorNextCommand(data);
2304
- const next = {
2305
- ...data,
2306
- next_command: nextCommand
2307
- };
2308
- if (next.auth.code === "auth_required") next.auth = {
2309
- ...next.auth,
2310
- recovery: authRecovery(next, nextCommand)
2216
+ function parseFilters(parsed, options = {}) {
2217
+ const tools = parseTools(parsed.options.tool, options);
2218
+ if (tools.error) return { error: tools.error };
2219
+ const scope = parseScope(parsed.options.scope);
2220
+ if (scope.error) return { error: scope.error };
2221
+ if (tools.auto && scope.scope === "user") return { error: validationError("--tool auto supports project scope only.", "Use --tool auto --scope project, or pass an explicit --tool for user scope.") };
2222
+ const unsupported = scope.scope === void 0 ? void 0 : tools.tools.find((tool) => !TOOL_CONFIG[tool].scopes.includes(scope.scope));
2223
+ if (unsupported) return { error: validationError(`The ${unsupported} tool does not support --scope ${scope.scope}.`, `Use --tool ${unsupported} --scope project.`) };
2224
+ return {
2225
+ tools: tools.tools,
2226
+ auto: tools.auto,
2227
+ scope: scope.scope
2311
2228
  };
2312
- return next;
2313
2229
  }
2314
- async function runDoctor(parsed, mode) {
2315
- const command = "doctor";
2316
- const project = await resolveProjectConfig();
2317
- const credential = await resolveCredential(parsed.options, project);
2318
- const destination = resolveDestination(parsed.options, project.config);
2319
- const data = {
2320
- next_command: null,
2321
- base_url: baseUrlOf(parsed.options),
2322
- config: await configDiagnostics(project),
2323
- auth: {
2324
- credential_source: credential.source,
2325
- ...credential.profile ? { profile: credential.profile } : {},
2326
- token_present: credential.ok,
2327
- ok: false
2328
- },
2329
- destination: destination.error ? {
2330
- ok: false,
2331
- code: destination.error.code,
2332
- hint: destination.error.hint
2333
- } : {
2334
- ok: true,
2335
- type: destination.containerId ? "project" : "home",
2336
- project_id: destination.containerId ?? null
2337
- },
2338
- network: { ok: false },
2339
- upload: {
2340
- ok: false,
2341
- checked: false
2342
- }
2343
- };
2344
- if (!credential.ok) {
2345
- if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
2346
- data.auth.code = credential.error.code;
2347
- data.auth.hint = credential.error.hint;
2348
- return writeSuccess(command, doctorDataWithNextCommand(data), mode);
2349
- }
2350
- const request = await requestConfig(parsed.options);
2351
- if (request.error) return writeFailure(command, request.error, mode, 1);
2352
- const response = await fetch(apiUrl("/api/cli/doctor", baseUrlOf(parsed.options)), {
2353
- headers: { Authorization: `Bearer ${credential.token}` },
2354
- ...request.init
2355
- }).catch((error) => ({ networkError: error }));
2356
- if ("networkError" in response) {
2357
- data.network = {
2358
- ok: false,
2359
- code: "network_failed",
2360
- hint: networkError(response.networkError).hint
2361
- };
2362
- return writeSuccess(command, doctorDataWithNextCommand(data), mode);
2230
+ function filteredTargets(tools, scope) {
2231
+ return allTargets().filter((target) => (tools.length === 0 || tools.includes(target.tool)) && (scope === void 0 || target.scope === scope));
2232
+ }
2233
+ function detectionBase(scope) {
2234
+ return scope === "project" ? process.cwd() : homedir();
2235
+ }
2236
+ async function isToolDetected(tool, scope) {
2237
+ const base = detectionBase(scope);
2238
+ for (const dir of TOOL_CONFIG[tool].detectDirs) if ((await stat(join(base, dir)).catch(() => null))?.isDirectory()) return true;
2239
+ return false;
2240
+ }
2241
+ async function autoTargets(scope) {
2242
+ const targetScope = scope ?? "project";
2243
+ const autoOrder = [
2244
+ "claude",
2245
+ "codex",
2246
+ "cursor"
2247
+ ];
2248
+ const detected = /* @__PURE__ */ new Set();
2249
+ for (const tool of autoOrder) if (TOOL_CONFIG[tool].scopes.includes(targetScope) && await isToolDetected(tool, targetScope)) detected.add(tool);
2250
+ return (detected.size > 0 ? [...detected] : ["codex", "claude"]).filter((tool) => TOOL_CONFIG[tool].scopes.includes(targetScope)).map((tool) => skillTarget(tool, targetScope));
2251
+ }
2252
+ async function applyAction({ target, action, content }) {
2253
+ if (content !== void 0) {
2254
+ await mkdir(dirname(target.absolutePath), { recursive: true });
2255
+ await writeFile(target.absolutePath, content);
2256
+ return;
2363
2257
  }
2364
- data.network.ok = true;
2365
- const body = await readJson(response);
2366
- if (!response.ok) {
2367
- const error = mapApiError(response.status, body, { authenticated: true });
2368
- data.auth.code = error.code;
2369
- data.auth.hint = error.hint;
2370
- return writeSuccess(command, doctorDataWithNextCommand(data), mode);
2258
+ if (action === "removed") {
2259
+ await rm(target.absolutePath, { force: true });
2260
+ await cleanupSkillDirs(target);
2371
2261
  }
2372
- if (!body) throw new Error("Doctor response was not valid JSON.");
2373
- data.auth.ok = body.auth?.ok ?? true;
2374
- data.auth.email = body.user?.email ?? null;
2375
- data.upload.checked = true;
2376
- data.upload.ok = body.upload?.ok ?? false;
2377
- if (!data.upload.ok) {
2378
- data.upload.code = normalizeApiCode(body.upload?.code);
2379
- data.upload.hint = uploadBlockedHint(data.upload.code);
2262
+ }
2263
+ async function cleanupSkillDirs(target) {
2264
+ let dir = dirname(target.absolutePath);
2265
+ for (const expected of TOOL_CONFIG[target.tool].pruneDirs) {
2266
+ if (basename(dir) !== expected) return;
2267
+ try {
2268
+ await rmdir(dir);
2269
+ } catch {
2270
+ return;
2271
+ }
2272
+ dir = dirname(dir);
2380
2273
  }
2381
- return writeSuccess(command, doctorDataWithNextCommand(data), mode);
2382
2274
  }
2383
- async function configDiagnostics(project) {
2384
- const globalConfig = await readGlobalConfig();
2385
- const cwd = process.cwd();
2386
- const directory = project.directory;
2387
- const localRaw = directory ? await readProjectConfigAtDirectory(directory, "local") : null;
2388
- const sharedRaw = directory ? await readProjectConfigAtDirectory(directory, "shared") : null;
2275
+ async function finishActions(command, planned, dryRun, mode) {
2276
+ if (!dryRun) try {
2277
+ for (const item of planned) await applyAction(item);
2278
+ } catch (error) {
2279
+ writeFailure(command, unexpectedError(error), mode, 1);
2280
+ return;
2281
+ }
2389
2282
  return {
2390
- local: fileDiagnostics(localRaw, directory ? relativeProjectConfigPath(cwd, directory, PROJECT_CONFIG_LOCAL_PATH) : null),
2391
- project: fileDiagnostics(sharedRaw, directory ? relativeProjectConfigPath(cwd, directory, PROJECT_CONFIG_PATH) : null),
2392
- global: {
2393
- present: globalConfig !== null,
2394
- default_profile: configString(globalConfig?.default_profile),
2395
- profile_count: Object.keys(globalConfig?.profiles ?? {}).length
2396
- },
2397
- effective: effectiveDiagnostics(project, globalConfig)
2283
+ dry_run: dryRun,
2284
+ targets: planned.map(({ target, action }) => ({
2285
+ tool: target.tool,
2286
+ scope: target.scope,
2287
+ path: target.path,
2288
+ action
2289
+ }))
2398
2290
  };
2399
2291
  }
2400
- function fileDiagnostics(raw, path) {
2401
- const unsafeKey = Object.keys(raw ?? {}).find((key) => key.toLowerCase().includes("token"));
2402
- return {
2403
- present: raw !== null,
2404
- path,
2405
- default_profile: configString(raw?.default_profile),
2406
- default_project_id: configString(raw?.default_project_id),
2407
- ...unsafeKey ? {
2408
- code: "token_store_unsafe",
2409
- hint: `Remove "${unsafeKey}" from ${path ?? "the working-directory config"} and run ${CLI_INVOCATION} login instead; the working-directory config must never hold secrets.`
2410
- } : {}
2411
- };
2292
+ async function runActions(command, planned, dryRun, mode) {
2293
+ const data = await finishActions(command, planned, dryRun, mode);
2294
+ if (data) writeSuccess(command, data, mode);
2412
2295
  }
2413
- function effectiveDiagnostics(project, globalConfig) {
2414
- const projectProfile = configString(project.config?.default_profile);
2415
- const projectProjectId = configString(project.config?.default_project_id);
2416
- const globalProfile = configString(globalConfig?.default_profile);
2417
- const defaultProfile = projectProfile ?? globalProfile;
2418
- const defaultProfileSource = projectProfile ? project.kind === "local" ? "local" : "project" : globalProfile ? "global" : "none";
2419
- const defaultProfilePath = defaultProfileSource === "local" || defaultProfileSource === "project" ? project.path : null;
2420
- const defaultProjectId = projectProjectId;
2421
- const defaultProjectIdSource = projectProjectId ? project.kind === "local" ? "local" : "project" : "none";
2422
- return {
2423
- default_profile: defaultProfile,
2424
- default_profile_source: defaultProfileSource,
2425
- default_profile_path: defaultProfilePath,
2426
- default_project_id: defaultProjectId,
2427
- default_project_id_source: defaultProjectIdSource,
2428
- default_project_id_path: defaultProjectIdSource === "local" || defaultProjectIdSource === "project" ? project.path : null
2429
- };
2296
+ async function bundledOrFailure(command, mode) {
2297
+ try {
2298
+ return await loadBundledSkills();
2299
+ } catch (error) {
2300
+ writeFailure(command, unexpectedError(error), mode, 1);
2301
+ return;
2302
+ }
2303
+ }
2304
+ async function runSkillsInstall(parsed, mode) {
2305
+ const command = "skills install";
2306
+ const filters = parseFilters(parsed);
2307
+ if (filters.error) return writeFailure(command, filters.error, mode, 1);
2308
+ const { tools } = filters;
2309
+ if (tools.length === 0) return writeFailure(command, validationError("--tool is required.", "Pass --tool codex, --tool claude, or --tool cursor; repeat for multiple tools."), mode, 1);
2310
+ const scope = filters.scope ?? "project";
2311
+ const force = parsed.options.force === true;
2312
+ const bundled = await bundledOrFailure(command, mode);
2313
+ if (!bundled) return;
2314
+ const planned = [];
2315
+ for (const tool of tools) {
2316
+ const target = skillTarget(tool, scope);
2317
+ const state = await readTarget(target);
2318
+ if ((state.kind === "unmanaged" || state.kind === "broken") && !force) return writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
2319
+ if (state.kind === "managed" && state.version === bundled.version && !force) {
2320
+ planned.push({
2321
+ target,
2322
+ action: "unchanged"
2323
+ });
2324
+ continue;
2325
+ }
2326
+ planned.push({
2327
+ target,
2328
+ action: state.kind === "missing" ? "installed" : "updated",
2329
+ content: bundled.contents[tool]
2330
+ });
2331
+ }
2332
+ await runActions(command, planned, parsed.options.dryRun === true, mode);
2430
2333
  }
2431
- //#endregion
2432
- //#region src/files.ts
2433
- async function prepareUploadPayload(targetPath, fileStat, initialForm = new FormData()) {
2434
- if (fileStat.isDirectory()) {
2435
- let files;
2436
- try {
2437
- files = await collectDirectoryFiles(resolve(targetPath));
2438
- } catch (error) {
2439
- if (error instanceof CollectDirectoryFilesError) return { error: validationError(error.message, error.hint) };
2440
- throw error;
2334
+ async function ensureSkills(parsed, mode, options = {}) {
2335
+ const command = options.command ?? "skills ensure";
2336
+ const filters = parseFilters(parsed, { allowAuto: true });
2337
+ if (filters.error) {
2338
+ writeFailure(command, filters.error, mode, 1);
2339
+ return;
2340
+ }
2341
+ if (filters.tools.length === 0 && !filters.auto) {
2342
+ writeFailure(command, validationError("--tool is required.", "Pass --tool auto, --tool codex, --tool claude, or --tool cursor; repeat explicit tools for multiple targets."), mode, 1);
2343
+ return;
2344
+ }
2345
+ const bundled = await bundledOrFailure(command, mode);
2346
+ if (!bundled) return void 0;
2347
+ const targets = filters.auto ? await autoTargets(filters.scope) : filteredTargets(filters.tools, filters.scope ?? "project");
2348
+ const planned = [];
2349
+ for (const target of targets) {
2350
+ const state = await readTarget(target);
2351
+ if (state.kind === "unmanaged" || state.kind === "broken") {
2352
+ writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
2353
+ return;
2441
2354
  }
2442
- if (files.length === 0) return { error: validationError("Directory has no publishable files.", "Add index.html or index.md and retry.") };
2443
- for (const file of files) initialForm.append("file", await blobFor(file.path), file.relativePath);
2444
- return { payload: {
2445
- form: initialForm,
2446
- kind: "static_site"
2447
- } };
2355
+ const unchanged = state.kind === "managed" && state.version === bundled.version;
2356
+ planned.push(unchanged ? {
2357
+ target,
2358
+ action: "unchanged"
2359
+ } : {
2360
+ target,
2361
+ action: state.kind === "missing" ? "installed" : "updated",
2362
+ content: bundled.contents[target.tool]
2363
+ });
2448
2364
  }
2449
- if (fileStat.isFile()) {
2450
- initialForm.append("file", await blobFor(targetPath), basename(targetPath));
2451
- return { payload: {
2452
- form: initialForm,
2453
- kind: artifactKindForFile(targetPath)
2454
- } };
2365
+ return finishActions(command, planned, parsed.options.dryRun === true, mode);
2366
+ }
2367
+ async function runSkillsEnsure(parsed, mode) {
2368
+ const data = await ensureSkills(parsed, mode);
2369
+ if (data) writeSuccess("skills ensure", data, mode);
2370
+ }
2371
+ async function runSkillsList(parsed, mode) {
2372
+ const bundled = await bundledOrFailure("skills list", mode);
2373
+ if (!bundled) return;
2374
+ const targets = [];
2375
+ for (const target of allTargets()) {
2376
+ const state = await readTarget(target);
2377
+ targets.push({
2378
+ tool: target.tool,
2379
+ scope: target.scope,
2380
+ path: target.path,
2381
+ detected: await isToolDetected(target.tool, target.scope),
2382
+ installed: state.kind !== "missing",
2383
+ managed: state.kind === "managed",
2384
+ installed_version: state.kind === "managed" ? state.version : null,
2385
+ update_available: state.kind === "managed" && state.version !== bundled.version
2386
+ });
2455
2387
  }
2456
- return { error: validationError("Path must be a file or directory.", "Pass a regular file or directory.") };
2388
+ return writeSuccess("skills list", {
2389
+ bundled_version: bundled.version,
2390
+ targets
2391
+ }, mode);
2457
2392
  }
2458
- async function prepareDownloadPlan(manifest, outputPath, force) {
2459
- if (manifest.files.length === 0) return { error: validationError("Download manifest contains no files.", "Check the artifact and retry.") };
2460
- if (outputPath === "") return { error: validationError("--output requires a non-empty directory.", "Pass --output <path> or omit --output to use the artifact ID.") };
2461
- const root = resolve(outputPath);
2462
- const existing = await lstat(root).catch(() => null);
2463
- if (existing?.isSymbolicLink()) return { error: validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry.") };
2464
- if (existing && !force) return { error: cliError({
2465
- code: "output_exists",
2466
- message: "Output path already exists.",
2467
- why: "Download will not write into an existing path unless --force is set.",
2468
- hint: "Choose a different --output path or retry with --force.",
2469
- agentRecoverable: true,
2470
- requiresHuman: false,
2471
- recovery: { kind: "change_input" }
2472
- }) };
2473
- if (existing && !existing.isDirectory()) return { error: validationError("Output path is not a directory.", "Choose a directory path or remove the existing file.") };
2474
- const seen = /* @__PURE__ */ new Set();
2475
- const relativeFiles = [];
2476
- for (const file of manifest.files) {
2477
- const relativePath = downloadRelativePath(file.path);
2478
- if (relativePath.error) return { error: relativePath.error };
2479
- if (seen.has(relativePath.value)) return { error: validationError("Download manifest contains duplicate file paths.", "Retry later. If this repeats, report the artifact ID.") };
2480
- seen.add(relativePath.value);
2481
- relativeFiles.push({
2482
- ...file,
2483
- relativePath: relativePath.value
2393
+ async function runSkillsUpdate(parsed, mode) {
2394
+ const command = "skills update";
2395
+ const filters = parseFilters(parsed);
2396
+ if (filters.error) return writeFailure(command, filters.error, mode, 1);
2397
+ const force = parsed.options.force === true;
2398
+ const bundled = await bundledOrFailure(command, mode);
2399
+ if (!bundled) return;
2400
+ const planned = [];
2401
+ for (const target of filteredTargets(filters.tools, filters.scope)) {
2402
+ const state = await readTarget(target);
2403
+ if (state.kind === "broken") return writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
2404
+ if (state.kind === "missing") planned.push({
2405
+ target,
2406
+ action: "not_installed"
2407
+ });
2408
+ else if (state.kind === "unmanaged") planned.push({
2409
+ target,
2410
+ action: "skipped_unmanaged"
2411
+ });
2412
+ else if (state.version !== bundled.version || force) planned.push({
2413
+ target,
2414
+ action: "updated",
2415
+ content: bundled.contents[target.tool]
2416
+ });
2417
+ else planned.push({
2418
+ target,
2419
+ action: "unchanged"
2484
2420
  });
2485
2421
  }
2486
- const parent = dirname(root);
2487
- await mkdir(parent, { recursive: true });
2488
- const tempRoot = await mkdtemp(join(parent, `.${basename(root)}.tmp-`));
2489
- const files = [];
2490
- for (const file of relativeFiles) {
2491
- const targetPath = resolve(tempRoot, file.relativePath);
2492
- files.push({
2493
- ...file,
2494
- targetPath
2422
+ await runActions(command, planned, parsed.options.dryRun === true, mode);
2423
+ }
2424
+ async function runSkillsRemove(parsed, mode) {
2425
+ const command = "skills remove";
2426
+ const filters = parseFilters(parsed);
2427
+ if (filters.error) return writeFailure(command, filters.error, mode, 1);
2428
+ const planned = [];
2429
+ for (const target of filteredTargets(filters.tools, filters.scope)) {
2430
+ const state = await readTarget(target);
2431
+ const action = state.kind === "missing" ? "not_installed" : state.kind === "managed" ? "removed" : "skipped_unmanaged";
2432
+ planned.push({
2433
+ target,
2434
+ action
2495
2435
  });
2496
2436
  }
2497
- return { value: {
2498
- root,
2499
- tempRoot,
2500
- replaceExisting: Boolean(existing),
2501
- files
2502
- } };
2437
+ await runActions(command, planned, parsed.options.dryRun === true, mode);
2438
+ }
2439
+ //#endregion
2440
+ //#region src/command-runners/agent.ts
2441
+ async function runAgentOpen(parsed, mode) {
2442
+ const command = "agent open";
2443
+ const skills = await ensureSkills({
2444
+ ...parsed,
2445
+ options: {
2446
+ ...parsed.options,
2447
+ tool: "auto",
2448
+ scope: "project"
2449
+ }
2450
+ }, mode, { command });
2451
+ if (!skills) return;
2452
+ const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to read.");
2453
+ if (target.error) return writeFailure(command, target.error, mode, 1);
2454
+ const result = await readArtifact(parsed, command);
2455
+ if (result.error) {
2456
+ if (result.error.code === "unsupported_kind") return writeSuccess(command, {
2457
+ skills,
2458
+ open: {
2459
+ kind: "download_required",
2460
+ next_command: agentDownloadCommand(target.artifactId)
2461
+ }
2462
+ }, mode);
2463
+ return writeFailure(command, result.error, mode, 1);
2464
+ }
2465
+ return writeSuccess(command, {
2466
+ skills,
2467
+ open: {
2468
+ kind: "read",
2469
+ artifact: result.data
2470
+ }
2471
+ }, mode);
2472
+ }
2473
+ //#endregion
2474
+ //#region src/command-runners/comments.ts
2475
+ async function runCommentsList(parsed, mode) {
2476
+ const command = "comments list";
2477
+ const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2478
+ if (target.error) return writeFailure(command, target.error, mode, 1);
2479
+ const artifactId = target.artifactId;
2480
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2481
+ if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2482
+ const request = await requestConfig(parsed.options);
2483
+ if (request.error) return writeFailure(command, request.error, mode, 1);
2484
+ const result = await apiGet(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, parsed.options, request.init, {
2485
+ artifactTarget: true,
2486
+ credentialSource: credential.source,
2487
+ profile: credential.profile
2488
+ });
2489
+ if (result.error) return writeFailure(command, result.error, mode, 1);
2490
+ const comments = Array.isArray(result.body?.comments) ? result.body.comments : [];
2491
+ writeSuccess(command, {
2492
+ artifact_id: artifactId,
2493
+ share_url: configString(result.body?.share_url),
2494
+ comments,
2495
+ has_more: result.body?.has_more === true
2496
+ }, mode);
2497
+ if (!mode.json && comments.length === 0) writeText("No comments yet.\n");
2498
+ }
2499
+ async function runCommentsPost(parsed, mode) {
2500
+ const command = "comments post";
2501
+ const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2502
+ if (target.error) return writeFailure(command, target.error, mode, 1);
2503
+ const artifactId = target.artifactId;
2504
+ const body = parsed.options.body;
2505
+ if (!body || !body.trim()) return writeFailure(command, validationError("A comment body is required.", "Retry with --body <text>."), mode, 1);
2506
+ const replyTo = parsed.options.replyTo;
2507
+ const quote = parsed.options.quote;
2508
+ 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);
2509
+ 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);
2510
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2511
+ if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2512
+ const request = await requestConfig(parsed.options);
2513
+ if (request.error) return writeFailure(command, request.error, mode, 1);
2514
+ const result = await apiPost(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, {
2515
+ body,
2516
+ reply_to: replyTo,
2517
+ quote,
2518
+ quote_before: parsed.options.quoteBefore,
2519
+ quote_after: parsed.options.quoteAfter
2520
+ }, parsed.options, request.init, {
2521
+ artifactTarget: true,
2522
+ credentialSource: credential.source,
2523
+ profile: credential.profile
2524
+ });
2525
+ if (result.error) return writeFailure(command, result.error, mode, 1);
2526
+ const threadId = configString(result.body?.thread_id);
2527
+ if (!threadId) return writeFailure(command, serviceError("Comment was saved but the response had no thread id."), mode, 1);
2528
+ writeSuccess(command, {
2529
+ artifact_id: artifactId,
2530
+ share_url: configString(result.body?.share_url),
2531
+ thread_id: threadId,
2532
+ reply: result.body?.reply === true,
2533
+ thread: result.body?.thread ?? null
2534
+ }, mode);
2503
2535
  }
2504
- function downloadRelativePath(path) {
2505
- if (!path.startsWith("/") || path.includes("\0") || path.includes("\\")) return { error: validationError("Download manifest contains an invalid file path.", "Retry later. If this repeats, report the artifact ID.") };
2506
- const segments = path.split("/").slice(1);
2507
- if (segments.length === 0 || segments.some((segment) => segment === "" || segment === "." || segment === "..")) return { error: validationError("Download manifest contains an unsafe file path.", "Retry later. If this repeats, report the artifact ID.") };
2508
- return { value: segments.join("/") };
2536
+ async function runCommentsEdit(parsed, mode) {
2537
+ const command = "comments edit";
2538
+ const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2539
+ if (target.error) return writeFailure(command, target.error, mode, 1);
2540
+ const messageId = requiredOption(parsed.options.messageId, "--message-id is required.", "Run comments list and retry with a listed message_id.");
2541
+ if (messageId.error) return writeFailure(command, messageId.error, mode, 1);
2542
+ const body = requiredOption(parsed.options.body, "--body is required.", "Pass --body <text> with the updated comment.");
2543
+ if (body.error) return writeFailure(command, body.error, mode, 1);
2544
+ const result = await postCommentAction(parsed, command, target.artifactId, {
2545
+ action: "edit",
2546
+ message_id: messageId.value,
2547
+ body: body.value
2548
+ }, mode);
2549
+ if (!result) return;
2550
+ const threadId = configString(result.thread_id);
2551
+ if (!threadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
2552
+ writeSuccess(command, {
2553
+ artifact_id: target.artifactId,
2554
+ share_url: configString(result.share_url),
2555
+ thread_id: threadId,
2556
+ thread: result.thread
2557
+ }, mode);
2509
2558
  }
2510
- function verifyDownloadedBytes(file, bytes) {
2511
- if (bytes.byteLength !== file.size_bytes) return { error: downloadIntegrityError(file.path, "size mismatch") };
2512
- if (file.sha256) {
2513
- if (createHash("sha256").update(bytes).digest("base64url") !== file.sha256) return { error: downloadIntegrityError(file.path, "sha256 mismatch") };
2514
- }
2515
- return { ok: true };
2559
+ async function runCommentsResolve(parsed, mode) {
2560
+ return await runCommentsStatus(parsed, mode, "comments resolve", "resolve");
2516
2561
  }
2517
- function downloadIntegrityError(path, reason) {
2518
- return cliError({
2519
- code: "download_integrity_failed",
2520
- message: "Downloaded file did not match the manifest.",
2521
- why: `The downloaded file ${path} failed integrity verification: ${reason}.`,
2522
- hint: "Retry the download. If this repeats, report the artifact ID.",
2523
- agentRecoverable: true,
2524
- requiresHuman: false,
2525
- recovery: { kind: "retry_later" }
2526
- });
2562
+ async function runCommentsReopen(parsed, mode) {
2563
+ return await runCommentsStatus(parsed, mode, "comments reopen", "reopen");
2527
2564
  }
2528
- function backupPathFor(root) {
2529
- return join(dirname(root), `.${basename(root)}.old-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
2565
+ async function runCommentsDelete(parsed, mode) {
2566
+ const command = "comments delete";
2567
+ const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2568
+ if (target.error) return writeFailure(command, target.error, mode, 1);
2569
+ const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
2570
+ if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
2571
+ const payload = {
2572
+ action: "delete",
2573
+ thread_id: threadId.value
2574
+ };
2575
+ if (parsed.options.messageId !== void 0) {
2576
+ if (!parsed.options.messageId.trim()) return writeFailure(command, validationError("--message-id cannot be empty.", "Run comments list and retry with a listed message_id."), mode, 1);
2577
+ payload.message_id = parsed.options.messageId.trim();
2578
+ }
2579
+ const result = await postCommentAction(parsed, command, target.artifactId, payload, mode);
2580
+ if (!result) return;
2581
+ const responseThreadId = configString(result.thread_id);
2582
+ if (!responseThreadId || result.deleted !== true) return writeFailure(command, serviceError("Comment was deleted but the response was incomplete."), mode, 1);
2583
+ writeSuccess(command, {
2584
+ artifact_id: target.artifactId,
2585
+ share_url: configString(result.share_url),
2586
+ thread_id: responseThreadId,
2587
+ deleted: true,
2588
+ thread_deleted: result.thread_deleted === true,
2589
+ ...result.thread !== void 0 ? { thread: result.thread } : {}
2590
+ }, mode);
2530
2591
  }
2531
- async function pathExists(path) {
2532
- return Boolean(await lstat(path).catch(() => null));
2592
+ async function runCommentsStatus(parsed, mode, command, action) {
2593
+ const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
2594
+ if (target.error) return writeFailure(command, target.error, mode, 1);
2595
+ const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
2596
+ if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
2597
+ const result = await postCommentAction(parsed, command, target.artifactId, {
2598
+ action,
2599
+ thread_id: threadId.value
2600
+ }, mode);
2601
+ if (!result) return;
2602
+ const responseThreadId = configString(result.thread_id);
2603
+ if (!responseThreadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
2604
+ writeSuccess(command, {
2605
+ artifact_id: target.artifactId,
2606
+ share_url: configString(result.share_url),
2607
+ thread_id: responseThreadId,
2608
+ thread: result.thread
2609
+ }, mode);
2533
2610
  }
2534
- function downloadFileSystemError(error) {
2535
- return cliError({
2536
- code: "download_failed",
2537
- message: "Could not write downloaded files.",
2538
- why: error instanceof Error ? error.message : "The local filesystem rejected a download operation.",
2539
- hint: "Check --output permissions and available disk space, then retry.",
2540
- agentRecoverable: true,
2541
- requiresHuman: false,
2542
- recovery: { kind: "change_input" }
2611
+ async function postCommentAction(parsed, command, artifactId, payload, mode) {
2612
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2613
+ if (!credential.ok) {
2614
+ writeFailure(command, credential.error, mode, 1);
2615
+ return null;
2616
+ }
2617
+ const request = await requestConfig(parsed.options);
2618
+ if (request.error) {
2619
+ writeFailure(command, request.error, mode, 1);
2620
+ return null;
2621
+ }
2622
+ const result = await apiPost(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, payload, parsed.options, request.init, {
2623
+ artifactTarget: true,
2624
+ credentialSource: credential.source,
2625
+ profile: credential.profile
2543
2626
  });
2544
- }
2545
- async function collectDirectoryFiles(root) {
2546
- const results = [];
2547
- async function visit(dir) {
2548
- for (const entry of await readdir(dir, { withFileTypes: true })) {
2549
- if (entry.name === "__MACOSX") continue;
2550
- const fullPath = join(dir, entry.name);
2551
- if (entry.isSymbolicLink()) throw new CollectDirectoryFilesError("Directory contains a symbolic link.", "Remove or replace symlinked files and directories before publishing.");
2552
- if (entry.isDirectory()) {
2553
- if (EXCLUDED_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
2554
- await visit(fullPath);
2555
- continue;
2556
- }
2557
- if (!entry.isFile() || IGNORED_FILENAMES.has(entry.name) || entry.name.startsWith(".")) continue;
2558
- const relativePath = relative(root, fullPath).split(sep).join("/");
2559
- results.push({
2560
- path: fullPath,
2561
- relativePath
2562
- });
2563
- }
2627
+ if (result.error) {
2628
+ writeFailure(command, result.error, mode, 1);
2629
+ return null;
2564
2630
  }
2565
- await visit(root);
2566
- results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
2567
- return results;
2568
- }
2569
- var CollectDirectoryFilesError = class extends Error {
2570
- hint;
2571
- constructor(message, hint) {
2572
- super(message);
2573
- this.name = "CollectDirectoryFilesError";
2574
- this.hint = hint;
2631
+ if (result.body === null) {
2632
+ writeFailure(command, serviceError("Comment was changed but the response was empty."), mode, 1);
2633
+ return null;
2575
2634
  }
2576
- };
2577
- async function blobFor(path) {
2578
- const chunks = [];
2579
- for await (const chunk of createReadStream(path)) chunks.push(chunk);
2580
- return new Blob(chunks, { type: contentTypeFor(path) });
2581
- }
2582
- function contentTypeFor(path) {
2583
- if (path.endsWith(".html")) return "text/html";
2584
- if (path.endsWith(".md")) return "text/markdown";
2585
- if (path.endsWith(".css")) return "text/css";
2586
- if (path.endsWith(".js")) return "text/javascript";
2587
- if (path.endsWith(".json")) return "application/json";
2588
- if (path.endsWith(".svg")) return "image/svg+xml";
2589
- if (path.endsWith(".png")) return "image/png";
2590
- if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
2591
- return "application/octet-stream";
2635
+ return result.body;
2592
2636
  }
2593
- function artifactKindForFile(path) {
2594
- return path.endsWith(".md") ? "markdown_page" : "html_page";
2637
+ function requiredOption(value, message, hint) {
2638
+ if (!value || !value.trim()) return { error: validationError(message, hint) };
2639
+ return { value: value.trim() };
2595
2640
  }
2596
2641
  //#endregion
2597
- //#region src/command-runners/login.ts
2598
- async function performDeviceLogin(profile, options, mode) {
2599
- const request = await requestConfig(options);
2600
- if (request.error) return {
2601
- ok: false,
2602
- error: request.error
2603
- };
2604
- const code = await requestDeviceCode(options, request.init);
2605
- if ("error" in code) return {
2606
- ok: false,
2607
- error: code.error
2608
- };
2609
- const deadline = Date.now() + code.expires_in * 1e3;
2610
- if (mode.json) writeEvent({
2611
- status: "pending",
2612
- verification_uri: code.verification_uri,
2613
- verification_uri_complete: code.verification_uri_complete ?? null,
2614
- user_code: code.user_code,
2615
- expires_at: new Date(deadline).toISOString(),
2616
- interval_seconds: code.interval
2642
+ //#region src/command-runners/delete.ts
2643
+ async function runDelete(parsed, mode) {
2644
+ const command = "delete";
2645
+ const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to delete.");
2646
+ if (target.error) return writeFailure(command, target.error, mode, 1);
2647
+ const artifactId = target.artifactId;
2648
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
2649
+ if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
2650
+ const request = await requestConfig(parsed.options);
2651
+ if (request.error) return writeFailure(command, request.error, mode, 1);
2652
+ const result = await apiDelete(`/api/cli/artifacts/${encodeURIComponent(artifactId)}`, credential.token, parsed.options, request.init, {
2653
+ authenticated: true,
2654
+ artifactTarget: true,
2655
+ credentialSource: credential.source,
2656
+ profile: credential.profile
2617
2657
  });
2618
- else writeText([
2619
- "Open this URL in a browser to sign in:",
2620
- code.verification_uri_complete ?? code.verification_uri,
2621
- "",
2622
- `Code: ${code.user_code}`,
2623
- `Waiting for approval for profile "${profile}"...`,
2624
- ""
2625
- ].join("\n"));
2626
- const token = await pollForToken(options, code, request.init, profile, deadline);
2627
- if ("error" in token) return {
2628
- ok: false,
2629
- error: token.error
2658
+ if (result.error) return writeFailure(command, result.error, mode, 1);
2659
+ const body = result.body;
2660
+ if (!deleteSuccessFields(body)) return writeFailure(command, serviceError("Delete succeeded but the response did not include deletion metadata."), mode, 1);
2661
+ return writeSuccess(command, body, mode);
2662
+ }
2663
+ //#endregion
2664
+ //#region src/command-runners/doctor.ts
2665
+ const LOGIN_COMMAND = `${CLI_INVOCATION} login`;
2666
+ const REQUEST_ACCESS_COMMAND = `${CLI_INVOCATION} request-access`;
2667
+ function bearerTokenBlocksLogin(data) {
2668
+ return data.auth.credential_source === "env" || data.auth.credential_source === "token_option";
2669
+ }
2670
+ function resolveDoctorNextCommand(data) {
2671
+ if (data.config.local.code === "token_store_unsafe") {
2672
+ if (bearerTokenBlocksLogin(data)) return null;
2673
+ return LOGIN_COMMAND;
2674
+ }
2675
+ if (data.config.project.code === "token_store_unsafe") {
2676
+ if (bearerTokenBlocksLogin(data)) return null;
2677
+ return LOGIN_COMMAND;
2678
+ }
2679
+ if ((data.auth.code === "auth_required" || data.auth.code === "token_invalid") && !bearerTokenBlocksLogin(data)) return data.auth.profile ? `${LOGIN_COMMAND} --profile ${data.auth.profile}` : LOGIN_COMMAND;
2680
+ if (!data.network.ok) return null;
2681
+ if (data.upload.checked && !data.upload.ok) {
2682
+ if (data.upload.code === "upload-not-allowed") return REQUEST_ACCESS_COMMAND;
2683
+ return null;
2684
+ }
2685
+ return null;
2686
+ }
2687
+ function authRecovery(data, nextCommand) {
2688
+ const loginCommand = nextCommand?.startsWith(LOGIN_COMMAND) === true ? nextCommand : data.auth.profile ? `${LOGIN_COMMAND} --profile ${data.auth.profile}` : LOGIN_COMMAND;
2689
+ return authRecoveryDetails(data.base_url, loginCommand);
2690
+ }
2691
+ function doctorDataWithNextCommand(data) {
2692
+ const nextCommand = resolveDoctorNextCommand(data);
2693
+ const next = {
2694
+ ...data,
2695
+ next_command: nextCommand
2630
2696
  };
2631
- const sessionExpiresAt = token.expires_in === void 0 ? null : new Date(Date.now() + token.expires_in * 1e3).toISOString();
2632
- const stored = await verifyAndStoreProfileToken(profile, token.access_token, options, request.init);
2633
- if (!stored.ok) return {
2634
- ok: false,
2635
- error: stored.error
2697
+ if (next.auth.code === "auth_required") next.auth = {
2698
+ ...next.auth,
2699
+ recovery: authRecovery(next, nextCommand)
2636
2700
  };
2637
- const effective = await resolveEffectiveDefaultProfile(await resolveProjectConfig());
2701
+ return next;
2702
+ }
2703
+ async function runDoctor(parsed, mode) {
2704
+ const command = "doctor";
2705
+ const project = await resolveProjectConfig();
2706
+ const credential = await resolveCredential(parsed.options, project);
2707
+ const destination = resolveDestination(parsed.options, project.config);
2638
2708
  const data = {
2639
- profile,
2640
- status: "completed",
2641
- credential_source: "profile",
2642
- token_store: stored.data.token_store,
2643
- user: stored.data.user,
2644
- workspace: stored.data.workspace,
2645
- verification_uri: code.verification_uri,
2646
- verification_uri_complete: code.verification_uri_complete ?? null,
2647
- user_code: code.user_code,
2648
- expires_at: sessionExpiresAt,
2649
- interval_seconds: code.interval
2709
+ next_command: null,
2710
+ base_url: baseUrlOf(parsed.options),
2711
+ config: await configDiagnostics(project),
2712
+ auth: {
2713
+ credential_source: credential.source,
2714
+ ...credential.profile ? { profile: credential.profile } : {},
2715
+ token_present: credential.ok,
2716
+ ok: false
2717
+ },
2718
+ destination: destination.error ? {
2719
+ ok: false,
2720
+ code: destination.error.code,
2721
+ hint: destination.error.hint
2722
+ } : {
2723
+ ok: true,
2724
+ type: destination.containerId ? "project" : "home",
2725
+ project_id: destination.containerId ?? null
2726
+ },
2727
+ network: { ok: false },
2728
+ upload: {
2729
+ ok: false,
2730
+ checked: false
2731
+ }
2650
2732
  };
2651
- if (effective.profile && effective.profile !== profile) {
2652
- data.effective_default_profile = effective.profile;
2653
- 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.`;
2733
+ if (!credential.ok) {
2734
+ if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
2735
+ data.auth.code = credential.error.code;
2736
+ data.auth.hint = credential.error.hint;
2737
+ return writeSuccess(command, doctorDataWithNextCommand(data), mode);
2654
2738
  }
2655
- return {
2656
- ok: true,
2657
- data
2658
- };
2659
- }
2660
- async function runLogin(parsed, mode) {
2661
- const command = "login";
2662
- const profile = nonEmpty(parsed.options.profile) ?? "default";
2663
- if (nonEmpty(process.env.ARTIFACTSHARE_TOKEN) || nonEmpty(parsed.options.token)) return writeFailure(command, validationError("Login cannot run with a bearer token already selected.", "Unset ARTIFACTSHARE_TOKEN and remove --token before running login."), mode, 1);
2664
- const result = await performDeviceLogin(profile, parsed.options, mode);
2665
- if (!result.ok) return writeFailure(command, result.error, mode, 1);
2666
- return writeSuccess(command, result.data, mode);
2667
- }
2668
- async function requestDeviceCode(options, init) {
2669
- const response = await fetch(apiUrl("/api/auth/device/code", baseUrlOf(options)), {
2670
- method: "POST",
2671
- headers: { "content-type": "application/json" },
2672
- body: JSON.stringify({ client_id: DEVICE_CLIENT_ID }),
2673
- ...init
2739
+ const request = await requestConfig(parsed.options);
2740
+ if (request.error) return writeFailure(command, request.error, mode, 1);
2741
+ const response = await fetch(apiUrl("/api/cli/doctor", baseUrlOf(parsed.options)), {
2742
+ headers: { Authorization: `Bearer ${credential.token}` },
2743
+ ...request.init
2674
2744
  }).catch((error) => ({ networkError: error }));
2675
- if ("networkError" in response) return { error: networkError(response.networkError) };
2745
+ if ("networkError" in response) {
2746
+ data.network = {
2747
+ ok: false,
2748
+ code: "network_failed",
2749
+ hint: networkError(response.networkError).hint
2750
+ };
2751
+ return writeSuccess(command, doctorDataWithNextCommand(data), mode);
2752
+ }
2753
+ data.network.ok = true;
2676
2754
  const body = await readJson(response);
2677
- if (!response.ok) return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
2678
- if (!isDeviceCodeResponse(body)) return { error: validationError("Device login response was invalid.", "Retry login. If this repeats, report the response shape.", "service_error") };
2679
- return body;
2755
+ if (!response.ok) {
2756
+ const error = mapApiError(response.status, body, {
2757
+ authenticated: true,
2758
+ baseUrl: baseUrlOf(parsed.options),
2759
+ credentialSource: credential.source,
2760
+ profile: credential.profile
2761
+ });
2762
+ data.auth.code = error.code;
2763
+ data.auth.hint = error.hint;
2764
+ return writeSuccess(command, doctorDataWithNextCommand(data), mode);
2765
+ }
2766
+ if (!body) throw new Error("Doctor response was not valid JSON.");
2767
+ data.auth.ok = body.auth?.ok ?? true;
2768
+ data.auth.email = body.user?.email ?? null;
2769
+ data.upload.checked = true;
2770
+ data.upload.ok = body.upload?.ok ?? false;
2771
+ if (!data.upload.ok) {
2772
+ data.upload.code = normalizeApiCode(body.upload?.code);
2773
+ data.upload.hint = uploadBlockedHint(data.upload.code);
2774
+ }
2775
+ return writeSuccess(command, doctorDataWithNextCommand(data), mode);
2680
2776
  }
2681
- async function exchangeDeviceTokenOnce(options, deviceCode, init) {
2682
- const response = await fetch(apiUrl("/api/auth/device/token", baseUrlOf(options)), {
2683
- method: "POST",
2684
- headers: { "content-type": "application/json" },
2685
- body: JSON.stringify({
2686
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
2687
- device_code: deviceCode,
2688
- client_id: DEVICE_CLIENT_ID
2689
- }),
2690
- ...init
2691
- }).catch((error) => ({ networkError: error }));
2692
- if ("networkError" in response) return { error: networkError(response.networkError) };
2693
- const body = await readJson(response);
2694
- if (response.ok && isDeviceTokenResponse(body)) return {
2695
- status: "success",
2696
- token: body
2777
+ async function configDiagnostics(project) {
2778
+ const globalConfig = await readGlobalConfig();
2779
+ const cwd = process.cwd();
2780
+ const directory = project.directory;
2781
+ const localRaw = directory ? await readProjectConfigAtDirectory(directory, "local") : null;
2782
+ const sharedRaw = directory ? await readProjectConfigAtDirectory(directory, "shared") : null;
2783
+ return {
2784
+ local: fileDiagnostics(localRaw, directory ? relativeProjectConfigPath(cwd, directory, PROJECT_CONFIG_LOCAL_PATH) : null),
2785
+ project: fileDiagnostics(sharedRaw, directory ? relativeProjectConfigPath(cwd, directory, PROJECT_CONFIG_PATH) : null),
2786
+ global: {
2787
+ present: globalConfig !== null,
2788
+ default_profile: configString(globalConfig?.default_profile),
2789
+ profile_count: Object.keys(globalConfig?.profiles ?? {}).length
2790
+ },
2791
+ effective: effectiveDiagnostics(project, globalConfig)
2697
2792
  };
2698
- const authError = deviceTokenError(body);
2699
- if (authError === "authorization_pending") return { status: "pending" };
2700
- if (authError === "slow_down") return { status: "slow_down" };
2701
- if (authError === "access_denied") return { status: "denied" };
2702
- if (authError === "expired_token") return { status: "expired" };
2703
- if (response.status === 429 || response.status >= 500) return { status: "retry_later" };
2704
- return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
2705
2793
  }
2706
- function pendingDeviceAuthFromCode(profile, options, code) {
2794
+ function fileDiagnostics(raw, path) {
2795
+ const unsafeKey = Object.keys(raw ?? {}).find((key) => key.toLowerCase().includes("token"));
2707
2796
  return {
2708
- base_url: baseUrlOf(options),
2709
- profile,
2710
- device_code: code.device_code,
2711
- verification_uri: code.verification_uri,
2712
- verification_uri_complete: code.verification_uri_complete ?? null,
2713
- user_code: code.user_code,
2714
- expires_at: new Date(Date.now() + code.expires_in * 1e3).toISOString(),
2715
- interval_seconds: code.interval,
2716
- created_at: (/* @__PURE__ */ new Date()).toISOString()
2797
+ present: raw !== null,
2798
+ path,
2799
+ default_profile: configString(raw?.default_profile),
2800
+ default_project_id: configString(raw?.default_project_id),
2801
+ ...unsafeKey ? {
2802
+ code: "token_store_unsafe",
2803
+ hint: `Remove "${unsafeKey}" from ${path ?? "the working-directory config"} and run ${CLI_INVOCATION} login instead; the working-directory config must never hold secrets.`
2804
+ } : {}
2717
2805
  };
2718
2806
  }
2719
- async function pollForToken(options, code, init, profile, deadline) {
2720
- let intervalMs = Math.max(code.interval, 1) * 1e3;
2721
- let networkFailures = 0;
2722
- while (Date.now() < deadline) {
2723
- await setTimeout(intervalMs);
2724
- const response = await fetch(apiUrl("/api/auth/device/token", baseUrlOf(options)), {
2725
- method: "POST",
2726
- headers: { "content-type": "application/json" },
2727
- body: JSON.stringify({
2728
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
2729
- device_code: code.device_code,
2730
- client_id: DEVICE_CLIENT_ID
2731
- }),
2732
- ...init
2733
- }).catch((error) => ({ networkError: error }));
2734
- if ("networkError" in response) {
2735
- networkFailures += 1;
2736
- if (networkFailures >= 5) return { error: networkError(response.networkError) };
2737
- continue;
2738
- }
2739
- networkFailures = 0;
2740
- const body = await readJson(response);
2741
- if (response.ok && isDeviceTokenResponse(body)) return body;
2742
- const authError = deviceTokenError(body);
2743
- if (authError === "authorization_pending") continue;
2744
- if (authError === "slow_down") {
2745
- intervalMs += 5e3;
2746
- continue;
2747
- }
2748
- if (authError === "access_denied") return { error: authDeniedError(profile) };
2749
- if (authError === "expired_token") return { error: authExpiredError(profile) };
2750
- return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
2751
- }
2752
- return { error: authExpiredError(profile) };
2753
- }
2754
- async function verifyAndStoreProfileToken(profile, token, options, init) {
2755
- const config = await readGlobalConfig() ?? {};
2756
- const whoamiResult = await apiGet("/api/cli/whoami", token, options, init);
2757
- if (whoamiResult.error) return {
2758
- ok: false,
2759
- error: whoamiResult.error
2760
- };
2761
- const whoami = whoamiProfile(whoamiResult.body);
2762
- const profiles = config.profiles ?? {};
2763
- const expectedEmail = nonEmpty((Object.hasOwn(profiles, profile) ? profiles[profile] : void 0)?.email);
2764
- if (expectedEmail && whoami.email !== expectedEmail) return {
2765
- ok: false,
2766
- error: authAccountMismatchError(profile, expectedEmail, whoami.email)
2767
- };
2768
- const saved = await saveProfileToken(profile, token, options);
2769
- if (!saved.ok) return {
2770
- ok: false,
2771
- error: tokenStoreUnavailableError(profile)
2772
- };
2773
- await writeProfileConfig(profile, options, saved.store, whoami);
2807
+ function effectiveDiagnostics(project, globalConfig) {
2808
+ const projectProfile = configString(project.config?.default_profile);
2809
+ const projectProjectId = configString(project.config?.default_project_id);
2810
+ const globalProfile = configString(globalConfig?.default_profile);
2811
+ const defaultProfile = projectProfile ?? globalProfile;
2812
+ const defaultProfileSource = projectProfile ? project.kind === "local" ? "local" : "project" : globalProfile ? "global" : "none";
2813
+ const defaultProfilePath = defaultProfileSource === "local" || defaultProfileSource === "project" ? project.path : null;
2814
+ const defaultProjectId = projectProjectId;
2815
+ const defaultProjectIdSource = projectProjectId ? project.kind === "local" ? "local" : "project" : "none";
2774
2816
  return {
2775
- ok: true,
2776
- data: {
2777
- profile,
2778
- token_store: saved.store,
2779
- user: { email: whoami.email },
2780
- workspace: {
2781
- id: whoami.workspace_id,
2782
- hosted_domain: whoami.hosted_domain
2783
- }
2784
- }
2817
+ default_profile: defaultProfile,
2818
+ default_profile_source: defaultProfileSource,
2819
+ default_profile_path: defaultProfilePath,
2820
+ default_project_id: defaultProjectId,
2821
+ default_project_id_source: defaultProjectIdSource,
2822
+ default_project_id_path: defaultProjectIdSource === "local" || defaultProjectIdSource === "project" ? project.path : null
2785
2823
  };
2786
2824
  }
2787
- async function writeProfileConfig(profile, options, tokenStore, whoami) {
2788
- const config = await readGlobalConfig() ?? {};
2789
- const profiles = config.profiles ?? {};
2790
- const currentProfile = Object.hasOwn(profiles, profile) ? profiles[profile] : void 0;
2791
- await writeGlobalConfig({
2792
- ...config,
2793
- default_profile: nonEmpty(config.default_profile) ?? profile,
2794
- profiles: {
2795
- ...profiles,
2796
- [profile]: {
2797
- ...currentProfile,
2798
- base_url: baseUrlOf(options),
2799
- email: whoami.email ?? currentProfile?.email ?? null,
2800
- workspace_id: whoami.workspace_id,
2801
- token_store: tokenStore,
2802
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
2803
- }
2825
+ //#endregion
2826
+ //#region src/files.ts
2827
+ async function prepareUploadPayload(targetPath, fileStat, initialForm = new FormData()) {
2828
+ if (fileStat.isDirectory()) {
2829
+ let files;
2830
+ try {
2831
+ files = await collectDirectoryFiles(resolve(targetPath));
2832
+ } catch (error) {
2833
+ if (error instanceof CollectDirectoryFilesError) return { error: validationError(error.message, error.hint) };
2834
+ throw error;
2804
2835
  }
2805
- });
2836
+ if (files.length === 0) return { error: validationError("Directory has no publishable files.", "Add index.html or index.md and retry.") };
2837
+ for (const file of files) initialForm.append("file", await blobFor(file.path), file.relativePath);
2838
+ return { payload: {
2839
+ form: initialForm,
2840
+ kind: "static_site"
2841
+ } };
2842
+ }
2843
+ if (fileStat.isFile()) {
2844
+ initialForm.append("file", await blobFor(targetPath), basename(targetPath));
2845
+ return { payload: {
2846
+ form: initialForm,
2847
+ kind: artifactKindForFile(targetPath)
2848
+ } };
2849
+ }
2850
+ return { error: validationError("Path must be a file or directory.", "Pass a regular file or directory.") };
2806
2851
  }
2807
- function isDeviceCodeResponse(body) {
2808
- if (!isRecord(body)) return false;
2809
- return typeof body.device_code === "string" && typeof body.user_code === "string" && typeof body.verification_uri === "string" && (typeof body.verification_uri_complete === "string" || body.verification_uri_complete === void 0) && typeof body.expires_in === "number" && typeof body.interval === "number";
2852
+ async function prepareDownloadPlan(manifest, outputPath, force) {
2853
+ if (manifest.files.length === 0) return { error: validationError("Download manifest contains no files.", "Check the artifact and retry.") };
2854
+ if (outputPath === "") return { error: validationError("--output requires a non-empty directory.", "Pass --output <path> or omit --output to use the artifact ID.") };
2855
+ const root = resolve(outputPath);
2856
+ const existing = await lstat(root).catch(() => null);
2857
+ if (existing?.isSymbolicLink()) return { error: validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry.") };
2858
+ if (existing && !force) return { error: cliError({
2859
+ code: "output_exists",
2860
+ message: "Output path already exists.",
2861
+ why: "Download will not write into an existing path unless --force is set.",
2862
+ hint: "Choose a different --output path or retry with --force.",
2863
+ agentRecoverable: true,
2864
+ requiresHuman: false,
2865
+ recovery: { kind: "change_input" }
2866
+ }) };
2867
+ if (existing && !existing.isDirectory()) return { error: validationError("Output path is not a directory.", "Choose a directory path or remove the existing file.") };
2868
+ const seen = /* @__PURE__ */ new Set();
2869
+ const relativeFiles = [];
2870
+ for (const file of manifest.files) {
2871
+ const relativePath = downloadRelativePath(file.path);
2872
+ if (relativePath.error) return { error: relativePath.error };
2873
+ if (seen.has(relativePath.value)) return { error: validationError("Download manifest contains duplicate file paths.", "Retry later. If this repeats, report the artifact ID.") };
2874
+ seen.add(relativePath.value);
2875
+ relativeFiles.push({
2876
+ ...file,
2877
+ relativePath: relativePath.value
2878
+ });
2879
+ }
2880
+ const parent = dirname(root);
2881
+ await mkdir(parent, { recursive: true });
2882
+ const tempRoot = await mkdtemp(join(parent, `.${basename(root)}.tmp-`));
2883
+ const files = [];
2884
+ for (const file of relativeFiles) {
2885
+ const targetPath = resolve(tempRoot, file.relativePath);
2886
+ files.push({
2887
+ ...file,
2888
+ targetPath
2889
+ });
2890
+ }
2891
+ return { value: {
2892
+ root,
2893
+ tempRoot,
2894
+ replaceExisting: Boolean(existing),
2895
+ files
2896
+ } };
2810
2897
  }
2811
- function isDeviceTokenResponse(body) {
2812
- if (!isRecord(body)) return false;
2813
- return typeof body.access_token === "string" && typeof body.token_type === "string" && body.token_type.toLowerCase() === "bearer" && (typeof body.expires_in === "number" || body.expires_in === void 0);
2898
+ function downloadRelativePath(path) {
2899
+ if (!path.startsWith("/") || path.includes("\0") || path.includes("\\")) return { error: validationError("Download manifest contains an invalid file path.", "Retry later. If this repeats, report the artifact ID.") };
2900
+ const segments = path.split("/").slice(1);
2901
+ if (segments.length === 0 || segments.some((segment) => segment === "" || segment === "." || segment === "..")) return { error: validationError("Download manifest contains an unsafe file path.", "Retry later. If this repeats, report the artifact ID.") };
2902
+ return { value: segments.join("/") };
2814
2903
  }
2815
- function deviceTokenError(body) {
2816
- if (!isRecord(body)) return null;
2817
- return typeof body.error === "string" ? body.error : null;
2904
+ function verifyDownloadedBytes(file, bytes) {
2905
+ if (bytes.byteLength !== file.size_bytes) return { error: downloadIntegrityError(file.path, "size mismatch") };
2906
+ if (file.sha256) {
2907
+ if (createHash("sha256").update(bytes).digest("base64url") !== file.sha256) return { error: downloadIntegrityError(file.path, "sha256 mismatch") };
2908
+ }
2909
+ return { ok: true };
2818
2910
  }
2819
- function whoamiProfile(body) {
2820
- const record = isRecord(body) ? body : null;
2821
- const user = record && isRecord(record.user) ? record.user : null;
2822
- const workspace = record && isRecord(record.workspace) ? record.workspace : null;
2823
- return {
2824
- email: typeof user?.email === "string" ? user.email : null,
2825
- workspace_id: typeof workspace?.id === "string" ? workspace.id : null,
2826
- hosted_domain: typeof workspace?.hosted_domain === "string" ? workspace.hosted_domain : null
2827
- };
2911
+ function downloadIntegrityError(path, reason) {
2912
+ return cliError({
2913
+ code: "download_integrity_failed",
2914
+ message: "Downloaded file did not match the manifest.",
2915
+ why: `The downloaded file ${path} failed integrity verification: ${reason}.`,
2916
+ hint: "Retry the download. If this repeats, report the artifact ID.",
2917
+ agentRecoverable: true,
2918
+ requiresHuman: false,
2919
+ recovery: { kind: "retry_later" }
2920
+ });
2828
2921
  }
2829
- //#endregion
2830
- //#region src/command-runners/auto-login.ts
2831
- const JSON_PENDING_AUTH_COMMANDS = new Set(["publish", "update"]);
2832
- function isInteractiveTerminal(mode) {
2833
- return !mode.json && process.stdin.isTTY === true;
2922
+ function backupPathFor(root) {
2923
+ return join(dirname(root), `.${basename(root)}.old-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
2834
2924
  }
2835
- function profileForAutoLogin(credential) {
2836
- return credential.source === "none" ? "default" : credential.profile ?? "default";
2925
+ async function pathExists(path) {
2926
+ return Boolean(await lstat(path).catch(() => null));
2837
2927
  }
2838
- function isPendingExpired(pending) {
2839
- const expiresAt = Date.parse(pending.expires_at);
2840
- return Number.isNaN(expiresAt) || expiresAt <= Date.now();
2928
+ function downloadFileSystemError(error) {
2929
+ return cliError({
2930
+ code: "download_failed",
2931
+ message: "Could not write downloaded files.",
2932
+ why: error instanceof Error ? error.message : "The local filesystem rejected a download operation.",
2933
+ hint: "Check --output permissions and available disk space, then retry.",
2934
+ agentRecoverable: true,
2935
+ requiresHuman: false,
2936
+ recovery: { kind: "change_input" }
2937
+ });
2841
2938
  }
2842
- async function canAttemptProfileTokenSave(profile, options) {
2843
- const stored = await readProfileToken(profile, options);
2844
- return stored.ok || stored.reason !== "unavailable";
2939
+ async function collectDirectoryFiles(root) {
2940
+ const results = [];
2941
+ async function visit(dir) {
2942
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
2943
+ if (entry.name === "__MACOSX") continue;
2944
+ const fullPath = join(dir, entry.name);
2945
+ if (entry.isSymbolicLink()) throw new CollectDirectoryFilesError("Directory contains a symbolic link.", "Remove or replace symlinked files and directories before publishing.");
2946
+ if (entry.isDirectory()) {
2947
+ if (EXCLUDED_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
2948
+ await visit(fullPath);
2949
+ continue;
2950
+ }
2951
+ if (!entry.isFile() || IGNORED_FILENAMES.has(entry.name) || entry.name.startsWith(".")) continue;
2952
+ const relativePath = relative(root, fullPath).split(sep).join("/");
2953
+ results.push({
2954
+ path: fullPath,
2955
+ relativePath
2956
+ });
2957
+ }
2958
+ }
2959
+ await visit(root);
2960
+ results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
2961
+ return results;
2845
2962
  }
2846
- async function handleCredentialFailure(command, credential, options, mode, rerun, isRetry = false, deps = {}) {
2847
- if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
2848
- if (mode.json && JSON_PENDING_AUTH_COMMANDS.has(command) && !isRetry) return handleJsonPendingAuth(command, credential, options, mode, rerun);
2849
- if (!isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
2850
- const performLogin = deps.performLogin ?? performDeviceLogin;
2851
- const profile = profileForAutoLogin(credential);
2852
- writeText("Not signed in. Starting device login to continue...\n");
2853
- const loginResult = await performLogin(profile, options, mode);
2854
- if (!loginResult.ok) return writeFailure(command, loginResult.error, mode, 1);
2855
- return rerun();
2963
+ var CollectDirectoryFilesError = class extends Error {
2964
+ hint;
2965
+ constructor(message, hint) {
2966
+ super(message);
2967
+ this.name = "CollectDirectoryFilesError";
2968
+ this.hint = hint;
2969
+ }
2970
+ };
2971
+ async function blobFor(path) {
2972
+ const chunks = [];
2973
+ for await (const chunk of createReadStream(path)) chunks.push(chunk);
2974
+ return new Blob(chunks, { type: contentTypeFor(path) });
2856
2975
  }
2857
- async function handleJsonPendingAuth(command, credential, options, mode, rerun) {
2858
- const profile = profileForAutoLogin(credential);
2859
- const baseUrl = baseUrlOf(options);
2860
- const request = await requestConfig(options);
2861
- if (request.error) return writeFailure(command, request.error, mode, 1);
2862
- if (!await canAttemptProfileTokenSave(profile, options)) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
2863
- const existing = await readPendingDeviceAuth(baseUrl, profile);
2864
- if (existing && !isPendingExpired(existing)) {
2865
- const exchange = await exchangeDeviceTokenOnce(options, existing.device_code, request.init);
2866
- if ("error" in exchange) {
2867
- if (exchange.error.code !== "network_failed") await clearPendingDeviceAuth(baseUrl, profile);
2868
- return writeFailure(command, exchange.error, mode, 1);
2869
- }
2870
- if (exchange.status === "success") {
2871
- const stored = await verifyAndStoreProfileToken(profile, exchange.token.access_token, options, request.init);
2872
- if (!stored.ok) return writeFailure(command, stored.error, mode, 1);
2873
- await clearPendingDeviceAuth(baseUrl, profile);
2874
- return rerun();
2875
- }
2876
- if (exchange.status === "denied") {
2877
- await clearPendingDeviceAuth(baseUrl, profile);
2878
- return writeFailure(command, authDeniedError(profile), mode, 1);
2879
- }
2880
- if (exchange.status === "expired") await clearPendingDeviceAuth(baseUrl, profile);
2881
- else if (exchange.status === "retry_later") return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing), mode, 1);
2882
- else return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing), mode, 1);
2883
- } else if (existing) await clearPendingDeviceAuth(baseUrl, profile);
2884
- const code = await requestDeviceCode(options, request.init);
2885
- if ("error" in code) return writeFailure(command, credential.error, mode, 1);
2886
- const pending = pendingDeviceAuthFromCode(profile, options, code);
2887
- if (!await writePendingDeviceAuth(pending)) return writeFailure(command, credential.error, mode, 1);
2888
- return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, pending), mode, 1);
2976
+ function contentTypeFor(path) {
2977
+ if (path.endsWith(".html")) return "text/html";
2978
+ if (path.endsWith(".md")) return "text/markdown";
2979
+ if (path.endsWith(".css")) return "text/css";
2980
+ if (path.endsWith(".js")) return "text/javascript";
2981
+ if (path.endsWith(".json")) return "application/json";
2982
+ if (path.endsWith(".svg")) return "image/svg+xml";
2983
+ if (path.endsWith(".png")) return "image/png";
2984
+ if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
2985
+ return "application/octet-stream";
2986
+ }
2987
+ function artifactKindForFile(path) {
2988
+ return path.endsWith(".md") ? "markdown_page" : "html_page";
2889
2989
  }
2890
2990
  //#endregion
2891
2991
  //#region src/command-runners/download.ts
@@ -2906,10 +3006,13 @@ async function runDownload(parsed, mode, isRetry = false) {
2906
3006
  }).catch((error) => ({ networkError: error }));
2907
3007
  if ("networkError" in manifestResponse) return writeFailure(command, networkError(manifestResponse.networkError), mode, 1);
2908
3008
  const body = await readJson(manifestResponse);
2909
- if (!manifestResponse.ok) return writeFailure(command, mapApiError(manifestResponse.status, body, {
3009
+ if (!manifestResponse.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(manifestResponse.status, body, {
2910
3010
  authenticated: true,
2911
- artifactTarget: true
2912
- }), mode, 1);
3011
+ artifactTarget: true,
3012
+ baseUrl,
3013
+ credentialSource: credential.source,
3014
+ profile: credential.profile
3015
+ }), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
2913
3016
  if (!downloadManifestFields(body)) return writeFailure(command, serviceError("Download manifest succeeded but the response did not include file metadata."), mode, 1);
2914
3017
  const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force));
2915
3018
  if (plan.error) return writeFailure(command, plan.error, mode, 1);
@@ -2923,10 +3026,13 @@ async function runDownload(parsed, mode, isRetry = false) {
2923
3026
  ...request.init
2924
3027
  }).catch((error) => ({ networkError: error }));
2925
3028
  if ("networkError" in fileResponse) return writeFailure(command, networkError(fileResponse.networkError), mode, 1);
2926
- if (!fileResponse.ok) return writeFailure(command, mapApiError(fileResponse.status, await readJson(fileResponse), {
3029
+ if (!fileResponse.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(fileResponse.status, await readJson(fileResponse), {
2927
3030
  authenticated: true,
2928
- artifactTarget: true
2929
- }), mode, 1);
3031
+ artifactTarget: true,
3032
+ baseUrl,
3033
+ credentialSource: credential.source,
3034
+ profile: credential.profile
3035
+ }), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
2930
3036
  const bytes = Buffer.from(await fileResponse.arrayBuffer());
2931
3037
  const verified = verifyDownloadedBytes(file, bytes);
2932
3038
  if (verified.error) return writeFailure(command, verified.error, mode, 1);
@@ -2980,7 +3086,9 @@ async function runEdit(parsed, mode) {
2980
3086
  if (request.error) return writeFailure(command, request.error, mode, 1);
2981
3087
  const result = await apiPost(`/api/cli/shareables/${encodeURIComponent(target.artifactId)}/edit`, credential.token, payload.body, parsed.options, request.init, {
2982
3088
  artifactTarget: true,
2983
- editSettings: true
3089
+ editSettings: true,
3090
+ credentialSource: credential.source,
3091
+ profile: credential.profile
2984
3092
  });
2985
3093
  if (result.error) return writeFailure(command, result.error, mode, 1);
2986
3094
  const data = parseEditData(result.body);
@@ -3179,7 +3287,11 @@ async function runMove(parsed, mode) {
3179
3287
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3180
3288
  const request = await requestConfig(parsed.options);
3181
3289
  if (request.error) return writeFailure(command, request.error, mode, 1);
3182
- const result = await apiPost(`/api/cli/shareables/${encodeURIComponent(target.artifactId)}/move`, credential.token, { destination: home ? "home" : { project_id: projectId } }, parsed.options, request.init, { artifactTarget: true });
3290
+ const result = await apiPost(`/api/cli/shareables/${encodeURIComponent(target.artifactId)}/move`, credential.token, { destination: home ? "home" : { project_id: projectId } }, parsed.options, request.init, {
3291
+ artifactTarget: true,
3292
+ credentialSource: credential.source,
3293
+ profile: credential.profile
3294
+ });
3183
3295
  if (result.error) return writeFailure(command, result.error, mode, 1);
3184
3296
  const data = parseMoveData(result.body);
3185
3297
  if (!data) return writeFailure(command, serviceError("Move succeeded but the response did not include move data."), mode, 1);
@@ -3306,8 +3418,8 @@ async function runProfilesImportToken(parsed, mode) {
3306
3418
  }
3307
3419
  //#endregion
3308
3420
  //#region src/command-runners/projects.ts
3309
- async function fetchProjects(token, options, init) {
3310
- const result = await apiGet("/api/cli/projects", token, options, init);
3421
+ async function fetchProjects(token, options, init, errorOptions = {}) {
3422
+ const result = await apiGet("/api/cli/projects", token, options, init, errorOptions);
3311
3423
  if (result.error) return { error: result.error };
3312
3424
  return { projects: (Array.isArray(result.body?.projects) ? result.body.projects : []).filter(isRecord).flatMap((project) => {
3313
3425
  const id = configString(project.id);
@@ -3329,7 +3441,10 @@ async function runProjectsList(parsed, mode) {
3329
3441
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3330
3442
  const request = await requestConfig(parsed.options);
3331
3443
  if (request.error) return writeFailure(command, request.error, mode, 1);
3332
- const result = await fetchProjects(credential.token, parsed.options, request.init);
3444
+ const result = await fetchProjects(credential.token, parsed.options, request.init, {
3445
+ credentialSource: credential.source,
3446
+ profile: credential.profile
3447
+ });
3333
3448
  if (result.error) return writeFailure(command, result.error, mode, 1);
3334
3449
  const defaultProjectId = configString(projectConfig.config?.default_project_id);
3335
3450
  const projects = result.projects.map((project) => ({
@@ -3357,7 +3472,10 @@ async function runProjectsCreate(parsed, mode) {
3357
3472
  name,
3358
3473
  description: parsed.options.description ?? null,
3359
3474
  base_visibility: visibility ?? null
3360
- }, parsed.options, request.init);
3475
+ }, parsed.options, request.init, {
3476
+ credentialSource: credential.source,
3477
+ profile: credential.profile
3478
+ });
3361
3479
  if (result.error) return writeFailure(command, result.error, mode, 1);
3362
3480
  const project = isRecord(result.body?.project) ? result.body.project : null;
3363
3481
  const id = configString(project?.id);
@@ -3383,7 +3501,11 @@ async function runProjectsEdit(parsed, mode) {
3383
3501
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3384
3502
  const request = await requestConfig(parsed.options);
3385
3503
  if (request.error) return writeFailure(command, request.error, mode, 1);
3386
- const result = await apiPost(`/api/cli/projects/${encodeURIComponent(projectId)}`, credential.token, payload.body, parsed.options, request.init, { projectTarget: true });
3504
+ const result = await apiPost(`/api/cli/projects/${encodeURIComponent(projectId)}`, credential.token, payload.body, parsed.options, request.init, {
3505
+ projectTarget: true,
3506
+ credentialSource: credential.source,
3507
+ profile: credential.profile
3508
+ });
3387
3509
  if (result.error) return writeFailure(command, result.error, mode, 1);
3388
3510
  const data = parseProjectsEditData(result.body);
3389
3511
  if (!data) return writeFailure(command, serviceError("Project edit succeeded but the response did not include project data."), mode, 1);
@@ -3486,8 +3608,13 @@ async function runPublish(parsed, mode, isRetry = false) {
3486
3608
  const request = await requestConfig(parsed.options);
3487
3609
  if (request.error) return writeFailure(command, request.error, mode, 1);
3488
3610
  if (hasProjectFlag && projectName) {
3489
- const resolved = await resolveProjectIdByName(projectName, credential.token, parsed.options, request.init);
3490
- if (resolved.error) return writeFailure(command, resolved.error, mode, 1);
3611
+ const resolved = await resolveProjectIdByName(projectName, credential.token, parsed.options, request.init, {
3612
+ authenticated: true,
3613
+ baseUrl,
3614
+ credentialSource: credential.source,
3615
+ profile: credential.profile
3616
+ });
3617
+ if (resolved.error) return handleAuthenticatedCredentialFailure(command, resolved.error, credential, parsed.options, mode, () => runPublish(parsed, mode, true), isRetry);
3491
3618
  const { project: _project, ...rest } = parsed.options;
3492
3619
  destinationOptions = {
3493
3620
  ...rest,
@@ -3518,7 +3645,12 @@ async function runPublish(parsed, mode, isRetry = false) {
3518
3645
  }).catch((error) => ({ networkError: error }));
3519
3646
  if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
3520
3647
  const body = await readJson(response);
3521
- if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
3648
+ if (!response.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(response.status, body, {
3649
+ authenticated: true,
3650
+ baseUrl,
3651
+ credentialSource: credential.source,
3652
+ profile: credential.profile
3653
+ }), credential, parsed.options, mode, () => runPublish(parsed, mode, true), isRetry);
3522
3654
  const id = body?.id ?? null;
3523
3655
  return writeSuccess(command, {
3524
3656
  artifact: {
@@ -3539,8 +3671,8 @@ async function runPublish(parsed, mode, isRetry = false) {
3539
3671
  }
3540
3672
  }, mode);
3541
3673
  }
3542
- async function resolveProjectIdByName(projectName, token, options, init) {
3543
- const result = await fetchProjects(token, options, init);
3674
+ async function resolveProjectIdByName(projectName, token, options, init, errorOptions) {
3675
+ const result = await fetchProjects(token, options, init, errorOptions);
3544
3676
  if (result.error) return { error: result.error };
3545
3677
  const candidates = result.projects.flatMap((project) => {
3546
3678
  if (project.name !== projectName) return [];
@@ -3565,7 +3697,10 @@ async function runRequestAccess(parsed, mode) {
3565
3697
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3566
3698
  const request = await requestConfig(parsed.options);
3567
3699
  if (request.error) return writeFailure(command, request.error, mode, 1);
3568
- const result = await apiPost("/api/cli/request-access", credential.token, { note }, parsed.options, request.init);
3700
+ const result = await apiPost("/api/cli/request-access", credential.token, { note }, parsed.options, request.init, {
3701
+ credentialSource: credential.source,
3702
+ profile: credential.profile
3703
+ });
3569
3704
  if (result.error) return writeFailure(command, result.error, mode, 1);
3570
3705
  const body = result.body;
3571
3706
  const data = {
@@ -3597,7 +3732,12 @@ async function runResolve(parsed, mode) {
3597
3732
  }).catch((error) => ({ networkError: error }));
3598
3733
  if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
3599
3734
  const body = await readJson(response);
3600
- if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
3735
+ if (!response.ok) return writeFailure(command, mapApiError(response.status, body, {
3736
+ authenticated: true,
3737
+ baseUrl: baseUrlOf(parsed.options),
3738
+ credentialSource: credential.source,
3739
+ profile: credential.profile
3740
+ }), mode, 1);
3601
3741
  if (!resolveSuccessFields(body)) return writeFailure(command, serviceError("Resolve succeeded but the response did not include query, candidates, and has_more."), mode, 1);
3602
3742
  return writeSuccess(command, body, mode);
3603
3743
  }
@@ -3632,10 +3772,13 @@ async function runUpdate(parsed, mode, isRetry = false) {
3632
3772
  }).catch((error) => ({ networkError: error }));
3633
3773
  if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
3634
3774
  const body = await readJson(response);
3635
- if (!response.ok) return writeFailure(command, mapApiError(response.status, body, {
3775
+ if (!response.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(response.status, body, {
3636
3776
  authenticated: true,
3637
- artifactTarget: true
3638
- }), mode, 1);
3777
+ artifactTarget: true,
3778
+ baseUrl,
3779
+ credentialSource: credential.source,
3780
+ profile: credential.profile
3781
+ }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
3639
3782
  const id = body?.id ?? artifactId;
3640
3783
  const result = {
3641
3784
  artifact: {
@@ -3657,7 +3800,10 @@ async function runWhoami(parsed, mode) {
3657
3800
  if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3658
3801
  const request = await requestConfig(parsed.options);
3659
3802
  if (request.error) return writeFailure(command, request.error, mode, 1);
3660
- const whoami = await apiGet("/api/cli/whoami", credential.token, parsed.options, request.init);
3803
+ const whoami = await apiGet("/api/cli/whoami", credential.token, parsed.options, request.init, {
3804
+ credentialSource: credential.source,
3805
+ profile: credential.profile
3806
+ });
3661
3807
  if (whoami.error) return writeFailure(command, whoami.error, mode, 1);
3662
3808
  return writeSuccess(command, isRecord(whoami.body) ? {
3663
3809
  ...whoami.body,