@kenkaiiii/gg-core 5.98.1 → 5.98.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -40,6 +40,7 @@ __export(index_exports, {
40
40
  CLAUDE_CODE_AUTH_MARKER: () => CLAUDE_CODE_AUTH_MARKER,
41
41
  CLAUDE_CODE_MANIFEST: () => CLAUDE_CODE_MANIFEST,
42
42
  ChatGPTPlanNotEnabledError: () => ChatGPTPlanNotEnabledError,
43
+ ChatGPTSignInError: () => ChatGPTSignInError,
43
44
  DEFAULT_LOCAL_ENDPOINTS: () => DEFAULT_LOCAL_ENDPOINTS,
44
45
  DEFAULT_MAX_VIDEO_BYTES: () => DEFAULT_MAX_VIDEO_BYTES,
45
46
  FALLBACK_CONTEXT_WINDOW: () => FALLBACK_CONTEXT_WINDOW,
@@ -791,6 +792,29 @@ var ChatGPTPlanNotEnabledError = class extends Error {
791
792
  this.name = "ChatGPTPlanNotEnabledError";
792
793
  }
793
794
  };
795
+ var ChatGPTSignInError = class extends Error {
796
+ reason;
797
+ status;
798
+ detail;
799
+ /** Whether a saved app registration was used, rather than a first registration. */
800
+ returning = false;
801
+ /** Whether this was the second refusal, after the one automatic retry. */
802
+ retried = false;
803
+ /** Milliseconds from the browser callback to the token endpoint's answer. */
804
+ callbackToExchangeMs;
805
+ constructor(reason, status, detail = "") {
806
+ super(`ChatGPT token exchange failed (${status}): ${reason}`);
807
+ this.name = "ChatGPTSignInError";
808
+ this.reason = reason;
809
+ this.status = status;
810
+ this.detail = detail;
811
+ }
812
+ };
813
+ function cancelled() {
814
+ const err = new Error("ChatGPT sign-in was cancelled.");
815
+ err.name = "AbortError";
816
+ return err;
817
+ }
794
818
  function defaultHostIdFile() {
795
819
  return import_node_path3.default.join(getAppPaths().agentDir, "openai-host-id");
796
820
  }
@@ -827,81 +851,119 @@ async function readRegistration(file) {
827
851
  return void 0;
828
852
  }
829
853
  async function loginChatGPT(callbacks, options = {}) {
854
+ const { signal } = options;
830
855
  const hostId = await getChatGPTHostId(options.hostIdFile);
831
856
  const registrationFile = options.registrationFile ?? defaultRegistrationFile();
832
857
  const registration = await readRegistration(registrationFile);
833
- const { verifier, challenge } = await generatePKCE();
834
- const state = import_node_crypto2.default.randomBytes(16).toString("hex");
835
- const nonce = import_node_crypto2.default.randomBytes(16).toString("hex");
836
- const listener = await startCallbackListener(state, Boolean(registration));
837
- try {
838
- const redirectUri = `http://127.0.0.1:${listener.port}${CALLBACK_PATH}`;
839
- const url = new URL(AUTHORIZE_URL);
840
- url.searchParams.set("client_id", registration?.clientId ?? REGISTRATION_CLIENT_ID);
841
- if (!registration) url.searchParams.set("agent_name_hint", AGENT_NAME);
842
- url.searchParams.set("ext_agent_host_id", hostId);
843
- if (registration && options.previous?.idToken) {
844
- url.searchParams.set("id_token_hint", options.previous.idToken);
845
- }
846
- url.searchParams.set("response_type", "code");
847
- url.searchParams.set("redirect_uri", redirectUri);
848
- url.searchParams.set("scope", SCOPES);
849
- url.searchParams.set("resource", RESOURCE);
850
- url.searchParams.set("state", state);
851
- url.searchParams.set("nonce", nonce);
852
- url.searchParams.set("code_challenge_method", "S256");
853
- url.searchParams.set("code_challenge", challenge);
854
- const callback = await acquireCallback(url.toString(), state, listener, callbacks);
855
- if (callback.get("error")) {
856
- if (callback.get("error") === "access_denied") throw new ChatGPTPlanNotEnabledError();
857
- throw new Error(
858
- `ChatGPT sign-in failed: ${callback.get("error_description") ?? callback.get("error")}`
859
- );
860
- }
861
- const code = callback.get("code");
862
- if (!code) throw new Error("ChatGPT sign-in returned no authorization code.");
863
- const issued = callback.get("client_id") ?? void 0;
864
- if (registration && issued && issued !== registration.clientId) {
865
- throw new Error("ChatGPT returned a different app registration. Start the sign-in again.");
866
- }
867
- const clientId = registration?.clientId ?? issued;
868
- if (!clientId || clientId === REGISTRATION_CLIENT_ID) {
869
- throw new Error(
870
- "ChatGPT didn't finish registering GG Coder. Start the sign-in again, and paste the full callback URL if you're on another machine."
871
- );
872
- }
873
- const tokens = await exchangeCode({ code, verifier, clientId, redirectUri });
874
- const claims = await verifyIdToken(tokens.idToken, { clientId, nonce });
875
- const subject = String(claims.sub ?? "");
876
- if (!subject) throw new Error("ChatGPT ID token has no subject.");
877
- if (registration && registration.subject !== subject) {
878
- await import_promises3.default.unlink(registrationFile).catch(() => {
858
+ let issuedClientId;
859
+ const signIn = async (status) => {
860
+ if (signal?.aborted) throw cancelled();
861
+ const knownClientId = registration?.clientId ?? issuedClientId;
862
+ const { verifier, challenge } = await generatePKCE();
863
+ const state = import_node_crypto2.default.randomBytes(16).toString("hex");
864
+ const nonce = import_node_crypto2.default.randomBytes(16).toString("hex");
865
+ const listener = await startCallbackListener(state, Boolean(knownClientId));
866
+ try {
867
+ const redirectUri = `http://127.0.0.1:${listener.port}${CALLBACK_PATH}`;
868
+ const url = new URL(AUTHORIZE_URL);
869
+ url.searchParams.set("client_id", knownClientId ?? REGISTRATION_CLIENT_ID);
870
+ if (!knownClientId) url.searchParams.set("agent_name_hint", AGENT_NAME);
871
+ url.searchParams.set("ext_agent_host_id", hostId);
872
+ if (registration && options.previous?.idToken) {
873
+ url.searchParams.set("id_token_hint", options.previous.idToken);
874
+ }
875
+ url.searchParams.set("response_type", "code");
876
+ url.searchParams.set("redirect_uri", redirectUri);
877
+ url.searchParams.set("scope", SCOPES);
878
+ url.searchParams.set("resource", RESOURCE);
879
+ url.searchParams.set("state", state);
880
+ url.searchParams.set("nonce", nonce);
881
+ url.searchParams.set("code_challenge_method", "S256");
882
+ url.searchParams.set("code_challenge", challenge);
883
+ const callback = await acquireCallback(url.toString(), state, listener, callbacks, {
884
+ status,
885
+ signal
879
886
  });
880
- await revokeChatGPTSignIn({ refreshToken: tokens.refreshToken, clientId });
881
- throw new Error(
882
- "That was a different ChatGPT account. Continue with ChatGPT again to connect it."
887
+ const callbackAt = Date.now();
888
+ if (callback.get("error")) {
889
+ if (callback.get("error") === "access_denied") throw new ChatGPTPlanNotEnabledError();
890
+ throw new Error(
891
+ `ChatGPT sign-in failed: ${callback.get("error_description") ?? callback.get("error")}`
892
+ );
893
+ }
894
+ const code = callback.get("code");
895
+ if (!code) throw new Error("ChatGPT sign-in returned no authorization code.");
896
+ const issued = callback.get("client_id") ?? void 0;
897
+ if (knownClientId && issued && issued !== knownClientId) {
898
+ throw new Error("ChatGPT returned a different app registration. Start the sign-in again.");
899
+ }
900
+ const clientId = knownClientId ?? issued;
901
+ if (!clientId || clientId === REGISTRATION_CLIENT_ID) {
902
+ throw new Error(
903
+ "ChatGPT didn't finish registering GG Coder. Start the sign-in again, and paste the full callback URL if you're on another machine."
904
+ );
905
+ }
906
+ issuedClientId = clientId;
907
+ const tokens = await exchangeCode({ code, verifier, clientId, redirectUri, signal }).catch(
908
+ (err) => {
909
+ if (err instanceof ChatGPTSignInError) {
910
+ err.returning = Boolean(registration);
911
+ err.callbackToExchangeMs = Date.now() - callbackAt;
912
+ }
913
+ throw err;
914
+ }
883
915
  );
916
+ const claims = await verifyIdToken(tokens.idToken, { clientId, nonce });
917
+ const subject = String(claims.sub ?? "");
918
+ if (!subject) throw new Error("ChatGPT ID token has no subject.");
919
+ if (registration && registration.subject !== subject) {
920
+ await import_promises3.default.unlink(registrationFile).catch(() => {
921
+ });
922
+ await revokeChatGPTSignIn({ refreshToken: tokens.refreshToken, clientId });
923
+ throw new Error(
924
+ "That was a different ChatGPT account. Continue with ChatGPT again to connect it."
925
+ );
926
+ }
927
+ if (!tokens.scopes.includes(CHATGPT_PLAN_SCOPE)) {
928
+ await revokeChatGPTSignIn({ refreshToken: tokens.refreshToken, clientId });
929
+ throw new ChatGPTPlanNotEnabledError();
930
+ }
931
+ if (!registration) {
932
+ await writePrivateFile(registrationFile, JSON.stringify({ clientId, subject }));
933
+ }
934
+ return {
935
+ accessToken: tokens.accessToken,
936
+ refreshToken: tokens.refreshToken,
937
+ expiresAt: Date.now() + tokens.expiresIn * 1e3,
938
+ expiresIn: tokens.expiresIn,
939
+ accountId: subject,
940
+ clientId,
941
+ idToken: tokens.idToken,
942
+ scopes: tokens.scopes,
943
+ baseUrl: CHATGPT_PLAN_BASE_URL
944
+ };
945
+ } finally {
946
+ listener.close();
884
947
  }
885
- if (!tokens.scopes.includes(CHATGPT_PLAN_SCOPE)) {
886
- await revokeChatGPTSignIn({ refreshToken: tokens.refreshToken, clientId });
887
- throw new ChatGPTPlanNotEnabledError();
948
+ };
949
+ try {
950
+ try {
951
+ return await signIn("Waiting for ChatGPT sign-in in your browser...");
952
+ } catch (err) {
953
+ if (!(err instanceof ChatGPTSignInError) || err.reason !== "invalid_grant") throw err;
954
+ if (signal?.aborted) throw err;
888
955
  }
889
- if (!registration) {
890
- await writePrivateFile(registrationFile, JSON.stringify({ clientId, subject }));
956
+ try {
957
+ return await signIn(
958
+ "ChatGPT didn't accept that sign-in. Trying once more in your browser..."
959
+ );
960
+ } catch (err) {
961
+ if (err instanceof ChatGPTSignInError) err.retried = true;
962
+ throw err;
891
963
  }
892
- return {
893
- accessToken: tokens.accessToken,
894
- refreshToken: tokens.refreshToken,
895
- expiresAt: Date.now() + tokens.expiresIn * 1e3,
896
- expiresIn: tokens.expiresIn,
897
- accountId: subject,
898
- clientId,
899
- idToken: tokens.idToken,
900
- scopes: tokens.scopes,
901
- baseUrl: CHATGPT_PLAN_BASE_URL
902
- };
903
- } finally {
904
- listener.close();
964
+ } catch (err) {
965
+ if (signal?.aborted) throw cancelled();
966
+ throw err;
905
967
  }
906
968
  }
907
969
  async function fetchChatGPTPlanModels(accessToken, fetchFn = fetch) {
@@ -968,12 +1030,15 @@ async function startCallbackListener(expectedState, anyPort) {
968
1030
  });
969
1031
  return { port, result, close: () => server.close() };
970
1032
  }
971
- async function acquireCallback(authUrl, expectedState, listener, callbacks) {
1033
+ async function acquireCallback(authUrl, expectedState, listener, callbacks, options) {
972
1034
  callbacks.onOpenUrl(authUrl);
973
- callbacks.onStatus("Waiting for ChatGPT sign-in in your browser...");
1035
+ callbacks.onStatus(options.status);
974
1036
  const done = new AbortController();
1037
+ let onAbort;
975
1038
  try {
976
1039
  return await new Promise((resolve, reject) => {
1040
+ onAbort = () => reject(cancelled());
1041
+ options.signal?.addEventListener("abort", onAbort, { once: true });
977
1042
  let listenerFailed = false;
978
1043
  let pasteError;
979
1044
  const failIfExhausted = () => {
@@ -996,6 +1061,7 @@ async function acquireCallback(authUrl, expectedState, listener, callbacks) {
996
1061
  });
997
1062
  });
998
1063
  } finally {
1064
+ if (onAbort) options.signal?.removeEventListener("abort", onAbort);
999
1065
  done.abort();
1000
1066
  listener.close();
1001
1067
  }
@@ -1031,26 +1097,51 @@ async function promptForCallback(expectedState, callbacks, signal) {
1031
1097
  }
1032
1098
  throw new Error("No callback URL found in input.");
1033
1099
  }
1034
- async function postForm(url, form) {
1100
+ async function postForm(url, form, signal) {
1035
1101
  return fetch(url, {
1036
1102
  method: "POST",
1037
1103
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
1038
1104
  body: new URLSearchParams(form),
1039
- signal: oauthRequestSignal()
1105
+ signal: signal ? AbortSignal.any([oauthRequestSignal(), signal]) : oauthRequestSignal()
1040
1106
  });
1041
1107
  }
1108
+ function signInError(status, body) {
1109
+ let reason = "";
1110
+ let detail = "";
1111
+ try {
1112
+ const data = JSON.parse(body);
1113
+ if (typeof data.error === "string") {
1114
+ reason = data.error;
1115
+ } else if (data.error && typeof data.error === "object") {
1116
+ const nested = data.error;
1117
+ reason = String(nested.code ?? nested.type ?? "");
1118
+ if (typeof nested.message === "string") detail = nested.message;
1119
+ }
1120
+ if (typeof data.error_description === "string") detail = data.error_description;
1121
+ } catch {
1122
+ detail = body.replace(/\s+/g, " ").trim();
1123
+ }
1124
+ return new ChatGPTSignInError(
1125
+ /^[\w.-]{1,60}$/.test(reason) ? reason : "unknown_error",
1126
+ status,
1127
+ detail.slice(0, 300)
1128
+ );
1129
+ }
1042
1130
  async function exchangeCode(input) {
1043
- const response = await postForm(TOKEN_URL, {
1044
- grant_type: "authorization_code",
1045
- client_id: input.clientId,
1046
- code: input.code,
1047
- code_verifier: input.verifier,
1048
- redirect_uri: input.redirectUri,
1049
- resource: RESOURCE
1050
- });
1131
+ const response = await postForm(
1132
+ TOKEN_URL,
1133
+ {
1134
+ grant_type: "authorization_code",
1135
+ client_id: input.clientId,
1136
+ code: input.code,
1137
+ code_verifier: input.verifier,
1138
+ redirect_uri: input.redirectUri,
1139
+ resource: RESOURCE
1140
+ },
1141
+ input.signal
1142
+ );
1051
1143
  if (!response.ok) {
1052
- const text = await response.text().catch(() => "");
1053
- throw new Error(`ChatGPT token exchange failed (${response.status}): ${text.slice(0, 300)}`);
1144
+ throw signInError(response.status, await response.text().catch(() => ""));
1054
1145
  }
1055
1146
  const data = await response.json();
1056
1147
  if (!data.access_token || !data.refresh_token || !data.id_token) {
@@ -4863,6 +4954,7 @@ function createAutoUpdater(config) {
4863
4954
  CLAUDE_CODE_AUTH_MARKER,
4864
4955
  CLAUDE_CODE_MANIFEST,
4865
4956
  ChatGPTPlanNotEnabledError,
4957
+ ChatGPTSignInError,
4866
4958
  DEFAULT_LOCAL_ENDPOINTS,
4867
4959
  DEFAULT_MAX_VIDEO_BYTES,
4868
4960
  FALLBACK_CONTEXT_WINDOW,