@frogbotai/piece-openai 0.0.0-stage → 0.39.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -2
  3. package/dist/chatgpt/constants.d.ts +22 -0
  4. package/dist/chatgpt/constants.d.ts.map +1 -0
  5. package/dist/chatgpt/constants.js +17 -0
  6. package/dist/chatgpt/constants.js.map +1 -0
  7. package/dist/chatgpt/fetch.d.ts +5 -0
  8. package/dist/chatgpt/fetch.d.ts.map +1 -0
  9. package/dist/chatgpt/fetch.js +19 -0
  10. package/dist/chatgpt/fetch.js.map +1 -0
  11. package/dist/chatgpt/index.d.ts +37 -0
  12. package/dist/chatgpt/index.d.ts.map +1 -0
  13. package/dist/chatgpt/index.js +40 -0
  14. package/dist/chatgpt/index.js.map +1 -0
  15. package/dist/chatgpt/middleware.d.ts +22 -0
  16. package/dist/chatgpt/middleware.d.ts.map +1 -0
  17. package/dist/chatgpt/middleware.js +326 -0
  18. package/dist/chatgpt/middleware.js.map +1 -0
  19. package/dist/chatgpt/models.d.ts +11 -0
  20. package/dist/chatgpt/models.d.ts.map +1 -0
  21. package/dist/chatgpt/models.js +49 -0
  22. package/dist/chatgpt/models.js.map +1 -0
  23. package/dist/chatgpt/page.d.ts +11 -0
  24. package/dist/chatgpt/page.d.ts.map +1 -0
  25. package/dist/chatgpt/page.js +40 -0
  26. package/dist/chatgpt/page.js.map +1 -0
  27. package/dist/chatgpt/provider.d.ts +19 -0
  28. package/dist/chatgpt/provider.d.ts.map +1 -0
  29. package/dist/chatgpt/provider.js +31 -0
  30. package/dist/chatgpt/provider.js.map +1 -0
  31. package/dist/chatgpt/signIn.d.ts +12 -0
  32. package/dist/chatgpt/signIn.d.ts.map +1 -0
  33. package/dist/chatgpt/signIn.js +185 -0
  34. package/dist/chatgpt/signIn.js.map +1 -0
  35. package/dist/chatgpt/tokens.d.ts +41 -0
  36. package/dist/chatgpt/tokens.d.ts.map +1 -0
  37. package/dist/chatgpt/tokens.js +93 -0
  38. package/dist/chatgpt/tokens.js.map +1 -0
  39. package/dist/config.d.ts +18 -0
  40. package/dist/config.d.ts.map +1 -0
  41. package/dist/config.js +18 -0
  42. package/dist/config.js.map +1 -0
  43. package/dist/icon.d.ts +3 -0
  44. package/dist/icon.d.ts.map +1 -0
  45. package/dist/icon.js +3 -0
  46. package/dist/icon.js.map +1 -0
  47. package/dist/index.d.ts +86 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +50 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/models.d.ts +14 -0
  52. package/dist/models.d.ts.map +1 -0
  53. package/dist/models.js +44 -0
  54. package/dist/models.js.map +1 -0
  55. package/package.json +44 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FrogBot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # `@frogbotai/piece-openai`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenAI as a linked account: each user runs FrogBot's AI on their own OpenAI API key or ChatGPT plan.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import { createOpenAI } from '@frogbotai/piece-openai';
9
+ import { buildConfig } from 'frogbot';
10
+
11
+ export default buildConfig({
12
+ // secret, db, and collections omitted
13
+ connections: [{ piece: createOpenAI(), oauth: true, secret: true }],
14
+ });
15
+ ```
16
+
17
+ Users paste a key in **Settings → Linked accounts**, or choose **Continue with ChatGPT** to run on their ChatGPT plan when the app runs on their own computer. FrogBot checks a pasted key with one `GET /v1/models` call before saving it. See [OpenAI](https://docs.frogbot.ai/pieces/openai) for the credential order, the ChatGPT sign-in and the app key.
@@ -0,0 +1,22 @@
1
+ /** OpenAI's sign-in for ChatGPT plan use, as OpenCode and OpenAI's open-source guide set it up. */
2
+ export declare const ISSUER = "https://auth.openai.com";
3
+ export declare const AUTHORIZE_URL = "https://auth.openai.com/api/accounts/authorize";
4
+ export declare const TOKEN_URL = "https://auth.openai.com/api/accounts/oauth/token";
5
+ export declare const JWKS_URL = "https://auth.openai.com/.well-known/jwks.json";
6
+ export declare const DISCOVERY_URL = "https://auth.openai.com/.well-known/openid-configuration";
7
+ /** The API base a plan token is sent to, and the `resource` it is issued for. */
8
+ export declare const RESOURCE = "https://api.openai.com/v1";
9
+ /** The first sign-in registers a client for the user; the callback returns its issued ID. */
10
+ export declare const REGISTRATION_CLIENT_ID = "dynamic_agent_client";
11
+ export declare const AGENT_NAME = "FrogBot";
12
+ export declare const PLAN_SCOPE = "chatgpt.tokens.use.direct";
13
+ export declare const SCOPE = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";
14
+ export declare const USAGE_URL = "https://chatgpt.com/settings/usage";
15
+ /** This install's `ext_agent_host_id`, made once. */
16
+ export declare const HOST_KEY = "openai:chatgpt:host";
17
+ /** The issued client ID of a user's registration, kept across Disconnect. */
18
+ export declare function clientKey(user: {
19
+ collection: string;
20
+ id: number | string;
21
+ }): string;
22
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/chatgpt/constants.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,eAAO,MAAM,MAAM,4BAA4B,CAAC;AAChD,eAAO,MAAM,aAAa,mDAAqC,CAAC;AAChE,eAAO,MAAM,SAAS,qDAAuC,CAAC;AAC9D,eAAO,MAAM,QAAQ,kDAAoC,CAAC;AAC1D,eAAO,MAAM,aAAa,6DAA+C,CAAC;AAE1E,iFAAiF;AACjF,eAAO,MAAM,QAAQ,8BAA8B,CAAC;AAEpD,6FAA6F;AAC7F,eAAO,MAAM,sBAAsB,yBAAyB,CAAC;AAC7D,eAAO,MAAM,UAAU,YAAY,CAAC;AAEpC,eAAO,MAAM,UAAU,8BAA8B,CAAC;AACtD,eAAO,MAAM,KAAK,kFAAsE,CAAC;AAEzF,eAAO,MAAM,SAAS,uCAAuC,CAAC;AAE9D,qDAAqD;AACrD,eAAO,MAAM,QAAQ,wBAAwB,CAAC;AAE9C,6EAA6E;AAC7E,wBAAgB,SAAS,CAAC,IAAI,EAAE;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,GAAG,MAAM,CAEnF"}
@@ -0,0 +1,17 @@
1
+ /** OpenAI's sign-in for ChatGPT plan use, as OpenCode and OpenAI's open-source guide set it up. */ export const ISSUER = 'https://auth.openai.com';
2
+ export const AUTHORIZE_URL = `${ISSUER}/api/accounts/authorize`;
3
+ export const TOKEN_URL = `${ISSUER}/api/accounts/oauth/token`;
4
+ export const JWKS_URL = `${ISSUER}/.well-known/jwks.json`;
5
+ export const DISCOVERY_URL = `${ISSUER}/.well-known/openid-configuration`;
6
+ /** The API base a plan token is sent to, and the `resource` it is issued for. */ export const RESOURCE = 'https://api.openai.com/v1';
7
+ /** The first sign-in registers a client for the user; the callback returns its issued ID. */ export const REGISTRATION_CLIENT_ID = 'dynamic_agent_client';
8
+ export const AGENT_NAME = 'FrogBot';
9
+ export const PLAN_SCOPE = 'chatgpt.tokens.use.direct';
10
+ export const SCOPE = `openid profile email offline_access resource.invoke ${PLAN_SCOPE}`;
11
+ export const USAGE_URL = 'https://chatgpt.com/settings/usage';
12
+ /** This install's `ext_agent_host_id`, made once. */ export const HOST_KEY = 'openai:chatgpt:host';
13
+ /** The issued client ID of a user's registration, kept across Disconnect. */ export function clientKey(user) {
14
+ return `openai:chatgpt:client:${user.collection}:${user.id}`;
15
+ }
16
+
17
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/chatgpt/constants.ts"],"names":["ISSUER","AUTHORIZE_URL","TOKEN_URL","JWKS_URL","DISCOVERY_URL","RESOURCE","REGISTRATION_CLIENT_ID","AGENT_NAME","PLAN_SCOPE","SCOPE","USAGE_URL","HOST_KEY","clientKey","user","collection","id"],"mappings":"AAAA,iGAAiG,GACjG,OAAO,MAAMA,SAAS,0BAA0B;AAChD,OAAO,MAAMC,gBAAgB,GAAGD,OAAO,uBAAuB,CAAC,CAAC;AAChE,OAAO,MAAME,YAAY,GAAGF,OAAO,yBAAyB,CAAC,CAAC;AAC9D,OAAO,MAAMG,WAAW,GAAGH,OAAO,sBAAsB,CAAC,CAAC;AAC1D,OAAO,MAAMI,gBAAgB,GAAGJ,OAAO,iCAAiC,CAAC,CAAC;AAE1E,+EAA+E,GAC/E,OAAO,MAAMK,WAAW,4BAA4B;AAEpD,2FAA2F,GAC3F,OAAO,MAAMC,yBAAyB,uBAAuB;AAC7D,OAAO,MAAMC,aAAa,UAAU;AAEpC,OAAO,MAAMC,aAAa,4BAA4B;AACtD,OAAO,MAAMC,QAAQ,CAAC,oDAAoD,EAAED,YAAY,CAAC;AAEzF,OAAO,MAAME,YAAY,qCAAqC;AAE9D,mDAAmD,GACnD,OAAO,MAAMC,WAAW,sBAAsB;AAE9C,2EAA2E,GAC3E,OAAO,SAASC,UAAUC,IAAiD;IACzE,OAAO,CAAC,sBAAsB,EAAEA,KAAKC,UAAU,CAAC,CAAC,EAAED,KAAKE,EAAE,EAAE;AAC9D","file":"constants.js"}
@@ -0,0 +1,5 @@
1
+ /** Request bodies above this size are sent zstd-compressed, as OpenCode does on a plan. */
2
+ export declare const COMPRESS_ABOVE_BYTES: number;
3
+ /** `fetch` for plan calls: compresses large JSON bodies with zstd. */
4
+ export declare function chatgptFetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
5
+ //# sourceMappingURL=fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/chatgpt/fetch.ts"],"names":[],"mappings":"AAKA,2FAA2F;AAC3F,eAAO,MAAM,oBAAoB,QAAc,CAAC;AAEhD,sEAAsE;AACtE,wBAAsB,YAAY,CAChC,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,EAC7B,IAAI,CAAC,EAAE,WAAW,GACjB,OAAO,CAAC,QAAQ,CAAC,CAYnB"}
@@ -0,0 +1,19 @@
1
+ import { promisify } from 'node:util';
2
+ import { zstdCompress } from 'node:zlib';
3
+ const compress = promisify(zstdCompress);
4
+ /** Request bodies above this size are sent zstd-compressed, as OpenCode does on a plan. */ export const COMPRESS_ABOVE_BYTES = 1024 * 1024;
5
+ /** `fetch` for plan calls: compresses large JSON bodies with zstd. */ export async function chatgptFetch(input, init) {
6
+ const body = init?.body;
7
+ if (typeof body !== 'string' || Buffer.byteLength(body) <= COMPRESS_ABOVE_BYTES) {
8
+ return fetch(input, init);
9
+ }
10
+ const headers = new Headers(init?.headers);
11
+ headers.set('content-encoding', 'zstd');
12
+ return fetch(input, {
13
+ ...init,
14
+ headers,
15
+ body: new Uint8Array(await compress(body))
16
+ });
17
+ }
18
+
19
+ //# sourceMappingURL=fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/chatgpt/fetch.ts"],"names":["promisify","zstdCompress","compress","COMPRESS_ABOVE_BYTES","chatgptFetch","input","init","body","Buffer","byteLength","fetch","headers","Headers","set","Uint8Array"],"mappings":"AAAA,SAASA,SAAS,QAAQ,YAAY;AACtC,SAASC,YAAY,QAAQ,YAAY;AAEzC,MAAMC,WAAWF,UAAUC;AAE3B,yFAAyF,GACzF,OAAO,MAAME,uBAAuB,OAAO,KAAK;AAEhD,oEAAoE,GACpE,OAAO,eAAeC,aACpBC,KAA6B,EAC7BC,IAAkB;IAElB,MAAMC,OAAOD,MAAMC;IAEnB,IAAI,OAAOA,SAAS,YAAYC,OAAOC,UAAU,CAACF,SAASJ,sBAAsB;QAC/E,OAAOO,MAAML,OAAOC;IACtB;IAEA,MAAMK,UAAU,IAAIC,QAAQN,MAAMK;IAElCA,QAAQE,GAAG,CAAC,oBAAoB;IAEhC,OAAOH,MAAML,OAAO;QAAE,GAAGC,IAAI;QAAEK;QAASJ,MAAM,IAAIO,WAAW,MAAMZ,SAASK;IAAO;AACrF","file":"fetch.js"}
@@ -0,0 +1,37 @@
1
+ import type { OAuthTokens } from 'frogbot/pieces';
2
+ import { authorizeChatGPT } from './signIn.js';
3
+ /** "Continue with ChatGPT": OpenAI's sign-in for running AI on the user's ChatGPT plan. */
4
+ export declare const chatgptSignIn: {
5
+ label: string;
6
+ scopes: {
7
+ catalog: {
8
+ plan: string;
9
+ };
10
+ defaults: never[];
11
+ required: "plan"[];
12
+ };
13
+ auth: import("zod").ZodObject<{
14
+ apiKey: import("zod").ZodString;
15
+ chatgpt: import("zod").ZodObject<{
16
+ clientId: import("zod").ZodString;
17
+ }, import("zod/v4/core").$strip>;
18
+ }, import("zod/v4/core").$strip>;
19
+ toAuth: ({ tokens }: {
20
+ tokens: OAuthTokens;
21
+ }) => {
22
+ apiKey: string;
23
+ chatgpt: {
24
+ clientId: string;
25
+ };
26
+ };
27
+ authorize: typeof authorizeChatGPT;
28
+ refresh: ({ tokens }: {
29
+ tokens: OAuthTokens;
30
+ req: import("frogbot/pieces").FrogBotRequest;
31
+ }) => Promise<OAuthTokens>;
32
+ revoke: ({ tokens }: {
33
+ tokens: OAuthTokens;
34
+ req: import("frogbot/pieces").FrogBotRequest;
35
+ }) => Promise<void>;
36
+ };
37
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/chatgpt/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAoB,MAAM,gBAAgB,CAAC;AAIpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAa/C,2FAA2F;AAC3F,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAWuB,CAAC"}
@@ -0,0 +1,40 @@
1
+ import { chatgptAuth } from '../config.js';
2
+ import { PLAN_SCOPE } from './constants.js';
3
+ import { authorizeChatGPT } from './signIn.js';
4
+ import { refreshTokens, revokeRefreshToken } from './tokens.js';
5
+ function stored(tokens) {
6
+ const { refresh_token: refreshToken, client_id: clientId } = tokens;
7
+ if (typeof refreshToken !== 'string' || typeof clientId !== 'string' || !clientId) {
8
+ throw new Error('This ChatGPT account has no refresh token or client ID. Reconnect it.');
9
+ }
10
+ return {
11
+ refreshToken,
12
+ clientId
13
+ };
14
+ }
15
+ /** "Continue with ChatGPT": OpenAI's sign-in for running AI on the user's ChatGPT plan. */ export const chatgptSignIn = {
16
+ label: 'ChatGPT',
17
+ scopes: {
18
+ catalog: {
19
+ plan: PLAN_SCOPE
20
+ },
21
+ defaults: [],
22
+ required: [
23
+ 'plan'
24
+ ]
25
+ },
26
+ auth: chatgptAuth,
27
+ toAuth: ({ tokens })=>({
28
+ apiKey: tokens.access_token ?? '',
29
+ chatgpt: {
30
+ clientId: typeof tokens.client_id === 'string' ? tokens.client_id : ''
31
+ }
32
+ }),
33
+ authorize: authorizeChatGPT,
34
+ refresh: async ({ tokens })=>({
35
+ ...await refreshTokens(stored(tokens))
36
+ }),
37
+ revoke: ({ tokens })=>revokeRefreshToken(stored(tokens))
38
+ };
39
+
40
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/chatgpt/index.ts"],"names":["chatgptAuth","PLAN_SCOPE","authorizeChatGPT","refreshTokens","revokeRefreshToken","stored","tokens","refresh_token","refreshToken","client_id","clientId","Error","chatgptSignIn","label","scopes","catalog","plan","defaults","required","auth","toAuth","apiKey","access_token","chatgpt","authorize","refresh","revoke"],"mappings":"AAEA,SAA2BA,WAAW,QAAQ,eAAe;AAC7D,SAASC,UAAU,QAAQ,iBAAiB;AAC5C,SAASC,gBAAgB,QAAQ,cAAc;AAC/C,SAASC,aAAa,EAAEC,kBAAkB,QAAQ,cAAc;AAEhE,SAASC,OAAOC,MAAmB;IACjC,MAAM,EAAEC,eAAeC,YAAY,EAAEC,WAAWC,QAAQ,EAAE,GAAGJ;IAE7D,IAAI,OAAOE,iBAAiB,YAAY,OAAOE,aAAa,YAAY,CAACA,UAAU;QACjF,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QAAEH;QAAcE;IAAS;AAClC;AAEA,yFAAyF,GACzF,OAAO,MAAME,gBAAgB;IAC3BC,OAAO;IACPC,QAAQ;QAAEC,SAAS;YAAEC,MAAMf;QAAW;QAAGgB,UAAU,EAAE;QAAEC,UAAU;YAAC;SAAO;IAAC;IAC1EC,MAAMnB;IACNoB,QAAQ,CAAC,EAAEd,MAAM,EAAE,GAAM,CAAA;YACvBe,QAAQf,OAAOgB,YAAY,IAAI;YAC/BC,SAAS;gBAAEb,UAAU,OAAOJ,OAAOG,SAAS,KAAK,WAAWH,OAAOG,SAAS,GAAG;YAAG;QACpF,CAAA;IACAe,WAAWtB;IACXuB,SAAS,OAAO,EAAEnB,MAAM,EAAE,GAAM,CAAA;YAAE,GAAI,MAAMH,cAAcE,OAAOC,QAAQ;QAAE,CAAA;IAC3EoB,QAAQ,CAAC,EAAEpB,MAAM,EAAE,GAAKF,mBAAmBC,OAAOC;AACpD,EAAkD","file":"index.js"}
@@ -0,0 +1,22 @@
1
+ import type { LanguageModelV4CallOptions, LanguageModelV4Middleware } from '@ai-sdk/provider';
2
+ import { GatewayError } from '@frogbotai/gateway/errors';
3
+ /**
4
+ * The error a plan call shows: OpenAI's plan codes, matched in the body or stream error as
5
+ * OpenCode does, and a bare 401. `undefined` leaves the error as it is.
6
+ */
7
+ export declare function planError(error: unknown): GatewayError | undefined;
8
+ /** Call options the plan route takes: no store, developer system text, no rejected fields. */
9
+ export declare function planParams(params: LanguageModelV4CallOptions): LanguageModelV4CallOptions;
10
+ /**
11
+ * The middleware for language models on a ChatGPT plan. It reshapes each call for the plan route,
12
+ * always streams (building non-streamed calls from the stream), and turns OpenAI's plan errors
13
+ * into messages: the seven refusal codes fail at once, the two busy codes retry after each delay
14
+ * while no output has arrived. That includes a busy error OpenAI sends after
15
+ * `response.in_progress`, past the SDK's own early-error check, so each stream is read up to its
16
+ * first output part before it is returned.
17
+ */
18
+ export declare function createChatGPTMiddleware({ retryDelays, }?: {
19
+ retryDelays?: readonly number[];
20
+ }): LanguageModelV4Middleware;
21
+ export declare const chatgptMiddleware: LanguageModelV4Middleware;
22
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/chatgpt/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAG1B,yBAAyB,EAI1B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAyEzD;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,GAAG,SAAS,CAIlE;AAED,8FAA8F;AAC9F,wBAAgB,UAAU,CAAC,MAAM,EAAE,0BAA0B,GAAG,0BAA0B,CAwCzF;AAmLD;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,EACtC,WAA0B,GAC3B,GAAE;IAAE,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAO,GAAG,yBAAyB,CA0BtE;AAED,eAAO,MAAM,iBAAiB,2BAA4B,CAAC"}
@@ -0,0 +1,326 @@
1
+ import { GatewayError } from '@frogbotai/gateway/errors';
2
+ import { USAGE_URL } from './constants.js';
3
+ const REJECTED_OPTIONS = [
4
+ 'conversation',
5
+ 'logprobs',
6
+ 'maxToolCalls',
7
+ 'metadata',
8
+ 'previousResponseId',
9
+ 'promptCacheRetention',
10
+ 'reasoningEffortUpdate',
11
+ 'safetyIdentifier',
12
+ 'truncation',
13
+ 'user'
14
+ ];
15
+ const HOSTED_TOOLS = new Set([
16
+ 'openai.web_search',
17
+ 'openai.web_search_preview'
18
+ ]);
19
+ const RECONNECT = 'Reconnect ChatGPT in Settings → Linked accounts.';
20
+ const UNSUPPORTED = "This request isn't supported on a ChatGPT plan.";
21
+ const BUSY = 'ChatGPT is busy. Try again in a moment.';
22
+ const PLAN_ERRORS = {
23
+ subscription_sharing_usage_limit_exceeded: {
24
+ status: 429,
25
+ message: `You've reached your ChatGPT plan's usage limit. Manage usage at ${USAGE_URL}.`
26
+ },
27
+ subscription_sharing_user_not_eligible: {
28
+ status: 403,
29
+ message: "This ChatGPT account can't use its plan in other apps. Paste an OpenAI API key in Settings → Linked accounts instead."
30
+ },
31
+ subscription_sharing_invalid_user: {
32
+ status: 401,
33
+ message: RECONNECT
34
+ },
35
+ chatpass_v2_scope_not_authorized: {
36
+ status: 403,
37
+ message: RECONNECT
38
+ },
39
+ chatpass_v2_invalid_authorization_context: {
40
+ status: 403,
41
+ message: RECONNECT
42
+ },
43
+ subscription_sharing_unsupported_capability: {
44
+ status: 400,
45
+ message: UNSUPPORTED
46
+ },
47
+ subscription_sharing_route_not_supported: {
48
+ status: 403,
49
+ message: UNSUPPORTED
50
+ },
51
+ subscription_sharing_usage_unavailable: {
52
+ status: 503,
53
+ message: BUSY,
54
+ busy: true
55
+ },
56
+ subscription_sharing_user_unavailable: {
57
+ status: 503,
58
+ message: BUSY,
59
+ busy: true
60
+ }
61
+ };
62
+ function errorText(error) {
63
+ if (!error || typeof error !== 'object') return String(error);
64
+ const { responseBody, data, code, message } = error;
65
+ let json = '';
66
+ try {
67
+ json = JSON.stringify(data) ?? '';
68
+ } catch {
69
+ json = '';
70
+ }
71
+ return [
72
+ responseBody,
73
+ json,
74
+ code,
75
+ message
76
+ ].filter((value)=>typeof value === 'string').join(' ');
77
+ }
78
+ function matchPlanError(error) {
79
+ const text = errorText(error);
80
+ const code = Object.keys(PLAN_ERRORS).find((candidate)=>text.includes(candidate));
81
+ if (code) return PLAN_ERRORS[code];
82
+ return error?.statusCode === 401 ? {
83
+ status: 401,
84
+ message: RECONNECT
85
+ } : undefined;
86
+ }
87
+ const toGatewayError = ({ status, message })=>new GatewayError({
88
+ message,
89
+ status,
90
+ code: 'upstream_refused'
91
+ });
92
+ /**
93
+ * The error a plan call shows: OpenAI's plan codes, matched in the body or stream error as
94
+ * OpenCode does, and a bare 401. `undefined` leaves the error as it is.
95
+ */ export function planError(error) {
96
+ const known = matchPlanError(error);
97
+ return known && toGatewayError(known);
98
+ }
99
+ /** Call options the plan route takes: no store, developer system text, no rejected fields. */ export function planParams(params) {
100
+ const { temperature: _temperature, topP: _topP, maxOutputTokens: _maxOutputTokens, ...rest } = params;
101
+ const openai = {
102
+ ...params.providerOptions?.openai
103
+ };
104
+ for (const option of REJECTED_OPTIONS)delete openai[option];
105
+ const tools = params.tools?.filter((tool)=>tool.type === 'function' || HOSTED_TOOLS.has(tool.id));
106
+ const toolChoice = params.toolChoice?.type === 'tool' && !tools?.some((tool)=>tool.name === params.toolChoice.toolName) ? undefined : params.toolChoice;
107
+ return {
108
+ ...rest,
109
+ prompt: params.prompt.map((message)=>{
110
+ const options = message.providerOptions?.openai;
111
+ if (!options || !('reasoningEffortUpdate' in options)) return message;
112
+ const { reasoningEffortUpdate: _update, ...kept } = options;
113
+ return {
114
+ ...message,
115
+ providerOptions: {
116
+ ...message.providerOptions,
117
+ openai: kept
118
+ }
119
+ };
120
+ }),
121
+ ...tools ? {
122
+ tools
123
+ } : {},
124
+ ...toolChoice ? {
125
+ toolChoice
126
+ } : {},
127
+ providerOptions: {
128
+ ...params.providerOptions,
129
+ openai: {
130
+ ...openai,
131
+ store: false,
132
+ systemMessageMode: 'developer'
133
+ }
134
+ }
135
+ };
136
+ }
137
+ function wait(ms, signal) {
138
+ return new Promise((resolve, reject)=>{
139
+ if (signal?.aborted) {
140
+ reject(signal.reason);
141
+ return;
142
+ }
143
+ const timer = setTimeout(resolve, ms);
144
+ signal?.addEventListener('abort', ()=>{
145
+ clearTimeout(timer);
146
+ reject(signal.reason);
147
+ }, {
148
+ once: true
149
+ });
150
+ });
151
+ }
152
+ function mapStreamErrors(result) {
153
+ return {
154
+ ...result,
155
+ stream: result.stream.pipeThrough(new TransformStream({
156
+ transform (part, controller) {
157
+ controller.enqueue(part.type === 'error' ? {
158
+ type: 'error',
159
+ error: planError(part.error) ?? part.error
160
+ } : part);
161
+ }
162
+ }))
163
+ };
164
+ }
165
+ const emptyUsage = {
166
+ inputTokens: {
167
+ total: undefined,
168
+ noCache: undefined,
169
+ cacheRead: undefined,
170
+ cacheWrite: undefined
171
+ },
172
+ outputTokens: {
173
+ total: undefined,
174
+ text: undefined,
175
+ reasoning: undefined
176
+ }
177
+ };
178
+ async function collect(result) {
179
+ const content = [];
180
+ const open = new Map();
181
+ const generated = {
182
+ content,
183
+ finishReason: {
184
+ unified: 'other',
185
+ raw: undefined
186
+ },
187
+ usage: emptyUsage,
188
+ warnings: [],
189
+ ...result.request ? {
190
+ request: result.request
191
+ } : {},
192
+ response: {
193
+ ...result.response
194
+ }
195
+ };
196
+ const reader = result.stream.getReader();
197
+ for(;;){
198
+ const { done, value: part } = await reader.read();
199
+ if (done) break;
200
+ switch(part.type){
201
+ case 'text-start':
202
+ case 'reasoning-start':
203
+ {
204
+ const block = {
205
+ type: part.type === 'text-start' ? 'text' : 'reasoning',
206
+ text: '',
207
+ ...part.providerMetadata ? {
208
+ providerMetadata: part.providerMetadata
209
+ } : {}
210
+ };
211
+ open.set(`${block.type}:${part.id}`, block);
212
+ content.push(block);
213
+ break;
214
+ }
215
+ case 'text-delta':
216
+ case 'reasoning-delta':
217
+ {
218
+ const block = open.get(`${part.type === 'text-delta' ? 'text' : 'reasoning'}:${part.id}`);
219
+ if (block) block.text += part.delta;
220
+ break;
221
+ }
222
+ case 'text-end':
223
+ case 'reasoning-end':
224
+ {
225
+ const block = open.get(`${part.type === 'text-end' ? 'text' : 'reasoning'}:${part.id}`);
226
+ if (block && part.providerMetadata) block.providerMetadata = part.providerMetadata;
227
+ break;
228
+ }
229
+ case 'stream-start':
230
+ generated.warnings = part.warnings;
231
+ break;
232
+ case 'response-metadata':
233
+ {
234
+ const { type: _type, ...metadata } = part;
235
+ generated.response = {
236
+ ...generated.response,
237
+ ...metadata
238
+ };
239
+ break;
240
+ }
241
+ case 'finish':
242
+ generated.finishReason = part.finishReason;
243
+ generated.usage = part.usage;
244
+ if (part.providerMetadata) generated.providerMetadata = part.providerMetadata;
245
+ break;
246
+ case 'error':
247
+ await reader.cancel().catch(()=>undefined);
248
+ throw part.error;
249
+ case 'tool-input-start':
250
+ case 'tool-input-delta':
251
+ case 'tool-input-end':
252
+ case 'raw':
253
+ break;
254
+ default:
255
+ content.push(part);
256
+ }
257
+ }
258
+ return generated;
259
+ }
260
+ const PREAMBLE = new Set([
261
+ 'stream-start',
262
+ 'response-metadata',
263
+ 'raw'
264
+ ]);
265
+ async function untilOutput(result) {
266
+ const reader = result.stream.getReader();
267
+ const head = [];
268
+ for(;;){
269
+ const { done, value: part } = await reader.read();
270
+ if (done) break;
271
+ if (part.type === 'error' && matchPlanError(part.error)?.busy) {
272
+ await reader.cancel().catch(()=>undefined);
273
+ throw part.error;
274
+ }
275
+ head.push(part);
276
+ if (!PREAMBLE.has(part.type)) break;
277
+ }
278
+ return {
279
+ ...result,
280
+ stream: new ReadableStream({
281
+ start (controller) {
282
+ for (const part of head)controller.enqueue(part);
283
+ },
284
+ async pull (controller) {
285
+ const { done, value } = await reader.read();
286
+ if (done) controller.close();
287
+ else controller.enqueue(value);
288
+ },
289
+ cancel: (reason)=>reader.cancel(reason)
290
+ })
291
+ };
292
+ }
293
+ /**
294
+ * The middleware for language models on a ChatGPT plan. It reshapes each call for the plan route,
295
+ * always streams (building non-streamed calls from the stream), and turns OpenAI's plan errors
296
+ * into messages: the seven refusal codes fail at once, the two busy codes retry after each delay
297
+ * while no output has arrived. That includes a busy error OpenAI sends after
298
+ * `response.in_progress`, past the SDK's own early-error check, so each stream is read up to its
299
+ * first output part before it is returned.
300
+ */ export function createChatGPTMiddleware({ retryDelays = [
301
+ 1000,
302
+ 2000
303
+ ] } = {}) {
304
+ const open = async (doStream, signal)=>{
305
+ for(let attempt = 0;; attempt++){
306
+ try {
307
+ return mapStreamErrors(await untilOutput(await doStream()));
308
+ } catch (error) {
309
+ const known = matchPlanError(error);
310
+ if (!known?.busy || attempt >= retryDelays.length) {
311
+ throw known ? toGatewayError(known) : error;
312
+ }
313
+ await wait(retryDelays[attempt], signal);
314
+ }
315
+ }
316
+ };
317
+ return {
318
+ specificationVersion: 'v4',
319
+ transformParams: ({ params })=>Promise.resolve(planParams(params)),
320
+ wrapGenerate: async ({ doStream, params })=>collect(await open(doStream, params.abortSignal)),
321
+ wrapStream: ({ doStream, params })=>open(doStream, params.abortSignal)
322
+ };
323
+ }
324
+ export const chatgptMiddleware = createChatGPTMiddleware();
325
+
326
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/chatgpt/middleware.ts"],"names":["GatewayError","USAGE_URL","REJECTED_OPTIONS","HOSTED_TOOLS","Set","RECONNECT","UNSUPPORTED","BUSY","PLAN_ERRORS","subscription_sharing_usage_limit_exceeded","status","message","subscription_sharing_user_not_eligible","subscription_sharing_invalid_user","chatpass_v2_scope_not_authorized","chatpass_v2_invalid_authorization_context","subscription_sharing_unsupported_capability","subscription_sharing_route_not_supported","subscription_sharing_usage_unavailable","busy","subscription_sharing_user_unavailable","errorText","error","String","responseBody","data","code","json","JSON","stringify","filter","value","join","matchPlanError","text","Object","keys","find","candidate","includes","statusCode","undefined","toGatewayError","planError","known","planParams","params","temperature","_temperature","topP","_topP","maxOutputTokens","_maxOutputTokens","rest","openai","providerOptions","option","tools","tool","type","has","id","toolChoice","some","name","toolName","prompt","map","options","reasoningEffortUpdate","_update","kept","store","systemMessageMode","wait","ms","signal","Promise","resolve","reject","aborted","reason","timer","setTimeout","addEventListener","clearTimeout","once","mapStreamErrors","result","stream","pipeThrough","TransformStream","transform","part","controller","enqueue","emptyUsage","inputTokens","total","noCache","cacheRead","cacheWrite","outputTokens","reasoning","collect","content","open","Map","generated","finishReason","unified","raw","usage","warnings","request","response","reader","getReader","done","read","block","providerMetadata","set","push","get","delta","_type","metadata","cancel","catch","PREAMBLE","untilOutput","head","ReadableStream","start","pull","close","createChatGPTMiddleware","retryDelays","doStream","attempt","length","specificationVersion","transformParams","wrapGenerate","abortSignal","wrapStream","chatgptMiddleware"],"mappings":"AASA,SAASA,YAAY,QAAQ,4BAA4B;AAEzD,SAASC,SAAS,QAAQ,iBAAiB;AAE3C,MAAMC,mBAAmB;IACvB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,eAAe,IAAIC,IAAI;IAAC;IAAqB;CAA4B;AAE/E,MAAMC,YAAY;AAClB,MAAMC,cAAc;AACpB,MAAMC,OAAO;AAIb,MAAMC,cAAyC;IAC7CC,2CAA2C;QACzCC,QAAQ;QACRC,SAAS,CAAC,gEAAgE,EAAEV,UAAU,CAAC,CAAC;IAC1F;IACAW,wCAAwC;QACtCF,QAAQ;QACRC,SACE;IACJ;IACAE,mCAAmC;QAAEH,QAAQ;QAAKC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SAAWmC,OAAOY,MAAM,CAAC/C;QACpC;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,SAASwD,wBAAwB,EACtCC,cAAc;IAAC;IAAM;CAAK,EACU,GAAG,CAAC,CAAC;IACzC,MAAMhC,OAAO,OACXiC,UACA/D;QAEA,IAAK,IAAIgE,UAAU,IAAKA,UAAW;YACjC,IAAI;gBACF,OAAOrD,gBAAgB,MAAM4C,YAAY,MAAMQ;YACjD,EAAE,OAAOrH,OAAO;gBACd,MAAMsB,QAAQX,eAAeX;gBAE7B,IAAI,CAACsB,OAAOzB,QAAQyH,WAAWF,YAAYG,MAAM,EAAE;oBACjD,MAAMjG,QAAQF,eAAeE,SAAStB;gBACxC;gBAEA,MAAMoD,KAAKgE,WAAW,CAACE,QAAQ,EAAEhE;YACnC;QACF;IACF;IAEA,OAAO;QACLkE,sBAAsB;QACtBC,iBAAiB,CAAC,EAAEjG,MAAM,EAAE,GAAK+B,QAAQC,OAAO,CAACjC,WAAWC;QAC5DkG,cAAc,OAAO,EAAEL,QAAQ,EAAE7F,MAAM,EAAE,GAAK0D,QAAQ,MAAME,KAAKiC,UAAU7F,OAAOmG,WAAW;QAC7FC,YAAY,CAAC,EAAEP,QAAQ,EAAE7F,MAAM,EAAE,GAAK4D,KAAKiC,UAAU7F,OAAOmG,WAAW;IACzE;AACF;AAEA,OAAO,MAAME,oBAAoBV,0BAA0B","file":"middleware.js"}
@@ -0,0 +1,11 @@
1
+ /** OpenCode `dev`'s fixed ChatGPT plan list (2026-10-31), used when `/models` fails or is empty. */
2
+ export declare const PLAN_FALLBACK_MODELS: readonly string[];
3
+ /**
4
+ * The models a ChatGPT plan offers: its `/models` entries listed for display and usable in the
5
+ * API, as OpenCode keeps them. Never throws: a failed or empty listing gives the fixed list.
6
+ */
7
+ export declare function listPlanModels({ apiKey, signal, }: {
8
+ apiKey: string;
9
+ signal: AbortSignal;
10
+ }): Promise<string[]>;
11
+ //# sourceMappingURL=models.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../../src/chatgpt/models.ts"],"names":[],"mappings":"AAIA,oGAAoG;AACpG,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EAUb,CAAC;AAQtC;;;GAGG;AACH,wBAAsB,cAAc,CAAC,EACnC,MAAM,EACN,MAAM,GACP,EAAE;IACD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,WAAW,CAAC;CACrB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAkBpB"}
@@ -0,0 +1,49 @@
1
+ import { z } from 'zod';
2
+ import { RESOURCE } from './constants.js';
3
+ /** OpenCode `dev`'s fixed ChatGPT plan list (2026-10-31), used when `/models` fails or is empty. */ export const PLAN_FALLBACK_MODELS = [
4
+ 'gpt-5.5',
5
+ 'gpt-5.6-luna',
6
+ 'gpt-5.6-sol',
7
+ 'gpt-5.6-terra',
8
+ 'gpt-6-astra',
9
+ 'gpt-6-luna',
10
+ 'gpt-6-sol',
11
+ 'gpt-6.1-sol',
12
+ 'gpt-6.1-terra'
13
+ ].flatMap((id)=>[
14
+ id,
15
+ `${id}-fast`
16
+ ]);
17
+ const planModels = z.object({
18
+ models: z.array(z.looseObject({
19
+ slug: z.string(),
20
+ visibility: z.string(),
21
+ supported_in_api: z.boolean()
22
+ }))
23
+ });
24
+ /**
25
+ * The models a ChatGPT plan offers: its `/models` entries listed for display and usable in the
26
+ * API, as OpenCode keeps them. Never throws: a failed or empty listing gives the fixed list.
27
+ */ export async function listPlanModels({ apiKey, signal }) {
28
+ try {
29
+ const response = await fetch(`${RESOURCE}/models`, {
30
+ headers: {
31
+ authorization: `Bearer ${apiKey}`
32
+ },
33
+ signal
34
+ });
35
+ if (!response.ok) return [
36
+ ...PLAN_FALLBACK_MODELS
37
+ ];
38
+ const ids = planModels.parse(await response.json()).models.filter((model)=>model.visibility === 'list' && model.supported_in_api).map(({ slug })=>slug);
39
+ return ids.length ? ids : [
40
+ ...PLAN_FALLBACK_MODELS
41
+ ];
42
+ } catch {
43
+ return [
44
+ ...PLAN_FALLBACK_MODELS
45
+ ];
46
+ }
47
+ }
48
+
49
+ //# sourceMappingURL=models.js.map