@artifactshare/cli 0.1.6 → 0.1.7

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,14 +3,15 @@ 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 { homedir } from "node:os";
6
7
  import { createReadStream } from "node:fs";
7
8
  import { createHash } from "node:crypto";
8
9
  import { setTimeout } from "node:timers/promises";
9
- import { homedir } from "node:os";
10
10
  //#region src/constants.ts
11
11
  const DEFAULT_BASE_URL = "https://artifactshare.com";
12
12
  const DEVICE_CLIENT_ID = "artifactshare-cli";
13
13
  const CLI_INVOCATION = "npx --yes @artifactshare/cli";
14
+ const AGENT_DOWNLOAD_OUTPUT = "./artifact";
14
15
  const TOKEN_ENV_VAR = "ARTIFACTSHARE_TOKEN";
15
16
  const TOKEN_OPTION = "--token";
16
17
  const IGNORED_FILENAMES = new Set([
@@ -73,6 +74,7 @@ const COMMAND_NAMES = new Set([
73
74
  "delete",
74
75
  "resolve",
75
76
  "download",
77
+ "agent",
76
78
  "move",
77
79
  "artifacts",
78
80
  "comments",
@@ -85,6 +87,7 @@ const COMMAND_NAMES = new Set([
85
87
  "init"
86
88
  ]);
87
89
  const SUBCOMMANDS = {
90
+ agent: ["open"],
88
91
  artifacts: ["list", "get"],
89
92
  comments: [
90
93
  "list",
@@ -108,7 +111,8 @@ const SUBCOMMANDS = {
108
111
  "install",
109
112
  "list",
110
113
  "update",
111
- "remove"
114
+ "remove",
115
+ "ensure"
112
116
  ]
113
117
  };
114
118
  const UPDATE_OPTION_KEYS = new Set([
@@ -120,6 +124,9 @@ const UPDATE_OPTION_KEYS = new Set([
120
124
  "profile",
121
125
  "token"
122
126
  ]);
127
+ function agentDownloadCommand(target) {
128
+ return `${CLI_INVOCATION} download ${target} --output ${AGENT_DOWNLOAD_OUTPUT} --json`;
129
+ }
123
130
  //#endregion
124
131
  //#region src/errors.ts
125
132
  const REQUEST_ACCESS_COMMAND$1 = `${CLI_INVOCATION} request-access --json`;
@@ -582,7 +589,7 @@ function skillUpdateConflictError(path) {
582
589
  code: "skill_update_conflict",
583
590
  message: `The file at ${path} is not managed by Artifact Share CLI.`,
584
591
  why: "Artifact Share only rewrites or removes skill files it created with a managed marker comment.",
585
- hint: "Inspect the file and resolve it yourself, or rerun skills install with --force to overwrite it.",
592
+ hint: "Inspect the file and resolve it yourself, or rerun skills install --tool <tool> --force to overwrite it.",
586
593
  agentRecoverable: false,
587
594
  requiresHuman: true,
588
595
  recovery: { kind: "ask_human" },
@@ -729,6 +736,7 @@ const TARGET_COMMAND_LABELS = {
729
736
  update: "Update",
730
737
  "artifacts get": "Artifacts get",
731
738
  download: "Download",
739
+ "agent open": "Agent open",
732
740
  "comments list": "Comments list",
733
741
  "comments post": "Comments post",
734
742
  "comments edit": "Comments edit",
@@ -818,24 +826,32 @@ function isKnownFlagToken(token) {
818
826
  const name = eqIndex === -1 ? token.slice(2) : token.slice(2, eqIndex);
819
827
  return BOOLEAN_FLAGS.has(name) || VALUE_FLAGS.has(name) || name === "help" || name === "version";
820
828
  }
821
- function validateRawArgs(argv) {
829
+ function validateRawArgs(argv, command) {
822
830
  for (let i = 0; i < argv.length; i += 1) {
823
831
  const arg = argv[i] ?? "";
824
832
  if (!arg.startsWith("--")) continue;
825
833
  const eqIndex = arg.indexOf("=");
826
834
  if (eqIndex === -1) {
827
835
  const rawName = arg.slice(2);
836
+ const artifactIdError = unsupportedPublishArtifactId(rawName, command);
837
+ if (artifactIdError) return artifactIdError;
828
838
  const next = argv[i + 1];
829
839
  if (VALUE_FLAGS.has(rawName) && (next === void 0 || isKnownFlagToken(next) || next === "" && !allowsEmptyValue(rawName))) return validationError(`--${rawName} requires a value.`, `Pass --${rawName} <value> and retry.`);
830
840
  continue;
831
841
  }
832
842
  const rawName = arg.slice(2, eqIndex);
843
+ const artifactIdError = unsupportedPublishArtifactId(rawName, command);
844
+ if (artifactIdError) return artifactIdError;
833
845
  const value = arg.slice(eqIndex + 1);
834
846
  if (BOOLEAN_FLAGS.has(rawName)) return validationError(`--${rawName} does not accept a value.`, `Use --${rawName} without =value.`);
835
847
  if (VALUE_FLAGS.has(rawName) && value === "" && !allowsEmptyValue(rawName)) return validationError(`--${rawName} requires a value.`, `Pass --${rawName} <value> and retry.`);
836
848
  }
837
849
  return null;
838
850
  }
851
+ function unsupportedPublishArtifactId(rawName, command) {
852
+ if (command !== "publish" || rawName !== "artifact-id" && rawName !== "artifactId") return null;
853
+ return validationError("Publish does not accept --artifact-id.", `To keep an existing share URL, run ${CLI_INVOCATION} update <artifact-id-or-url> <path> --json. For repeat jobs, use publish --key <key>.`);
854
+ }
839
855
  function allowsEmptyValue(rawName) {
840
856
  return rawName === "title" || rawName === "description";
841
857
  }
@@ -963,8 +979,26 @@ function humanSuccess(command, data) {
963
979
  ].join("\n");
964
980
  }
965
981
  if (command === "doctor") return doctorHumanOutput(data);
982
+ if (command === "agent open") return agentOpenHumanOutput(data);
966
983
  return `${JSON.stringify(data, null, 2)}\n`;
967
984
  }
985
+ function agentOpenHumanOutput(data) {
986
+ const body = `${JSON.stringify(data, null, 2)}`;
987
+ const nextCommand = agentOpenNextCommand(data);
988
+ if (!nextCommand) return `${body}\n`;
989
+ return `${body}\nNext command: ${nextCommand}\n`;
990
+ }
991
+ function agentOpenNextCommand(data) {
992
+ if (!isAgentOpenData(data)) return null;
993
+ return data.open.kind === "download_required" ? data.open.next_command : null;
994
+ }
995
+ function isAgentOpenData(data) {
996
+ if (!isRecord(data)) return false;
997
+ const open = data.open;
998
+ if (!isRecord(open)) return false;
999
+ if (open.kind === "read") return true;
1000
+ return open.kind === "download_required" && typeof open.next_command === "string";
1001
+ }
968
1002
  function doctorHumanOutput(data) {
969
1003
  const nextCommand = doctorNextCommand(data);
970
1004
  const body = `${JSON.stringify(data, null, 2)}`;
@@ -1636,17 +1670,22 @@ async function resolveEffectiveDefaultProfile(projectInput = null) {
1636
1670
  //#region src/command-runners/artifacts-get.ts
1637
1671
  async function runArtifactsGet(parsed, mode) {
1638
1672
  const command = "artifacts get";
1673
+ const result = await readArtifact(parsed, command);
1674
+ if (result.error) return writeFailure(command, result.error, mode, 1);
1675
+ return writeSuccess(command, result.data, mode);
1676
+ }
1677
+ async function readArtifact(parsed, command) {
1639
1678
  const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to read.");
1640
- if (target.error) return writeFailure(command, target.error, mode, 1);
1679
+ if (target.error) return { error: target.error };
1641
1680
  const artifactId = target.artifactId;
1642
1681
  const offset = parseOffsetOption(parsed.options.offset);
1643
- if (offset.error) return writeFailure(command, offset.error, mode, 1);
1682
+ if (offset.error) return { error: offset.error };
1644
1683
  const include = parseIncludeOptions(parsed.options.include);
1645
- if (include.error) return writeFailure(command, include.error, mode, 1);
1684
+ if (include.error) return { error: include.error };
1646
1685
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1647
- if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
1686
+ if (!credential.ok) return { error: credential.error };
1648
1687
  const request = await requestConfig(parsed.options);
1649
- if (request.error) return writeFailure(command, request.error, mode, 1);
1688
+ if (request.error) return { error: request.error };
1650
1689
  const url = apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}`, baseUrlOf(parsed.options));
1651
1690
  if (offset.value !== void 0) url.searchParams.set("offset", offset.value);
1652
1691
  for (const item of include.values) url.searchParams.append("include", item);
@@ -1654,14 +1693,14 @@ async function runArtifactsGet(parsed, mode) {
1654
1693
  headers: { Authorization: `Bearer ${credential.token}` },
1655
1694
  ...request.init
1656
1695
  }).catch((error) => ({ networkError: error }));
1657
- if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
1696
+ if ("networkError" in response) return { error: networkError(response.networkError) };
1658
1697
  const body = await readJson(response);
1659
- if (!response.ok) return writeFailure(command, mapApiError(response.status, body, {
1698
+ if (!response.ok) return { error: mapApiError(response.status, body, {
1660
1699
  authenticated: true,
1661
1700
  artifactTarget: true
1662
- }), mode, 1);
1663
- if (!artifactGetSuccessFields(body)) return writeFailure(command, serviceError("Artifact read succeeded but the response did not include source metadata."), mode, 1);
1664
- return writeSuccess(command, body, mode);
1701
+ }) };
1702
+ if (!artifactGetSuccessFields(body)) return { error: serviceError("Artifact read succeeded but the response did not include source metadata.") };
1703
+ return { data: body };
1665
1704
  }
1666
1705
  async function runArtifactsList(parsed, mode) {
1667
1706
  const command = "artifacts list";
@@ -1691,162 +1730,528 @@ async function runArtifactsList(parsed, mode) {
1691
1730
  return writeSuccess(command, body, mode);
1692
1731
  }
1693
1732
  //#endregion
1694
- //#region src/command-runners/comments.ts
1695
- async function runCommentsList(parsed, mode) {
1696
- const command = "comments list";
1697
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
1698
- if (target.error) return writeFailure(command, target.error, mode, 1);
1699
- const artifactId = target.artifactId;
1700
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1701
- if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
1702
- const request = await requestConfig(parsed.options);
1703
- if (request.error) return writeFailure(command, request.error, mode, 1);
1704
- const result = await apiGet(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, parsed.options, request.init, { artifactTarget: true });
1705
- if (result.error) return writeFailure(command, result.error, mode, 1);
1706
- const comments = Array.isArray(result.body?.comments) ? result.body.comments : [];
1707
- writeSuccess(command, {
1708
- artifact_id: artifactId,
1709
- share_url: configString(result.body?.share_url),
1710
- comments,
1711
- has_more: result.body?.has_more === true
1712
- }, mode);
1713
- if (!mode.json && comments.length === 0) writeText("No comments yet.\n");
1714
- }
1715
- async function runCommentsPost(parsed, mode) {
1716
- const command = "comments post";
1717
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
1718
- if (target.error) return writeFailure(command, target.error, mode, 1);
1719
- const artifactId = target.artifactId;
1720
- const body = parsed.options.body;
1721
- if (!body || !body.trim()) return writeFailure(command, validationError("A comment body is required.", "Retry with --body <text>."), mode, 1);
1722
- const replyTo = parsed.options.replyTo;
1723
- const quote = parsed.options.quote;
1724
- 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);
1725
- 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);
1726
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1727
- if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
1728
- const request = await requestConfig(parsed.options);
1729
- if (request.error) return writeFailure(command, request.error, mode, 1);
1730
- const result = await apiPost(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, {
1731
- body,
1732
- reply_to: replyTo,
1733
- quote,
1734
- quote_before: parsed.options.quoteBefore,
1735
- quote_after: parsed.options.quoteAfter
1736
- }, parsed.options, request.init, { artifactTarget: true });
1737
- if (result.error) return writeFailure(command, result.error, mode, 1);
1738
- const threadId = configString(result.body?.thread_id);
1739
- if (!threadId) return writeFailure(command, serviceError("Comment was saved but the response had no thread id."), mode, 1);
1740
- writeSuccess(command, {
1741
- artifact_id: artifactId,
1742
- share_url: configString(result.body?.share_url),
1743
- thread_id: threadId,
1744
- reply: result.body?.reply === true,
1745
- thread: result.body?.thread ?? null
1746
- }, mode);
1747
- }
1748
- async function runCommentsEdit(parsed, mode) {
1749
- const command = "comments edit";
1750
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
1751
- if (target.error) return writeFailure(command, target.error, mode, 1);
1752
- const messageId = requiredOption(parsed.options.messageId, "--message-id is required.", "Run comments list and retry with a listed message_id.");
1753
- if (messageId.error) return writeFailure(command, messageId.error, mode, 1);
1754
- const body = requiredOption(parsed.options.body, "--body is required.", "Pass --body <text> with the updated comment.");
1755
- if (body.error) return writeFailure(command, body.error, mode, 1);
1756
- const result = await postCommentAction(parsed, command, target.artifactId, {
1757
- action: "edit",
1758
- message_id: messageId.value,
1759
- body: body.value
1760
- }, mode);
1761
- if (!result) return;
1762
- const threadId = configString(result.thread_id);
1763
- if (!threadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
1764
- writeSuccess(command, {
1765
- artifact_id: target.artifactId,
1766
- share_url: configString(result.share_url),
1767
- thread_id: threadId,
1768
- thread: result.thread
1769
- }, mode);
1770
- }
1771
- async function runCommentsResolve(parsed, mode) {
1772
- return await runCommentsStatus(parsed, mode, "comments resolve", "resolve");
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
+ };
1773
1772
  }
1774
- async function runCommentsReopen(parsed, mode) {
1775
- return await runCommentsStatus(parsed, mode, "comments reopen", "reopen");
1773
+ function allTargets() {
1774
+ return SKILL_TOOLS.flatMap((tool) => TOOL_CONFIG[tool].scopes.map((scope) => skillTarget(tool, scope)));
1776
1775
  }
1777
- async function runCommentsDelete(parsed, mode) {
1778
- const command = "comments delete";
1779
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
1780
- if (target.error) return writeFailure(command, target.error, mode, 1);
1781
- const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
1782
- if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
1783
- const payload = {
1784
- action: "delete",
1785
- thread_id: threadId.value
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)
1786
1786
  };
1787
- if (parsed.options.messageId !== void 0) {
1788
- 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);
1789
- payload.message_id = parsed.options.messageId.trim();
1790
- }
1791
- const result = await postCommentAction(parsed, command, target.artifactId, payload, mode);
1792
- if (!result) return;
1793
- const responseThreadId = configString(result.thread_id);
1794
- if (!responseThreadId || result.deleted !== true) return writeFailure(command, serviceError("Comment was deleted but the response was incomplete."), mode, 1);
1795
- writeSuccess(command, {
1796
- artifact_id: target.artifactId,
1797
- share_url: configString(result.share_url),
1798
- thread_id: responseThreadId,
1799
- deleted: true,
1800
- thread_deleted: result.thread_deleted === true,
1801
- ...result.thread !== void 0 ? { thread: result.thread } : {}
1802
- }, mode);
1803
1787
  }
1804
- async function runCommentsStatus(parsed, mode, command, action) {
1805
- const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
1806
- if (target.error) return writeFailure(command, target.error, mode, 1);
1807
- const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
1808
- if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
1809
- const result = await postCommentAction(parsed, command, target.artifactId, {
1810
- action,
1811
- thread_id: threadId.value
1812
- }, mode);
1813
- if (!result) return;
1814
- const responseThreadId = configString(result.thread_id);
1815
- if (!responseThreadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
1816
- writeSuccess(command, {
1817
- artifact_id: target.artifactId,
1818
- share_url: configString(result.share_url),
1819
- thread_id: responseThreadId,
1820
- thread: result.thread
1821
- }, mode);
1788
+ async function readTarget(target) {
1789
+ return managedState(await readFile(target.absolutePath, "utf8").catch(() => null));
1822
1790
  }
1823
- async function postCommentAction(parsed, command, artifactId, payload, mode) {
1824
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
1825
- if (!credential.ok) {
1826
- writeFailure(command, credential.error, mode, 1);
1827
- return null;
1828
- }
1829
- const request = await requestConfig(parsed.options);
1830
- if (request.error) {
1831
- writeFailure(command, request.error, mode, 1);
1832
- return null;
1833
- }
1834
- const result = await apiPost(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, payload, parsed.options, request.init, { artifactTarget: true });
1835
- if (result.error) {
1836
- writeFailure(command, result.error, mode, 1);
1837
- return null;
1838
- }
1839
- if (result.body === null) {
1840
- writeFailure(command, serviceError("Comment was changed but the response was empty."), mode, 1);
1841
- return null;
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;
1842
1806
  }
1843
- return result.body;
1807
+ return {
1808
+ contents,
1809
+ version
1810
+ };
1844
1811
  }
1845
- function requiredOption(value, message, hint) {
1846
- if (!value || !value.trim()) return { error: validationError(message, hint) };
1847
- return { value: value.trim() };
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);
1821
+ continue;
1822
+ }
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);
1825
+ }
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.") };
1830
+ return {
1831
+ tools: unique.filter((tool) => tool !== "auto"),
1832
+ auto
1833
+ };
1848
1834
  }
1849
- //#endregion
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.") };
1840
+ }
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.`) };
1849
+ return {
1850
+ tools: tools.tools,
1851
+ auto: tools.auto,
1852
+ scope: scope.scope
1853
+ };
1854
+ }
1855
+ function filteredTargets(tools, scope) {
1856
+ return allTargets().filter((target) => (tools.length === 0 || tools.includes(target.tool)) && (scope === void 0 || target.scope === scope));
1857
+ }
1858
+ function detectionBase(scope) {
1859
+ return scope === "project" ? process.cwd() : homedir();
1860
+ }
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;
1865
+ }
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));
1876
+ }
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
+ }
1887
+ }
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
+ }
1899
+ }
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
+ };
1916
+ }
1917
+ async function runActions(command, planned, dryRun, mode) {
1918
+ const data = await finishActions(command, planned, dryRun, mode);
1919
+ if (data) writeSuccess(command, data, mode);
1920
+ }
1921
+ async function bundledOrFailure(command, mode) {
1922
+ try {
1923
+ return await loadBundledSkills();
1924
+ } catch (error) {
1925
+ writeFailure(command, unexpectedError(error), mode, 1);
1926
+ return;
1927
+ }
1928
+ }
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;
2105
+ 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");
2119
+ }
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);
2124
+ 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);
2227
+ }
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
+ }
2234
+ 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() };
2253
+ }
2254
+ //#endregion
1850
2255
  //#region src/command-runners/delete.ts
1851
2256
  async function runDelete(parsed, mode) {
1852
2257
  const command = "delete";
@@ -3071,391 +3476,130 @@ async function runPublish(parsed, mode, isRetry = false) {
3071
3476
  projectName = nonEmpty(typeof parsed.options.project === "string" ? parsed.options.project : "");
3072
3477
  if (!projectName) return writeFailure(command, validationError("--project requires a value.", "Pass --project <name> and retry."), mode, 1);
3073
3478
  const conflict = destinationConflictError(parsed.options);
3074
- if (conflict) return writeFailure(command, conflict, mode, 1);
3075
- } else {
3076
- const earlyDestination = resolveDestination(parsed.options, project.config);
3077
- if (earlyDestination.error) return writeFailure(command, earlyDestination.error, mode, 1);
3078
- }
3079
- const fileStat = await stat(targetPath).catch(() => null);
3080
- if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
3081
- const request = await requestConfig(parsed.options);
3082
- if (request.error) return writeFailure(command, request.error, mode, 1);
3083
- if (hasProjectFlag && projectName) {
3084
- const resolved = await resolveProjectIdByName(projectName, credential.token, parsed.options, request.init);
3085
- if (resolved.error) return writeFailure(command, resolved.error, mode, 1);
3086
- const { project: _project, ...rest } = parsed.options;
3087
- destinationOptions = {
3088
- ...rest,
3089
- projectId: resolved.projectId
3090
- };
3091
- }
3092
- const destination = resolveDestination(destinationOptions, project.config);
3093
- if (destination.error) return writeFailure(command, destination.error, mode, 1);
3094
- const initialForm = new FormData();
3095
- const grantEmails = arrayOption(parsed.options.grantEmail);
3096
- const requestedVisibility = parsed.options.visibility ?? (destination.containerId && grantEmails.length === 0 ? "project" : "private");
3097
- initialForm.set("visibility", requestedVisibility);
3098
- for (const email of grantEmails) initialForm.append("grant_email", email);
3099
- if (destination.containerId) initialForm.set("container_id", destination.containerId);
3100
- const uploadUrl = apiUrl("/api/shareables/uploads", baseUrl);
3101
- if (publishKey !== null) uploadUrl.searchParams.set("publish_key", publishKey);
3102
- const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
3103
- if (upload.error) return writeFailure(command, upload.error, mode, 1);
3104
- if (upload.payload.kind === "static_site") {
3105
- uploadUrl.searchParams.set("artifact_kind", "static_site");
3106
- if (destination.containerId) uploadUrl.searchParams.set("container_id", destination.containerId);
3107
- }
3108
- const response = await fetch(uploadUrl, {
3109
- method: "POST",
3110
- headers: { Authorization: `Bearer ${credential.token}` },
3111
- body: upload.payload.form,
3112
- ...request.init
3113
- }).catch((error) => ({ networkError: error }));
3114
- if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
3115
- const body = await readJson(response);
3116
- if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
3117
- const id = body?.id ?? null;
3118
- return writeSuccess(command, {
3119
- artifact: {
3120
- id,
3121
- url: body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
3122
- kind: body?.artifactKind ?? upload.payload.kind
3123
- },
3124
- version: { id: body?.versionId ?? null },
3125
- result: { created: body?.created ?? true },
3126
- ...publishKey !== null ? { key: publishKey } : {},
3127
- destination: destination.containerId ? {
3128
- type: "project",
3129
- project_id: destination.containerId
3130
- } : { type: "home" },
3131
- share: {
3132
- visibility: body?.visibility ?? requestedVisibility,
3133
- grant_emails: grantEmails
3134
- }
3135
- }, mode);
3136
- }
3137
- async function resolveProjectIdByName(projectName, token, options, init) {
3138
- const result = await fetchProjects(token, options, init);
3139
- if (result.error) return { error: result.error };
3140
- const candidates = result.projects.flatMap((project) => {
3141
- if (project.name !== projectName) return [];
3142
- return [{
3143
- project_id: project.id,
3144
- name: project.name,
3145
- updated_at: project.updated_at
3146
- }];
3147
- });
3148
- if (candidates.length === 0) return { error: projectNotFoundByNameError() };
3149
- if (candidates.length > 1) return { error: projectAmbiguousError(candidates) };
3150
- return { projectId: candidates[0].project_id };
3151
- }
3152
- //#endregion
3153
- //#region src/command-runners/request-access.ts
3154
- const NOTE_MAX = 2e3;
3155
- async function runRequestAccess(parsed, mode) {
3156
- const command = "request-access";
3157
- const note = parsed.options.note;
3158
- if (note !== void 0 && note.length > NOTE_MAX) return writeFailure(command, validationError(`A note can be at most ${NOTE_MAX} characters.`, "Shorten --note and retry."), mode, 1);
3159
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
3160
- if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3161
- const request = await requestConfig(parsed.options);
3162
- if (request.error) return writeFailure(command, request.error, mode, 1);
3163
- const result = await apiPost("/api/cli/request-access", credential.token, { note }, parsed.options, request.init);
3164
- if (result.error) return writeFailure(command, result.error, mode, 1);
3165
- const body = result.body;
3166
- const data = {
3167
- requested: body?.requested === true,
3168
- already_enabled: body?.already_enabled === true,
3169
- status: typeof body?.status === "string" ? body.status : null,
3170
- created: body?.created === true,
3171
- requires_operator_action: body?.requires_operator_action === true,
3172
- message: typeof body?.message === "string" ? body.message : ""
3173
- };
3174
- writeSuccess(command, data, mode);
3175
- if (!mode.json && data.message) writeText(`${data.message}\n`);
3176
- }
3177
- //#endregion
3178
- //#region src/command-runners/resolve.ts
3179
- async function runResolve(parsed, mode) {
3180
- const command = "resolve";
3181
- const value = parsed.positionals[0]?.trim();
3182
- if (!value) return writeFailure(command, validationError("Resolve value is required.", "Pass a URL, ID, title, or project name to resolve."), mode, 1);
3183
- const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
3184
- if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3185
- const request = await requestConfig(parsed.options);
3186
- if (request.error) return writeFailure(command, request.error, mode, 1);
3187
- const url = apiUrl("/api/cli/resolve", baseUrlOf(parsed.options));
3188
- url.searchParams.set("q", value);
3189
- const response = await fetch(url, {
3190
- headers: { Authorization: `Bearer ${credential.token}` },
3191
- ...request.init
3192
- }).catch((error) => ({ networkError: error }));
3193
- if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
3194
- const body = await readJson(response);
3195
- if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
3196
- if (!resolveSuccessFields(body)) return writeFailure(command, serviceError("Resolve succeeded but the response did not include query, candidates, and has_more."), mode, 1);
3197
- return writeSuccess(command, body, mode);
3198
- }
3199
- //#endregion
3200
- //#region src/command-runners/skills.ts
3201
- const SKILL_TOOLS = [
3202
- "codex",
3203
- "claude",
3204
- "cursor"
3205
- ];
3206
- const SKILL_FILE_PATH = join("skills", "artifactshare", "SKILL.md");
3207
- const TOOL_CONFIG = {
3208
- codex: {
3209
- relativePath: join(".agents", SKILL_FILE_PATH),
3210
- scopes: ["project", "user"],
3211
- detectDirs: [".codex", ".agents"],
3212
- bundledFile: "SKILL.md",
3213
- pruneDirs: ["artifactshare", "skills"]
3214
- },
3215
- claude: {
3216
- relativePath: join(".claude", SKILL_FILE_PATH),
3217
- scopes: ["project", "user"],
3218
- detectDirs: [".claude"],
3219
- bundledFile: "SKILL.md",
3220
- pruneDirs: ["artifactshare", "skills"]
3221
- },
3222
- cursor: {
3223
- relativePath: join(".cursor", "rules", "artifactshare.mdc"),
3224
- scopes: ["project"],
3225
- detectDirs: [".cursor"],
3226
- bundledFile: "artifactshare.mdc",
3227
- pruneDirs: []
3228
- }
3229
- };
3230
- function skillTarget(tool, scope) {
3231
- const relative = TOOL_CONFIG[tool].relativePath;
3232
- const path = scope === "project" ? relative : join(homedir(), relative);
3233
- return {
3234
- tool,
3235
- scope,
3236
- path,
3237
- absolutePath: resolve(path)
3238
- };
3239
- }
3240
- function allTargets() {
3241
- return SKILL_TOOLS.flatMap((tool) => TOOL_CONFIG[tool].scopes.map((scope) => skillTarget(tool, scope)));
3242
- }
3243
- function managedState(content) {
3244
- if (content === null) return { kind: "missing" };
3245
- if (!content.includes("artifactshare-skill")) return { kind: "unmanaged" };
3246
- const block = content.match(/<!--\s*artifactshare-skill([\s\S]*?)-->/)?.[1];
3247
- const version = block?.match(/(?:^|\n)\s*version:\s*(\d+)\s*(?:\n|$)/)?.[1];
3248
- const managed = block !== void 0 && /(?:^|\n)\s*managed:\s*true\s*(?:\n|$)/.test(block);
3249
- if (version === void 0 || !managed) return { kind: "broken" };
3250
- return {
3251
- kind: "managed",
3252
- version: Number(version)
3253
- };
3254
- }
3255
- async function readTarget(target) {
3256
- return managedState(await readFile(target.absolutePath, "utf8").catch(() => null));
3257
- }
3258
- async function loadBundledSkills() {
3259
- const byFile = /* @__PURE__ */ new Map();
3260
- const contents = {};
3261
- let version;
3262
- for (const tool of SKILL_TOOLS) {
3263
- const file = TOOL_CONFIG[tool].bundledFile;
3264
- let content = byFile.get(file);
3265
- if (content === void 0) {
3266
- content = await readFile(new URL(`../skills/artifactshare/${file}`, import.meta.url), "utf8");
3267
- const state = managedState(content);
3268
- if (state.kind !== "managed" || (version ?? state.version) !== state.version) throw new Error(`The bundled ${file} has a missing or mismatched managed marker.`);
3269
- version = state.version;
3270
- byFile.set(file, content);
3271
- }
3272
- contents[tool] = content;
3273
- }
3274
- return {
3275
- contents,
3276
- version
3277
- };
3278
- }
3279
- function parseTools(value) {
3280
- const raws = arrayOption(value);
3281
- const tools = [];
3282
- for (const raw of raws) for (const item of raw.split(",")) {
3283
- const trimmed = item.trim();
3284
- if (!trimmed) continue;
3285
- if (!SKILL_TOOLS.includes(trimmed)) return { error: validationError(`Unknown --tool value: ${trimmed}`, "Pass --tool codex, --tool claude, or --tool cursor.") };
3286
- tools.push(trimmed);
3287
- }
3288
- if (raws.length > 0 && tools.length === 0) return { error: validationError("--tool has no value.", "Pass --tool codex, --tool claude, or --tool cursor.") };
3289
- return { tools: [...new Set(tools)] };
3290
- }
3291
- function parseScope(value) {
3292
- const trimmed = nonEmpty(value);
3293
- if (trimmed === void 0) return { scope: void 0 };
3294
- if (trimmed === "project" || trimmed === "user") return { scope: trimmed };
3295
- return { error: validationError(`Unknown --scope value: ${trimmed}`, "Pass --scope project or --scope user.") };
3296
- }
3297
- function parseFilters(parsed) {
3298
- const tools = parseTools(parsed.options.tool);
3299
- if (tools.error) return { error: tools.error };
3300
- const scope = parseScope(parsed.options.scope);
3301
- if (scope.error) return { error: scope.error };
3302
- const unsupported = scope.scope === void 0 ? void 0 : tools.tools.find((tool) => !TOOL_CONFIG[tool].scopes.includes(scope.scope));
3303
- if (unsupported) return { error: validationError(`The ${unsupported} tool does not support --scope ${scope.scope}.`, `Use --tool ${unsupported} --scope project.`) };
3304
- return {
3305
- tools: tools.tools,
3306
- scope: scope.scope
3307
- };
3308
- }
3309
- function filteredTargets(tools, scope) {
3310
- return allTargets().filter((target) => (tools.length === 0 || tools.includes(target.tool)) && (scope === void 0 || target.scope === scope));
3311
- }
3312
- async function applyAction({ target, action, content }) {
3313
- if (content !== void 0) {
3314
- await mkdir(dirname(target.absolutePath), { recursive: true });
3315
- await writeFile(target.absolutePath, content);
3316
- return;
3317
- }
3318
- if (action === "removed") {
3319
- await rm(target.absolutePath, { force: true });
3320
- await cleanupSkillDirs(target);
3321
- }
3322
- }
3323
- async function cleanupSkillDirs(target) {
3324
- let dir = dirname(target.absolutePath);
3325
- for (const expected of TOOL_CONFIG[target.tool].pruneDirs) {
3326
- if (basename(dir) !== expected) return;
3327
- try {
3328
- await rmdir(dir);
3329
- } catch {
3330
- return;
3331
- }
3332
- dir = dirname(dir);
3479
+ if (conflict) return writeFailure(command, conflict, mode, 1);
3480
+ } else {
3481
+ const earlyDestination = resolveDestination(parsed.options, project.config);
3482
+ if (earlyDestination.error) return writeFailure(command, earlyDestination.error, mode, 1);
3333
3483
  }
3334
- }
3335
- async function finishActions(command, planned, dryRun, mode) {
3336
- if (!dryRun) try {
3337
- for (const item of planned) await applyAction(item);
3338
- } catch (error) {
3339
- return writeFailure(command, unexpectedError(error), mode, 1);
3484
+ const fileStat = await stat(targetPath).catch(() => null);
3485
+ if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
3486
+ const request = await requestConfig(parsed.options);
3487
+ if (request.error) return writeFailure(command, request.error, mode, 1);
3488
+ 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);
3491
+ const { project: _project, ...rest } = parsed.options;
3492
+ destinationOptions = {
3493
+ ...rest,
3494
+ projectId: resolved.projectId
3495
+ };
3340
3496
  }
3341
- return writeSuccess(command, {
3342
- dry_run: dryRun,
3343
- targets: planned.map(({ target, action }) => ({
3344
- tool: target.tool,
3345
- scope: target.scope,
3346
- path: target.path,
3347
- action
3348
- }))
3349
- }, mode);
3350
- }
3351
- async function bundledOrFailure(command, mode) {
3352
- try {
3353
- return await loadBundledSkills();
3354
- } catch (error) {
3355
- writeFailure(command, unexpectedError(error), mode, 1);
3356
- return;
3497
+ const destination = resolveDestination(destinationOptions, project.config);
3498
+ if (destination.error) return writeFailure(command, destination.error, mode, 1);
3499
+ const initialForm = new FormData();
3500
+ const grantEmails = arrayOption(parsed.options.grantEmail);
3501
+ const requestedVisibility = parsed.options.visibility ?? (destination.containerId && grantEmails.length === 0 ? "project" : "private");
3502
+ initialForm.set("visibility", requestedVisibility);
3503
+ for (const email of grantEmails) initialForm.append("grant_email", email);
3504
+ if (destination.containerId) initialForm.set("container_id", destination.containerId);
3505
+ const uploadUrl = apiUrl("/api/shareables/uploads", baseUrl);
3506
+ if (publishKey !== null) uploadUrl.searchParams.set("publish_key", publishKey);
3507
+ const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
3508
+ if (upload.error) return writeFailure(command, upload.error, mode, 1);
3509
+ if (upload.payload.kind === "static_site") {
3510
+ uploadUrl.searchParams.set("artifact_kind", "static_site");
3511
+ if (destination.containerId) uploadUrl.searchParams.set("container_id", destination.containerId);
3357
3512
  }
3358
- }
3359
- async function runSkillsInstall(parsed, mode) {
3360
- const command = "skills install";
3361
- const filters = parseFilters(parsed);
3362
- if (filters.error) return writeFailure(command, filters.error, mode, 1);
3363
- const { tools } = filters;
3364
- 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);
3365
- const scope = filters.scope ?? "project";
3366
- const force = parsed.options.force === true;
3367
- const bundled = await bundledOrFailure(command, mode);
3368
- if (!bundled) return;
3369
- const planned = [];
3370
- for (const tool of tools) {
3371
- const target = skillTarget(tool, scope);
3372
- const state = await readTarget(target);
3373
- if ((state.kind === "unmanaged" || state.kind === "broken") && !force) return writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
3374
- if (state.kind === "managed" && state.version === bundled.version && !force) {
3375
- planned.push({
3376
- target,
3377
- action: "unchanged"
3378
- });
3379
- continue;
3513
+ const response = await fetch(uploadUrl, {
3514
+ method: "POST",
3515
+ headers: { Authorization: `Bearer ${credential.token}` },
3516
+ body: upload.payload.form,
3517
+ ...request.init
3518
+ }).catch((error) => ({ networkError: error }));
3519
+ if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
3520
+ const body = await readJson(response);
3521
+ if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
3522
+ const id = body?.id ?? null;
3523
+ return writeSuccess(command, {
3524
+ artifact: {
3525
+ id,
3526
+ url: body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
3527
+ kind: body?.artifactKind ?? upload.payload.kind
3528
+ },
3529
+ version: { id: body?.versionId ?? null },
3530
+ result: { created: body?.created ?? true },
3531
+ ...publishKey !== null ? { key: publishKey } : {},
3532
+ destination: destination.containerId ? {
3533
+ type: "project",
3534
+ project_id: destination.containerId
3535
+ } : { type: "home" },
3536
+ share: {
3537
+ visibility: body?.visibility ?? requestedVisibility,
3538
+ grant_emails: grantEmails
3380
3539
  }
3381
- planned.push({
3382
- target,
3383
- action: state.kind === "missing" ? "installed" : "updated",
3384
- content: bundled.contents[tool]
3385
- });
3386
- }
3387
- return finishActions(command, planned, parsed.options.dryRun === true, mode);
3388
- }
3389
- async function runSkillsList(parsed, mode) {
3390
- const bundled = await bundledOrFailure("skills list", mode);
3391
- if (!bundled) return;
3392
- const targets = [];
3393
- for (const target of allTargets()) {
3394
- const base = target.scope === "project" ? process.cwd() : homedir();
3395
- let detected = false;
3396
- for (const dir of TOOL_CONFIG[target.tool].detectDirs) if ((await stat(join(base, dir)).catch(() => null))?.isDirectory()) detected = true;
3397
- const state = await readTarget(target);
3398
- targets.push({
3399
- tool: target.tool,
3400
- scope: target.scope,
3401
- path: target.path,
3402
- detected,
3403
- installed: state.kind !== "missing",
3404
- managed: state.kind === "managed",
3405
- installed_version: state.kind === "managed" ? state.version : null,
3406
- update_available: state.kind === "managed" && state.version !== bundled.version
3407
- });
3408
- }
3409
- return writeSuccess("skills list", {
3410
- bundled_version: bundled.version,
3411
- targets
3412
3540
  }, mode);
3413
3541
  }
3414
- async function runSkillsUpdate(parsed, mode) {
3415
- const command = "skills update";
3416
- const filters = parseFilters(parsed);
3417
- if (filters.error) return writeFailure(command, filters.error, mode, 1);
3418
- const force = parsed.options.force === true;
3419
- const bundled = await bundledOrFailure(command, mode);
3420
- if (!bundled) return;
3421
- const planned = [];
3422
- for (const target of filteredTargets(filters.tools, filters.scope)) {
3423
- const state = await readTarget(target);
3424
- if (state.kind === "broken") return writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
3425
- if (state.kind === "missing") planned.push({
3426
- target,
3427
- action: "not_installed"
3428
- });
3429
- else if (state.kind === "unmanaged") planned.push({
3430
- target,
3431
- action: "skipped_unmanaged"
3432
- });
3433
- else if (state.version !== bundled.version || force) planned.push({
3434
- target,
3435
- action: "updated",
3436
- content: bundled.contents[target.tool]
3437
- });
3438
- else planned.push({
3439
- target,
3440
- action: "unchanged"
3441
- });
3442
- }
3443
- return finishActions(command, planned, parsed.options.dryRun === true, mode);
3542
+ async function resolveProjectIdByName(projectName, token, options, init) {
3543
+ const result = await fetchProjects(token, options, init);
3544
+ if (result.error) return { error: result.error };
3545
+ const candidates = result.projects.flatMap((project) => {
3546
+ if (project.name !== projectName) return [];
3547
+ return [{
3548
+ project_id: project.id,
3549
+ name: project.name,
3550
+ updated_at: project.updated_at
3551
+ }];
3552
+ });
3553
+ if (candidates.length === 0) return { error: projectNotFoundByNameError() };
3554
+ if (candidates.length > 1) return { error: projectAmbiguousError(candidates) };
3555
+ return { projectId: candidates[0].project_id };
3444
3556
  }
3445
- async function runSkillsRemove(parsed, mode) {
3446
- const command = "skills remove";
3447
- const filters = parseFilters(parsed);
3448
- if (filters.error) return writeFailure(command, filters.error, mode, 1);
3449
- const planned = [];
3450
- for (const target of filteredTargets(filters.tools, filters.scope)) {
3451
- const state = await readTarget(target);
3452
- const action = state.kind === "missing" ? "not_installed" : state.kind === "managed" ? "removed" : "skipped_unmanaged";
3453
- planned.push({
3454
- target,
3455
- action
3456
- });
3457
- }
3458
- return finishActions(command, planned, parsed.options.dryRun === true, mode);
3557
+ //#endregion
3558
+ //#region src/command-runners/request-access.ts
3559
+ const NOTE_MAX = 2e3;
3560
+ async function runRequestAccess(parsed, mode) {
3561
+ const command = "request-access";
3562
+ const note = parsed.options.note;
3563
+ if (note !== void 0 && note.length > NOTE_MAX) return writeFailure(command, validationError(`A note can be at most ${NOTE_MAX} characters.`, "Shorten --note and retry."), mode, 1);
3564
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
3565
+ if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3566
+ const request = await requestConfig(parsed.options);
3567
+ 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);
3569
+ if (result.error) return writeFailure(command, result.error, mode, 1);
3570
+ const body = result.body;
3571
+ const data = {
3572
+ requested: body?.requested === true,
3573
+ already_enabled: body?.already_enabled === true,
3574
+ status: typeof body?.status === "string" ? body.status : null,
3575
+ created: body?.created === true,
3576
+ requires_operator_action: body?.requires_operator_action === true,
3577
+ message: typeof body?.message === "string" ? body.message : ""
3578
+ };
3579
+ writeSuccess(command, data, mode);
3580
+ if (!mode.json && data.message) writeText(`${data.message}\n`);
3581
+ }
3582
+ //#endregion
3583
+ //#region src/command-runners/resolve.ts
3584
+ async function runResolve(parsed, mode) {
3585
+ const command = "resolve";
3586
+ const value = parsed.positionals[0]?.trim();
3587
+ if (!value) return writeFailure(command, validationError("Resolve value is required.", "Pass a URL, ID, title, or project name to resolve."), mode, 1);
3588
+ const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
3589
+ if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
3590
+ const request = await requestConfig(parsed.options);
3591
+ if (request.error) return writeFailure(command, request.error, mode, 1);
3592
+ const url = apiUrl("/api/cli/resolve", baseUrlOf(parsed.options));
3593
+ url.searchParams.set("q", value);
3594
+ const response = await fetch(url, {
3595
+ headers: { Authorization: `Bearer ${credential.token}` },
3596
+ ...request.init
3597
+ }).catch((error) => ({ networkError: error }));
3598
+ if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
3599
+ const body = await readJson(response);
3600
+ if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
3601
+ if (!resolveSuccessFields(body)) return writeFailure(command, serviceError("Resolve succeeded but the response did not include query, candidates, and has_more."), mode, 1);
3602
+ return writeSuccess(command, body, mode);
3459
3603
  }
3460
3604
  //#endregion
3461
3605
  //#region src/command-runners/update.ts
@@ -3550,6 +3694,10 @@ async function downloadRunner(ctx) {
3550
3694
  const parsed = parsedArgsFromContext("download", ctx);
3551
3695
  return await runDownload(parsed, outputMode(parsed.options));
3552
3696
  }
3697
+ async function agentOpenRunner(ctx) {
3698
+ const parsed = parsedArgsFromContext("agent open", ctx);
3699
+ return await runAgentOpen(parsed, outputMode(parsed.options));
3700
+ }
3553
3701
  async function moveRunner(ctx) {
3554
3702
  const parsed = parsedArgsFromContext("move", ctx);
3555
3703
  return await runMove(parsed, outputMode(parsed.options));
@@ -3635,6 +3783,10 @@ async function skillsUpdateRunner(ctx) {
3635
3783
  const parsed = parsedArgsFromContext("skills update", ctx);
3636
3784
  return await runSkillsUpdate(parsed, outputMode(parsed.options));
3637
3785
  }
3786
+ async function skillsEnsureRunner(ctx) {
3787
+ const parsed = parsedArgsFromContext("skills ensure", ctx);
3788
+ return await runSkillsEnsure(parsed, outputMode(parsed.options));
3789
+ }
3638
3790
  async function skillsRemoveRunner(ctx) {
3639
3791
  const parsed = parsedArgsFromContext("skills remove", ctx);
3640
3792
  return await runSkillsRemove(parsed, outputMode(parsed.options));
@@ -3662,7 +3814,7 @@ async function main(rawArgv) {
3662
3814
  const argv = joinLeadingDashValues(rawArgv);
3663
3815
  const command = commandNameFromArgv(argv);
3664
3816
  const commandCandidate = firstCommandCandidate(argv);
3665
- const rawError = validateRawArgs(argv);
3817
+ const rawError = validateRawArgs(argv, command);
3666
3818
  if (rawError) return writeFailure(command ?? "unknown", rawError, outputModeFromArgv(argv), 1);
3667
3819
  if (command === void 0 && commandCandidate !== void 0) return writeFailure("unknown", unknownCommandError(commandCandidate), outputModeFromArgv(argv), 1);
3668
3820
  const usage = await runGunshi(command === void 0 ? ["--help"] : normalizeArgvForGunshi(argv, commandCandidate)).catch((error) => {
@@ -3696,6 +3848,7 @@ async function runGunshi(argv) {
3696
3848
  delete: lazyCommand(deleteDefinition, deleteRunner),
3697
3849
  resolve: lazyCommand(resolveDefinition, resolveRunner),
3698
3850
  download: lazyCommand(downloadDefinition, downloadRunner),
3851
+ agent: agentDefinition,
3699
3852
  move: lazyCommand(moveDefinition, moveRunner),
3700
3853
  artifacts: artifactsDefinition,
3701
3854
  comments: commentsDefinition,
@@ -3764,7 +3917,7 @@ npx --yes @artifactshare/cli artifacts list --json
3764
3917
  npx --yes @artifactshare/cli artifacts get <artifact-id-or-url> --json
3765
3918
  npx --yes @artifactshare/cli comments list <artifact-id-or-url> --json
3766
3919
  npx --yes @artifactshare/cli comments post <artifact-id-or-url> --body "<text>" --json
3767
- npx --yes @artifactshare/cli download <artifact-id-or-url> --output ./artifact --json
3920
+ ${agentDownloadCommand("<artifact-id-or-url>")}
3768
3921
  npx --yes @artifactshare/cli login --profile default
3769
3922
  npx --yes @artifactshare/cli profiles list --json
3770
3923
  npx --yes @artifactshare/cli profiles use <name> --json
@@ -3847,7 +4000,13 @@ const publishDefinition = define({
3847
4000
  description: "Stable key for create-or-update: the first publish creates the artifact, repeats add versions. Not a secret; it appears in logs and JSON"
3848
4001
  }
3849
4002
  },
3850
- examples: `npx --yes @artifactshare/cli publish report.html --project-id <id> --key nightly-report --json
4003
+ examples: `npx --yes @artifactshare/cli publish report.html --project-id <id> --json
4004
+ npx --yes @artifactshare/cli publish report.html --project-id <id> --key nightly-report --json
4005
+
4006
+ To keep an existing share URL, use update:
4007
+ npx --yes @artifactshare/cli update <artifact-id-or-url> <path> --json
4008
+
4009
+ For repeat jobs, use --key: first publish creates the artifact, later runs add versions.
3851
4010
 
3852
4011
  Common failures:
3853
4012
  auth_required Set ARTIFACTSHARE_TOKEN before publish
@@ -4014,7 +4173,7 @@ const downloadDefinition = define({
4014
4173
  }
4015
4174
  },
4016
4175
  examples: `npx --yes @artifactshare/cli download abc123def4 --json
4017
- npx --yes @artifactshare/cli download https://artifactshare.com/a/abc123def4 --output ./artifact --json
4176
+ ${agentDownloadCommand("https://artifactshare.com/a/abc123def4")}
4018
4177
 
4019
4178
  Use resolve first when a user gives a title or project name, then pass the id here.
4020
4179
  Download writes files to a directory so the result can be inspected or passed to update.
@@ -4025,6 +4184,39 @@ Common failures:
4025
4184
  output_exists Choose another --output path or pass --force
4026
4185
  validation_failed Check --output and downloaded file paths`
4027
4186
  });
4187
+ const agentDefinition = define({
4188
+ name: "agent",
4189
+ description: "Agent-first helpers for Artifact Share URLs.",
4190
+ toKebab: true,
4191
+ args: commonArgs,
4192
+ subCommands: { open: lazyCommand(define({
4193
+ name: "open",
4194
+ description: "Prepare agent skills and read an Artifact Share URL.",
4195
+ toKebab: true,
4196
+ args: {
4197
+ ...commonArgs,
4198
+ artifactIdOrUrl: {
4199
+ type: "positional",
4200
+ toKebab: true,
4201
+ description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
4202
+ }
4203
+ },
4204
+ examples: `npx --yes @artifactshare/cli agent open https://artifactshare.com/a/abc123def4 --json
4205
+ npx --yes @artifactshare/cli agent open abc123def4 --json
4206
+
4207
+ Use this as the first command when an agent receives an Artifact Share URL.
4208
+ It installs or updates the local Artifact Share skill, then reads single-file artifacts.
4209
+ For static sites or multi-file artifacts, the JSON includes a download next_command.
4210
+
4211
+ Common failures:
4212
+ auth_required Set ARTIFACTSHARE_TOKEN before agent open
4213
+ skill_update_conflict Inspect the file or run skills install --tool <tool> --force
4214
+ target_not_found Retry with an artifact ID, share URL, or sandbox URL
4215
+ validation_failed Pass a non-empty artifact ID or URL`
4216
+ }), agentOpenRunner) },
4217
+ examples: `npx --yes @artifactshare/cli agent open https://artifactshare.com/a/abc123def4 --json`,
4218
+ run: parentCommandRunner("agent")
4219
+ });
4028
4220
  const moveDefinition = define({
4029
4221
  name: "move",
4030
4222
  description: "Move an artifact into a project or back home.",
@@ -4576,6 +4768,30 @@ Only files created by skills install (managed marker present) are updated.
4576
4768
  Common failures:
4577
4769
  skill_update_conflict A managed marker is broken; inspect the file or reinstall with --force`
4578
4770
  });
4771
+ const skillsEnsureDefinition = define({
4772
+ name: "ensure",
4773
+ description: "Install or update the bundled Artifact Share skill.",
4774
+ toKebab: true,
4775
+ args: {
4776
+ ...commonArgs,
4777
+ ...skillsToolArgs,
4778
+ dryRun: {
4779
+ type: "boolean",
4780
+ toKebab: true,
4781
+ description: "Show planned file changes without writing"
4782
+ }
4783
+ },
4784
+ examples: `npx --yes @artifactshare/cli skills ensure --tool auto --scope project --json
4785
+ npx --yes @artifactshare/cli skills ensure --tool claude --json
4786
+
4787
+ Use --tool auto from an agent workspace. It detects .claude, .agents/.codex,
4788
+ and .cursor in the current directory; if none are present, it prepares Codex
4789
+ and Claude Code project skills.
4790
+
4791
+ Common failures:
4792
+ validation_failed Pass --tool auto|codex|claude|cursor; auto supports --scope project only
4793
+ skill_update_conflict An unmanaged or broken skill file exists; inspect it before overwriting`
4794
+ });
4579
4795
  const skillsRemoveDefinition = define({
4580
4796
  name: "remove",
4581
4797
  description: "Remove Artifact Share skills installed by this CLI.",
@@ -4598,9 +4814,11 @@ const skillsDefinition = define({
4598
4814
  install: lazyCommand(skillsInstallDefinition, skillsInstallRunner),
4599
4815
  list: lazyCommand(skillsListDefinition, skillsListRunner),
4600
4816
  update: lazyCommand(skillsUpdateDefinition, skillsUpdateRunner),
4817
+ ensure: lazyCommand(skillsEnsureDefinition, skillsEnsureRunner),
4601
4818
  remove: lazyCommand(skillsRemoveDefinition, skillsRemoveRunner)
4602
4819
  },
4603
4820
  examples: `npx --yes @artifactshare/cli skills install --tool codex --json
4821
+ npx --yes @artifactshare/cli skills ensure --tool auto --json
4604
4822
  npx --yes @artifactshare/cli skills list --json`,
4605
4823
  run: parentCommandRunner("skills")
4606
4824
  });