@happyvertical/ai 0.103.2 → 0.103.4

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 (54) hide show
  1. package/README.md +71 -0
  2. package/dist/chunks/{anthropic-CdbK9Jl-.js → anthropic-DhNGsQpl.js} +3 -3
  3. package/dist/chunks/{anthropic-CdbK9Jl-.js.map → anthropic-DhNGsQpl.js.map} +1 -1
  4. package/dist/chunks/{bedrock-DNkxz3ow.js → bedrock-CrtUO8yx.js} +3 -3
  5. package/dist/chunks/{bedrock-DNkxz3ow.js.map → bedrock-CrtUO8yx.js.map} +1 -1
  6. package/dist/chunks/{bifrost-DmbaXObX.js → bifrost-DZxTeE1Q.js} +4 -4
  7. package/dist/chunks/{bifrost-DmbaXObX.js.map → bifrost-DZxTeE1Q.js.map} +1 -1
  8. package/dist/chunks/{byteplus-modelark-BAi0y9SK.js → byteplus-modelark-gG941oea.js} +3 -3
  9. package/dist/chunks/{byteplus-modelark-BAi0y9SK.js.map → byteplus-modelark-gG941oea.js.map} +1 -1
  10. package/dist/chunks/{claude-cli-C40pIzrp.js → claude-cli-CW_gIocm.js} +3 -3
  11. package/dist/chunks/{claude-cli-C40pIzrp.js.map → claude-cli-CW_gIocm.js.map} +1 -1
  12. package/dist/chunks/{continuation-L5KnnE9R.js → continuation-KdrnmvzP.js} +2 -2
  13. package/dist/chunks/{continuation-L5KnnE9R.js.map → continuation-KdrnmvzP.js.map} +1 -1
  14. package/dist/chunks/{gateway-audio-models-B1tGNv1H.js → gateway-audio-models-DuXbi_2q.js} +2 -2
  15. package/dist/chunks/{gateway-audio-models-B1tGNv1H.js.map → gateway-audio-models-DuXbi_2q.js.map} +1 -1
  16. package/dist/chunks/{gemini-C-r6c4N9.js → gemini-DCo6d-n1.js} +3 -3
  17. package/dist/chunks/{gemini-C-r6c4N9.js.map → gemini-DCo6d-n1.js.map} +1 -1
  18. package/dist/chunks/{huggingface-DtuYF1vb.js → huggingface-jqjeFPdr.js} +3 -3
  19. package/dist/chunks/{huggingface-DtuYF1vb.js.map → huggingface-jqjeFPdr.js.map} +1 -1
  20. package/dist/chunks/{laya-D-P82D0h.js → laya-D8o5TEO7.js} +3 -3
  21. package/dist/chunks/{laya-D-P82D0h.js.map → laya-D8o5TEO7.js.map} +1 -1
  22. package/dist/chunks/{litellm-BaGgWzHR.js → litellm-8k7PMuh_.js} +4 -4
  23. package/dist/chunks/{litellm-BaGgWzHR.js.map → litellm-8k7PMuh_.js.map} +1 -1
  24. package/dist/chunks/{ollama-C3T3mn68.js → ollama-DHbYj2lH.js} +4 -4
  25. package/dist/chunks/{ollama-C3T3mn68.js.map → ollama-DHbYj2lH.js.map} +1 -1
  26. package/dist/chunks/{openai-compat-video-CwFsKAxR.js → openai-compat-video-ByTC2nzb.js} +3 -3
  27. package/dist/chunks/{openai-compat-video-CwFsKAxR.js.map → openai-compat-video-ByTC2nzb.js.map} +1 -1
  28. package/dist/chunks/{qwen-tts-DqMxfA54.js → qwen-tts-CWdO07D_.js} +2 -2
  29. package/dist/chunks/{qwen-tts-DqMxfA54.js.map → qwen-tts-CWdO07D_.js.map} +1 -1
  30. package/dist/chunks/{rate-limit-BkK4-hXY.js → rate-limit-Dwyde1BY.js} +2 -2
  31. package/dist/chunks/{rate-limit-BkK4-hXY.js.map → rate-limit-Dwyde1BY.js.map} +1 -1
  32. package/dist/chunks/{seevio-EzC6eKz-.js → seevio-B9V2nZtr.js} +3 -3
  33. package/dist/chunks/{seevio-EzC6eKz-.js.map → seevio-B9V2nZtr.js.map} +1 -1
  34. package/dist/chunks/{src-Cc5yFnnQ.js → src-BnMUshQt.js} +462 -20
  35. package/dist/chunks/src-BnMUshQt.js.map +1 -0
  36. package/dist/chunks/{typesafe-D7ZmI9-n.js → typesafe-B1_jGusy.js} +3 -3
  37. package/dist/chunks/{typesafe-D7ZmI9-n.js.map → typesafe-B1_jGusy.js.map} +1 -1
  38. package/dist/chunks/{usage-B9gPCWSa.js → usage-DS7uDhi1.js} +2 -1
  39. package/dist/chunks/usage-DS7uDhi1.js.map +1 -0
  40. package/dist/chunks/{webllm-DT31sqUY.js → webllm-DVDsgVT7.js} +2 -2
  41. package/dist/chunks/{webllm-DT31sqUY.js.map → webllm-DVDsgVT7.js.map} +1 -1
  42. package/dist/index.d.ts +1 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +3 -3
  45. package/dist/local.js +2 -2
  46. package/dist/node.js +4 -4
  47. package/dist/shared/factory.d.ts.map +1 -1
  48. package/dist/shared/providers/chatgpt-plan.d.ts +60 -0
  49. package/dist/shared/providers/chatgpt-plan.d.ts.map +1 -0
  50. package/dist/shared/types.d.ts +28 -2
  51. package/dist/shared/types.d.ts.map +1 -1
  52. package/package.json +2 -2
  53. package/dist/chunks/src-Cc5yFnnQ.js.map +0 -1
  54. package/dist/chunks/usage-B9gPCWSa.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { a as createObservedAI, c as normalizeImageGenerationOptions, d as AI_PROVIDER_TYPES, f as AuthenticationError, g as ModelNotFoundError, l as prepareRequestControls, m as ContextLengthError, o as normalizeBaseAIOptions, p as ContentFilterError, s as normalizeChatOptions, t as emitUsage, u as AIError } from "./usage-B9gPCWSa.js";
3
- import { n as rateLimitErrorFrom, t as createRateLimitedAI } from "./rate-limit-BkK4-hXY.js";
4
- import { t as createContinuingAI } from "./continuation-L5KnnE9R.js";
2
+ import { a as createObservedAI, c as normalizeImageGenerationOptions, d as AI_PROVIDER_TYPES, f as AuthenticationError, g as ModelNotFoundError, l as prepareRequestControls, m as ContextLengthError, o as normalizeBaseAIOptions, p as ContentFilterError, s as normalizeChatOptions, t as emitUsage, u as AIError } from "./usage-DS7uDhi1.js";
3
+ import { n as rateLimitErrorFrom, t as createRateLimitedAI } from "./rate-limit-Dwyde1BY.js";
4
+ import { t as createContinuingAI } from "./continuation-KdrnmvzP.js";
5
5
  import { ApiError, ValidationError, loadEnvConfig } from "@happyvertical/utils";
6
6
  import OpenAI from "openai";
7
7
  //#region src/shared/providers/openai.ts
@@ -1037,6 +1037,9 @@ var factory_exports = /* @__PURE__ */ __exportAll({
1037
1037
  function isOpenAIOptions(options) {
1038
1038
  return !options.type || options.type === "openai";
1039
1039
  }
1040
+ function isChatGPTPlanOptions(options) {
1041
+ return options.type === "chatgpt-plan";
1042
+ }
1040
1043
  /**
1041
1044
  * Checks if the options are for LiteLLM provider
1042
1045
  * @param options - The AI provider options to check
@@ -1214,50 +1217,53 @@ async function getAI(options = {}) {
1214
1217
  if (isOpenAIOptions(options)) {
1215
1218
  const { OpenAIProvider } = await Promise.resolve().then(() => openai_exports);
1216
1219
  client = new OpenAIProvider(options);
1220
+ } else if (isChatGPTPlanOptions(options)) {
1221
+ const { ChatGPTPlanProvider } = await Promise.resolve().then(() => chatgpt_plan_exports);
1222
+ client = new ChatGPTPlanProvider(options);
1217
1223
  } else if (isLiteLLMOptions(options)) {
1218
- const { LiteLLMProvider } = await import("./litellm-BaGgWzHR.js");
1224
+ const { LiteLLMProvider } = await import("./litellm-8k7PMuh_.js");
1219
1225
  client = new LiteLLMProvider(options);
1220
1226
  } else if (isBifrostOptions(options)) {
1221
- const { BifrostProvider } = await import("./bifrost-DmbaXObX.js");
1227
+ const { BifrostProvider } = await import("./bifrost-DZxTeE1Q.js");
1222
1228
  client = new BifrostProvider(options);
1223
1229
  } else if (isOllamaOptions(options)) {
1224
- const { OllamaProvider } = await import("./ollama-C3T3mn68.js");
1230
+ const { OllamaProvider } = await import("./ollama-DHbYj2lH.js");
1225
1231
  client = new OllamaProvider(options);
1226
1232
  } else if (isGeminiOptions(options)) {
1227
- const { GeminiProvider } = await import("./gemini-C-r6c4N9.js");
1233
+ const { GeminiProvider } = await import("./gemini-DCo6d-n1.js");
1228
1234
  client = new GeminiProvider(options);
1229
1235
  } else if (isAnthropicOptions(options)) {
1230
- const { AnthropicProvider } = await import("./anthropic-CdbK9Jl-.js");
1236
+ const { AnthropicProvider } = await import("./anthropic-DhNGsQpl.js");
1231
1237
  client = new AnthropicProvider(options);
1232
1238
  } else if (isHuggingFaceOptions(options)) {
1233
- const { HuggingFaceProvider } = await import("./huggingface-DtuYF1vb.js");
1239
+ const { HuggingFaceProvider } = await import("./huggingface-jqjeFPdr.js");
1234
1240
  client = new HuggingFaceProvider(options);
1235
1241
  } else if (isBedrockOptions(options)) {
1236
- const { BedrockProvider } = await import("./bedrock-DNkxz3ow.js");
1242
+ const { BedrockProvider } = await import("./bedrock-CrtUO8yx.js");
1237
1243
  client = new BedrockProvider(options);
1238
1244
  } else if (isClaudeCliOptions(options)) {
1239
- const { ClaudeCliProvider } = await import("./claude-cli-C40pIzrp.js");
1245
+ const { ClaudeCliProvider } = await import("./claude-cli-CW_gIocm.js");
1240
1246
  client = new ClaudeCliProvider(options);
1241
1247
  } else if (isQwen3TTSOptions(options)) {
1242
- const { Qwen3TTSProvider } = await import("./qwen-tts-DqMxfA54.js");
1248
+ const { Qwen3TTSProvider } = await import("./qwen-tts-CWdO07D_.js");
1243
1249
  client = new Qwen3TTSProvider(options);
1244
1250
  } else if (isOpenAICompatVideoOptions(options)) {
1245
- const { OpenAICompatVideoProvider } = await import("./openai-compat-video-CwFsKAxR.js");
1251
+ const { OpenAICompatVideoProvider } = await import("./openai-compat-video-ByTC2nzb.js");
1246
1252
  client = new OpenAICompatVideoProvider(options);
1247
1253
  } else if (isByteplusModelArkOptions(options)) {
1248
- const { ByteplusModelArkProvider } = await import("./byteplus-modelark-BAi0y9SK.js");
1254
+ const { ByteplusModelArkProvider } = await import("./byteplus-modelark-gG941oea.js");
1249
1255
  client = new ByteplusModelArkProvider(options);
1250
1256
  } else if (isSeevioOptions(options)) {
1251
- const { SeevioProvider } = await import("./seevio-EzC6eKz-.js");
1257
+ const { SeevioProvider } = await import("./seevio-B9V2nZtr.js");
1252
1258
  client = new SeevioProvider(options);
1253
1259
  } else if (isTypeSafeOptions(options)) {
1254
- const { TypeSafeProvider } = await import("./typesafe-D7ZmI9-n.js");
1260
+ const { TypeSafeProvider } = await import("./typesafe-B1_jGusy.js");
1255
1261
  client = new TypeSafeProvider(options);
1256
1262
  } else if (isLayaOptions(options)) {
1257
- const { LayaProvider } = await import("./laya-D-P82D0h.js");
1263
+ const { LayaProvider } = await import("./laya-D8o5TEO7.js");
1258
1264
  client = new LayaProvider(options);
1259
1265
  } else if (isWebLLMOptions(options)) {
1260
- const { WebLLMProvider } = await import("./webllm-DT31sqUY.js").then((n) => n.o);
1266
+ const { WebLLMProvider } = await import("./webllm-DVDsgVT7.js").then((n) => n.o);
1261
1267
  client = new WebLLMProvider(options);
1262
1268
  } else throw new ValidationError("Unsupported AI provider type", {
1263
1269
  supportedTypes: [...AI_PROVIDER_TYPES],
@@ -1383,6 +1389,442 @@ var AIMessage = class AIMessage {
1383
1389
  }
1384
1390
  };
1385
1391
  //#endregion
1392
+ //#region src/shared/providers/chatgpt-plan.ts
1393
+ var chatgpt_plan_exports = /* @__PURE__ */ __exportAll({
1394
+ ChatGPTPlanError: () => ChatGPTPlanError,
1395
+ ChatGPTPlanProvider: () => ChatGPTPlanProvider,
1396
+ ChatGPTPlanSessionRevokedError: () => ChatGPTPlanSessionRevokedError,
1397
+ ChatGPTPlanUsageLimitError: () => ChatGPTPlanUsageLimitError,
1398
+ ChatGPTPlanUsageUnavailableError: () => ChatGPTPlanUsageUnavailableError,
1399
+ ChatGPTPlanWorkspaceError: () => ChatGPTPlanWorkspaceError
1400
+ });
1401
+ var PROVIDER = "chatgpt-plan";
1402
+ var MODELS_URL = "https://api.openai.com/v1/models";
1403
+ var RESPONSES_URL = "https://api.openai.com/v1/responses";
1404
+ /** Base error for the local ChatGPT plan-usage provider. */
1405
+ var ChatGPTPlanError = class extends AIError {
1406
+ status;
1407
+ requestId;
1408
+ param;
1409
+ constructor(message, code, status, requestId, param, retryable = false, model) {
1410
+ super(message, code, PROVIDER, model, retryable);
1411
+ this.status = status;
1412
+ this.requestId = requestId;
1413
+ this.param = param;
1414
+ this.name = "ChatGPTPlanError";
1415
+ }
1416
+ };
1417
+ /** The selected account or application limit stopped plan-usage inference. */
1418
+ var ChatGPTPlanUsageLimitError = class extends ChatGPTPlanError {
1419
+ constructor(message, status, requestId, model) {
1420
+ super(message, "subscription_sharing_usage_limit_exceeded", status, requestId, void 0, false, model);
1421
+ this.name = "ChatGPTPlanUsageLimitError";
1422
+ }
1423
+ };
1424
+ /** The selected user/workspace/policy does not allow this request. */
1425
+ var ChatGPTPlanWorkspaceError = class extends ChatGPTPlanError {
1426
+ constructor(message, code, status, requestId, param, model) {
1427
+ super(message, code, status, requestId, param, false, model);
1428
+ this.name = "ChatGPTPlanWorkspaceError";
1429
+ }
1430
+ };
1431
+ /** The saved registration can no longer authorize plan-usage requests. */
1432
+ var ChatGPTPlanSessionRevokedError = class extends ChatGPTPlanError {
1433
+ constructor(message, code = "subscription_sharing_invalid_user", status, requestId, model) {
1434
+ super(message, code, status, requestId, void 0, false, model);
1435
+ this.name = "ChatGPTPlanSessionRevokedError";
1436
+ }
1437
+ };
1438
+ /** Plan usage or account/workspace lookup is temporarily unavailable. */
1439
+ var ChatGPTPlanUsageUnavailableError = class extends ChatGPTPlanError {
1440
+ constructor(message, code = "subscription_sharing_usage_unavailable", status, requestId, model) {
1441
+ super(message, code, status, requestId, void 0, true, model);
1442
+ this.name = "ChatGPTPlanUsageUnavailableError";
1443
+ }
1444
+ };
1445
+ function isRecord(value) {
1446
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1447
+ }
1448
+ function safeTokenCount(value) {
1449
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1450
+ }
1451
+ function mapUsage(value) {
1452
+ if (!isRecord(value)) return void 0;
1453
+ const promptTokens = safeTokenCount(value.input_tokens);
1454
+ const completionTokens = safeTokenCount(value.output_tokens);
1455
+ const totalTokens = safeTokenCount(value.total_tokens);
1456
+ if (promptTokens === void 0 || completionTokens === void 0 || totalTokens === void 0) return void 0;
1457
+ return {
1458
+ promptTokens,
1459
+ completionTokens,
1460
+ totalTokens
1461
+ };
1462
+ }
1463
+ function redact(value, token) {
1464
+ return token ? value.split(token).join("[REDACTED]") : value;
1465
+ }
1466
+ function safeDiagnostic(value, token) {
1467
+ return value === void 0 ? void 0 : redact(value, token);
1468
+ }
1469
+ function errorMessage(error) {
1470
+ return typeof error?.message === "string" ? error.message : void 0;
1471
+ }
1472
+ function errorCode(error) {
1473
+ return typeof error?.code === "string" ? error.code : void 0;
1474
+ }
1475
+ function errorParam(error) {
1476
+ return typeof error?.param === "string" ? error.param : void 0;
1477
+ }
1478
+ function mappedError(input) {
1479
+ const rawCode = errorCode(input.error);
1480
+ const code = safeDiagnostic(rawCode, input.token);
1481
+ const requestId = safeDiagnostic(input.requestId, input.token);
1482
+ const diagnostic = redact(errorMessage(input.error) || input.detail || `ChatGPT plan request failed${input.status ? ` (${input.status})` : ""}`, input.token);
1483
+ const param = safeDiagnostic(errorParam(input.error), input.token);
1484
+ if (rawCode === "subscription_sharing_usage_limit_exceeded") return new ChatGPTPlanUsageLimitError(diagnostic, input.status, requestId, input.model);
1485
+ if (rawCode === "subscription_sharing_usage_unavailable" || rawCode === "subscription_sharing_user_unavailable" || input.status === 503) return new ChatGPTPlanUsageUnavailableError(diagnostic, code || "subscription_sharing_usage_unavailable", input.status, requestId, input.model);
1486
+ if (rawCode === "subscription_sharing_invalid_user" || input.status === 401) return new ChatGPTPlanSessionRevokedError(diagnostic, code || "subscription_sharing_invalid_user", input.status, requestId, input.model);
1487
+ if (rawCode === "subscription_sharing_user_not_eligible" || rawCode === "subscription_sharing_route_not_supported" || rawCode === "chatpass_v2_scope_not_authorized" || rawCode === "chatpass_v2_invalid_authorization_context" || input.status === 403) return new ChatGPTPlanWorkspaceError(diagnostic, code || "workspace_restricted", input.status, requestId, param, input.model);
1488
+ return new ChatGPTPlanError(diagnostic, code || "CHATGPT_PLAN_REQUEST_FAILED", input.status, requestId, param, Boolean(input.status && input.status >= 500), input.model);
1489
+ }
1490
+ async function responseError(response, token, model) {
1491
+ const requestId = response.headers.get("x-request-id") || void 0;
1492
+ const text = await response.text();
1493
+ let body;
1494
+ try {
1495
+ body = JSON.parse(text);
1496
+ } catch {
1497
+ body = void 0;
1498
+ }
1499
+ const record = isRecord(body) ? body : void 0;
1500
+ return mappedError({
1501
+ error: isRecord(record?.error) ? record?.error : void 0,
1502
+ detail: typeof record?.detail === "string" ? record.detail : text.slice(0, 500) || void 0,
1503
+ status: response.status,
1504
+ requestId,
1505
+ token,
1506
+ model
1507
+ });
1508
+ }
1509
+ function frameData(frame) {
1510
+ const values = frame.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart());
1511
+ return values.length ? values.join("\n") : void 0;
1512
+ }
1513
+ async function* sse(body) {
1514
+ const reader = body.getReader();
1515
+ const decoder = new TextDecoder();
1516
+ let buffer = "";
1517
+ try {
1518
+ while (true) {
1519
+ const { done, value } = await reader.read();
1520
+ buffer += decoder.decode(value, { stream: !done });
1521
+ const frames = buffer.split(/\r?\n\r?\n/);
1522
+ buffer = frames.pop() || "";
1523
+ for (const frame of frames) {
1524
+ const data = frameData(frame);
1525
+ if (data !== void 0) yield data;
1526
+ }
1527
+ if (done) break;
1528
+ }
1529
+ if (buffer.trim()) {
1530
+ const data = frameData(buffer);
1531
+ if (data !== void 0) yield data;
1532
+ }
1533
+ } finally {
1534
+ reader.releaseLock();
1535
+ }
1536
+ }
1537
+ function validateOptions(options) {
1538
+ const present = [
1539
+ "maxTokens",
1540
+ "temperature",
1541
+ "topP",
1542
+ "n",
1543
+ "stop",
1544
+ "frequencyPenalty",
1545
+ "presencePenalty",
1546
+ "user",
1547
+ "tools",
1548
+ "toolChoice",
1549
+ "responseFormat",
1550
+ "responseSchema",
1551
+ "seed",
1552
+ "reasoning",
1553
+ "thinkingLevel",
1554
+ "includeThoughts"
1555
+ ].filter((key) => options[key] !== void 0);
1556
+ if (present.length) throw new ChatGPTPlanError(`ChatGPT plan usage does not support request option(s): ${present.join(", ")}`, "subscription_sharing_unsupported_capability", 400, void 0, present[0]);
1557
+ }
1558
+ function inputFor(messages) {
1559
+ if (!messages.length) throw new ChatGPTPlanError("ChatGPT plan usage requires at least one input message", "INVALID_REQUEST", 400);
1560
+ return messages.map((message) => {
1561
+ if (message.role === "function" || message.role === "tool" || message.tool_calls?.length || message.tool_call_id || message.name) throw new ChatGPTPlanError("ChatGPT plan usage does not support this tool/function message shape", "subscription_sharing_unsupported_capability", 400, void 0, "input");
1562
+ return {
1563
+ role: message.role === "system" ? "developer" : message.role,
1564
+ content: typeof message.content === "string" ? message.content : message.content.map((part) => part.type === "text" ? {
1565
+ type: "input_text",
1566
+ text: part.text
1567
+ } : {
1568
+ type: "input_image",
1569
+ image_url: part.image_url.url,
1570
+ ...part.image_url.detail ? { detail: part.image_url.detail } : {}
1571
+ })
1572
+ };
1573
+ });
1574
+ }
1575
+ /**
1576
+ * Responses API adapter for an explicitly selected, locally authorized
1577
+ * ChatGPT plan. It uses only the public SIWC routes and never falls back to an
1578
+ * API-key provider.
1579
+ */
1580
+ var ChatGPTPlanProvider = class {
1581
+ options;
1582
+ fetcher;
1583
+ constructor(options) {
1584
+ if (!options.clientId?.trim()) throw new ChatGPTPlanError("clientId is required for ChatGPT plan usage", "INVALID_CONFIGURATION");
1585
+ if (typeof options.sessionManager?.accessToken !== "function") throw new ChatGPTPlanError("sessionManager.accessToken is required for ChatGPT plan usage", "INVALID_CONFIGURATION");
1586
+ this.options = normalizeBaseAIOptions(options);
1587
+ this.fetcher = options.fetch ?? fetch;
1588
+ }
1589
+ async token(model) {
1590
+ try {
1591
+ const token = await this.options.sessionManager.accessToken(this.options.clientId);
1592
+ if (!token) throw new ChatGPTPlanSessionRevokedError("The selected ChatGPT session has no usable access token; sign in again", "session_invalidated", void 0, void 0, model);
1593
+ return token;
1594
+ } catch (error) {
1595
+ if (error instanceof ChatGPTPlanError) throw error;
1596
+ const code = isRecord(error) && typeof error.code === "string" ? error.code : void 0;
1597
+ if (code && (/* @__PURE__ */ new Set([
1598
+ "unknown_account",
1599
+ "refresh_invalid",
1600
+ "session_invalidated",
1601
+ "plan_permission_missing"
1602
+ ])).has(code)) throw new ChatGPTPlanSessionRevokedError("The selected ChatGPT session is no longer authorized; sign in again", code, void 0, void 0, model);
1603
+ throw new ChatGPTPlanUsageUnavailableError("The selected ChatGPT session is temporarily unavailable", "subscription_sharing_usage_unavailable", void 0, void 0, model);
1604
+ }
1605
+ }
1606
+ async *events(messages, options) {
1607
+ validateOptions(options);
1608
+ const model = options.model || this.options.defaultModel;
1609
+ if (!model) throw new ChatGPTPlanError("Select a model returned by getModels() before inference", "MODEL_REQUIRED");
1610
+ const input = inputFor(messages);
1611
+ const controls = prepareRequestControls(this.options, options);
1612
+ let token = "";
1613
+ try {
1614
+ token = await this.token(model);
1615
+ const response = await this.fetcher(RESPONSES_URL, {
1616
+ method: "POST",
1617
+ headers: {
1618
+ ...this.options.headers,
1619
+ Authorization: `Bearer ${token}`,
1620
+ "Content-Type": "application/json",
1621
+ Accept: "text/event-stream"
1622
+ },
1623
+ body: JSON.stringify({
1624
+ model,
1625
+ input,
1626
+ store: false,
1627
+ stream: true
1628
+ }),
1629
+ signal: controls.signal
1630
+ });
1631
+ if (!response.ok) throw await responseError(response, token, model);
1632
+ if (!response.body || !response.headers.get("content-type")?.toLowerCase().includes("text/event-stream")) throw new ChatGPTPlanError("ChatGPT plan response did not provide an event stream", "INVALID_RESPONSE", response.status, safeDiagnostic(response.headers.get("x-request-id") || void 0, token), void 0, false, model);
1633
+ let completed = false;
1634
+ for await (const data of sse(response.body)) {
1635
+ if (data === "[DONE]") continue;
1636
+ let event;
1637
+ try {
1638
+ event = JSON.parse(data);
1639
+ } catch {
1640
+ throw new ChatGPTPlanError("ChatGPT plan stream contained invalid JSON", "INVALID_RESPONSE", response.status, safeDiagnostic(response.headers.get("x-request-id") || void 0, token), void 0, false, model);
1641
+ }
1642
+ if (event.type === "response.output_text.delta" && typeof event.delta === "string") yield { delta: event.delta };
1643
+ else if (event.type === "response.completed") {
1644
+ completed = true;
1645
+ yield { completed: {
1646
+ model: typeof event.response?.model === "string" ? event.response.model : model,
1647
+ usage: mapUsage(event.response?.usage)
1648
+ } };
1649
+ } else if (event.type === "response.failed") throw mappedError({
1650
+ error: event.response?.error || event.error,
1651
+ token,
1652
+ status: response.status,
1653
+ requestId: response.headers.get("x-request-id") || void 0,
1654
+ model
1655
+ });
1656
+ else if (event.type === "error") throw mappedError({
1657
+ error: event.error || event,
1658
+ token,
1659
+ status: response.status,
1660
+ requestId: response.headers.get("x-request-id") || void 0,
1661
+ model
1662
+ });
1663
+ else if (event.type === "response.incomplete") throw new ChatGPTPlanError("ChatGPT plan response was incomplete", "RESPONSE_INCOMPLETE", response.status, safeDiagnostic(response.headers.get("x-request-id") || void 0, token), "incomplete_details", false, model);
1664
+ }
1665
+ if (!completed) throw new ChatGPTPlanError("ChatGPT plan stream ended before response.completed", "STREAM_INTERRUPTED", response.status, safeDiagnostic(response.headers.get("x-request-id") || void 0, token), void 0, true, model);
1666
+ } catch (error) {
1667
+ if (controls.didTimeout()) throw new ChatGPTPlanError(`ChatGPT plan request timed out after ${controls.timeout}ms`, "AI_TIMEOUT", void 0, void 0, void 0, true, model);
1668
+ if (options.signal?.aborted) throw new ChatGPTPlanError("ChatGPT plan request was aborted", "AI_ABORTED", void 0, void 0, void 0, false, model);
1669
+ if (error instanceof ChatGPTPlanError) throw error;
1670
+ throw new ChatGPTPlanError(`Network error calling ChatGPT plan usage: ${redact(error instanceof Error ? error.message : String(error), token)}`, "NETWORK_ERROR", void 0, void 0, void 0, true, model);
1671
+ } finally {
1672
+ controls.cleanup();
1673
+ }
1674
+ }
1675
+ async chat(messages, options = {}) {
1676
+ const startedAt = Date.now();
1677
+ let content = "";
1678
+ let completed;
1679
+ for await (const event of this.events(messages, options)) {
1680
+ if (event.delta !== void 0) {
1681
+ content += event.delta;
1682
+ options.onProgress?.(event.delta);
1683
+ }
1684
+ if (event.completed) completed = event.completed;
1685
+ }
1686
+ options.onFinishReason?.("stop");
1687
+ const model = completed?.model || options.model || this.options.defaultModel || "";
1688
+ emitUsage(this.options, PROVIDER, "chat", model, completed?.usage, startedAt, options.usageTags);
1689
+ return {
1690
+ content,
1691
+ model,
1692
+ usage: completed?.usage,
1693
+ finishReason: "stop"
1694
+ };
1695
+ }
1696
+ async *stream(messages, options = {}) {
1697
+ const startedAt = Date.now();
1698
+ let completed;
1699
+ for await (const event of this.events(messages, options)) {
1700
+ if (event.delta !== void 0) {
1701
+ options.onProgress?.(event.delta);
1702
+ yield event.delta;
1703
+ }
1704
+ if (event.completed) completed = event.completed;
1705
+ }
1706
+ options.onFinishReason?.("stop");
1707
+ emitUsage(this.options, PROVIDER, "stream", completed?.model || options.model || this.options.defaultModel || "", completed?.usage, startedAt, options.usageTags);
1708
+ }
1709
+ async complete(prompt, options = {}) {
1710
+ return this.chat([{
1711
+ role: "user",
1712
+ content: prompt
1713
+ }], options);
1714
+ }
1715
+ async message(text, options = {}) {
1716
+ return (await this.chat([...options.history || [], {
1717
+ role: options.role || "user",
1718
+ content: text
1719
+ }], options)).content;
1720
+ }
1721
+ async getModels() {
1722
+ const controls = prepareRequestControls(this.options);
1723
+ let token = "";
1724
+ try {
1725
+ token = await this.token();
1726
+ const response = await this.fetcher(MODELS_URL, {
1727
+ headers: {
1728
+ ...this.options.headers,
1729
+ Authorization: `Bearer ${token}`,
1730
+ Accept: "application/json"
1731
+ },
1732
+ signal: controls.signal
1733
+ });
1734
+ if (!response.ok) throw await responseError(response, token);
1735
+ const body = await response.json();
1736
+ if (!isRecord(body) || !Array.isArray(body.models)) throw new ChatGPTPlanError("ChatGPT plan model catalog omitted models", "INVALID_RESPONSE", response.status, safeDiagnostic(response.headers.get("x-request-id") || void 0, token));
1737
+ return body.models.filter((entry) => isRecord(entry) && entry.visibility === "list" && typeof entry.slug === "string" && Boolean(entry.slug)).map((entry) => ({
1738
+ id: entry.slug,
1739
+ name: typeof entry.display_name === "string" ? entry.display_name : entry.slug,
1740
+ contextLength: 0,
1741
+ capabilities: ["text", "chat"],
1742
+ supportsFunctions: false,
1743
+ supportsVision: true
1744
+ }));
1745
+ } catch (error) {
1746
+ if (controls.didTimeout()) throw new ChatGPTPlanUsageUnavailableError(`ChatGPT plan model discovery timed out after ${controls.timeout}ms`, "AI_TIMEOUT");
1747
+ if (error instanceof ChatGPTPlanError) throw error;
1748
+ throw new ChatGPTPlanError(`ChatGPT plan model discovery failed: ${redact(error instanceof Error ? error.message : String(error), token)}`, "NETWORK_ERROR", void 0, void 0, void 0, true);
1749
+ } finally {
1750
+ controls.cleanup();
1751
+ }
1752
+ }
1753
+ async getCapabilities() {
1754
+ return {
1755
+ chat: true,
1756
+ completion: true,
1757
+ embeddings: false,
1758
+ streaming: true,
1759
+ functions: false,
1760
+ vision: true,
1761
+ fineTuning: false,
1762
+ imageEmbeddings: false,
1763
+ imageGeneration: false,
1764
+ videoGeneration: false,
1765
+ tts: false,
1766
+ voiceCloning: false,
1767
+ voiceDesign: false,
1768
+ maxContextLength: 0,
1769
+ supportedOperations: [
1770
+ "chat",
1771
+ "completion",
1772
+ "streaming",
1773
+ "vision"
1774
+ ]
1775
+ };
1776
+ }
1777
+ async countTokens(text) {
1778
+ return Math.ceil(text.length / 4);
1779
+ }
1780
+ unsupported() {
1781
+ throw new ChatGPTPlanError("This operation is not supported by ChatGPT plan usage.", "NOT_IMPLEMENTED");
1782
+ }
1783
+ async embed(_text, _options) {
1784
+ return this.unsupported();
1785
+ }
1786
+ async embedImage(_image, _options) {
1787
+ return this.unsupported();
1788
+ }
1789
+ async describeImage(_image, _prompt, _options) {
1790
+ return this.unsupported();
1791
+ }
1792
+ async generateImage(_prompt, _options) {
1793
+ return this.unsupported();
1794
+ }
1795
+ async submitVideoGenerationJob(_options) {
1796
+ return this.unsupported();
1797
+ }
1798
+ async getVideoGenerationJob(_handle) {
1799
+ return this.unsupported();
1800
+ }
1801
+ async fetchVideoGenerationResult(_handle) {
1802
+ return this.unsupported();
1803
+ }
1804
+ async cancelVideoGenerationJob(_handle) {
1805
+ return this.unsupported();
1806
+ }
1807
+ async validateVideoGenerationAccess() {
1808
+ return this.unsupported();
1809
+ }
1810
+ async synthesizeSpeech(_text, _options) {
1811
+ return this.unsupported();
1812
+ }
1813
+ streamSpeech(_text, _options) {
1814
+ const error = new ChatGPTPlanError("Speech streaming is not supported by ChatGPT plan usage.", "NOT_IMPLEMENTED");
1815
+ return { [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }) };
1816
+ }
1817
+ async cloneVoice(_options) {
1818
+ return this.unsupported();
1819
+ }
1820
+ async designVoice(_options) {
1821
+ return this.unsupported();
1822
+ }
1823
+ async getVoices(_options) {
1824
+ return this.unsupported();
1825
+ }
1826
+ };
1827
+ //#endregion
1386
1828
  //#region src/shared/thread.ts
1387
1829
  /**
1388
1830
  * Represents a conversation thread with an AI model
@@ -1529,6 +1971,6 @@ var AIThread = class AIThread {
1529
1971
  /** @internal */
1530
1972
  var PACKAGE_VERSION_INITIALIZED = true;
1531
1973
  //#endregion
1532
- export { getAI as a, OpenAIClient as c, OpenAIProvider as d, factory_exports as i, getAIClient as l, AIThread as n, getAIAuto as o, AIMessage as r, AIClient as s, PACKAGE_VERSION_INITIALIZED as t, getOpenAI as u };
1974
+ export { OpenAIProvider as _, ChatGPTPlanSessionRevokedError as a, ChatGPTPlanWorkspaceError as c, getAI as d, getAIAuto as f, getOpenAI as g, getAIClient as h, ChatGPTPlanProvider as i, AIMessage as l, OpenAIClient as m, AIThread as n, ChatGPTPlanUsageLimitError as o, AIClient as p, ChatGPTPlanError as r, ChatGPTPlanUsageUnavailableError as s, PACKAGE_VERSION_INITIALIZED as t, factory_exports as u };
1533
1975
 
1534
- //# sourceMappingURL=src-Cc5yFnnQ.js.map
1976
+ //# sourceMappingURL=src-BnMUshQt.js.map