@kenkaiiii/gg-core 5.98.1 → 5.99.0

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.
@@ -596,6 +596,29 @@ var ChatGPTPlanNotEnabledError = class extends Error {
596
596
  this.name = "ChatGPTPlanNotEnabledError";
597
597
  }
598
598
  };
599
+ var ChatGPTSignInError = class extends Error {
600
+ reason;
601
+ status;
602
+ detail;
603
+ /** Whether a saved app registration was used, rather than a first registration. */
604
+ returning = false;
605
+ /** Whether this was the second refusal, after the one automatic retry. */
606
+ retried = false;
607
+ /** Milliseconds from the browser callback to the token endpoint's answer. */
608
+ callbackToExchangeMs;
609
+ constructor(reason, status, detail = "") {
610
+ super(`ChatGPT token exchange failed (${status}): ${reason}`);
611
+ this.name = "ChatGPTSignInError";
612
+ this.reason = reason;
613
+ this.status = status;
614
+ this.detail = detail;
615
+ }
616
+ };
617
+ function cancelled() {
618
+ const err = new Error("ChatGPT sign-in was cancelled.");
619
+ err.name = "AbortError";
620
+ return err;
621
+ }
599
622
  function defaultHostIdFile() {
600
623
  return path2.join(getAppPaths().agentDir, "openai-host-id");
601
624
  }
@@ -632,81 +655,119 @@ async function readRegistration(file) {
632
655
  return void 0;
633
656
  }
634
657
  async function loginChatGPT(callbacks, options = {}) {
658
+ const { signal } = options;
635
659
  const hostId = await getChatGPTHostId(options.hostIdFile);
636
660
  const registrationFile = options.registrationFile ?? defaultRegistrationFile();
637
661
  const registration = await readRegistration(registrationFile);
638
- const { verifier, challenge } = await generatePKCE();
639
- const state = crypto3.randomBytes(16).toString("hex");
640
- const nonce = crypto3.randomBytes(16).toString("hex");
641
- const listener = await startCallbackListener(state, Boolean(registration));
642
- try {
643
- const redirectUri = `http://127.0.0.1:${listener.port}${CALLBACK_PATH}`;
644
- const url = new URL(AUTHORIZE_URL);
645
- url.searchParams.set("client_id", registration?.clientId ?? REGISTRATION_CLIENT_ID);
646
- if (!registration) url.searchParams.set("agent_name_hint", AGENT_NAME);
647
- url.searchParams.set("ext_agent_host_id", hostId);
648
- if (registration && options.previous?.idToken) {
649
- url.searchParams.set("id_token_hint", options.previous.idToken);
650
- }
651
- url.searchParams.set("response_type", "code");
652
- url.searchParams.set("redirect_uri", redirectUri);
653
- url.searchParams.set("scope", SCOPES);
654
- url.searchParams.set("resource", RESOURCE);
655
- url.searchParams.set("state", state);
656
- url.searchParams.set("nonce", nonce);
657
- url.searchParams.set("code_challenge_method", "S256");
658
- url.searchParams.set("code_challenge", challenge);
659
- const callback = await acquireCallback(url.toString(), state, listener, callbacks);
660
- if (callback.get("error")) {
661
- if (callback.get("error") === "access_denied") throw new ChatGPTPlanNotEnabledError();
662
- throw new Error(
663
- `ChatGPT sign-in failed: ${callback.get("error_description") ?? callback.get("error")}`
664
- );
665
- }
666
- const code = callback.get("code");
667
- if (!code) throw new Error("ChatGPT sign-in returned no authorization code.");
668
- const issued = callback.get("client_id") ?? void 0;
669
- if (registration && issued && issued !== registration.clientId) {
670
- throw new Error("ChatGPT returned a different app registration. Start the sign-in again.");
671
- }
672
- const clientId = registration?.clientId ?? issued;
673
- if (!clientId || clientId === REGISTRATION_CLIENT_ID) {
674
- throw new Error(
675
- "ChatGPT didn't finish registering GG Coder. Start the sign-in again, and paste the full callback URL if you're on another machine."
676
- );
677
- }
678
- const tokens = await exchangeCode({ code, verifier, clientId, redirectUri });
679
- const claims = await verifyIdToken(tokens.idToken, { clientId, nonce });
680
- const subject = String(claims.sub ?? "");
681
- if (!subject) throw new Error("ChatGPT ID token has no subject.");
682
- if (registration && registration.subject !== subject) {
683
- await fs3.unlink(registrationFile).catch(() => {
662
+ let issuedClientId;
663
+ const signIn = async (status) => {
664
+ if (signal?.aborted) throw cancelled();
665
+ const knownClientId = registration?.clientId ?? issuedClientId;
666
+ const { verifier, challenge } = await generatePKCE();
667
+ const state = crypto3.randomBytes(16).toString("hex");
668
+ const nonce = crypto3.randomBytes(16).toString("hex");
669
+ const listener = await startCallbackListener(state, Boolean(knownClientId));
670
+ try {
671
+ const redirectUri = `http://127.0.0.1:${listener.port}${CALLBACK_PATH}`;
672
+ const url = new URL(AUTHORIZE_URL);
673
+ url.searchParams.set("client_id", knownClientId ?? REGISTRATION_CLIENT_ID);
674
+ if (!knownClientId) url.searchParams.set("agent_name_hint", AGENT_NAME);
675
+ url.searchParams.set("ext_agent_host_id", hostId);
676
+ if (registration && options.previous?.idToken) {
677
+ url.searchParams.set("id_token_hint", options.previous.idToken);
678
+ }
679
+ url.searchParams.set("response_type", "code");
680
+ url.searchParams.set("redirect_uri", redirectUri);
681
+ url.searchParams.set("scope", SCOPES);
682
+ url.searchParams.set("resource", RESOURCE);
683
+ url.searchParams.set("state", state);
684
+ url.searchParams.set("nonce", nonce);
685
+ url.searchParams.set("code_challenge_method", "S256");
686
+ url.searchParams.set("code_challenge", challenge);
687
+ const callback = await acquireCallback(url.toString(), state, listener, callbacks, {
688
+ status,
689
+ signal
684
690
  });
685
- await revokeChatGPTSignIn({ refreshToken: tokens.refreshToken, clientId });
686
- throw new Error(
687
- "That was a different ChatGPT account. Continue with ChatGPT again to connect it."
691
+ const callbackAt = Date.now();
692
+ if (callback.get("error")) {
693
+ if (callback.get("error") === "access_denied") throw new ChatGPTPlanNotEnabledError();
694
+ throw new Error(
695
+ `ChatGPT sign-in failed: ${callback.get("error_description") ?? callback.get("error")}`
696
+ );
697
+ }
698
+ const code = callback.get("code");
699
+ if (!code) throw new Error("ChatGPT sign-in returned no authorization code.");
700
+ const issued = callback.get("client_id") ?? void 0;
701
+ if (knownClientId && issued && issued !== knownClientId) {
702
+ throw new Error("ChatGPT returned a different app registration. Start the sign-in again.");
703
+ }
704
+ const clientId = knownClientId ?? issued;
705
+ if (!clientId || clientId === REGISTRATION_CLIENT_ID) {
706
+ throw new Error(
707
+ "ChatGPT didn't finish registering GG Coder. Start the sign-in again, and paste the full callback URL if you're on another machine."
708
+ );
709
+ }
710
+ issuedClientId = clientId;
711
+ const tokens = await exchangeCode({ code, verifier, clientId, redirectUri, signal }).catch(
712
+ (err) => {
713
+ if (err instanceof ChatGPTSignInError) {
714
+ err.returning = Boolean(registration);
715
+ err.callbackToExchangeMs = Date.now() - callbackAt;
716
+ }
717
+ throw err;
718
+ }
688
719
  );
720
+ const claims = await verifyIdToken(tokens.idToken, { clientId, nonce });
721
+ const subject = String(claims.sub ?? "");
722
+ if (!subject) throw new Error("ChatGPT ID token has no subject.");
723
+ if (registration && registration.subject !== subject) {
724
+ await fs3.unlink(registrationFile).catch(() => {
725
+ });
726
+ await revokeChatGPTSignIn({ refreshToken: tokens.refreshToken, clientId });
727
+ throw new Error(
728
+ "That was a different ChatGPT account. Continue with ChatGPT again to connect it."
729
+ );
730
+ }
731
+ if (!tokens.scopes.includes(CHATGPT_PLAN_SCOPE)) {
732
+ await revokeChatGPTSignIn({ refreshToken: tokens.refreshToken, clientId });
733
+ throw new ChatGPTPlanNotEnabledError();
734
+ }
735
+ if (!registration) {
736
+ await writePrivateFile(registrationFile, JSON.stringify({ clientId, subject }));
737
+ }
738
+ return {
739
+ accessToken: tokens.accessToken,
740
+ refreshToken: tokens.refreshToken,
741
+ expiresAt: Date.now() + tokens.expiresIn * 1e3,
742
+ expiresIn: tokens.expiresIn,
743
+ accountId: subject,
744
+ clientId,
745
+ idToken: tokens.idToken,
746
+ scopes: tokens.scopes,
747
+ baseUrl: CHATGPT_PLAN_BASE_URL
748
+ };
749
+ } finally {
750
+ listener.close();
689
751
  }
690
- if (!tokens.scopes.includes(CHATGPT_PLAN_SCOPE)) {
691
- await revokeChatGPTSignIn({ refreshToken: tokens.refreshToken, clientId });
692
- throw new ChatGPTPlanNotEnabledError();
752
+ };
753
+ try {
754
+ try {
755
+ return await signIn("Waiting for ChatGPT sign-in in your browser...");
756
+ } catch (err) {
757
+ if (!(err instanceof ChatGPTSignInError) || err.reason !== "invalid_grant") throw err;
758
+ if (signal?.aborted) throw err;
693
759
  }
694
- if (!registration) {
695
- await writePrivateFile(registrationFile, JSON.stringify({ clientId, subject }));
760
+ try {
761
+ return await signIn(
762
+ "ChatGPT didn't accept that sign-in. Trying once more in your browser..."
763
+ );
764
+ } catch (err) {
765
+ if (err instanceof ChatGPTSignInError) err.retried = true;
766
+ throw err;
696
767
  }
697
- return {
698
- accessToken: tokens.accessToken,
699
- refreshToken: tokens.refreshToken,
700
- expiresAt: Date.now() + tokens.expiresIn * 1e3,
701
- expiresIn: tokens.expiresIn,
702
- accountId: subject,
703
- clientId,
704
- idToken: tokens.idToken,
705
- scopes: tokens.scopes,
706
- baseUrl: CHATGPT_PLAN_BASE_URL
707
- };
708
- } finally {
709
- listener.close();
768
+ } catch (err) {
769
+ if (signal?.aborted) throw cancelled();
770
+ throw err;
710
771
  }
711
772
  }
712
773
  async function fetchChatGPTPlanModels(accessToken, fetchFn = fetch) {
@@ -773,12 +834,15 @@ async function startCallbackListener(expectedState, anyPort) {
773
834
  });
774
835
  return { port, result, close: () => server.close() };
775
836
  }
776
- async function acquireCallback(authUrl, expectedState, listener, callbacks) {
837
+ async function acquireCallback(authUrl, expectedState, listener, callbacks, options) {
777
838
  callbacks.onOpenUrl(authUrl);
778
- callbacks.onStatus("Waiting for ChatGPT sign-in in your browser...");
839
+ callbacks.onStatus(options.status);
779
840
  const done = new AbortController();
841
+ let onAbort;
780
842
  try {
781
843
  return await new Promise((resolve, reject) => {
844
+ onAbort = () => reject(cancelled());
845
+ options.signal?.addEventListener("abort", onAbort, { once: true });
782
846
  let listenerFailed = false;
783
847
  let pasteError;
784
848
  const failIfExhausted = () => {
@@ -801,6 +865,7 @@ async function acquireCallback(authUrl, expectedState, listener, callbacks) {
801
865
  });
802
866
  });
803
867
  } finally {
868
+ if (onAbort) options.signal?.removeEventListener("abort", onAbort);
804
869
  done.abort();
805
870
  listener.close();
806
871
  }
@@ -836,26 +901,51 @@ async function promptForCallback(expectedState, callbacks, signal) {
836
901
  }
837
902
  throw new Error("No callback URL found in input.");
838
903
  }
839
- async function postForm(url, form) {
904
+ async function postForm(url, form, signal) {
840
905
  return fetch(url, {
841
906
  method: "POST",
842
907
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
843
908
  body: new URLSearchParams(form),
844
- signal: oauthRequestSignal()
909
+ signal: signal ? AbortSignal.any([oauthRequestSignal(), signal]) : oauthRequestSignal()
845
910
  });
846
911
  }
912
+ function signInError(status, body) {
913
+ let reason = "";
914
+ let detail = "";
915
+ try {
916
+ const data = JSON.parse(body);
917
+ if (typeof data.error === "string") {
918
+ reason = data.error;
919
+ } else if (data.error && typeof data.error === "object") {
920
+ const nested = data.error;
921
+ reason = String(nested.code ?? nested.type ?? "");
922
+ if (typeof nested.message === "string") detail = nested.message;
923
+ }
924
+ if (typeof data.error_description === "string") detail = data.error_description;
925
+ } catch {
926
+ detail = body.replace(/\s+/g, " ").trim();
927
+ }
928
+ return new ChatGPTSignInError(
929
+ /^[\w.-]{1,60}$/.test(reason) ? reason : "unknown_error",
930
+ status,
931
+ detail.slice(0, 300)
932
+ );
933
+ }
847
934
  async function exchangeCode(input) {
848
- const response = await postForm(TOKEN_URL, {
849
- grant_type: "authorization_code",
850
- client_id: input.clientId,
851
- code: input.code,
852
- code_verifier: input.verifier,
853
- redirect_uri: input.redirectUri,
854
- resource: RESOURCE
855
- });
935
+ const response = await postForm(
936
+ TOKEN_URL,
937
+ {
938
+ grant_type: "authorization_code",
939
+ client_id: input.clientId,
940
+ code: input.code,
941
+ code_verifier: input.verifier,
942
+ redirect_uri: input.redirectUri,
943
+ resource: RESOURCE
944
+ },
945
+ input.signal
946
+ );
856
947
  if (!response.ok) {
857
- const text = await response.text().catch(() => "");
858
- throw new Error(`ChatGPT token exchange failed (${response.status}): ${text.slice(0, 300)}`);
948
+ throw signInError(response.status, await response.text().catch(() => ""));
859
949
  }
860
950
  const data = await response.json();
861
951
  if (!data.access_token || !data.refresh_token || !data.id_token) {
@@ -3104,6 +3194,7 @@ export {
3104
3194
  CHATGPT_USAGE_URL,
3105
3195
  CHATGPT_PLAN_NOT_ENABLED_MESSAGE,
3106
3196
  ChatGPTPlanNotEnabledError,
3197
+ ChatGPTSignInError,
3107
3198
  getChatGPTHostId,
3108
3199
  loginChatGPT,
3109
3200
  fetchChatGPTPlanModels,
@@ -3164,4 +3255,4 @@ export {
3164
3255
  getDefaultThinkingLevel,
3165
3256
  getSummaryModel
3166
3257
  };
3167
- //# sourceMappingURL=chunk-Q6ZD2VQV.js.map
3258
+ //# sourceMappingURL=chunk-E76ARVZJ.js.map