@artifactshare/cli 0.1.6 → 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/README.md +24 -7
- package/dist/index.js +2008 -1644
- package/package.json +1 -1
- package/skills/artifactshare/SKILL.md +16 -8
- package/skills/artifactshare/artifactshare.mdc +12 -5
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 { createReadStream } from "node:fs";
|
|
7
|
-
import { createHash } from "node:crypto";
|
|
8
6
|
import { setTimeout } from "node:timers/promises";
|
|
9
7
|
import { homedir } from "node:os";
|
|
8
|
+
import { createReadStream } from "node:fs";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
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,14 @@ 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
|
+
}
|
|
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
|
+
}
|
|
123
135
|
//#endregion
|
|
124
136
|
//#region src/errors.ts
|
|
125
137
|
const REQUEST_ACCESS_COMMAND$1 = `${CLI_INVOCATION} request-access --json`;
|
|
@@ -137,7 +149,13 @@ function apiError(body) {
|
|
|
137
149
|
}
|
|
138
150
|
function mapApiError(status, body, options = {}) {
|
|
139
151
|
const { code: apiCode, message: apiMessage } = apiError(body);
|
|
140
|
-
if (status === 401)
|
|
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
|
+
}
|
|
141
159
|
if (apiCode === "upload-not-allowed") return cliError({
|
|
142
160
|
code: "upload_not_allowed",
|
|
143
161
|
message: "This account cannot publish yet.",
|
|
@@ -466,6 +484,24 @@ function authRequiredError(baseUrl) {
|
|
|
466
484
|
details: authRecoveryDetails(baseUrl)
|
|
467
485
|
});
|
|
468
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
|
+
}
|
|
469
505
|
function deviceAuthErrorDetails(pending) {
|
|
470
506
|
const openUrl = pending.verification_uri_complete ?? pending.verification_uri;
|
|
471
507
|
return {
|
|
@@ -479,7 +515,7 @@ function deviceAuthErrorDetails(pending) {
|
|
|
479
515
|
retry_hint: "After approval in the browser, rerun the same command to continue."
|
|
480
516
|
};
|
|
481
517
|
}
|
|
482
|
-
function authRequiredWithDeviceAuthError(baseUrl, pending) {
|
|
518
|
+
function authRequiredWithDeviceAuthError(baseUrl, pending, extraDetails = {}) {
|
|
483
519
|
const device = deviceAuthErrorDetails(pending);
|
|
484
520
|
const openUrl = pending.verification_uri_complete ?? pending.verification_uri;
|
|
485
521
|
return cliError({
|
|
@@ -492,6 +528,7 @@ function authRequiredWithDeviceAuthError(baseUrl, pending) {
|
|
|
492
528
|
recovery: { kind: "ask_human" },
|
|
493
529
|
details: {
|
|
494
530
|
...authRecoveryDetails(baseUrl, `${CLI_INVOCATION} login --profile ${pending.profile}`),
|
|
531
|
+
...extraDetails,
|
|
495
532
|
...device
|
|
496
533
|
}
|
|
497
534
|
});
|
|
@@ -582,7 +619,7 @@ function skillUpdateConflictError(path) {
|
|
|
582
619
|
code: "skill_update_conflict",
|
|
583
620
|
message: `The file at ${path} is not managed by Artifact Share CLI.`,
|
|
584
621
|
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
|
|
622
|
+
hint: "Inspect the file and resolve it yourself, or rerun skills install --tool <tool> --force to overwrite it.",
|
|
586
623
|
agentRecoverable: false,
|
|
587
624
|
requiresHuman: true,
|
|
588
625
|
recovery: { kind: "ask_human" },
|
|
@@ -729,6 +766,7 @@ const TARGET_COMMAND_LABELS = {
|
|
|
729
766
|
update: "Update",
|
|
730
767
|
"artifacts get": "Artifacts get",
|
|
731
768
|
download: "Download",
|
|
769
|
+
"agent open": "Agent open",
|
|
732
770
|
"comments list": "Comments list",
|
|
733
771
|
"comments post": "Comments post",
|
|
734
772
|
"comments edit": "Comments edit",
|
|
@@ -818,24 +856,32 @@ function isKnownFlagToken(token) {
|
|
|
818
856
|
const name = eqIndex === -1 ? token.slice(2) : token.slice(2, eqIndex);
|
|
819
857
|
return BOOLEAN_FLAGS.has(name) || VALUE_FLAGS.has(name) || name === "help" || name === "version";
|
|
820
858
|
}
|
|
821
|
-
function validateRawArgs(argv) {
|
|
859
|
+
function validateRawArgs(argv, command) {
|
|
822
860
|
for (let i = 0; i < argv.length; i += 1) {
|
|
823
861
|
const arg = argv[i] ?? "";
|
|
824
862
|
if (!arg.startsWith("--")) continue;
|
|
825
863
|
const eqIndex = arg.indexOf("=");
|
|
826
864
|
if (eqIndex === -1) {
|
|
827
865
|
const rawName = arg.slice(2);
|
|
866
|
+
const artifactIdError = unsupportedPublishArtifactId(rawName, command);
|
|
867
|
+
if (artifactIdError) return artifactIdError;
|
|
828
868
|
const next = argv[i + 1];
|
|
829
869
|
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
870
|
continue;
|
|
831
871
|
}
|
|
832
872
|
const rawName = arg.slice(2, eqIndex);
|
|
873
|
+
const artifactIdError = unsupportedPublishArtifactId(rawName, command);
|
|
874
|
+
if (artifactIdError) return artifactIdError;
|
|
833
875
|
const value = arg.slice(eqIndex + 1);
|
|
834
876
|
if (BOOLEAN_FLAGS.has(rawName)) return validationError(`--${rawName} does not accept a value.`, `Use --${rawName} without =value.`);
|
|
835
877
|
if (VALUE_FLAGS.has(rawName) && value === "" && !allowsEmptyValue(rawName)) return validationError(`--${rawName} requires a value.`, `Pass --${rawName} <value> and retry.`);
|
|
836
878
|
}
|
|
837
879
|
return null;
|
|
838
880
|
}
|
|
881
|
+
function unsupportedPublishArtifactId(rawName, command) {
|
|
882
|
+
if (command !== "publish" || rawName !== "artifact-id" && rawName !== "artifactId") return null;
|
|
883
|
+
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>.`);
|
|
884
|
+
}
|
|
839
885
|
function allowsEmptyValue(rawName) {
|
|
840
886
|
return rawName === "title" || rawName === "description";
|
|
841
887
|
}
|
|
@@ -963,8 +1009,26 @@ function humanSuccess(command, data) {
|
|
|
963
1009
|
].join("\n");
|
|
964
1010
|
}
|
|
965
1011
|
if (command === "doctor") return doctorHumanOutput(data);
|
|
1012
|
+
if (command === "agent open") return agentOpenHumanOutput(data);
|
|
966
1013
|
return `${JSON.stringify(data, null, 2)}\n`;
|
|
967
1014
|
}
|
|
1015
|
+
function agentOpenHumanOutput(data) {
|
|
1016
|
+
const body = `${JSON.stringify(data, null, 2)}`;
|
|
1017
|
+
const nextCommand = agentOpenNextCommand(data);
|
|
1018
|
+
if (!nextCommand) return `${body}\n`;
|
|
1019
|
+
return `${body}\nNext command: ${nextCommand}\n`;
|
|
1020
|
+
}
|
|
1021
|
+
function agentOpenNextCommand(data) {
|
|
1022
|
+
if (!isAgentOpenData(data)) return null;
|
|
1023
|
+
return data.open.kind === "download_required" ? data.open.next_command : null;
|
|
1024
|
+
}
|
|
1025
|
+
function isAgentOpenData(data) {
|
|
1026
|
+
if (!isRecord(data)) return false;
|
|
1027
|
+
const open = data.open;
|
|
1028
|
+
if (!isRecord(open)) return false;
|
|
1029
|
+
if (open.kind === "read") return true;
|
|
1030
|
+
return open.kind === "download_required" && typeof open.next_command === "string";
|
|
1031
|
+
}
|
|
968
1032
|
function doctorHumanOutput(data) {
|
|
969
1033
|
const nextCommand = doctorNextCommand(data);
|
|
970
1034
|
const body = `${JSON.stringify(data, null, 2)}`;
|
|
@@ -1098,6 +1162,7 @@ async function apiRequest(path, options, init, errorOptions) {
|
|
|
1098
1162
|
const body = await readJson(response);
|
|
1099
1163
|
if (!response.ok) return { error: mapApiError(response.status, body, {
|
|
1100
1164
|
authenticated: true,
|
|
1165
|
+
baseUrl: baseUrlOf(options),
|
|
1101
1166
|
...errorOptions
|
|
1102
1167
|
}) };
|
|
1103
1168
|
return { body };
|
|
@@ -1520,7 +1585,7 @@ async function resolveProfileCredential(source, profile, options, globalConfig,
|
|
|
1520
1585
|
const stored = await readProfileToken(profile, options);
|
|
1521
1586
|
if (stored.ok) return {
|
|
1522
1587
|
ok: true,
|
|
1523
|
-
source
|
|
1588
|
+
source,
|
|
1524
1589
|
profile,
|
|
1525
1590
|
token: stored.token
|
|
1526
1591
|
};
|
|
@@ -1633,1829 +1698,2048 @@ async function resolveEffectiveDefaultProfile(projectInput = null) {
|
|
|
1633
1698
|
};
|
|
1634
1699
|
}
|
|
1635
1700
|
//#endregion
|
|
1636
|
-
//#region src/command-runners/
|
|
1637
|
-
async function
|
|
1638
|
-
const
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
const
|
|
1649
|
-
if (
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
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);
|
|
1770
|
+
return writeSuccess(command, result.data, mode);
|
|
1771
|
+
}
|
|
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
|
|
1656
1778
|
}).catch((error) => ({ networkError: error }));
|
|
1657
|
-
if ("networkError" in response) return
|
|
1779
|
+
if ("networkError" in response) return { error: networkError(response.networkError) };
|
|
1658
1780
|
const body = await readJson(response);
|
|
1659
|
-
if (!response.ok) return
|
|
1660
|
-
|
|
1661
|
-
|
|
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);
|
|
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;
|
|
1665
1784
|
}
|
|
1666
|
-
async function
|
|
1667
|
-
const
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
1677
|
-
const request = await requestConfig(parsed.options);
|
|
1678
|
-
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1679
|
-
const url = apiUrl("/api/cli/artifacts", baseUrlOf(parsed.options));
|
|
1680
|
-
if (home) url.searchParams.set("project_id", "");
|
|
1681
|
-
else if (projectId) url.searchParams.set("project_id", projectId);
|
|
1682
|
-
if (query) url.searchParams.set("query", query);
|
|
1683
|
-
const response = await fetch(url, {
|
|
1684
|
-
headers: { Authorization: `Bearer ${credential.token}` },
|
|
1685
|
-
...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
|
|
1686
1795
|
}).catch((error) => ({ networkError: error }));
|
|
1687
|
-
if ("networkError" in response) return
|
|
1796
|
+
if ("networkError" in response) return { error: networkError(response.networkError) };
|
|
1688
1797
|
const body = await readJson(response);
|
|
1689
|
-
if (
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
}
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
if (
|
|
1699
|
-
|
|
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");
|
|
1798
|
+
if (response.ok && isDeviceTokenResponse(body)) return {
|
|
1799
|
+
status: "success",
|
|
1800
|
+
token: body
|
|
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) }) };
|
|
1714
1809
|
}
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
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);
|
|
1810
|
+
function pendingDeviceAuthFromCode(profile, options, code) {
|
|
1811
|
+
return {
|
|
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()
|
|
1821
|
+
};
|
|
1747
1822
|
}
|
|
1748
|
-
async function
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
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) };
|
|
1841
|
+
continue;
|
|
1842
|
+
}
|
|
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) }) };
|
|
1855
|
+
}
|
|
1856
|
+
return { error: authExpiredError(profile) };
|
|
1770
1857
|
}
|
|
1771
|
-
async function
|
|
1772
|
-
|
|
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);
|
|
1878
|
+
return {
|
|
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
|
+
}
|
|
1889
|
+
};
|
|
1773
1890
|
}
|
|
1774
|
-
async function
|
|
1775
|
-
|
|
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
|
+
});
|
|
1776
1910
|
}
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
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
|
|
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);
|
|
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";
|
|
1803
1914
|
}
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
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);
|
|
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);
|
|
1822
1918
|
}
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
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;
|
|
1842
|
-
}
|
|
1843
|
-
return result.body;
|
|
1919
|
+
function deviceTokenError(body) {
|
|
1920
|
+
if (!isRecord(body)) return null;
|
|
1921
|
+
return typeof body.error === "string" ? body.error : null;
|
|
1844
1922
|
}
|
|
1845
|
-
function
|
|
1846
|
-
|
|
1847
|
-
|
|
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;
|
|
1927
|
+
return {
|
|
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
|
|
1931
|
+
};
|
|
1848
1932
|
}
|
|
1849
1933
|
//#endregion
|
|
1850
|
-
//#region src/command-runners/
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1860
|
-
const result = await apiDelete(`/api/cli/artifacts/${encodeURIComponent(artifactId)}`, credential.token, parsed.options, request.init, {
|
|
1861
|
-
authenticated: true,
|
|
1862
|
-
artifactTarget: true
|
|
1863
|
-
});
|
|
1864
|
-
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
1865
|
-
const body = result.body;
|
|
1866
|
-
if (!deleteSuccessFields(body)) return writeFailure(command, serviceError("Delete succeeded but the response did not include deletion metadata."), mode, 1);
|
|
1867
|
-
return writeSuccess(command, body, mode);
|
|
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;
|
|
1868
1943
|
}
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
const LOGIN_COMMAND = `${CLI_INVOCATION} login`;
|
|
1872
|
-
const REQUEST_ACCESS_COMMAND = `${CLI_INVOCATION} request-access`;
|
|
1873
|
-
function bearerTokenBlocksLogin(data) {
|
|
1874
|
-
return data.auth.credential_source === "env" || data.auth.credential_source === "token_option";
|
|
1944
|
+
function profileForAutoLogin(credential) {
|
|
1945
|
+
return credential.source === "none" ? "default" : credential.profile ?? "default";
|
|
1875
1946
|
}
|
|
1876
|
-
function
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
return LOGIN_COMMAND;
|
|
1880
|
-
}
|
|
1881
|
-
if (data.config.project.code === "token_store_unsafe") {
|
|
1882
|
-
if (bearerTokenBlocksLogin(data)) return null;
|
|
1883
|
-
return LOGIN_COMMAND;
|
|
1884
|
-
}
|
|
1885
|
-
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;
|
|
1886
|
-
if (!data.network.ok) return null;
|
|
1887
|
-
if (data.upload.checked && !data.upload.ok) {
|
|
1888
|
-
if (data.upload.code === "upload-not-allowed") return REQUEST_ACCESS_COMMAND;
|
|
1889
|
-
return null;
|
|
1890
|
-
}
|
|
1891
|
-
return null;
|
|
1947
|
+
function isPendingExpired(pending) {
|
|
1948
|
+
const expiresAt = Date.parse(pending.expires_at);
|
|
1949
|
+
return Number.isNaN(expiresAt) || expiresAt <= Date.now();
|
|
1892
1950
|
}
|
|
1893
|
-
function
|
|
1894
|
-
const
|
|
1895
|
-
return
|
|
1951
|
+
function authRequiredExtraDetails(error) {
|
|
1952
|
+
const credentialSource = error.details?.credential_source;
|
|
1953
|
+
return typeof credentialSource === "string" ? { credential_source: credentialSource } : {};
|
|
1896
1954
|
}
|
|
1897
|
-
function
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
...data,
|
|
1901
|
-
next_command: nextCommand
|
|
1902
|
-
};
|
|
1903
|
-
if (next.auth.code === "auth_required") next.auth = {
|
|
1904
|
-
...next.auth,
|
|
1905
|
-
recovery: authRecovery(next, nextCommand)
|
|
1906
|
-
};
|
|
1907
|
-
return next;
|
|
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";
|
|
1908
1958
|
}
|
|
1909
|
-
async function
|
|
1910
|
-
const
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1959
|
+
async function canAttemptProfileTokenSave(profile, options) {
|
|
1960
|
+
const stored = await readProfileToken(profile, options);
|
|
1961
|
+
return stored.ok || stored.reason !== "unavailable";
|
|
1962
|
+
}
|
|
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();
|
|
1973
|
+
}
|
|
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);
|
|
1982
|
+
}
|
|
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);
|
|
1937
1996
|
}
|
|
1938
|
-
|
|
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());
|
|
1939
2024
|
if (!credential.ok) {
|
|
1940
|
-
if (
|
|
1941
|
-
|
|
1942
|
-
data.auth.hint = credential.error.hint;
|
|
1943
|
-
return writeSuccess(command, doctorDataWithNextCommand(data), mode);
|
|
2025
|
+
if (!mode.json) return writeFailure(command, credential.error, mode, 1);
|
|
2026
|
+
return handleCredentialFailure(command, credential, parsed.options, mode, () => runArtifactsGet(parsed, mode, true), isRetry);
|
|
1944
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);
|
|
2031
|
+
}
|
|
2032
|
+
async function readArtifact(parsed, command) {
|
|
2033
|
+
const target = parseArtifactReadTarget(parsed, command);
|
|
2034
|
+
if (target.error) return { error: target.error };
|
|
2035
|
+
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
2036
|
+
if (!credential.ok) return { error: credential.error };
|
|
2037
|
+
return await fetchArtifact(parsed, target.value, credential);
|
|
2038
|
+
}
|
|
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 };
|
|
2042
|
+
const artifactId = target.artifactId;
|
|
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
|
+
} };
|
|
2052
|
+
}
|
|
2053
|
+
async function fetchArtifact(parsed, target, credential) {
|
|
2054
|
+
const request = await requestConfig(parsed.options);
|
|
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 };
|
|
2074
|
+
}
|
|
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);
|
|
2084
|
+
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
2085
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
1945
2086
|
const request = await requestConfig(parsed.options);
|
|
1946
2087
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1947
|
-
const
|
|
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, {
|
|
1948
2093
|
headers: { Authorization: `Bearer ${credential.token}` },
|
|
1949
2094
|
...request.init
|
|
1950
2095
|
}).catch((error) => ({ networkError: error }));
|
|
1951
|
-
if ("networkError" in response)
|
|
1952
|
-
data.network = {
|
|
1953
|
-
ok: false,
|
|
1954
|
-
code: "network_failed",
|
|
1955
|
-
hint: networkError(response.networkError).hint
|
|
1956
|
-
};
|
|
1957
|
-
return writeSuccess(command, doctorDataWithNextCommand(data), mode);
|
|
1958
|
-
}
|
|
1959
|
-
data.network.ok = true;
|
|
2096
|
+
if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
|
|
1960
2097
|
const body = await readJson(response);
|
|
1961
|
-
if (!response.ok) {
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
}
|
|
1967
|
-
if (!body)
|
|
1968
|
-
|
|
1969
|
-
data.auth.email = body.user?.email ?? null;
|
|
1970
|
-
data.upload.checked = true;
|
|
1971
|
-
data.upload.ok = body.upload?.ok ?? false;
|
|
1972
|
-
if (!data.upload.ok) {
|
|
1973
|
-
data.upload.code = normalizeApiCode(body.upload?.code);
|
|
1974
|
-
data.upload.hint = uploadBlockedHint(data.upload.code);
|
|
1975
|
-
}
|
|
1976
|
-
return writeSuccess(command, doctorDataWithNextCommand(data), mode);
|
|
2098
|
+
if (!response.ok) return writeFailure(command, mapApiError(response.status, body, {
|
|
2099
|
+
authenticated: true,
|
|
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);
|
|
2105
|
+
return writeSuccess(command, body, mode);
|
|
1977
2106
|
}
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
2107
|
+
//#endregion
|
|
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: []
|
|
2136
|
+
}
|
|
2137
|
+
};
|
|
2138
|
+
function skillTarget(tool, scope) {
|
|
2139
|
+
const relative = TOOL_CONFIG[tool].relativePath;
|
|
2140
|
+
const path = scope === "project" ? relative : join(homedir(), relative);
|
|
1984
2141
|
return {
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
default_profile: configString(globalConfig?.default_profile),
|
|
1990
|
-
profile_count: Object.keys(globalConfig?.profiles ?? {}).length
|
|
1991
|
-
},
|
|
1992
|
-
effective: effectiveDiagnostics(project, globalConfig)
|
|
2142
|
+
tool,
|
|
2143
|
+
scope,
|
|
2144
|
+
path,
|
|
2145
|
+
absolutePath: resolve(path)
|
|
1993
2146
|
};
|
|
1994
2147
|
}
|
|
1995
|
-
function
|
|
1996
|
-
|
|
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" };
|
|
1997
2158
|
return {
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
default_profile: configString(raw?.default_profile),
|
|
2001
|
-
default_project_id: configString(raw?.default_project_id),
|
|
2002
|
-
...unsafeKey ? {
|
|
2003
|
-
code: "token_store_unsafe",
|
|
2004
|
-
hint: `Remove "${unsafeKey}" from ${path ?? "the working-directory config"} and run ${CLI_INVOCATION} login instead; the working-directory config must never hold secrets.`
|
|
2005
|
-
} : {}
|
|
2159
|
+
kind: "managed",
|
|
2160
|
+
version: Number(version)
|
|
2006
2161
|
};
|
|
2007
2162
|
}
|
|
2008
|
-
function
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
const
|
|
2013
|
-
const
|
|
2014
|
-
|
|
2015
|
-
const
|
|
2016
|
-
|
|
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;
|
|
2181
|
+
}
|
|
2017
2182
|
return {
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
default_profile_path: defaultProfilePath,
|
|
2021
|
-
default_project_id: defaultProjectId,
|
|
2022
|
-
default_project_id_source: defaultProjectIdSource,
|
|
2023
|
-
default_project_id_path: defaultProjectIdSource === "local" || defaultProjectIdSource === "project" ? project.path : null
|
|
2183
|
+
contents,
|
|
2184
|
+
version
|
|
2024
2185
|
};
|
|
2025
2186
|
}
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
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;
|
|
2036
2197
|
}
|
|
2037
|
-
if (
|
|
2038
|
-
|
|
2039
|
-
return { payload: {
|
|
2040
|
-
form: initialForm,
|
|
2041
|
-
kind: "static_site"
|
|
2042
|
-
} };
|
|
2043
|
-
}
|
|
2044
|
-
if (fileStat.isFile()) {
|
|
2045
|
-
initialForm.append("file", await blobFor(targetPath), basename(targetPath));
|
|
2046
|
-
return { payload: {
|
|
2047
|
-
form: initialForm,
|
|
2048
|
-
kind: artifactKindForFile(targetPath)
|
|
2049
|
-
} };
|
|
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);
|
|
2050
2200
|
}
|
|
2051
|
-
return { error: validationError("
|
|
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
|
+
};
|
|
2052
2209
|
}
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
if (
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
if (existing?.isSymbolicLink()) return { error: validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry.") };
|
|
2059
|
-
if (existing && !force) return { error: cliError({
|
|
2060
|
-
code: "output_exists",
|
|
2061
|
-
message: "Output path already exists.",
|
|
2062
|
-
why: "Download will not write into an existing path unless --force is set.",
|
|
2063
|
-
hint: "Choose a different --output path or retry with --force.",
|
|
2064
|
-
agentRecoverable: true,
|
|
2065
|
-
requiresHuman: false,
|
|
2066
|
-
recovery: { kind: "change_input" }
|
|
2067
|
-
}) };
|
|
2068
|
-
if (existing && !existing.isDirectory()) return { error: validationError("Output path is not a directory.", "Choose a directory path or remove the existing file.") };
|
|
2069
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2070
|
-
const relativeFiles = [];
|
|
2071
|
-
for (const file of manifest.files) {
|
|
2072
|
-
const relativePath = downloadRelativePath(file.path);
|
|
2073
|
-
if (relativePath.error) return { error: relativePath.error };
|
|
2074
|
-
if (seen.has(relativePath.value)) return { error: validationError("Download manifest contains duplicate file paths.", "Retry later. If this repeats, report the artifact ID.") };
|
|
2075
|
-
seen.add(relativePath.value);
|
|
2076
|
-
relativeFiles.push({
|
|
2077
|
-
...file,
|
|
2078
|
-
relativePath: relativePath.value
|
|
2079
|
-
});
|
|
2080
|
-
}
|
|
2081
|
-
const parent = dirname(root);
|
|
2082
|
-
await mkdir(parent, { recursive: true });
|
|
2083
|
-
const tempRoot = await mkdtemp(join(parent, `.${basename(root)}.tmp-`));
|
|
2084
|
-
const files = [];
|
|
2085
|
-
for (const file of relativeFiles) {
|
|
2086
|
-
const targetPath = resolve(tempRoot, file.relativePath);
|
|
2087
|
-
files.push({
|
|
2088
|
-
...file,
|
|
2089
|
-
targetPath
|
|
2090
|
-
});
|
|
2091
|
-
}
|
|
2092
|
-
return { value: {
|
|
2093
|
-
root,
|
|
2094
|
-
tempRoot,
|
|
2095
|
-
replaceExisting: Boolean(existing),
|
|
2096
|
-
files
|
|
2097
|
-
} };
|
|
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.") };
|
|
2098
2215
|
}
|
|
2099
|
-
function
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
return {
|
|
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
|
|
2228
|
+
};
|
|
2104
2229
|
}
|
|
2105
|
-
function
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
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;
|
|
2257
|
+
}
|
|
2258
|
+
if (action === "removed") {
|
|
2259
|
+
await rm(target.absolutePath, { force: true });
|
|
2260
|
+
await cleanupSkillDirs(target);
|
|
2109
2261
|
}
|
|
2110
|
-
return { ok: true };
|
|
2111
2262
|
}
|
|
2112
|
-
function
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
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);
|
|
2273
|
+
}
|
|
2122
2274
|
}
|
|
2123
|
-
function
|
|
2124
|
-
|
|
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
|
+
}
|
|
2282
|
+
return {
|
|
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
|
+
}))
|
|
2290
|
+
};
|
|
2125
2291
|
}
|
|
2126
|
-
async function
|
|
2127
|
-
|
|
2292
|
+
async function runActions(command, planned, dryRun, mode) {
|
|
2293
|
+
const data = await finishActions(command, planned, dryRun, mode);
|
|
2294
|
+
if (data) writeSuccess(command, data, mode);
|
|
2128
2295
|
}
|
|
2129
|
-
function
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
requiresHuman: false,
|
|
2137
|
-
recovery: { kind: "change_input" }
|
|
2138
|
-
});
|
|
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
|
+
}
|
|
2139
2303
|
}
|
|
2140
|
-
async function
|
|
2141
|
-
const
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
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"
|
|
2157
2323
|
});
|
|
2324
|
+
continue;
|
|
2158
2325
|
}
|
|
2326
|
+
planned.push({
|
|
2327
|
+
target,
|
|
2328
|
+
action: state.kind === "missing" ? "installed" : "updated",
|
|
2329
|
+
content: bundled.contents[tool]
|
|
2330
|
+
});
|
|
2159
2331
|
}
|
|
2160
|
-
await
|
|
2161
|
-
results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
|
2162
|
-
return results;
|
|
2332
|
+
await runActions(command, planned, parsed.options.dryRun === true, mode);
|
|
2163
2333
|
}
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
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;
|
|
2170
2340
|
}
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
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;
|
|
2354
|
+
}
|
|
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
|
+
});
|
|
2364
|
+
}
|
|
2365
|
+
return finishActions(command, planned, parsed.options.dryRun === true, mode);
|
|
2187
2366
|
}
|
|
2188
|
-
function
|
|
2189
|
-
|
|
2367
|
+
async function runSkillsEnsure(parsed, mode) {
|
|
2368
|
+
const data = await ensureSkills(parsed, mode);
|
|
2369
|
+
if (data) writeSuccess("skills ensure", data, mode);
|
|
2190
2370
|
}
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
const
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
verification_uri: code.verification_uri,
|
|
2208
|
-
verification_uri_complete: code.verification_uri_complete ?? null,
|
|
2209
|
-
user_code: code.user_code,
|
|
2210
|
-
expires_at: new Date(deadline).toISOString(),
|
|
2211
|
-
interval_seconds: code.interval
|
|
2212
|
-
});
|
|
2213
|
-
else writeText([
|
|
2214
|
-
"Open this URL in a browser to sign in:",
|
|
2215
|
-
code.verification_uri_complete ?? code.verification_uri,
|
|
2216
|
-
"",
|
|
2217
|
-
`Code: ${code.user_code}`,
|
|
2218
|
-
`Waiting for approval for profile "${profile}"...`,
|
|
2219
|
-
""
|
|
2220
|
-
].join("\n"));
|
|
2221
|
-
const token = await pollForToken(options, code, request.init, profile, deadline);
|
|
2222
|
-
if ("error" in token) return {
|
|
2223
|
-
ok: false,
|
|
2224
|
-
error: token.error
|
|
2225
|
-
};
|
|
2226
|
-
const sessionExpiresAt = token.expires_in === void 0 ? null : new Date(Date.now() + token.expires_in * 1e3).toISOString();
|
|
2227
|
-
const stored = await verifyAndStoreProfileToken(profile, token.access_token, options, request.init);
|
|
2228
|
-
if (!stored.ok) return {
|
|
2229
|
-
ok: false,
|
|
2230
|
-
error: stored.error
|
|
2231
|
-
};
|
|
2232
|
-
const effective = await resolveEffectiveDefaultProfile(await resolveProjectConfig());
|
|
2233
|
-
const data = {
|
|
2234
|
-
profile,
|
|
2235
|
-
status: "completed",
|
|
2236
|
-
credential_source: "profile",
|
|
2237
|
-
token_store: stored.data.token_store,
|
|
2238
|
-
user: stored.data.user,
|
|
2239
|
-
workspace: stored.data.workspace,
|
|
2240
|
-
verification_uri: code.verification_uri,
|
|
2241
|
-
verification_uri_complete: code.verification_uri_complete ?? null,
|
|
2242
|
-
user_code: code.user_code,
|
|
2243
|
-
expires_at: sessionExpiresAt,
|
|
2244
|
-
interval_seconds: code.interval
|
|
2245
|
-
};
|
|
2246
|
-
if (effective.profile && effective.profile !== profile) {
|
|
2247
|
-
data.effective_default_profile = effective.profile;
|
|
2248
|
-
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.`;
|
|
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
|
+
});
|
|
2249
2387
|
}
|
|
2250
|
-
return {
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
};
|
|
2254
|
-
}
|
|
2255
|
-
async function runLogin(parsed, mode) {
|
|
2256
|
-
const command = "login";
|
|
2257
|
-
const profile = nonEmpty(parsed.options.profile) ?? "default";
|
|
2258
|
-
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);
|
|
2259
|
-
const result = await performDeviceLogin(profile, parsed.options, mode);
|
|
2260
|
-
if (!result.ok) return writeFailure(command, result.error, mode, 1);
|
|
2261
|
-
return writeSuccess(command, result.data, mode);
|
|
2262
|
-
}
|
|
2263
|
-
async function requestDeviceCode(options, init) {
|
|
2264
|
-
const response = await fetch(apiUrl("/api/auth/device/code", baseUrlOf(options)), {
|
|
2265
|
-
method: "POST",
|
|
2266
|
-
headers: { "content-type": "application/json" },
|
|
2267
|
-
body: JSON.stringify({ client_id: DEVICE_CLIENT_ID }),
|
|
2268
|
-
...init
|
|
2269
|
-
}).catch((error) => ({ networkError: error }));
|
|
2270
|
-
if ("networkError" in response) return { error: networkError(response.networkError) };
|
|
2271
|
-
const body = await readJson(response);
|
|
2272
|
-
if (!response.ok) return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
|
|
2273
|
-
if (!isDeviceCodeResponse(body)) return { error: validationError("Device login response was invalid.", "Retry login. If this repeats, report the response shape.", "service_error") };
|
|
2274
|
-
return body;
|
|
2275
|
-
}
|
|
2276
|
-
async function exchangeDeviceTokenOnce(options, deviceCode, init) {
|
|
2277
|
-
const response = await fetch(apiUrl("/api/auth/device/token", baseUrlOf(options)), {
|
|
2278
|
-
method: "POST",
|
|
2279
|
-
headers: { "content-type": "application/json" },
|
|
2280
|
-
body: JSON.stringify({
|
|
2281
|
-
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
2282
|
-
device_code: deviceCode,
|
|
2283
|
-
client_id: DEVICE_CLIENT_ID
|
|
2284
|
-
}),
|
|
2285
|
-
...init
|
|
2286
|
-
}).catch((error) => ({ networkError: error }));
|
|
2287
|
-
if ("networkError" in response) return { error: networkError(response.networkError) };
|
|
2288
|
-
const body = await readJson(response);
|
|
2289
|
-
if (response.ok && isDeviceTokenResponse(body)) return {
|
|
2290
|
-
status: "success",
|
|
2291
|
-
token: body
|
|
2292
|
-
};
|
|
2293
|
-
const authError = deviceTokenError(body);
|
|
2294
|
-
if (authError === "authorization_pending") return { status: "pending" };
|
|
2295
|
-
if (authError === "slow_down") return { status: "slow_down" };
|
|
2296
|
-
if (authError === "access_denied") return { status: "denied" };
|
|
2297
|
-
if (authError === "expired_token") return { status: "expired" };
|
|
2298
|
-
if (response.status === 429 || response.status >= 500) return { status: "retry_later" };
|
|
2299
|
-
return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
|
|
2388
|
+
return writeSuccess("skills list", {
|
|
2389
|
+
bundled_version: bundled.version,
|
|
2390
|
+
targets
|
|
2391
|
+
}, mode);
|
|
2300
2392
|
}
|
|
2301
|
-
function
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
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"
|
|
2420
|
+
});
|
|
2421
|
+
}
|
|
2422
|
+
await runActions(command, planned, parsed.options.dryRun === true, mode);
|
|
2313
2423
|
}
|
|
2314
|
-
async function
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
}),
|
|
2327
|
-
...init
|
|
2328
|
-
}).catch((error) => ({ networkError: error }));
|
|
2329
|
-
if ("networkError" in response) {
|
|
2330
|
-
networkFailures += 1;
|
|
2331
|
-
if (networkFailures >= 5) return { error: networkError(response.networkError) };
|
|
2332
|
-
continue;
|
|
2333
|
-
}
|
|
2334
|
-
networkFailures = 0;
|
|
2335
|
-
const body = await readJson(response);
|
|
2336
|
-
if (response.ok && isDeviceTokenResponse(body)) return body;
|
|
2337
|
-
const authError = deviceTokenError(body);
|
|
2338
|
-
if (authError === "authorization_pending") continue;
|
|
2339
|
-
if (authError === "slow_down") {
|
|
2340
|
-
intervalMs += 5e3;
|
|
2341
|
-
continue;
|
|
2342
|
-
}
|
|
2343
|
-
if (authError === "access_denied") return { error: authDeniedError(profile) };
|
|
2344
|
-
if (authError === "expired_token") return { error: authExpiredError(profile) };
|
|
2345
|
-
return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
|
|
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
|
|
2435
|
+
});
|
|
2346
2436
|
}
|
|
2347
|
-
|
|
2437
|
+
await runActions(command, planned, parsed.options.dryRun === true, mode);
|
|
2348
2438
|
}
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
if (expectedEmail && whoami.email !== expectedEmail) return {
|
|
2360
|
-
ok: false,
|
|
2361
|
-
error: authAccountMismatchError(profile, expectedEmail, whoami.email)
|
|
2362
|
-
};
|
|
2363
|
-
const saved = await saveProfileToken(profile, token, options);
|
|
2364
|
-
if (!saved.ok) return {
|
|
2365
|
-
ok: false,
|
|
2366
|
-
error: tokenStoreUnavailableError(profile)
|
|
2367
|
-
};
|
|
2368
|
-
await writeProfileConfig(profile, options, saved.store, whoami);
|
|
2369
|
-
return {
|
|
2370
|
-
ok: true,
|
|
2371
|
-
data: {
|
|
2372
|
-
profile,
|
|
2373
|
-
token_store: saved.store,
|
|
2374
|
-
user: { email: whoami.email },
|
|
2375
|
-
workspace: {
|
|
2376
|
-
id: whoami.workspace_id,
|
|
2377
|
-
hosted_domain: whoami.hosted_domain
|
|
2378
|
-
}
|
|
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"
|
|
2379
2449
|
}
|
|
2380
|
-
};
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
const
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
[profile]: {
|
|
2392
|
-
...currentProfile,
|
|
2393
|
-
base_url: baseUrlOf(options),
|
|
2394
|
-
email: whoami.email ?? currentProfile?.email ?? null,
|
|
2395
|
-
workspace_id: whoami.workspace_id,
|
|
2396
|
-
token_store: tokenStore,
|
|
2397
|
-
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
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)
|
|
2398
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
|
|
2399
2470
|
}
|
|
2400
|
-
});
|
|
2401
|
-
}
|
|
2402
|
-
function isDeviceCodeResponse(body) {
|
|
2403
|
-
if (!isRecord(body)) return false;
|
|
2404
|
-
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";
|
|
2405
|
-
}
|
|
2406
|
-
function isDeviceTokenResponse(body) {
|
|
2407
|
-
if (!isRecord(body)) return false;
|
|
2408
|
-
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);
|
|
2409
|
-
}
|
|
2410
|
-
function deviceTokenError(body) {
|
|
2411
|
-
if (!isRecord(body)) return null;
|
|
2412
|
-
return typeof body.error === "string" ? body.error : null;
|
|
2413
|
-
}
|
|
2414
|
-
function whoamiProfile(body) {
|
|
2415
|
-
const record = isRecord(body) ? body : null;
|
|
2416
|
-
const user = record && isRecord(record.user) ? record.user : null;
|
|
2417
|
-
const workspace = record && isRecord(record.workspace) ? record.workspace : null;
|
|
2418
|
-
return {
|
|
2419
|
-
email: typeof user?.email === "string" ? user.email : null,
|
|
2420
|
-
workspace_id: typeof workspace?.id === "string" ? workspace.id : null,
|
|
2421
|
-
hosted_domain: typeof workspace?.hosted_domain === "string" ? workspace.hosted_domain : null
|
|
2422
|
-
};
|
|
2471
|
+
}, mode);
|
|
2423
2472
|
}
|
|
2424
2473
|
//#endregion
|
|
2425
|
-
//#region src/command-runners/
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
const expiresAt = Date.parse(pending.expires_at);
|
|
2435
|
-
return Number.isNaN(expiresAt) || expiresAt <= Date.now();
|
|
2436
|
-
}
|
|
2437
|
-
async function canAttemptProfileTokenSave(profile, options) {
|
|
2438
|
-
const stored = await readProfileToken(profile, options);
|
|
2439
|
-
return stored.ok || stored.reason !== "unavailable";
|
|
2440
|
-
}
|
|
2441
|
-
async function handleCredentialFailure(command, credential, options, mode, rerun, isRetry = false, deps = {}) {
|
|
2442
|
-
if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
|
|
2443
|
-
if (mode.json && JSON_PENDING_AUTH_COMMANDS.has(command) && !isRetry) return handleJsonPendingAuth(command, credential, options, mode, rerun);
|
|
2444
|
-
if (!isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
|
|
2445
|
-
const performLogin = deps.performLogin ?? performDeviceLogin;
|
|
2446
|
-
const profile = profileForAutoLogin(credential);
|
|
2447
|
-
writeText("Not signed in. Starting device login to continue...\n");
|
|
2448
|
-
const loginResult = await performLogin(profile, options, mode);
|
|
2449
|
-
if (!loginResult.ok) return writeFailure(command, loginResult.error, mode, 1);
|
|
2450
|
-
return rerun();
|
|
2451
|
-
}
|
|
2452
|
-
async function handleJsonPendingAuth(command, credential, options, mode, rerun) {
|
|
2453
|
-
const profile = profileForAutoLogin(credential);
|
|
2454
|
-
const baseUrl = baseUrlOf(options);
|
|
2455
|
-
const request = await requestConfig(options);
|
|
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);
|
|
2456
2483
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
if (exchange.status === "denied") {
|
|
2472
|
-
await clearPendingDeviceAuth(baseUrl, profile);
|
|
2473
|
-
return writeFailure(command, authDeniedError(profile), mode, 1);
|
|
2474
|
-
}
|
|
2475
|
-
if (exchange.status === "expired") await clearPendingDeviceAuth(baseUrl, profile);
|
|
2476
|
-
else if (exchange.status === "retry_later") return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing), mode, 1);
|
|
2477
|
-
else return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing), mode, 1);
|
|
2478
|
-
} else if (existing) await clearPendingDeviceAuth(baseUrl, profile);
|
|
2479
|
-
const code = await requestDeviceCode(options, request.init);
|
|
2480
|
-
if ("error" in code) return writeFailure(command, credential.error, mode, 1);
|
|
2481
|
-
const pending = pendingDeviceAuthFromCode(profile, options, code);
|
|
2482
|
-
if (!await writePendingDeviceAuth(pending)) return writeFailure(command, credential.error, mode, 1);
|
|
2483
|
-
return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, pending), 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");
|
|
2484
2498
|
}
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
const command = "download";
|
|
2489
|
-
const target = parseArtifactTarget(parsed.positionals[0], "download", "Pass an artifact ID or share URL to download.");
|
|
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.");
|
|
2490
2502
|
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
2491
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);
|
|
2492
2510
|
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
2493
|
-
if (!credential.ok) return
|
|
2511
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
2494
2512
|
const request = await requestConfig(parsed.options);
|
|
2495
2513
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2496
|
-
const
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
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);
|
|
2535
|
+
}
|
|
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);
|
|
2558
|
+
}
|
|
2559
|
+
async function runCommentsResolve(parsed, mode) {
|
|
2560
|
+
return await runCommentsStatus(parsed, mode, "comments resolve", "resolve");
|
|
2561
|
+
}
|
|
2562
|
+
async function runCommentsReopen(parsed, mode) {
|
|
2563
|
+
return await runCommentsStatus(parsed, mode, "comments reopen", "reopen");
|
|
2564
|
+
}
|
|
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();
|
|
2549
2578
|
}
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
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);
|
|
2591
|
+
}
|
|
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
|
|
2562
2609
|
}, mode);
|
|
2563
2610
|
}
|
|
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
|
|
2626
|
+
});
|
|
2627
|
+
if (result.error) {
|
|
2628
|
+
writeFailure(command, result.error, mode, 1);
|
|
2629
|
+
return null;
|
|
2630
|
+
}
|
|
2631
|
+
if (result.body === null) {
|
|
2632
|
+
writeFailure(command, serviceError("Comment was changed but the response was empty."), mode, 1);
|
|
2633
|
+
return null;
|
|
2634
|
+
}
|
|
2635
|
+
return result.body;
|
|
2636
|
+
}
|
|
2637
|
+
function requiredOption(value, message, hint) {
|
|
2638
|
+
if (!value || !value.trim()) return { error: validationError(message, hint) };
|
|
2639
|
+
return { value: value.trim() };
|
|
2640
|
+
}
|
|
2564
2641
|
//#endregion
|
|
2565
|
-
//#region src/command-runners/
|
|
2566
|
-
async function
|
|
2567
|
-
const command = "
|
|
2568
|
-
const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to
|
|
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.");
|
|
2569
2646
|
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
2570
|
-
const
|
|
2571
|
-
if (payload.error) return writeFailure(command, payload.error, mode, 1);
|
|
2647
|
+
const artifactId = target.artifactId;
|
|
2572
2648
|
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
2573
2649
|
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
2574
2650
|
const request = await requestConfig(parsed.options);
|
|
2575
2651
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2576
|
-
const result = await
|
|
2652
|
+
const result = await apiDelete(`/api/cli/artifacts/${encodeURIComponent(artifactId)}`, credential.token, parsed.options, request.init, {
|
|
2653
|
+
authenticated: true,
|
|
2577
2654
|
artifactTarget: true,
|
|
2578
|
-
|
|
2655
|
+
credentialSource: credential.source,
|
|
2656
|
+
profile: credential.profile
|
|
2579
2657
|
});
|
|
2580
2658
|
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
2581
|
-
const
|
|
2582
|
-
if (!
|
|
2583
|
-
writeSuccess(command,
|
|
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);
|
|
2584
2662
|
}
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
if (
|
|
2595
|
-
|
|
2596
|
-
hasChange = true;
|
|
2597
|
-
}
|
|
2598
|
-
const addEmails = normalizedEmailOptions$1(parsed.options.grantEmail);
|
|
2599
|
-
if (addEmails.error) return { error: addEmails.error };
|
|
2600
|
-
if (parsed.options.grantEmail !== void 0) {
|
|
2601
|
-
body.add_emails = addEmails.values;
|
|
2602
|
-
hasChange = true;
|
|
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;
|
|
2603
2674
|
}
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
body.remove_emails = removeEmails.values;
|
|
2608
|
-
hasChange = true;
|
|
2675
|
+
if (data.config.project.code === "token_store_unsafe") {
|
|
2676
|
+
if (bearerTokenBlocksLogin(data)) return null;
|
|
2677
|
+
return LOGIN_COMMAND;
|
|
2609
2678
|
}
|
|
2610
|
-
if (
|
|
2611
|
-
if (
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
const projectId = parsed.options.projectId.trim();
|
|
2616
|
-
if (!projectId) return { error: validationError("--project-id must not be blank.", "Retry with an active project id from projects list, or use --home.", "invalid_destination") };
|
|
2617
|
-
body.destination = { project_id: projectId };
|
|
2618
|
-
hasChange = true;
|
|
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;
|
|
2619
2684
|
}
|
|
2620
|
-
|
|
2621
|
-
return { body };
|
|
2685
|
+
return null;
|
|
2622
2686
|
}
|
|
2623
|
-
function
|
|
2624
|
-
const
|
|
2625
|
-
|
|
2626
|
-
return { values };
|
|
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);
|
|
2627
2690
|
}
|
|
2628
|
-
function
|
|
2629
|
-
|
|
2630
|
-
const
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
if (!isRecord(artifact) || !isRecord(destination) || !isRecord(share)) return null;
|
|
2634
|
-
if (typeof artifact.id !== "string" || typeof body.title !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string") return null;
|
|
2635
|
-
const base = {
|
|
2636
|
-
artifact: {
|
|
2637
|
-
id: artifact.id,
|
|
2638
|
-
url: typeof artifact.url === "string" ? artifact.url : null
|
|
2639
|
-
},
|
|
2640
|
-
title: body.title,
|
|
2641
|
-
share: { visibility: share.visibility }
|
|
2691
|
+
function doctorDataWithNextCommand(data) {
|
|
2692
|
+
const nextCommand = resolveDoctorNextCommand(data);
|
|
2693
|
+
const next = {
|
|
2694
|
+
...data,
|
|
2695
|
+
next_command: nextCommand
|
|
2642
2696
|
};
|
|
2643
|
-
if (
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
...base,
|
|
2647
|
-
destination: {
|
|
2648
|
-
type: "project",
|
|
2649
|
-
project_id: destination.project_id
|
|
2650
|
-
}
|
|
2651
|
-
};
|
|
2652
|
-
}
|
|
2653
|
-
if (destination.type === "home" && destination.project_id === null) return {
|
|
2654
|
-
...base,
|
|
2655
|
-
destination: {
|
|
2656
|
-
type: "home",
|
|
2657
|
-
project_id: null
|
|
2658
|
-
}
|
|
2697
|
+
if (next.auth.code === "auth_required") next.auth = {
|
|
2698
|
+
...next.auth,
|
|
2699
|
+
recovery: authRecovery(next, nextCommand)
|
|
2659
2700
|
};
|
|
2660
|
-
return
|
|
2701
|
+
return next;
|
|
2661
2702
|
}
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
const
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
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);
|
|
2708
|
+
const data = {
|
|
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
|
+
}
|
|
2732
|
+
};
|
|
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);
|
|
2689
2738
|
}
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
}
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
workTree: current
|
|
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
|
|
2744
|
+
}).catch((error) => ({ networkError: error }));
|
|
2745
|
+
if ("networkError" in response) {
|
|
2746
|
+
data.network = {
|
|
2747
|
+
ok: false,
|
|
2748
|
+
code: "network_failed",
|
|
2749
|
+
hint: networkError(response.networkError).hint
|
|
2702
2750
|
};
|
|
2703
|
-
|
|
2704
|
-
current = dirname(current);
|
|
2751
|
+
return writeSuccess(command, doctorDataWithNextCommand(data), mode);
|
|
2705
2752
|
}
|
|
2753
|
+
data.network.ok = true;
|
|
2754
|
+
const body = await readJson(response);
|
|
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);
|
|
2706
2776
|
}
|
|
2707
|
-
async function
|
|
2708
|
-
const
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
const
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
}
|
|
2720
|
-
|
|
2721
|
-
|
|
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)
|
|
2792
|
+
};
|
|
2722
2793
|
}
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
|
|
2735
|
-
}
|
|
2736
|
-
const next = {
|
|
2737
|
-
...await readRawLocalProjectConfig() ?? {},
|
|
2738
|
-
...profile ? { default_profile: profile } : {},
|
|
2739
|
-
...projectId ? { default_project_id: projectId } : {}
|
|
2794
|
+
function fileDiagnostics(raw, path) {
|
|
2795
|
+
const unsafeKey = Object.keys(raw ?? {}).find((key) => key.toLowerCase().includes("token"));
|
|
2796
|
+
return {
|
|
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
|
+
} : {}
|
|
2740
2805
|
};
|
|
2741
|
-
const path = projectConfigLocalPath();
|
|
2742
|
-
await mkdir(dirname(path), { recursive: true });
|
|
2743
|
-
await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
|
|
2744
|
-
const gitExclude = await ensureGitExclude(process.cwd());
|
|
2745
|
-
const data = initData(true, next, resolved);
|
|
2746
|
-
delete data.read_path;
|
|
2747
|
-
if (gitExclude.warning) data.git_exclude_warning = gitExclude.warning;
|
|
2748
|
-
if (gitExclude.applied) data.git_exclude_applied = true;
|
|
2749
|
-
return writeSuccess(command, data, mode);
|
|
2750
2806
|
}
|
|
2751
|
-
function
|
|
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";
|
|
2752
2816
|
return {
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
...resolved.path ? { read_path: resolved.path } : {}
|
|
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
|
|
2760
2823
|
};
|
|
2761
2824
|
}
|
|
2762
2825
|
//#endregion
|
|
2763
|
-
//#region src/
|
|
2764
|
-
async function
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
if (
|
|
2781
|
-
|
|
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;
|
|
2835
|
+
}
|
|
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.") };
|
|
2782
2851
|
}
|
|
2783
|
-
function
|
|
2784
|
-
if (
|
|
2785
|
-
|
|
2786
|
-
const
|
|
2787
|
-
const
|
|
2788
|
-
if (
|
|
2789
|
-
if (
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
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
|
+
} };
|
|
2897
|
+
}
|
|
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("/") };
|
|
2903
|
+
}
|
|
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") };
|
|
2806
2908
|
}
|
|
2807
|
-
|
|
2808
|
-
artifact: {
|
|
2809
|
-
id: artifact.id,
|
|
2810
|
-
url: typeof artifact.url === "string" ? artifact.url : null
|
|
2811
|
-
},
|
|
2812
|
-
destination: {
|
|
2813
|
-
type: "home",
|
|
2814
|
-
project_id: null
|
|
2815
|
-
},
|
|
2816
|
-
share: {
|
|
2817
|
-
visibility: share.visibility,
|
|
2818
|
-
project_audience_may_change: share.project_audience_may_change
|
|
2819
|
-
}
|
|
2820
|
-
};
|
|
2821
|
-
return null;
|
|
2909
|
+
return { ok: true };
|
|
2822
2910
|
}
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
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
|
+
});
|
|
2830
2921
|
}
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
|
|
2834
|
-
const config = await readGlobalConfig() ?? {};
|
|
2835
|
-
const defaultProfile = nonEmpty(config.default_profile) ?? null;
|
|
2836
|
-
const profiles = await Promise.all(Object.entries(config.profiles ?? {}).map(async ([name, rawEntry]) => {
|
|
2837
|
-
const entry = isRecord(rawEntry) ? rawEntry : {};
|
|
2838
|
-
const stored = await readProfileToken(name, {
|
|
2839
|
-
...parsed.options,
|
|
2840
|
-
baseUrl: nonEmpty(entry.base_url) ?? "https://artifactshare.com"
|
|
2841
|
-
});
|
|
2842
|
-
return {
|
|
2843
|
-
name,
|
|
2844
|
-
base_url: nonEmpty(entry.base_url) ?? null,
|
|
2845
|
-
email: nonEmpty(entry.email) ?? null,
|
|
2846
|
-
workspace_id: nonEmpty(entry.workspace_id) ?? null,
|
|
2847
|
-
token_store: entry.token_store ?? null,
|
|
2848
|
-
updated_at: nonEmpty(entry.updated_at) ?? null,
|
|
2849
|
-
is_default: name === defaultProfile,
|
|
2850
|
-
token_present: stored.ok
|
|
2851
|
-
};
|
|
2852
|
-
}));
|
|
2853
|
-
writeSuccess(command, {
|
|
2854
|
-
default_profile: defaultProfile,
|
|
2855
|
-
profiles
|
|
2856
|
-
}, mode);
|
|
2857
|
-
if (!mode.json && profiles.length === 0) writeText(`No profiles yet. Run ${CLI_INVOCATION} login --profile default to create one.\n`);
|
|
2922
|
+
function backupPathFor(root) {
|
|
2923
|
+
return join(dirname(root), `.${basename(root)}.old-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
|
|
2858
2924
|
}
|
|
2859
|
-
async function
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2925
|
+
async function pathExists(path) {
|
|
2926
|
+
return Boolean(await lstat(path).catch(() => null));
|
|
2927
|
+
}
|
|
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" }
|
|
2870
2937
|
});
|
|
2871
|
-
return writeSuccess(command, {
|
|
2872
|
-
default_profile: name,
|
|
2873
|
-
previous_default: previous
|
|
2874
|
-
}, mode);
|
|
2875
2938
|
}
|
|
2876
|
-
async function
|
|
2877
|
-
const
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
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
|
+
}
|
|
2888
2958
|
}
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
const stored = await verifyAndStoreProfileToken(profile, token, parsed.options, request.init);
|
|
2893
|
-
if (!stored.ok) return writeFailure(command, stored.error, mode, 1);
|
|
2894
|
-
return writeSuccess(command, {
|
|
2895
|
-
profile,
|
|
2896
|
-
token_store: stored.data.token_store,
|
|
2897
|
-
user: stored.data.user,
|
|
2898
|
-
workspace: stored.data.workspace,
|
|
2899
|
-
base_url: baseUrlOf(parsed.options)
|
|
2900
|
-
}, mode);
|
|
2959
|
+
await visit(root);
|
|
2960
|
+
results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
|
2961
|
+
return results;
|
|
2901
2962
|
}
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
base_visibility: configString(project.base_visibility),
|
|
2915
|
-
file_count: typeof project.file_count === "number" ? project.file_count : null,
|
|
2916
|
-
updated_at: configString(project.updated_at)
|
|
2917
|
-
}];
|
|
2918
|
-
}) };
|
|
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) });
|
|
2919
2975
|
}
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
if (
|
|
2925
|
-
|
|
2926
|
-
if (
|
|
2927
|
-
|
|
2928
|
-
if (
|
|
2929
|
-
|
|
2930
|
-
const projects = result.projects.map((project) => ({
|
|
2931
|
-
...project,
|
|
2932
|
-
is_default: project.id === defaultProjectId
|
|
2933
|
-
}));
|
|
2934
|
-
writeSuccess(command, {
|
|
2935
|
-
default_project_id: defaultProjectId,
|
|
2936
|
-
projects
|
|
2937
|
-
}, mode);
|
|
2938
|
-
if (!mode.json && projects.length === 0) writeText("No projects yet. Create one on the web, then publish with --project-id.\n");
|
|
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";
|
|
2939
2986
|
}
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
const
|
|
2947
|
-
const
|
|
2948
|
-
if (
|
|
2987
|
+
function artifactKindForFile(path) {
|
|
2988
|
+
return path.endsWith(".md") ? "markdown_page" : "html_page";
|
|
2989
|
+
}
|
|
2990
|
+
//#endregion
|
|
2991
|
+
//#region src/command-runners/download.ts
|
|
2992
|
+
async function runDownload(parsed, mode, isRetry = false) {
|
|
2993
|
+
const command = "download";
|
|
2994
|
+
const target = parseArtifactTarget(parsed.positionals[0], "download", "Pass an artifact ID or share URL to download.");
|
|
2995
|
+
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
2996
|
+
const artifactId = target.artifactId;
|
|
2997
|
+
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
2998
|
+
if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
|
|
2949
2999
|
const request = await requestConfig(parsed.options);
|
|
2950
3000
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2951
|
-
const
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
const
|
|
2959
|
-
if (!
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
2964
|
-
|
|
2965
|
-
|
|
3001
|
+
const baseUrl = baseUrlOf(parsed.options);
|
|
3002
|
+
const manifestUrl = apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/download`, baseUrl);
|
|
3003
|
+
const manifestResponse = await fetch(manifestUrl, {
|
|
3004
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
3005
|
+
...request.init
|
|
3006
|
+
}).catch((error) => ({ networkError: error }));
|
|
3007
|
+
if ("networkError" in manifestResponse) return writeFailure(command, networkError(manifestResponse.networkError), mode, 1);
|
|
3008
|
+
const body = await readJson(manifestResponse);
|
|
3009
|
+
if (!manifestResponse.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(manifestResponse.status, body, {
|
|
3010
|
+
authenticated: true,
|
|
3011
|
+
artifactTarget: true,
|
|
3012
|
+
baseUrl,
|
|
3013
|
+
credentialSource: credential.source,
|
|
3014
|
+
profile: credential.profile
|
|
3015
|
+
}), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
|
|
3016
|
+
if (!downloadManifestFields(body)) return writeFailure(command, serviceError("Download manifest succeeded but the response did not include file metadata."), mode, 1);
|
|
3017
|
+
const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force));
|
|
3018
|
+
if (plan.error) return writeFailure(command, plan.error, mode, 1);
|
|
3019
|
+
let completed = false;
|
|
3020
|
+
let backupRoot = null;
|
|
3021
|
+
try {
|
|
3022
|
+
for (const file of plan.value.files) {
|
|
3023
|
+
const fileUrl = downloadFileUrl(baseUrl, artifactId, file.path);
|
|
3024
|
+
const fileResponse = await fetch(fileUrl, {
|
|
3025
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
3026
|
+
...request.init
|
|
3027
|
+
}).catch((error) => ({ networkError: error }));
|
|
3028
|
+
if ("networkError" in fileResponse) return writeFailure(command, networkError(fileResponse.networkError), mode, 1);
|
|
3029
|
+
if (!fileResponse.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(fileResponse.status, await readJson(fileResponse), {
|
|
3030
|
+
authenticated: true,
|
|
3031
|
+
artifactTarget: true,
|
|
3032
|
+
baseUrl,
|
|
3033
|
+
credentialSource: credential.source,
|
|
3034
|
+
profile: credential.profile
|
|
3035
|
+
}), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
|
|
3036
|
+
const bytes = Buffer.from(await fileResponse.arrayBuffer());
|
|
3037
|
+
const verified = verifyDownloadedBytes(file, bytes);
|
|
3038
|
+
if (verified.error) return writeFailure(command, verified.error, mode, 1);
|
|
3039
|
+
await mkdir(dirname(file.targetPath), { recursive: true });
|
|
3040
|
+
await writeFile(file.targetPath, bytes);
|
|
3041
|
+
}
|
|
3042
|
+
if (plan.value.replaceExisting) {
|
|
3043
|
+
backupRoot = backupPathFor(plan.value.root);
|
|
3044
|
+
await rename(plan.value.root, backupRoot);
|
|
3045
|
+
}
|
|
3046
|
+
await rename(plan.value.tempRoot, plan.value.root);
|
|
3047
|
+
completed = true;
|
|
3048
|
+
if (backupRoot) await rm(backupRoot, {
|
|
3049
|
+
recursive: true,
|
|
3050
|
+
force: true
|
|
3051
|
+
}).catch(() => {});
|
|
3052
|
+
} catch (error) {
|
|
3053
|
+
if (backupRoot && !await pathExists(plan.value.root) && await pathExists(backupRoot)) await rename(backupRoot, plan.value.root).catch(() => {});
|
|
3054
|
+
return writeFailure(command, downloadFileSystemError(error), mode, 1);
|
|
3055
|
+
} finally {
|
|
3056
|
+
if (!completed) await rm(plan.value.tempRoot, {
|
|
3057
|
+
recursive: true,
|
|
3058
|
+
force: true
|
|
3059
|
+
}).catch(() => {});
|
|
3060
|
+
}
|
|
3061
|
+
return writeSuccess(command, {
|
|
3062
|
+
artifact: {
|
|
3063
|
+
id: body.id,
|
|
3064
|
+
url: body.share_url,
|
|
3065
|
+
kind: body.artifact_kind
|
|
2966
3066
|
},
|
|
2967
|
-
|
|
3067
|
+
version: { id: body.version_id },
|
|
3068
|
+
destination: { path: plan.value.root },
|
|
3069
|
+
files: {
|
|
3070
|
+
count: plan.value.files.length,
|
|
3071
|
+
total_size_bytes: body.total_size_bytes
|
|
3072
|
+
}
|
|
2968
3073
|
}, mode);
|
|
2969
3074
|
}
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
const
|
|
3075
|
+
//#endregion
|
|
3076
|
+
//#region src/command-runners/edit.ts
|
|
3077
|
+
async function runEdit(parsed, mode) {
|
|
3078
|
+
const command = "edit";
|
|
3079
|
+
const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to edit.");
|
|
3080
|
+
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
3081
|
+
const payload = buildEditPayload(parsed);
|
|
2975
3082
|
if (payload.error) return writeFailure(command, payload.error, mode, 1);
|
|
2976
|
-
const
|
|
2977
|
-
const credential = await resolveCredential(parsed.options, projectConfig);
|
|
3083
|
+
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
2978
3084
|
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
2979
3085
|
const request = await requestConfig(parsed.options);
|
|
2980
3086
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2981
|
-
const result = await apiPost(`/api/cli/
|
|
3087
|
+
const result = await apiPost(`/api/cli/shareables/${encodeURIComponent(target.artifactId)}/edit`, credential.token, payload.body, parsed.options, request.init, {
|
|
3088
|
+
artifactTarget: true,
|
|
3089
|
+
editSettings: true,
|
|
3090
|
+
credentialSource: credential.source,
|
|
3091
|
+
profile: credential.profile
|
|
3092
|
+
});
|
|
2982
3093
|
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
2983
|
-
const data =
|
|
2984
|
-
if (!data) return writeFailure(command, serviceError("
|
|
3094
|
+
const data = parseEditData(result.body);
|
|
3095
|
+
if (!data) return writeFailure(command, serviceError("Edit succeeded but the response did not include edit data."), mode, 1);
|
|
2985
3096
|
writeSuccess(command, data, mode);
|
|
2986
3097
|
}
|
|
2987
|
-
function
|
|
3098
|
+
function buildEditPayload(parsed) {
|
|
2988
3099
|
const body = {};
|
|
2989
3100
|
let hasChange = false;
|
|
2990
|
-
if (parsed.options.
|
|
2991
|
-
|
|
2992
|
-
if (!name) return { error: validationError("--name must not be blank.", "Retry with a non-empty project name.") };
|
|
2993
|
-
body.name = name;
|
|
2994
|
-
hasChange = true;
|
|
2995
|
-
}
|
|
2996
|
-
if (parsed.options.description !== void 0) {
|
|
2997
|
-
body.description = parsed.options.description;
|
|
3101
|
+
if (parsed.options.title !== void 0) {
|
|
3102
|
+
body.title = parsed.options.title;
|
|
2998
3103
|
hasChange = true;
|
|
2999
3104
|
}
|
|
3000
3105
|
if (parsed.options.visibility !== void 0) {
|
|
3001
3106
|
const visibility = parsed.options.visibility.trim();
|
|
3002
|
-
if (visibility !== "
|
|
3003
|
-
body.
|
|
3107
|
+
if (visibility !== "private" && visibility !== "workspace") return { error: validationError("--visibility must be private or workspace.", "Retry with --visibility private or --visibility workspace.") };
|
|
3108
|
+
body.visibility = visibility;
|
|
3004
3109
|
hasChange = true;
|
|
3005
3110
|
}
|
|
3006
|
-
const addEmails = normalizedEmailOptions(parsed.options.
|
|
3111
|
+
const addEmails = normalizedEmailOptions$1(parsed.options.grantEmail);
|
|
3007
3112
|
if (addEmails.error) return { error: addEmails.error };
|
|
3008
|
-
if (parsed.options.
|
|
3113
|
+
if (parsed.options.grantEmail !== void 0) {
|
|
3009
3114
|
body.add_emails = addEmails.values;
|
|
3010
3115
|
hasChange = true;
|
|
3011
3116
|
}
|
|
3012
|
-
const removeEmails = normalizedEmailOptions(parsed.options.
|
|
3117
|
+
const removeEmails = normalizedEmailOptions$1(parsed.options.revokeEmail);
|
|
3013
3118
|
if (removeEmails.error) return { error: removeEmails.error };
|
|
3014
|
-
if (parsed.options.
|
|
3119
|
+
if (parsed.options.revokeEmail !== void 0) {
|
|
3015
3120
|
body.remove_emails = removeEmails.values;
|
|
3016
3121
|
hasChange = true;
|
|
3017
3122
|
}
|
|
3018
|
-
if (parsed.options
|
|
3019
|
-
if (parsed.options.
|
|
3020
|
-
body.
|
|
3123
|
+
if (hasProjectIdHomeConflict(parsed.options)) return { error: validationError("Edit destination is conflicting.", "Choose either --project-id <id> or --home.", "destination_conflict") };
|
|
3124
|
+
if (parsed.options.home) {
|
|
3125
|
+
body.destination = "home";
|
|
3021
3126
|
hasChange = true;
|
|
3022
|
-
}
|
|
3023
|
-
|
|
3024
|
-
|
|
3127
|
+
} else if (parsed.options.projectId !== void 0) {
|
|
3128
|
+
const projectId = parsed.options.projectId.trim();
|
|
3129
|
+
if (!projectId) return { error: validationError("--project-id must not be blank.", "Retry with an active project id from projects list, or use --home.", "invalid_destination") };
|
|
3130
|
+
body.destination = { project_id: projectId };
|
|
3025
3131
|
hasChange = true;
|
|
3026
3132
|
}
|
|
3027
|
-
if (!hasChange) return { error: validationError("At least one
|
|
3133
|
+
if (!hasChange) return { error: validationError("At least one edit option is required.", "Pass --title, --visibility, --grant-email, --revoke-email, --project-id, or --home.") };
|
|
3028
3134
|
return { body };
|
|
3029
3135
|
}
|
|
3030
|
-
function normalizedEmailOptions(value) {
|
|
3136
|
+
function normalizedEmailOptions$1(value) {
|
|
3031
3137
|
const values = arrayOption(value).map((email) => email.trim()).filter(Boolean);
|
|
3032
3138
|
if (value !== void 0 && values.length === 0) return { error: validationError("Email option must not be blank.", "Pass a non-empty email address.") };
|
|
3033
3139
|
return { values };
|
|
3034
3140
|
}
|
|
3035
|
-
function
|
|
3036
|
-
if (!isRecord(body)
|
|
3037
|
-
const
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
archived: project.archived
|
|
3141
|
+
function parseEditData(body) {
|
|
3142
|
+
if (!isRecord(body)) return null;
|
|
3143
|
+
const artifact = body.artifact;
|
|
3144
|
+
const destination = body.destination;
|
|
3145
|
+
const share = body.share;
|
|
3146
|
+
if (!isRecord(artifact) || !isRecord(destination) || !isRecord(share)) return null;
|
|
3147
|
+
if (typeof artifact.id !== "string" || typeof body.title !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string") return null;
|
|
3148
|
+
const base = {
|
|
3149
|
+
artifact: {
|
|
3150
|
+
id: artifact.id,
|
|
3151
|
+
url: typeof artifact.url === "string" ? artifact.url : null
|
|
3047
3152
|
},
|
|
3048
|
-
|
|
3153
|
+
title: body.title,
|
|
3154
|
+
share: { visibility: share.visibility }
|
|
3155
|
+
};
|
|
3156
|
+
if (destination.type === "project") {
|
|
3157
|
+
if (typeof destination.project_id !== "string") return null;
|
|
3158
|
+
return {
|
|
3159
|
+
...base,
|
|
3160
|
+
destination: {
|
|
3161
|
+
type: "project",
|
|
3162
|
+
project_id: destination.project_id
|
|
3163
|
+
}
|
|
3164
|
+
};
|
|
3165
|
+
}
|
|
3166
|
+
if (destination.type === "home" && destination.project_id === null) return {
|
|
3167
|
+
...base,
|
|
3168
|
+
destination: {
|
|
3169
|
+
type: "home",
|
|
3170
|
+
project_id: null
|
|
3171
|
+
}
|
|
3049
3172
|
};
|
|
3173
|
+
return null;
|
|
3050
3174
|
}
|
|
3051
3175
|
//#endregion
|
|
3052
|
-
//#region src/
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
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
|
|
3176
|
+
//#region src/git-exclude.ts
|
|
3177
|
+
async function ensureGitExclude(cwd) {
|
|
3178
|
+
const git = await findGitDir(cwd);
|
|
3179
|
+
if (!git) return {
|
|
3180
|
+
applied: false,
|
|
3181
|
+
warning: null
|
|
3182
|
+
};
|
|
3183
|
+
const excludePath = join(git.gitDir, "info", "exclude");
|
|
3184
|
+
const excludeEntry = gitPattern(relative(git.workTree, resolve(cwd, PROJECT_CONFIG_LOCAL_PATH)));
|
|
3185
|
+
try {
|
|
3186
|
+
const existing = await readFile(excludePath, "utf8").catch(() => "");
|
|
3187
|
+
if (excludeLines(existing).includes(excludeEntry)) return {
|
|
3188
|
+
applied: false,
|
|
3189
|
+
warning: null
|
|
3190
|
+
};
|
|
3191
|
+
await mkdir(dirname(excludePath), { recursive: true });
|
|
3192
|
+
await appendFile(excludePath, `${existing.endsWith("\n") || existing.length === 0 ? "" : "\n"}${excludeEntry}\n`, "utf8");
|
|
3193
|
+
return {
|
|
3194
|
+
applied: true,
|
|
3195
|
+
warning: null
|
|
3196
|
+
};
|
|
3197
|
+
} catch {
|
|
3198
|
+
return {
|
|
3199
|
+
applied: false,
|
|
3200
|
+
warning: `Could not update ${excludePath}; keep ${PROJECT_CONFIG_LOCAL_PATH} out of version control manually.`
|
|
3090
3201
|
};
|
|
3091
3202
|
}
|
|
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
3203
|
}
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3150
|
-
|
|
3204
|
+
function excludeLines(text) {
|
|
3205
|
+
return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
|
|
3206
|
+
}
|
|
3207
|
+
async function findGitDir(start) {
|
|
3208
|
+
let current = resolve(start);
|
|
3209
|
+
const root = resolve(current, "/");
|
|
3210
|
+
while (true) {
|
|
3211
|
+
const gitDir = await resolveGitDir(join(current, ".git"));
|
|
3212
|
+
if (gitDir) return {
|
|
3213
|
+
gitDir,
|
|
3214
|
+
workTree: current
|
|
3215
|
+
};
|
|
3216
|
+
if (current === root) return null;
|
|
3217
|
+
current = dirname(current);
|
|
3218
|
+
}
|
|
3219
|
+
}
|
|
3220
|
+
async function resolveGitDir(gitPath) {
|
|
3221
|
+
const info = await stat(gitPath).catch(() => null);
|
|
3222
|
+
if (!info) return null;
|
|
3223
|
+
if (info.isDirectory()) return gitPath;
|
|
3224
|
+
if (!info.isFile()) return null;
|
|
3225
|
+
const text = await readFile(gitPath, "utf8").catch(() => null);
|
|
3226
|
+
if (!text) return null;
|
|
3227
|
+
const gitDir = text.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
|
|
3228
|
+
if (!gitDir) return null;
|
|
3229
|
+
const resolvedGitDir = resolve(dirname(gitPath), gitDir);
|
|
3230
|
+
const commonDir = await readFile(join(resolvedGitDir, "commondir"), "utf8").then((value) => value.trim()).catch(() => null);
|
|
3231
|
+
return commonDir ? resolve(resolvedGitDir, commonDir) : resolvedGitDir;
|
|
3232
|
+
}
|
|
3233
|
+
function gitPattern(path) {
|
|
3234
|
+
return path.split("\\").join("/");
|
|
3151
3235
|
}
|
|
3152
3236
|
//#endregion
|
|
3153
|
-
//#region src/command-runners/
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
const
|
|
3157
|
-
const
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
if (
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
const
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3237
|
+
//#region src/command-runners/init.ts
|
|
3238
|
+
async function runInit(parsed, mode) {
|
|
3239
|
+
const command = "init";
|
|
3240
|
+
const profile = nonEmpty(parsed.options.profile);
|
|
3241
|
+
const projectId = nonEmpty(parsed.options.projectId);
|
|
3242
|
+
const resolved = await resolveProjectConfig();
|
|
3243
|
+
if (!profile && !projectId) return writeSuccess(command, initData(false, resolved.raw ?? {}, resolved), mode);
|
|
3244
|
+
if (profile) {
|
|
3245
|
+
if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
|
|
3246
|
+
const globalConfig = await readGlobalConfig();
|
|
3247
|
+
if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
|
|
3248
|
+
}
|
|
3249
|
+
const next = {
|
|
3250
|
+
...await readRawLocalProjectConfig() ?? {},
|
|
3251
|
+
...profile ? { default_profile: profile } : {},
|
|
3252
|
+
...projectId ? { default_project_id: projectId } : {}
|
|
3253
|
+
};
|
|
3254
|
+
const path = projectConfigLocalPath();
|
|
3255
|
+
await mkdir(dirname(path), { recursive: true });
|
|
3256
|
+
await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
|
|
3257
|
+
const gitExclude = await ensureGitExclude(process.cwd());
|
|
3258
|
+
const data = initData(true, next, resolved);
|
|
3259
|
+
delete data.read_path;
|
|
3260
|
+
if (gitExclude.warning) data.git_exclude_warning = gitExclude.warning;
|
|
3261
|
+
if (gitExclude.applied) data.git_exclude_applied = true;
|
|
3262
|
+
return writeSuccess(command, data, mode);
|
|
3263
|
+
}
|
|
3264
|
+
function initData(written, config, resolved) {
|
|
3265
|
+
return {
|
|
3266
|
+
path: PROJECT_CONFIG_LOCAL_PATH,
|
|
3267
|
+
written,
|
|
3268
|
+
config: {
|
|
3269
|
+
default_profile: configString(config.default_profile),
|
|
3270
|
+
default_project_id: configString(config.default_project_id)
|
|
3271
|
+
},
|
|
3272
|
+
...resolved.path ? { read_path: resolved.path } : {}
|
|
3173
3273
|
};
|
|
3174
|
-
writeSuccess(command, data, mode);
|
|
3175
|
-
if (!mode.json && data.message) writeText(`${data.message}\n`);
|
|
3176
3274
|
}
|
|
3177
3275
|
//#endregion
|
|
3178
|
-
//#region src/command-runners/
|
|
3179
|
-
async function
|
|
3180
|
-
const command = "
|
|
3181
|
-
const
|
|
3182
|
-
if (
|
|
3276
|
+
//#region src/command-runners/move.ts
|
|
3277
|
+
async function runMove(parsed, mode) {
|
|
3278
|
+
const command = "move";
|
|
3279
|
+
const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to move.");
|
|
3280
|
+
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
3281
|
+
parsed.options.projectId;
|
|
3282
|
+
const projectId = parsed.options.projectId?.trim() ?? "";
|
|
3283
|
+
const home = Boolean(parsed.options.home);
|
|
3284
|
+
const destinationConflict = hasProjectIdHomeConflict(parsed.options);
|
|
3285
|
+
if (destinationConflict || !projectId && !home) return writeFailure(command, validationError("Move destination is required.", "Choose exactly one destination: --project-id <id> or --home.", destinationConflict ? "destination_conflict" : "invalid_destination"), mode, 1);
|
|
3183
3286
|
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
3184
3287
|
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
3185
3288
|
const request = await requestConfig(parsed.options);
|
|
3186
3289
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
3187
|
-
const
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
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);
|
|
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
|
+
});
|
|
3295
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
3296
|
+
const data = parseMoveData(result.body);
|
|
3297
|
+
if (!data) return writeFailure(command, serviceError("Move succeeded but the response did not include move data."), mode, 1);
|
|
3298
|
+
writeSuccess(command, data, mode);
|
|
3198
3299
|
}
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
const
|
|
3202
|
-
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
cursor: {
|
|
3223
|
-
relativePath: join(".cursor", "rules", "artifactshare.mdc"),
|
|
3224
|
-
scopes: ["project"],
|
|
3225
|
-
detectDirs: [".cursor"],
|
|
3226
|
-
bundledFile: "artifactshare.mdc",
|
|
3227
|
-
pruneDirs: []
|
|
3300
|
+
function parseMoveData(body) {
|
|
3301
|
+
if (!isRecord(body)) return null;
|
|
3302
|
+
const artifact = body.artifact;
|
|
3303
|
+
const destination = body.destination;
|
|
3304
|
+
const share = body.share;
|
|
3305
|
+
if (!isRecord(artifact) || !isRecord(destination) || !isRecord(share)) return null;
|
|
3306
|
+
if (typeof artifact.id !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string" || typeof share.project_audience_may_change !== "boolean") return null;
|
|
3307
|
+
if (destination.type === "project") {
|
|
3308
|
+
if (typeof destination.project_id !== "string") return null;
|
|
3309
|
+
return {
|
|
3310
|
+
artifact: {
|
|
3311
|
+
id: artifact.id,
|
|
3312
|
+
url: typeof artifact.url === "string" ? artifact.url : null
|
|
3313
|
+
},
|
|
3314
|
+
destination: {
|
|
3315
|
+
type: "project",
|
|
3316
|
+
project_id: destination.project_id
|
|
3317
|
+
},
|
|
3318
|
+
share: {
|
|
3319
|
+
visibility: share.visibility,
|
|
3320
|
+
project_audience_may_change: share.project_audience_may_change
|
|
3321
|
+
}
|
|
3322
|
+
};
|
|
3228
3323
|
}
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3324
|
+
if (destination.type === "home" && destination.project_id === null) return {
|
|
3325
|
+
artifact: {
|
|
3326
|
+
id: artifact.id,
|
|
3327
|
+
url: typeof artifact.url === "string" ? artifact.url : null
|
|
3328
|
+
},
|
|
3329
|
+
destination: {
|
|
3330
|
+
type: "home",
|
|
3331
|
+
project_id: null
|
|
3332
|
+
},
|
|
3333
|
+
share: {
|
|
3334
|
+
visibility: share.visibility,
|
|
3335
|
+
project_audience_may_change: share.project_audience_may_change
|
|
3336
|
+
}
|
|
3238
3337
|
};
|
|
3338
|
+
return null;
|
|
3239
3339
|
}
|
|
3240
|
-
|
|
3241
|
-
|
|
3340
|
+
//#endregion
|
|
3341
|
+
//#region src/command-runners/profiles.ts
|
|
3342
|
+
async function readStdinToken() {
|
|
3343
|
+
if (process.stdin.isTTY === true) return "";
|
|
3344
|
+
const chunks = [];
|
|
3345
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
3346
|
+
return Buffer.concat(chunks).toString("utf8").trim();
|
|
3242
3347
|
}
|
|
3243
|
-
function
|
|
3244
|
-
|
|
3245
|
-
if (!
|
|
3246
|
-
const
|
|
3247
|
-
const
|
|
3248
|
-
const
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3348
|
+
async function runProfilesList(parsed, mode) {
|
|
3349
|
+
const command = "profiles list";
|
|
3350
|
+
if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
|
|
3351
|
+
const config = await readGlobalConfig() ?? {};
|
|
3352
|
+
const defaultProfile = nonEmpty(config.default_profile) ?? null;
|
|
3353
|
+
const profiles = await Promise.all(Object.entries(config.profiles ?? {}).map(async ([name, rawEntry]) => {
|
|
3354
|
+
const entry = isRecord(rawEntry) ? rawEntry : {};
|
|
3355
|
+
const stored = await readProfileToken(name, {
|
|
3356
|
+
...parsed.options,
|
|
3357
|
+
baseUrl: nonEmpty(entry.base_url) ?? "https://artifactshare.com"
|
|
3358
|
+
});
|
|
3359
|
+
return {
|
|
3360
|
+
name,
|
|
3361
|
+
base_url: nonEmpty(entry.base_url) ?? null,
|
|
3362
|
+
email: nonEmpty(entry.email) ?? null,
|
|
3363
|
+
workspace_id: nonEmpty(entry.workspace_id) ?? null,
|
|
3364
|
+
token_store: entry.token_store ?? null,
|
|
3365
|
+
updated_at: nonEmpty(entry.updated_at) ?? null,
|
|
3366
|
+
is_default: name === defaultProfile,
|
|
3367
|
+
token_present: stored.ok
|
|
3368
|
+
};
|
|
3369
|
+
}));
|
|
3370
|
+
writeSuccess(command, {
|
|
3371
|
+
default_profile: defaultProfile,
|
|
3372
|
+
profiles
|
|
3373
|
+
}, mode);
|
|
3374
|
+
if (!mode.json && profiles.length === 0) writeText(`No profiles yet. Run ${CLI_INVOCATION} login --profile default to create one.\n`);
|
|
3254
3375
|
}
|
|
3255
|
-
async function
|
|
3256
|
-
|
|
3376
|
+
async function runProfilesUse(parsed, mode) {
|
|
3377
|
+
const command = "profiles use";
|
|
3378
|
+
const name = nonEmpty(parsed.positionals[0]);
|
|
3379
|
+
if (!name) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles use <name>.`), mode, 1);
|
|
3380
|
+
if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
|
|
3381
|
+
const config = await readGlobalConfig() ?? {};
|
|
3382
|
+
if (!Object.hasOwn(config.profiles ?? {}, name)) return writeFailure(command, profileNotFoundError(name), mode, 1);
|
|
3383
|
+
const previous = nonEmpty(config.default_profile) ?? null;
|
|
3384
|
+
await writeGlobalConfig({
|
|
3385
|
+
...config,
|
|
3386
|
+
default_profile: name
|
|
3387
|
+
});
|
|
3388
|
+
return writeSuccess(command, {
|
|
3389
|
+
default_profile: name,
|
|
3390
|
+
previous_default: previous
|
|
3391
|
+
}, mode);
|
|
3257
3392
|
}
|
|
3258
|
-
async function
|
|
3259
|
-
const
|
|
3260
|
-
const
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
byFile.set(file, content);
|
|
3271
|
-
}
|
|
3272
|
-
contents[tool] = content;
|
|
3393
|
+
async function runProfilesImportToken(parsed, mode) {
|
|
3394
|
+
const command = "profiles import-token";
|
|
3395
|
+
const profile = nonEmpty(parsed.options.profile);
|
|
3396
|
+
if (!profile) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles import-token --profile <name>.`), mode, 1);
|
|
3397
|
+
if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
|
|
3398
|
+
if (nonEmpty(parsed.options.token)) return writeFailure(command, validationError("Do not pass API tokens with --token to import-token.", "Pipe the token on standard input so it does not appear in process arguments."), mode, 1);
|
|
3399
|
+
if (parsed.positionals.length > 0) return writeFailure(command, validationError("Do not pass API tokens as positional arguments.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`), mode, 1);
|
|
3400
|
+
let token;
|
|
3401
|
+
try {
|
|
3402
|
+
token = await readStdinToken();
|
|
3403
|
+
} catch {
|
|
3404
|
+
return writeFailure(command, validationError("The token could not be read from standard input.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`, "service_error"), mode, 1);
|
|
3273
3405
|
}
|
|
3274
|
-
return {
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3406
|
+
if (!token) return writeFailure(command, validationError("A token is required on standard input.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`), mode, 1);
|
|
3407
|
+
const request = await requestConfig(parsed.options);
|
|
3408
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
3409
|
+
const stored = await verifyAndStoreProfileToken(profile, token, parsed.options, request.init);
|
|
3410
|
+
if (!stored.ok) return writeFailure(command, stored.error, mode, 1);
|
|
3411
|
+
return writeSuccess(command, {
|
|
3412
|
+
profile,
|
|
3413
|
+
token_store: stored.data.token_store,
|
|
3414
|
+
user: stored.data.user,
|
|
3415
|
+
workspace: stored.data.workspace,
|
|
3416
|
+
base_url: baseUrlOf(parsed.options)
|
|
3417
|
+
}, mode);
|
|
3278
3418
|
}
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3284
|
-
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3419
|
+
//#endregion
|
|
3420
|
+
//#region src/command-runners/projects.ts
|
|
3421
|
+
async function fetchProjects(token, options, init, errorOptions = {}) {
|
|
3422
|
+
const result = await apiGet("/api/cli/projects", token, options, init, errorOptions);
|
|
3423
|
+
if (result.error) return { error: result.error };
|
|
3424
|
+
return { projects: (Array.isArray(result.body?.projects) ? result.body.projects : []).filter(isRecord).flatMap((project) => {
|
|
3425
|
+
const id = configString(project.id);
|
|
3426
|
+
if (!id) return [];
|
|
3427
|
+
return [{
|
|
3428
|
+
id,
|
|
3429
|
+
name: configString(project.name),
|
|
3430
|
+
description: configString(project.description),
|
|
3431
|
+
base_visibility: configString(project.base_visibility),
|
|
3432
|
+
file_count: typeof project.file_count === "number" ? project.file_count : null,
|
|
3433
|
+
updated_at: configString(project.updated_at)
|
|
3434
|
+
}];
|
|
3435
|
+
}) };
|
|
3290
3436
|
}
|
|
3291
|
-
function
|
|
3292
|
-
const
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3437
|
+
async function runProjectsList(parsed, mode) {
|
|
3438
|
+
const command = "projects list";
|
|
3439
|
+
const projectConfig = await resolveProjectConfig();
|
|
3440
|
+
const credential = await resolveCredential(parsed.options, projectConfig);
|
|
3441
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
3442
|
+
const request = await requestConfig(parsed.options);
|
|
3443
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
3444
|
+
const result = await fetchProjects(credential.token, parsed.options, request.init, {
|
|
3445
|
+
credentialSource: credential.source,
|
|
3446
|
+
profile: credential.profile
|
|
3447
|
+
});
|
|
3448
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
3449
|
+
const defaultProjectId = configString(projectConfig.config?.default_project_id);
|
|
3450
|
+
const projects = result.projects.map((project) => ({
|
|
3451
|
+
...project,
|
|
3452
|
+
is_default: project.id === defaultProjectId
|
|
3453
|
+
}));
|
|
3454
|
+
writeSuccess(command, {
|
|
3455
|
+
default_project_id: defaultProjectId,
|
|
3456
|
+
projects
|
|
3457
|
+
}, mode);
|
|
3458
|
+
if (!mode.json && projects.length === 0) writeText("No projects yet. Create one on the web, then publish with --project-id.\n");
|
|
3296
3459
|
}
|
|
3297
|
-
function
|
|
3298
|
-
const
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3460
|
+
async function runProjectsCreate(parsed, mode) {
|
|
3461
|
+
const command = "projects create";
|
|
3462
|
+
const name = parsed.positionals[0]?.trim();
|
|
3463
|
+
if (!name) return writeFailure(command, validationError("Project name is required.", "Pass a project name: projects create <name>."), mode, 1);
|
|
3464
|
+
const visibility = parsed.options.visibility;
|
|
3465
|
+
if (visibility !== void 0 && visibility !== "workspace" && visibility !== "private") return writeFailure(command, validationError("--visibility must be workspace or private.", "Retry with --visibility workspace or --visibility private."), mode, 1);
|
|
3466
|
+
const projectConfig = await resolveProjectConfig();
|
|
3467
|
+
const credential = await resolveCredential(parsed.options, projectConfig);
|
|
3468
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
3469
|
+
const request = await requestConfig(parsed.options);
|
|
3470
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
3471
|
+
const result = await apiPost("/api/cli/projects", credential.token, {
|
|
3472
|
+
name,
|
|
3473
|
+
description: parsed.options.description ?? null,
|
|
3474
|
+
base_visibility: visibility ?? null
|
|
3475
|
+
}, parsed.options, request.init, {
|
|
3476
|
+
credentialSource: credential.source,
|
|
3477
|
+
profile: credential.profile
|
|
3478
|
+
});
|
|
3479
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
3480
|
+
const project = isRecord(result.body?.project) ? result.body.project : null;
|
|
3481
|
+
const id = configString(project?.id);
|
|
3482
|
+
if (!id) return writeFailure(command, serviceError("Project create succeeded but no project id was returned."), mode, 1);
|
|
3483
|
+
writeSuccess(command, {
|
|
3484
|
+
project: {
|
|
3485
|
+
id,
|
|
3486
|
+
name: configString(project?.name),
|
|
3487
|
+
description: configString(project?.description),
|
|
3488
|
+
base_visibility: configString(project?.base_visibility)
|
|
3489
|
+
},
|
|
3490
|
+
next_command: `npx --yes @artifactshare/cli publish <path> --project-id ${id} --json`
|
|
3491
|
+
}, mode);
|
|
3308
3492
|
}
|
|
3309
|
-
function
|
|
3310
|
-
|
|
3493
|
+
async function runProjectsEdit(parsed, mode) {
|
|
3494
|
+
const command = "projects edit";
|
|
3495
|
+
const projectId = parsed.positionals[0]?.trim();
|
|
3496
|
+
if (!projectId) return writeFailure(command, validationError("Project id is required.", "Pass a project id: projects edit <id>."), mode, 1);
|
|
3497
|
+
const payload = buildProjectsEditPayload(parsed);
|
|
3498
|
+
if (payload.error) return writeFailure(command, payload.error, mode, 1);
|
|
3499
|
+
const projectConfig = await resolveProjectConfig();
|
|
3500
|
+
const credential = await resolveCredential(parsed.options, projectConfig);
|
|
3501
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
3502
|
+
const request = await requestConfig(parsed.options);
|
|
3503
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
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
|
+
});
|
|
3509
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
3510
|
+
const data = parseProjectsEditData(result.body);
|
|
3511
|
+
if (!data) return writeFailure(command, serviceError("Project edit succeeded but the response did not include project data."), mode, 1);
|
|
3512
|
+
writeSuccess(command, data, mode);
|
|
3311
3513
|
}
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3514
|
+
function buildProjectsEditPayload(parsed) {
|
|
3515
|
+
const body = {};
|
|
3516
|
+
let hasChange = false;
|
|
3517
|
+
if (parsed.options.name !== void 0) {
|
|
3518
|
+
const name = parsed.options.name.trim();
|
|
3519
|
+
if (!name) return { error: validationError("--name must not be blank.", "Retry with a non-empty project name.") };
|
|
3520
|
+
body.name = name;
|
|
3521
|
+
hasChange = true;
|
|
3317
3522
|
}
|
|
3318
|
-
if (
|
|
3319
|
-
|
|
3320
|
-
|
|
3523
|
+
if (parsed.options.description !== void 0) {
|
|
3524
|
+
body.description = parsed.options.description;
|
|
3525
|
+
hasChange = true;
|
|
3321
3526
|
}
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
|
|
3327
|
-
try {
|
|
3328
|
-
await rmdir(dir);
|
|
3329
|
-
} catch {
|
|
3330
|
-
return;
|
|
3331
|
-
}
|
|
3332
|
-
dir = dirname(dir);
|
|
3527
|
+
if (parsed.options.visibility !== void 0) {
|
|
3528
|
+
const visibility = parsed.options.visibility.trim();
|
|
3529
|
+
if (visibility !== "workspace" && visibility !== "private") return { error: validationError("--visibility must be workspace or private.", "Retry with --visibility workspace or --visibility private.") };
|
|
3530
|
+
body.base_visibility = visibility;
|
|
3531
|
+
hasChange = true;
|
|
3333
3532
|
}
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
if (
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
return writeFailure(command, unexpectedError(error), mode, 1);
|
|
3533
|
+
const addEmails = normalizedEmailOptions(parsed.options.addEmail);
|
|
3534
|
+
if (addEmails.error) return { error: addEmails.error };
|
|
3535
|
+
if (parsed.options.addEmail !== void 0) {
|
|
3536
|
+
body.add_emails = addEmails.values;
|
|
3537
|
+
hasChange = true;
|
|
3340
3538
|
}
|
|
3341
|
-
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
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;
|
|
3539
|
+
const removeEmails = normalizedEmailOptions(parsed.options.removeEmail);
|
|
3540
|
+
if (removeEmails.error) return { error: removeEmails.error };
|
|
3541
|
+
if (parsed.options.removeEmail !== void 0) {
|
|
3542
|
+
body.remove_emails = removeEmails.values;
|
|
3543
|
+
hasChange = true;
|
|
3357
3544
|
}
|
|
3358
|
-
}
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
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;
|
|
3380
|
-
}
|
|
3381
|
-
planned.push({
|
|
3382
|
-
target,
|
|
3383
|
-
action: state.kind === "missing" ? "installed" : "updated",
|
|
3384
|
-
content: bundled.contents[tool]
|
|
3385
|
-
});
|
|
3545
|
+
if (parsed.options.archive && parsed.options.unarchive) return { error: validationError("Archive state is conflicting.", "Choose either --archive or --unarchive.") };
|
|
3546
|
+
if (parsed.options.archive) {
|
|
3547
|
+
body.archived = true;
|
|
3548
|
+
hasChange = true;
|
|
3549
|
+
}
|
|
3550
|
+
if (parsed.options.unarchive) {
|
|
3551
|
+
body.archived = false;
|
|
3552
|
+
hasChange = true;
|
|
3386
3553
|
}
|
|
3387
|
-
return
|
|
3554
|
+
if (!hasChange) return { error: validationError("At least one project edit option is required.", "Pass --name, --description, --visibility, --add-email, --remove-email, --archive, or --unarchive.") };
|
|
3555
|
+
return { body };
|
|
3388
3556
|
}
|
|
3389
|
-
|
|
3390
|
-
const
|
|
3391
|
-
if (
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3557
|
+
function normalizedEmailOptions(value) {
|
|
3558
|
+
const values = arrayOption(value).map((email) => email.trim()).filter(Boolean);
|
|
3559
|
+
if (value !== void 0 && values.length === 0) return { error: validationError("Email option must not be blank.", "Pass a non-empty email address.") };
|
|
3560
|
+
return { values };
|
|
3561
|
+
}
|
|
3562
|
+
function parseProjectsEditData(body) {
|
|
3563
|
+
if (!isRecord(body) || !isRecord(body.project)) return null;
|
|
3564
|
+
const { project } = body;
|
|
3565
|
+
if (typeof project.id !== "string" || typeof project.archived !== "boolean" || !Array.isArray(body.audience) || body.audience.some((email) => typeof email !== "string")) return null;
|
|
3566
|
+
return {
|
|
3567
|
+
project: {
|
|
3568
|
+
id: project.id,
|
|
3569
|
+
name: configString(project.name),
|
|
3570
|
+
description: configString(project.description),
|
|
3571
|
+
base_visibility: configString(project.base_visibility),
|
|
3572
|
+
file_count: typeof project.file_count === "number" ? project.file_count : null,
|
|
3573
|
+
archived: project.archived
|
|
3574
|
+
},
|
|
3575
|
+
audience: body.audience
|
|
3576
|
+
};
|
|
3577
|
+
}
|
|
3578
|
+
//#endregion
|
|
3579
|
+
//#region src/command-runners/publish.ts
|
|
3580
|
+
const MAX_PUBLISH_KEY_LENGTH = 128;
|
|
3581
|
+
async function runPublish(parsed, mode, isRetry = false) {
|
|
3582
|
+
const command = "publish";
|
|
3583
|
+
const targetPath = parsed.positionals[0];
|
|
3584
|
+
if (!targetPath) return writeFailure(command, validationError("Path is required.", "Pass a file or directory to publish."), mode, 1);
|
|
3585
|
+
let publishKey = null;
|
|
3586
|
+
if ("key" in parsed.options) {
|
|
3587
|
+
publishKey = (typeof parsed.options.key === "string" ? parsed.options.key : "").trim();
|
|
3588
|
+
if (publishKey.length === 0 || publishKey.length > MAX_PUBLISH_KEY_LENGTH) return writeFailure(command, validationError(`--key must be 1-${MAX_PUBLISH_KEY_LENGTH} characters after trimming.`, "Pass a short stable identifier, like a job name or PR number."), mode, 1);
|
|
3589
|
+
}
|
|
3590
|
+
const project = await resolveProjectConfig();
|
|
3591
|
+
const credential = await resolveCredential(parsed.options, project);
|
|
3592
|
+
if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runPublish(parsed, mode, true), isRetry);
|
|
3593
|
+
const baseUrl = baseUrlOf(parsed.options);
|
|
3594
|
+
const hasProjectFlag = "project" in parsed.options;
|
|
3595
|
+
let destinationOptions = parsed.options;
|
|
3596
|
+
let projectName;
|
|
3597
|
+
if (hasProjectFlag) {
|
|
3598
|
+
projectName = nonEmpty(typeof parsed.options.project === "string" ? parsed.options.project : "");
|
|
3599
|
+
if (!projectName) return writeFailure(command, validationError("--project requires a value.", "Pass --project <name> and retry."), mode, 1);
|
|
3600
|
+
const conflict = destinationConflictError(parsed.options);
|
|
3601
|
+
if (conflict) return writeFailure(command, conflict, mode, 1);
|
|
3602
|
+
} else {
|
|
3603
|
+
const earlyDestination = resolveDestination(parsed.options, project.config);
|
|
3604
|
+
if (earlyDestination.error) return writeFailure(command, earlyDestination.error, mode, 1);
|
|
3605
|
+
}
|
|
3606
|
+
const fileStat = await stat(targetPath).catch(() => null);
|
|
3607
|
+
if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
|
|
3608
|
+
const request = await requestConfig(parsed.options);
|
|
3609
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
3610
|
+
if (hasProjectFlag && projectName) {
|
|
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
|
|
3407
3616
|
});
|
|
3617
|
+
if (resolved.error) return handleAuthenticatedCredentialFailure(command, resolved.error, credential, parsed.options, mode, () => runPublish(parsed, mode, true), isRetry);
|
|
3618
|
+
const { project: _project, ...rest } = parsed.options;
|
|
3619
|
+
destinationOptions = {
|
|
3620
|
+
...rest,
|
|
3621
|
+
projectId: resolved.projectId
|
|
3622
|
+
};
|
|
3408
3623
|
}
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
3624
|
+
const destination = resolveDestination(destinationOptions, project.config);
|
|
3625
|
+
if (destination.error) return writeFailure(command, destination.error, mode, 1);
|
|
3626
|
+
const initialForm = new FormData();
|
|
3627
|
+
const grantEmails = arrayOption(parsed.options.grantEmail);
|
|
3628
|
+
const requestedVisibility = parsed.options.visibility ?? (destination.containerId && grantEmails.length === 0 ? "project" : "private");
|
|
3629
|
+
initialForm.set("visibility", requestedVisibility);
|
|
3630
|
+
for (const email of grantEmails) initialForm.append("grant_email", email);
|
|
3631
|
+
if (destination.containerId) initialForm.set("container_id", destination.containerId);
|
|
3632
|
+
const uploadUrl = apiUrl("/api/shareables/uploads", baseUrl);
|
|
3633
|
+
if (publishKey !== null) uploadUrl.searchParams.set("publish_key", publishKey);
|
|
3634
|
+
const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
|
|
3635
|
+
if (upload.error) return writeFailure(command, upload.error, mode, 1);
|
|
3636
|
+
if (upload.payload.kind === "static_site") {
|
|
3637
|
+
uploadUrl.searchParams.set("artifact_kind", "static_site");
|
|
3638
|
+
if (destination.containerId) uploadUrl.searchParams.set("container_id", destination.containerId);
|
|
3639
|
+
}
|
|
3640
|
+
const response = await fetch(uploadUrl, {
|
|
3641
|
+
method: "POST",
|
|
3642
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
3643
|
+
body: upload.payload.form,
|
|
3644
|
+
...request.init
|
|
3645
|
+
}).catch((error) => ({ networkError: error }));
|
|
3646
|
+
if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
|
|
3647
|
+
const body = await readJson(response);
|
|
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);
|
|
3654
|
+
const id = body?.id ?? null;
|
|
3655
|
+
return writeSuccess(command, {
|
|
3656
|
+
artifact: {
|
|
3657
|
+
id,
|
|
3658
|
+
url: body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
|
|
3659
|
+
kind: body?.artifactKind ?? upload.payload.kind
|
|
3660
|
+
},
|
|
3661
|
+
version: { id: body?.versionId ?? null },
|
|
3662
|
+
result: { created: body?.created ?? true },
|
|
3663
|
+
...publishKey !== null ? { key: publishKey } : {},
|
|
3664
|
+
destination: destination.containerId ? {
|
|
3665
|
+
type: "project",
|
|
3666
|
+
project_id: destination.containerId
|
|
3667
|
+
} : { type: "home" },
|
|
3668
|
+
share: {
|
|
3669
|
+
visibility: body?.visibility ?? requestedVisibility,
|
|
3670
|
+
grant_emails: grantEmails
|
|
3671
|
+
}
|
|
3412
3672
|
}, mode);
|
|
3413
3673
|
}
|
|
3414
|
-
async function
|
|
3415
|
-
const
|
|
3416
|
-
|
|
3417
|
-
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
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);
|
|
3674
|
+
async function resolveProjectIdByName(projectName, token, options, init, errorOptions) {
|
|
3675
|
+
const result = await fetchProjects(token, options, init, errorOptions);
|
|
3676
|
+
if (result.error) return { error: result.error };
|
|
3677
|
+
const candidates = result.projects.flatMap((project) => {
|
|
3678
|
+
if (project.name !== projectName) return [];
|
|
3679
|
+
return [{
|
|
3680
|
+
project_id: project.id,
|
|
3681
|
+
name: project.name,
|
|
3682
|
+
updated_at: project.updated_at
|
|
3683
|
+
}];
|
|
3684
|
+
});
|
|
3685
|
+
if (candidates.length === 0) return { error: projectNotFoundByNameError() };
|
|
3686
|
+
if (candidates.length > 1) return { error: projectAmbiguousError(candidates) };
|
|
3687
|
+
return { projectId: candidates[0].project_id };
|
|
3444
3688
|
}
|
|
3445
|
-
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
3449
|
-
const
|
|
3450
|
-
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3689
|
+
//#endregion
|
|
3690
|
+
//#region src/command-runners/request-access.ts
|
|
3691
|
+
const NOTE_MAX = 2e3;
|
|
3692
|
+
async function runRequestAccess(parsed, mode) {
|
|
3693
|
+
const command = "request-access";
|
|
3694
|
+
const note = parsed.options.note;
|
|
3695
|
+
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);
|
|
3696
|
+
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
3697
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
3698
|
+
const request = await requestConfig(parsed.options);
|
|
3699
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
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
|
+
});
|
|
3704
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
3705
|
+
const body = result.body;
|
|
3706
|
+
const data = {
|
|
3707
|
+
requested: body?.requested === true,
|
|
3708
|
+
already_enabled: body?.already_enabled === true,
|
|
3709
|
+
status: typeof body?.status === "string" ? body.status : null,
|
|
3710
|
+
created: body?.created === true,
|
|
3711
|
+
requires_operator_action: body?.requires_operator_action === true,
|
|
3712
|
+
message: typeof body?.message === "string" ? body.message : ""
|
|
3713
|
+
};
|
|
3714
|
+
writeSuccess(command, data, mode);
|
|
3715
|
+
if (!mode.json && data.message) writeText(`${data.message}\n`);
|
|
3716
|
+
}
|
|
3717
|
+
//#endregion
|
|
3718
|
+
//#region src/command-runners/resolve.ts
|
|
3719
|
+
async function runResolve(parsed, mode) {
|
|
3720
|
+
const command = "resolve";
|
|
3721
|
+
const value = parsed.positionals[0]?.trim();
|
|
3722
|
+
if (!value) return writeFailure(command, validationError("Resolve value is required.", "Pass a URL, ID, title, or project name to resolve."), mode, 1);
|
|
3723
|
+
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
3724
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
3725
|
+
const request = await requestConfig(parsed.options);
|
|
3726
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
3727
|
+
const url = apiUrl("/api/cli/resolve", baseUrlOf(parsed.options));
|
|
3728
|
+
url.searchParams.set("q", value);
|
|
3729
|
+
const response = await fetch(url, {
|
|
3730
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
3731
|
+
...request.init
|
|
3732
|
+
}).catch((error) => ({ networkError: error }));
|
|
3733
|
+
if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
|
|
3734
|
+
const body = await readJson(response);
|
|
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);
|
|
3741
|
+
if (!resolveSuccessFields(body)) return writeFailure(command, serviceError("Resolve succeeded but the response did not include query, candidates, and has_more."), mode, 1);
|
|
3742
|
+
return writeSuccess(command, body, mode);
|
|
3459
3743
|
}
|
|
3460
3744
|
//#endregion
|
|
3461
3745
|
//#region src/command-runners/update.ts
|
|
@@ -3488,10 +3772,13 @@ async function runUpdate(parsed, mode, isRetry = false) {
|
|
|
3488
3772
|
}).catch((error) => ({ networkError: error }));
|
|
3489
3773
|
if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
|
|
3490
3774
|
const body = await readJson(response);
|
|
3491
|
-
if (!response.ok) return
|
|
3775
|
+
if (!response.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(response.status, body, {
|
|
3492
3776
|
authenticated: true,
|
|
3493
|
-
artifactTarget: true
|
|
3494
|
-
|
|
3777
|
+
artifactTarget: true,
|
|
3778
|
+
baseUrl,
|
|
3779
|
+
credentialSource: credential.source,
|
|
3780
|
+
profile: credential.profile
|
|
3781
|
+
}), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
|
|
3495
3782
|
const id = body?.id ?? artifactId;
|
|
3496
3783
|
const result = {
|
|
3497
3784
|
artifact: {
|
|
@@ -3513,7 +3800,10 @@ async function runWhoami(parsed, mode) {
|
|
|
3513
3800
|
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
3514
3801
|
const request = await requestConfig(parsed.options);
|
|
3515
3802
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
3516
|
-
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
|
+
});
|
|
3517
3807
|
if (whoami.error) return writeFailure(command, whoami.error, mode, 1);
|
|
3518
3808
|
return writeSuccess(command, isRecord(whoami.body) ? {
|
|
3519
3809
|
...whoami.body,
|
|
@@ -3550,6 +3840,10 @@ async function downloadRunner(ctx) {
|
|
|
3550
3840
|
const parsed = parsedArgsFromContext("download", ctx);
|
|
3551
3841
|
return await runDownload(parsed, outputMode(parsed.options));
|
|
3552
3842
|
}
|
|
3843
|
+
async function agentOpenRunner(ctx) {
|
|
3844
|
+
const parsed = parsedArgsFromContext("agent open", ctx);
|
|
3845
|
+
return await runAgentOpen(parsed, outputMode(parsed.options));
|
|
3846
|
+
}
|
|
3553
3847
|
async function moveRunner(ctx) {
|
|
3554
3848
|
const parsed = parsedArgsFromContext("move", ctx);
|
|
3555
3849
|
return await runMove(parsed, outputMode(parsed.options));
|
|
@@ -3635,6 +3929,10 @@ async function skillsUpdateRunner(ctx) {
|
|
|
3635
3929
|
const parsed = parsedArgsFromContext("skills update", ctx);
|
|
3636
3930
|
return await runSkillsUpdate(parsed, outputMode(parsed.options));
|
|
3637
3931
|
}
|
|
3932
|
+
async function skillsEnsureRunner(ctx) {
|
|
3933
|
+
const parsed = parsedArgsFromContext("skills ensure", ctx);
|
|
3934
|
+
return await runSkillsEnsure(parsed, outputMode(parsed.options));
|
|
3935
|
+
}
|
|
3638
3936
|
async function skillsRemoveRunner(ctx) {
|
|
3639
3937
|
const parsed = parsedArgsFromContext("skills remove", ctx);
|
|
3640
3938
|
return await runSkillsRemove(parsed, outputMode(parsed.options));
|
|
@@ -3662,7 +3960,7 @@ async function main(rawArgv) {
|
|
|
3662
3960
|
const argv = joinLeadingDashValues(rawArgv);
|
|
3663
3961
|
const command = commandNameFromArgv(argv);
|
|
3664
3962
|
const commandCandidate = firstCommandCandidate(argv);
|
|
3665
|
-
const rawError = validateRawArgs(argv);
|
|
3963
|
+
const rawError = validateRawArgs(argv, command);
|
|
3666
3964
|
if (rawError) return writeFailure(command ?? "unknown", rawError, outputModeFromArgv(argv), 1);
|
|
3667
3965
|
if (command === void 0 && commandCandidate !== void 0) return writeFailure("unknown", unknownCommandError(commandCandidate), outputModeFromArgv(argv), 1);
|
|
3668
3966
|
const usage = await runGunshi(command === void 0 ? ["--help"] : normalizeArgvForGunshi(argv, commandCandidate)).catch((error) => {
|
|
@@ -3696,6 +3994,7 @@ async function runGunshi(argv) {
|
|
|
3696
3994
|
delete: lazyCommand(deleteDefinition, deleteRunner),
|
|
3697
3995
|
resolve: lazyCommand(resolveDefinition, resolveRunner),
|
|
3698
3996
|
download: lazyCommand(downloadDefinition, downloadRunner),
|
|
3997
|
+
agent: agentDefinition,
|
|
3699
3998
|
move: lazyCommand(moveDefinition, moveRunner),
|
|
3700
3999
|
artifacts: artifactsDefinition,
|
|
3701
4000
|
comments: commentsDefinition,
|
|
@@ -3764,7 +4063,7 @@ npx --yes @artifactshare/cli artifacts list --json
|
|
|
3764
4063
|
npx --yes @artifactshare/cli artifacts get <artifact-id-or-url> --json
|
|
3765
4064
|
npx --yes @artifactshare/cli comments list <artifact-id-or-url> --json
|
|
3766
4065
|
npx --yes @artifactshare/cli comments post <artifact-id-or-url> --body "<text>" --json
|
|
3767
|
-
|
|
4066
|
+
${agentDownloadCommand("<artifact-id-or-url>")}
|
|
3768
4067
|
npx --yes @artifactshare/cli login --profile default
|
|
3769
4068
|
npx --yes @artifactshare/cli profiles list --json
|
|
3770
4069
|
npx --yes @artifactshare/cli profiles use <name> --json
|
|
@@ -3847,7 +4146,13 @@ const publishDefinition = define({
|
|
|
3847
4146
|
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
4147
|
}
|
|
3849
4148
|
},
|
|
3850
|
-
examples: `npx --yes @artifactshare/cli publish report.html --project-id <id> --
|
|
4149
|
+
examples: `npx --yes @artifactshare/cli publish report.html --project-id <id> --json
|
|
4150
|
+
npx --yes @artifactshare/cli publish report.html --project-id <id> --key nightly-report --json
|
|
4151
|
+
|
|
4152
|
+
To keep an existing share URL, use update:
|
|
4153
|
+
npx --yes @artifactshare/cli update <artifact-id-or-url> <path> --json
|
|
4154
|
+
|
|
4155
|
+
For repeat jobs, use --key: first publish creates the artifact, later runs add versions.
|
|
3851
4156
|
|
|
3852
4157
|
Common failures:
|
|
3853
4158
|
auth_required Set ARTIFACTSHARE_TOKEN before publish
|
|
@@ -4014,7 +4319,7 @@ const downloadDefinition = define({
|
|
|
4014
4319
|
}
|
|
4015
4320
|
},
|
|
4016
4321
|
examples: `npx --yes @artifactshare/cli download abc123def4 --json
|
|
4017
|
-
|
|
4322
|
+
${agentDownloadCommand("https://artifactshare.com/a/abc123def4")}
|
|
4018
4323
|
|
|
4019
4324
|
Use resolve first when a user gives a title or project name, then pass the id here.
|
|
4020
4325
|
Download writes files to a directory so the result can be inspected or passed to update.
|
|
@@ -4025,6 +4330,39 @@ Common failures:
|
|
|
4025
4330
|
output_exists Choose another --output path or pass --force
|
|
4026
4331
|
validation_failed Check --output and downloaded file paths`
|
|
4027
4332
|
});
|
|
4333
|
+
const agentDefinition = define({
|
|
4334
|
+
name: "agent",
|
|
4335
|
+
description: "Agent-first helpers for Artifact Share URLs.",
|
|
4336
|
+
toKebab: true,
|
|
4337
|
+
args: commonArgs,
|
|
4338
|
+
subCommands: { open: lazyCommand(define({
|
|
4339
|
+
name: "open",
|
|
4340
|
+
description: "Prepare agent skills and read an Artifact Share URL.",
|
|
4341
|
+
toKebab: true,
|
|
4342
|
+
args: {
|
|
4343
|
+
...commonArgs,
|
|
4344
|
+
artifactIdOrUrl: {
|
|
4345
|
+
type: "positional",
|
|
4346
|
+
toKebab: true,
|
|
4347
|
+
description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
|
|
4348
|
+
}
|
|
4349
|
+
},
|
|
4350
|
+
examples: `npx --yes @artifactshare/cli agent open https://artifactshare.com/a/abc123def4 --json
|
|
4351
|
+
npx --yes @artifactshare/cli agent open abc123def4 --json
|
|
4352
|
+
|
|
4353
|
+
Use this as the first command when an agent receives an Artifact Share URL.
|
|
4354
|
+
It installs or updates the local Artifact Share skill, then reads single-file artifacts.
|
|
4355
|
+
For static sites or multi-file artifacts, the JSON includes a download next_command.
|
|
4356
|
+
|
|
4357
|
+
Common failures:
|
|
4358
|
+
auth_required Set ARTIFACTSHARE_TOKEN before agent open
|
|
4359
|
+
skill_update_conflict Inspect the file or run skills install --tool <tool> --force
|
|
4360
|
+
target_not_found Retry with an artifact ID, share URL, or sandbox URL
|
|
4361
|
+
validation_failed Pass a non-empty artifact ID or URL`
|
|
4362
|
+
}), agentOpenRunner) },
|
|
4363
|
+
examples: `npx --yes @artifactshare/cli agent open https://artifactshare.com/a/abc123def4 --json`,
|
|
4364
|
+
run: parentCommandRunner("agent")
|
|
4365
|
+
});
|
|
4028
4366
|
const moveDefinition = define({
|
|
4029
4367
|
name: "move",
|
|
4030
4368
|
description: "Move an artifact into a project or back home.",
|
|
@@ -4576,6 +4914,30 @@ Only files created by skills install (managed marker present) are updated.
|
|
|
4576
4914
|
Common failures:
|
|
4577
4915
|
skill_update_conflict A managed marker is broken; inspect the file or reinstall with --force`
|
|
4578
4916
|
});
|
|
4917
|
+
const skillsEnsureDefinition = define({
|
|
4918
|
+
name: "ensure",
|
|
4919
|
+
description: "Install or update the bundled Artifact Share skill.",
|
|
4920
|
+
toKebab: true,
|
|
4921
|
+
args: {
|
|
4922
|
+
...commonArgs,
|
|
4923
|
+
...skillsToolArgs,
|
|
4924
|
+
dryRun: {
|
|
4925
|
+
type: "boolean",
|
|
4926
|
+
toKebab: true,
|
|
4927
|
+
description: "Show planned file changes without writing"
|
|
4928
|
+
}
|
|
4929
|
+
},
|
|
4930
|
+
examples: `npx --yes @artifactshare/cli skills ensure --tool auto --scope project --json
|
|
4931
|
+
npx --yes @artifactshare/cli skills ensure --tool claude --json
|
|
4932
|
+
|
|
4933
|
+
Use --tool auto from an agent workspace. It detects .claude, .agents/.codex,
|
|
4934
|
+
and .cursor in the current directory; if none are present, it prepares Codex
|
|
4935
|
+
and Claude Code project skills.
|
|
4936
|
+
|
|
4937
|
+
Common failures:
|
|
4938
|
+
validation_failed Pass --tool auto|codex|claude|cursor; auto supports --scope project only
|
|
4939
|
+
skill_update_conflict An unmanaged or broken skill file exists; inspect it before overwriting`
|
|
4940
|
+
});
|
|
4579
4941
|
const skillsRemoveDefinition = define({
|
|
4580
4942
|
name: "remove",
|
|
4581
4943
|
description: "Remove Artifact Share skills installed by this CLI.",
|
|
@@ -4598,9 +4960,11 @@ const skillsDefinition = define({
|
|
|
4598
4960
|
install: lazyCommand(skillsInstallDefinition, skillsInstallRunner),
|
|
4599
4961
|
list: lazyCommand(skillsListDefinition, skillsListRunner),
|
|
4600
4962
|
update: lazyCommand(skillsUpdateDefinition, skillsUpdateRunner),
|
|
4963
|
+
ensure: lazyCommand(skillsEnsureDefinition, skillsEnsureRunner),
|
|
4601
4964
|
remove: lazyCommand(skillsRemoveDefinition, skillsRemoveRunner)
|
|
4602
4965
|
},
|
|
4603
4966
|
examples: `npx --yes @artifactshare/cli skills install --tool codex --json
|
|
4967
|
+
npx --yes @artifactshare/cli skills ensure --tool auto --json
|
|
4604
4968
|
npx --yes @artifactshare/cli skills list --json`,
|
|
4605
4969
|
run: parentCommandRunner("skills")
|
|
4606
4970
|
});
|