ceulen 0.5.1 → 0.7.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.
- package/CHANGELOG.md +317 -12
- package/README.md +87 -91
- package/extensions/lib/advisor-marker.ts +33 -0
- package/extensions/lib/panel.ts +25 -2
- package/extensions/lib/rate.ts +24 -0
- package/extensions/lib/registry.ts +93 -7
- package/extensions/lib/tools.ts +47 -0
- package/extensions/lib/usage-store.ts +33 -0
- package/extensions/modules/advisor/commands/advisor.ts +244 -0
- package/extensions/modules/advisor/configPanel.ts +194 -0
- package/extensions/modules/advisor/index.ts +217 -0
- package/extensions/modules/advisor/lib/config.ts +248 -0
- package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
- package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
- package/extensions/modules/advisor/lib/model-picker.ts +47 -0
- package/extensions/modules/advisor/lib/watcher.ts +286 -0
- package/extensions/modules/advisor/test/compliance.test.ts +125 -0
- package/extensions/modules/advisor/test/config.test.ts +202 -0
- package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
- package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
- package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
- package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
- package/extensions/modules/advisor/test/module.test.ts +586 -0
- package/extensions/modules/advisor/test/watcher.test.ts +478 -0
- package/extensions/modules/classifier/configPanel.ts +104 -0
- package/extensions/modules/classifier/index.ts +297 -0
- package/extensions/modules/classifier/lib/settings.ts +95 -0
- package/extensions/modules/classifier/test/classifier.test.ts +475 -0
- package/extensions/modules/composer/index.ts +152 -3
- package/extensions/modules/composer/lib/footer.ts +119 -0
- package/extensions/modules/composer/lib/shapes.ts +265 -26
- package/extensions/modules/composer/test/editor.test.ts +1 -1
- package/extensions/modules/composer/test/footer.test.ts +96 -0
- package/extensions/modules/composer/test/module.test.ts +113 -11
- package/extensions/modules/composer/test/screen.test.ts +29 -1
- package/extensions/modules/composer/test/shapes.test.ts +224 -8
- package/extensions/modules/config/defaultTools.ts +96 -0
- package/extensions/modules/config/index.ts +147 -7
- package/extensions/modules/config/piSettings.ts +254 -69
- package/extensions/modules/config/test/defaultTools.test.ts +122 -0
- package/extensions/modules/config/test/menu.test.ts +64 -0
- package/extensions/modules/config/test/panel.test.ts +38 -23
- package/extensions/modules/config/test/piSettings.test.ts +130 -3
- package/extensions/modules/config/test/renderTools.test.ts +71 -0
- package/extensions/modules/config/test/tools.test.ts +146 -0
- package/extensions/modules/fff/index.ts +2094 -0
- package/extensions/modules/fff/lib/query.ts +129 -0
- package/extensions/modules/fff/test/index.test.ts +607 -0
- package/extensions/modules/fff/test/query.test.ts +71 -0
- package/extensions/modules/munin/configPanel.ts +105 -0
- package/extensions/modules/munin/index.ts +641 -0
- package/extensions/modules/munin/lib/helpers.ts +471 -0
- package/extensions/modules/munin/lib/retry.ts +20 -0
- package/extensions/modules/munin/lib/sdk.ts +218 -0
- package/extensions/modules/munin/test/config.test.ts +168 -0
- package/extensions/modules/munin/test/configPanel.test.ts +161 -0
- package/extensions/modules/munin/test/extension.test.ts +224 -0
- package/extensions/modules/munin/test/helpers.test.ts +523 -0
- package/extensions/modules/munin/test/retry.test.ts +145 -0
- package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
- package/extensions/modules/plan/configPanel.ts +152 -0
- package/extensions/modules/plan/index.ts +917 -0
- package/extensions/modules/plan/lib/plan-tools.ts +72 -0
- package/extensions/modules/plan/lib/prompt.ts +65 -0
- package/extensions/modules/plan/lib/settings.ts +166 -0
- package/extensions/modules/plan/lib/shell-gate.ts +200 -0
- package/extensions/modules/plan/test/configPanel.test.ts +96 -0
- package/extensions/modules/plan/test/harness.ts +133 -0
- package/extensions/modules/plan/test/module.test.ts +305 -0
- package/extensions/modules/plan/test/settings.test.ts +114 -0
- package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
- package/extensions/modules/ponytail/index.ts +23 -73
- package/extensions/modules/ponytail/lib/config.ts +1 -6
- package/extensions/modules/ponytail/test/extension.test.ts +1 -85
- package/extensions/modules/repair/configPanel.ts +96 -0
- package/extensions/modules/repair/index.ts +414 -0
- package/extensions/modules/repair/lib/auto-bg.ts +333 -0
- package/extensions/modules/repair/lib/edit-repair.ts +155 -0
- package/extensions/modules/repair/lib/editor.ts +251 -0
- package/extensions/modules/repair/lib/guards.ts +34 -0
- package/extensions/modules/repair/lib/input-repair.ts +324 -0
- package/extensions/modules/repair/lib/patch.ts +481 -0
- package/extensions/modules/repair/lib/settings.ts +114 -0
- package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
- package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
- package/extensions/modules/repair/test/editor.test.ts +141 -0
- package/extensions/modules/repair/test/guards.test.ts +64 -0
- package/extensions/modules/repair/test/input-repair.test.ts +231 -0
- package/extensions/modules/repair/test/patch.test.ts +563 -0
- package/extensions/modules/repair/test/settings.test.ts +167 -0
- package/extensions/modules/repair/test/wrapper.test.ts +210 -0
- package/extensions/modules/router/commands/commands.ts +4 -0
- package/extensions/modules/router/lib/client.ts +61 -0
- package/extensions/modules/router/lib/provider.ts +34 -13
- package/extensions/modules/router/lib/systemone.ts +152 -0
- package/extensions/modules/router/test/unit.test.ts +179 -0
- package/extensions/modules/rtk/findFallback.js +68 -0
- package/extensions/modules/rtk/index.ts +248 -0
- package/extensions/modules/rtk/safe-rewrite.js +74 -0
- package/extensions/modules/rtk/test/findFallback.test.js +66 -0
- package/extensions/modules/rtk/test/index.test.js +131 -0
- package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
- package/extensions/modules/rtk/version-gate.js +34 -0
- package/extensions/modules/serena/index.ts +629 -0
- package/extensions/modules/serena/lib/detect.ts +73 -0
- package/extensions/modules/serena/lib/env.ts +76 -0
- package/extensions/modules/serena/lib/guidance.ts +26 -0
- package/extensions/modules/serena/lib/normalize.ts +27 -0
- package/extensions/modules/serena/lib/symbol-key.ts +20 -0
- package/extensions/modules/serena/lib/truncate.ts +20 -0
- package/extensions/modules/serena/test/env.test.ts +122 -0
- package/extensions/modules/serena/test/index.test.ts +347 -0
- package/extensions/modules/serena/test/worker.test.ts +562 -0
- package/extensions/modules/serena/worker.ts +858 -0
- package/extensions/modules/steering/configPanel.ts +122 -0
- package/extensions/modules/steering/index.ts +616 -0
- package/extensions/modules/steering/lib/anchor.ts +175 -0
- package/extensions/modules/steering/lib/errors.ts +253 -0
- package/extensions/modules/steering/lib/family.ts +33 -0
- package/extensions/modules/steering/lib/guidance.ts +172 -0
- package/extensions/modules/steering/lib/history.ts +170 -0
- package/extensions/modules/steering/lib/settings.ts +127 -0
- package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
- package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
- package/extensions/modules/steering/test/anchor.test.ts +160 -0
- package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
- package/extensions/modules/steering/test/errors.test.ts +309 -0
- package/extensions/modules/steering/test/family.test.ts +43 -0
- package/extensions/modules/steering/test/guidance.test.ts +357 -0
- package/extensions/modules/steering/test/harness.ts +93 -0
- package/extensions/modules/steering/test/history.test.ts +118 -0
- package/extensions/modules/steering/test/settings.test.ts +182 -0
- package/extensions/modules/steering/test/status.test.ts +71 -0
- package/extensions/modules/steering/test/toolCall.test.ts +99 -0
- package/extensions/modules/subagent/agents/planner.md +14 -0
- package/extensions/modules/subagent/agents/reviewer.md +42 -0
- package/extensions/modules/subagent/agents/scout.md +47 -0
- package/extensions/modules/subagent/agents/tester.md +12 -0
- package/extensions/modules/subagent/agents/worker.md +18 -0
- package/extensions/modules/subagent/configPanel.ts +219 -0
- package/extensions/modules/subagent/index.ts +2451 -0
- package/extensions/modules/subagent/lib/agents.ts +408 -0
- package/extensions/modules/subagent/lib/background.ts +383 -0
- package/extensions/modules/subagent/lib/herdr.ts +1019 -0
- package/extensions/modules/subagent/lib/history.ts +126 -0
- package/extensions/modules/subagent/lib/model.ts +156 -0
- package/extensions/modules/subagent/lib/render.ts +335 -0
- package/extensions/modules/subagent/lib/result.ts +110 -0
- package/extensions/modules/subagent/lib/roles.ts +296 -0
- package/extensions/modules/subagent/lib/routing.ts +223 -0
- package/extensions/modules/subagent/lib/runner.ts +559 -0
- package/extensions/modules/subagent/lib/schema.ts +21 -0
- package/extensions/modules/subagent/lib/security.ts +752 -0
- package/extensions/modules/subagent/lib/settings.ts +159 -0
- package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
- package/extensions/modules/subagent/lib/threads.ts +135 -0
- package/extensions/modules/subagent/lib/types.ts +18 -0
- package/extensions/modules/subagent/lib/widget.ts +475 -0
- package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
- package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
- package/extensions/modules/subagent/test/routing.test.ts +350 -0
- package/extensions/modules/subagent/test/widget.test.ts +208 -0
- package/extensions/modules/usage/index.ts +59 -16
- package/extensions/modules/usage/test/genrate.test.ts +70 -0
- package/extensions/modules/usage/test/parsers.test.ts +13 -0
- package/extensions/modules/ux/UPSTREAM +24 -0
- package/extensions/modules/ux/index.ts +393 -0
- package/extensions/modules/ux/lib/audit.ts +562 -0
- package/extensions/modules/ux/lib/config.ts +136 -0
- package/extensions/modules/ux/lib/instructions.ts +77 -0
- package/extensions/modules/ux/test/audit.test.ts +756 -0
- package/extensions/modules/ux/test/extension.test.ts +394 -0
- package/extensions/modules/ux/test/instructions.test.ts +19 -0
- package/extensions/modules/web/configPanel.ts +193 -0
- package/extensions/modules/web/index.ts +978 -0
- package/extensions/modules/web/lib/agy.ts +209 -0
- package/extensions/modules/web/lib/brave.ts +42 -0
- package/extensions/modules/web/lib/cdp.ts +686 -0
- package/extensions/modules/web/lib/chatapi.ts +101 -0
- package/extensions/modules/web/lib/chatgpt.ts +796 -0
- package/extensions/modules/web/lib/chrome.ts +328 -0
- package/extensions/modules/web/lib/config.ts +136 -0
- package/extensions/modules/web/lib/content.ts +99 -0
- package/extensions/modules/web/lib/crawl4ai.ts +172 -0
- package/extensions/modules/web/lib/extract.ts +235 -0
- package/extensions/modules/web/lib/firecrawl.ts +56 -0
- package/extensions/modules/web/lib/format.ts +197 -0
- package/extensions/modules/web/lib/gemini-auth.ts +286 -0
- package/extensions/modules/web/lib/gemini-dr.ts +338 -0
- package/extensions/modules/web/lib/gemini.ts +551 -0
- package/extensions/modules/web/lib/imageapi.ts +559 -0
- package/extensions/modules/web/lib/retry.ts +71 -0
- package/extensions/modules/web/lib/search.ts +237 -0
- package/extensions/modules/web/lib/searxng.ts +69 -0
- package/extensions/modules/web/lib/settings.ts +148 -0
- package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
- package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
- package/extensions/modules/web/test/agy.test.ts +383 -0
- package/extensions/modules/web/test/cdp.test.ts +717 -0
- package/extensions/modules/web/test/chat.test.ts +171 -0
- package/extensions/modules/web/test/chatgpt.test.ts +633 -0
- package/extensions/modules/web/test/chrome.test.ts +282 -0
- package/extensions/modules/web/test/config.test.ts +218 -0
- package/extensions/modules/web/test/configPanel.test.ts +132 -0
- package/extensions/modules/web/test/crawl.test.ts +134 -0
- package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
- package/extensions/modules/web/test/extension.test.ts +118 -0
- package/extensions/modules/web/test/extract.test.ts +436 -0
- package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
- package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
- package/extensions/modules/web/test/fixtures/interaction.html +31 -0
- package/extensions/modules/web/test/format.test.ts +230 -0
- package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
- package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
- package/extensions/modules/web/test/gemini.test.ts +472 -0
- package/extensions/modules/web/test/hook.test.ts +101 -0
- package/extensions/modules/web/test/image.test.ts +1089 -0
- package/extensions/modules/web/test/retry.test.ts +119 -0
- package/extensions/modules/web/test/screenshot.test.ts +109 -0
- package/extensions/modules/web/test/search.test.ts +210 -0
- package/extensions/modules/web/test/settings.test.ts +165 -0
- package/extensions/modules/web/test/skill.test.ts +72 -0
- package/extensions/modules/web/types.d.ts +3 -0
- package/extensions/modules/web/vendor/package.json +1 -0
- package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
- package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
- package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
- package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
- package/extensions/modules/web/vendor/readability/index.js +9 -0
- package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
- package/extensions/modules/zai/configPanel.ts +151 -0
- package/extensions/modules/zai/index.ts +186 -0
- package/extensions/modules/zai/lib/anthropic.ts +159 -0
- package/extensions/modules/zai/lib/settings.ts +198 -0
- package/extensions/modules/zai/lib/signing.ts +718 -0
- package/extensions/modules/zai/lib/throttle.ts +198 -0
- package/extensions/modules/zai/test/anthropic.test.ts +132 -0
- package/extensions/modules/zai/test/configPanel.test.ts +207 -0
- package/extensions/modules/zai/test/extension.test.ts +249 -0
- package/extensions/modules/zai/test/settings.test.ts +183 -0
- package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
- package/extensions/modules/zai/test/signing.test.ts +345 -0
- package/extensions/modules/zai/test/throttle.test.ts +329 -0
- package/package.json +19 -4
- package/scripts/validate-themes.mjs +75 -0
- package/skills/munin/SKILL.md +117 -0
- package/skills/ux-capture/SKILL.md +202 -0
- package/skills/ux-design/SKILL.md +279 -0
- package/skills/ux-presets/SKILL.md +484 -0
- package/skills/ux-routing/SKILL.md +46 -0
- package/skills/web/SKILL.md +153 -0
- package/themes/alabaster.json +93 -0
- package/themes/amethyst.json +96 -0
- package/themes/anthracite.json +93 -0
- package/themes/basalt.json +91 -0
- package/themes/birch.json +95 -0
- package/themes/catppuccin-mocha.json +91 -0
- package/themes/dark-abyss.json +91 -0
- package/themes/dark-arctic.json +104 -0
- package/themes/dark-aurora.json +95 -0
- package/themes/dark-catppuccin.json +107 -0
- package/themes/dark-cavern.json +91 -0
- package/themes/dark-celestial.json +106 -0
- package/themes/dark-copper.json +95 -0
- package/themes/dark-cosmos.json +90 -0
- package/themes/dark-cyberpunk.json +102 -0
- package/themes/dark-dracula.json +98 -0
- package/themes/dark-eclipse.json +91 -0
- package/themes/dark-ember.json +95 -0
- package/themes/dark-equinox.json +90 -0
- package/themes/dark-forest.json +96 -0
- package/themes/dark-github.json +105 -0
- package/themes/dark-gruvbox.json +112 -0
- package/themes/dark-lavender.json +95 -0
- package/themes/dark-lunar.json +89 -0
- package/themes/dark-midnight.json +95 -0
- package/themes/dark-monochrome.json +94 -0
- package/themes/dark-monokai.json +98 -0
- package/themes/dark-nebula.json +90 -0
- package/themes/dark-neon-noir.json +100 -0
- package/themes/dark-nord.json +98 -0
- package/themes/dark-ocean.json +101 -0
- package/themes/dark-one.json +100 -0
- package/themes/dark-poimandres.json +115 -0
- package/themes/dark-rainforest.json +91 -0
- package/themes/dark-reef.json +91 -0
- package/themes/dark-retro.json +92 -0
- package/themes/dark-rose-pine.json +96 -0
- package/themes/dark-sakura.json +95 -0
- package/themes/dark-slate.json +95 -0
- package/themes/dark-solarized.json +97 -0
- package/themes/dark-solstice.json +90 -0
- package/themes/dark-starfall.json +91 -0
- package/themes/dark-sunset.json +99 -0
- package/themes/dark-swamp.json +90 -0
- package/themes/dark-synthwave.json +103 -0
- package/themes/dark-taiga.json +91 -0
- package/themes/dark-terminal.json +95 -0
- package/themes/dark-tokyo-night.json +101 -0
- package/themes/dark-tundra.json +91 -0
- package/themes/dark-twilight.json +91 -0
- package/themes/dark-volcanic.json +91 -0
- package/themes/dark.json +80 -0
- package/themes/graphite.json +92 -0
- package/themes/light-arctic.json +107 -0
- package/themes/light-aurora-day.json +91 -0
- package/themes/light-canyon.json +91 -0
- package/themes/light-catppuccin.json +106 -0
- package/themes/light-cirrus.json +90 -0
- package/themes/light-coral.json +95 -0
- package/themes/light-cyberpunk.json +96 -0
- package/themes/light-dawn.json +90 -0
- package/themes/light-dunes.json +91 -0
- package/themes/light-eucalyptus.json +95 -0
- package/themes/light-forest.json +100 -0
- package/themes/light-frost.json +95 -0
- package/themes/light-github.json +115 -0
- package/themes/light-glacier.json +91 -0
- package/themes/light-gruvbox.json +108 -0
- package/themes/light-haze.json +90 -0
- package/themes/light-honeycomb.json +95 -0
- package/themes/light-lagoon.json +91 -0
- package/themes/light-lavender.json +95 -0
- package/themes/light-meadow.json +91 -0
- package/themes/light-mint.json +95 -0
- package/themes/light-monochrome.json +101 -0
- package/themes/light-ocean.json +99 -0
- package/themes/light-one.json +99 -0
- package/themes/light-opal.json +91 -0
- package/themes/light-orchard.json +91 -0
- package/themes/light-paper.json +95 -0
- package/themes/light-poimandres.json +115 -0
- package/themes/light-prism.json +90 -0
- package/themes/light-retro.json +98 -0
- package/themes/light-sand.json +95 -0
- package/themes/light-savanna.json +91 -0
- package/themes/light-solarized.json +102 -0
- package/themes/light-soleil.json +90 -0
- package/themes/light-sunset.json +99 -0
- package/themes/light-synthwave.json +98 -0
- package/themes/light-tokyo-night.json +111 -0
- package/themes/light-wetland.json +91 -0
- package/themes/light-zenith.json +89 -0
- package/themes/light.json +80 -0
- package/themes/limestone.json +94 -0
- package/themes/mahogany.json +97 -0
- package/themes/marble.json +93 -0
- package/themes/mirage.json +79 -0
- package/themes/obsidian.json +91 -0
- package/themes/onyx.json +91 -0
- package/themes/pearl.json +93 -0
- package/themes/porcelain.json +91 -0
- package/themes/quartz.json +96 -0
- package/themes/sandstone.json +95 -0
- package/themes/titanium.json +90 -0
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for the direct ChatGPT web-tier client (lib/chatgpt.ts) and its
|
|
3
|
+
* web_image chain integration. No network — fetch is injected; SSE streams
|
|
4
|
+
* come from canned event lists.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, beforeEach, afterEach } from "node:test";
|
|
8
|
+
import assert from "node:assert/strict";
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import {
|
|
14
|
+
CHATGPT_MODEL_FALLBACK,
|
|
15
|
+
ChatGptApiError,
|
|
16
|
+
ChatGptAuthError,
|
|
17
|
+
chatgptWebChat,
|
|
18
|
+
chatgptWebGenerateImage,
|
|
19
|
+
defaultChatGptAuthStorePath,
|
|
20
|
+
describeChatGptError,
|
|
21
|
+
loadChatGptAuth,
|
|
22
|
+
refreshChatGptAuth,
|
|
23
|
+
__resetChatGptAuthState,
|
|
24
|
+
type ChatGptAuth,
|
|
25
|
+
type SSEFetchLike,
|
|
26
|
+
} from "../lib/chatgpt";
|
|
27
|
+
import { __resetImageRate, generateImageWithFallback, loadImageRateConfig } from "../lib/imageapi";
|
|
28
|
+
|
|
29
|
+
// chai-compat helpers (assert-based)
|
|
30
|
+
function includes(haystack: unknown, needle: unknown): boolean {
|
|
31
|
+
if (typeof haystack === "string") return haystack.includes(String(needle));
|
|
32
|
+
if (Array.isArray(haystack)) return (haystack as unknown[]).some((v) => {
|
|
33
|
+
if (typeof v === "string" && typeof needle === "string") return v.includes(needle);
|
|
34
|
+
if (v === needle) return true;
|
|
35
|
+
// chai's to.include on an array does DEEP membership for objects.
|
|
36
|
+
if (v && needle && typeof v === "object" && typeof needle === "object") {
|
|
37
|
+
try { assert.deepStrictEqual(v, needle); return true; } catch { return false; }
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
});
|
|
41
|
+
// chai's to.include on an OBJECT target: needle's properties are a subset.
|
|
42
|
+
if (haystack && typeof haystack === "object" && needle && typeof needle === "object") {
|
|
43
|
+
return deepIncludes(haystack, needle as Record<string, unknown>);
|
|
44
|
+
}
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
function lengthOf(v: unknown): number {
|
|
48
|
+
if (Array.isArray(v)) return v.length;
|
|
49
|
+
if (typeof v === "string") return v.length;
|
|
50
|
+
if (v && typeof v === "object" && "length" in (v as Record<string, unknown>)) return Number((v as Record<string, unknown>).length);
|
|
51
|
+
if (v && typeof v === "object" && "size" in (v as Record<string, unknown>)) return Number((v as Record<string, unknown>).size);
|
|
52
|
+
throw new Error("lengthOf: value has no length/size");
|
|
53
|
+
}
|
|
54
|
+
/** Deep "includes" — every own key of `part` must exist on `obj` with a
|
|
55
|
+
* deep-equal value (chai's to.deep.include for object subjects). */
|
|
56
|
+
function deepIncludes(obj: unknown, part: Record<string, unknown>): boolean {
|
|
57
|
+
if (Array.isArray(obj)) return includes(obj, part); // deep membership
|
|
58
|
+
if (typeof obj !== "object" || obj === null) return false;
|
|
59
|
+
return Object.entries(part).every(([k, v]) => {
|
|
60
|
+
try { assert.deepStrictEqual((obj as Record<string, unknown>)[k], v); return true; } catch { return false; }
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
// Fixtures
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
const ENV_VARS = [
|
|
69
|
+
"CHATGPT_WEB_AUTH_KEY",
|
|
70
|
+
"CHATGPT_WEB_CODEX_AUTH",
|
|
71
|
+
"CHATGPT_WEB_MODEL",
|
|
72
|
+
"CHATGPT_WEB_AUTH_STORE",
|
|
73
|
+
"PI_CODING_AGENT_DIR",
|
|
74
|
+
] as const;
|
|
75
|
+
const OLD_ENV: Record<string, string | undefined> = {};
|
|
76
|
+
|
|
77
|
+
beforeEach(() => {
|
|
78
|
+
for (const k of ENV_VARS) OLD_ENV[k] = process.env[k];
|
|
79
|
+
for (const k of ENV_VARS) delete process.env[k];
|
|
80
|
+
process.env.PI_CODING_AGENT_DIR = "/nonexistent-pi-agent-dir";
|
|
81
|
+
__resetChatGptAuthState();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
afterEach(() => {
|
|
85
|
+
for (const k of ENV_VARS) {
|
|
86
|
+
if (OLD_ENV[k] !== undefined) process.env[k] = OLD_ENV[k];
|
|
87
|
+
else delete process.env[k];
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
function jwt(claims: Record<string, unknown>): string {
|
|
92
|
+
const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");
|
|
93
|
+
return `${b64({ alg: "RS256", typ: "JWT" })}.${b64(claims)}.sig`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const FUTURE_EXP = Math.floor(Date.now() / 1000) + 3600;
|
|
97
|
+
const PAST_EXP = Math.floor(Date.now() / 1000) - 3600;
|
|
98
|
+
|
|
99
|
+
function accessToken(claimsExtra: Record<string, unknown> = {}): string {
|
|
100
|
+
return jwt({
|
|
101
|
+
exp: FUTURE_EXP,
|
|
102
|
+
"https://api.openai.com/auth": { chatgpt_account_id: "acc-123", chatgpt_plan_type: "plus" },
|
|
103
|
+
"https://api.openai.com/profile": { email: "user@example.com" },
|
|
104
|
+
...claimsExtra,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function makeAuth(overrides: Partial<ChatGptAuth> = {}): ChatGptAuth {
|
|
109
|
+
return { accessToken: accessToken(), source: "test", sourceKind: "env", accountId: "acc-123", ...overrides };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function sseFetch(events: unknown[], opts: { status?: number; statusText?: string; jsonBody?: unknown } = {}): { fetch: SSEFetchLike; calls: { url: string; init?: any }[] } {
|
|
113
|
+
const calls: { url: string; init?: any }[] = [];
|
|
114
|
+
const encoder = new TextEncoder();
|
|
115
|
+
const fetch: SSEFetchLike = (async (url: string, init?: any) => {
|
|
116
|
+
calls.push({ url, init });
|
|
117
|
+
const status = opts.status ?? 200;
|
|
118
|
+
if (status !== 200) {
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
status,
|
|
122
|
+
statusText: opts.statusText,
|
|
123
|
+
text: async () => JSON.stringify(opts.jsonBody ?? { error: { message: "nope" } }),
|
|
124
|
+
body: null,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
const payload = events.map((e) => `data: ${JSON.stringify(e)}`).join("\n\n") + "\n\ndata: [DONE]\n\n";
|
|
128
|
+
const bytes = encoder.encode(payload);
|
|
129
|
+
async function* body(): AsyncIterable<Uint8Array> {
|
|
130
|
+
// yield in two chunks to exercise line buffering across chunks
|
|
131
|
+
yield bytes.slice(0, Math.ceil(bytes.length / 2));
|
|
132
|
+
yield bytes.slice(Math.ceil(bytes.length / 2));
|
|
133
|
+
}
|
|
134
|
+
return { ok: true, status, body: body() };
|
|
135
|
+
}) as SSEFetchLike;
|
|
136
|
+
return { fetch, calls };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const sseText = (delta: string) => ({ type: "response.output_text.delta", delta });
|
|
140
|
+
const sseImageDone = (b64: string) => ({ type: "response.output_item.done", item: { type: "image_generation_call", result: b64 } });
|
|
141
|
+
const PNG_B64 = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4]).toString("base64");
|
|
142
|
+
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
// Credential resolution
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
describe("loadChatGptAuth", () => {
|
|
148
|
+
it("parses the codex-login tokens JSON from env", () => {
|
|
149
|
+
process.env.CHATGPT_WEB_AUTH_KEY = JSON.stringify({ tokens: { access_token: accessToken(), refresh_token: "rt", account_id: "acc-file" } });
|
|
150
|
+
const { auth, problem } = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: "/nonexistent", storePath: "/nonexistent-store" });
|
|
151
|
+
assert.equal(problem, undefined);
|
|
152
|
+
assert.equal(auth?.accessToken, accessToken());
|
|
153
|
+
assert.equal(auth?.refreshToken, "rt");
|
|
154
|
+
assert.equal(auth?.accountId, "acc-123"); // from claims
|
|
155
|
+
assert.equal(auth?.plan, "plus");
|
|
156
|
+
assert.equal(auth?.email, "user@example.com");
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("parses flat OAuth JSON", () => {
|
|
160
|
+
process.env.CHATGPT_WEB_AUTH_KEY = JSON.stringify({ access_token: accessToken(), refresh: "r2" });
|
|
161
|
+
const { auth } = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: "/nonexistent" });
|
|
162
|
+
assert.equal(auth?.refreshToken, "r2");
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("accepts a bare JWT", () => {
|
|
166
|
+
process.env.CHATGPT_WEB_AUTH_KEY = accessToken();
|
|
167
|
+
const { auth } = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: "/nonexistent" });
|
|
168
|
+
assert.equal(auth?.accountId, "acc-123");
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("reports a problem for opaque bridge-era keys (not an OAuth token)", () => {
|
|
172
|
+
process.env.CHATGPT_WEB_AUTH_KEY = "ae04ae981deadbeef";
|
|
173
|
+
const { auth, problem } = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: "/nonexistent" });
|
|
174
|
+
assert.equal(auth, null);
|
|
175
|
+
assert.ok(includes(problem, "not an OpenAI OAuth token"));
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("falls back to the codex auth file, then pi auth.json", () => {
|
|
179
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-test-"));
|
|
180
|
+
fs.writeFileSync(path.join(dir, "auth.json"), JSON.stringify({ tokens: { access_token: accessToken({ exp: FUTURE_EXP }), refresh_token: "rt-file" } }));
|
|
181
|
+
const { auth } = loadChatGptAuth("/nonexistent", false, { codexAuthPath: path.join(dir, "auth.json"), piAuthPath: "/nonexistent" });
|
|
182
|
+
assert.ok(includes(auth?.source, "auth.json"));
|
|
183
|
+
assert.equal(auth?.refreshToken, "rt-file");
|
|
184
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it("falls back to the pi auth.json openai-codex entry (read-only)", () => {
|
|
188
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-test-"));
|
|
189
|
+
fs.writeFileSync(path.join(dir, "pi-auth.json"), JSON.stringify({ "openai-codex": { type: "oauth", access: accessToken(), refresh: "rt-pi", accountId: "acc-pi" } }));
|
|
190
|
+
const { auth } = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: path.join(dir, "pi-auth.json") });
|
|
191
|
+
assert.equal(auth?.refreshToken, "rt-pi");
|
|
192
|
+
assert.ok(includes(auth?.source, "openai-codex"));
|
|
193
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it("returns null when nothing is configured", () => {
|
|
197
|
+
const { auth, problem } = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: "/nonexistent" });
|
|
198
|
+
assert.equal(auth, null);
|
|
199
|
+
assert.equal(problem, undefined);
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
// ---------------------------------------------------------------------------
|
|
204
|
+
// Refresh + store
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
// ponytail: plain structural fake — (url, init) => 200 + tokens JSON
|
|
208
|
+
function refreshOkFetch(newToken: string): any {
|
|
209
|
+
return (async (url: string) => {
|
|
210
|
+
void url;
|
|
211
|
+
return { status: 200, text: JSON.stringify({ access_token: newToken, refresh_token: "rt-rotated", expires_in: 3600 }) };
|
|
212
|
+
}) as any;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
describe("refreshChatGptAuth", () => {
|
|
216
|
+
it("refreshes, persists to the store (env source), and rotates the refresh token", async () => {
|
|
217
|
+
const storePath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-store-")), "store.json");
|
|
218
|
+
const auth: ChatGptAuth = { ...makeAuth({ expiresAt: Date.now() - 1000, refreshToken: "rt-old" }) };
|
|
219
|
+
const fresh = await refreshChatGptAuth(auth, { storePath, refreshFetch: refreshOkFetch(accessToken()) });
|
|
220
|
+
assert.equal(fresh.accessToken, accessToken());
|
|
221
|
+
assert.equal(fresh.refreshToken, "rt-rotated");
|
|
222
|
+
const stored = JSON.parse(fs.readFileSync(storePath, "utf8"));
|
|
223
|
+
assert.equal(stored.refreshToken, "rt-rotated");
|
|
224
|
+
assert.equal(stored.refreshKey, createHash("sha256").update("rt-rotated").digest("hex").slice(0, 16));
|
|
225
|
+
fs.rmSync(path.dirname(storePath), { recursive: true, force: true });
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("rewrites the codex auth file in place when that is the source", async () => {
|
|
229
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-codex-"));
|
|
230
|
+
const file = path.join(dir, "auth.json");
|
|
231
|
+
fs.writeFileSync(file, JSON.stringify({ tokens: { access_token: "old", refresh_token: "rt-old" }, other: "kept" }));
|
|
232
|
+
const auth: ChatGptAuth = { accessToken: "old", refreshToken: "rt-old", source: file, sourceKind: "codex-file" };
|
|
233
|
+
await refreshChatGptAuth(auth, { refreshFetch: refreshOkFetch(accessToken()) });
|
|
234
|
+
const rewritten = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
235
|
+
assert.equal(rewritten.other, "kept");
|
|
236
|
+
assert.equal(rewritten.tokens.access_token, accessToken());
|
|
237
|
+
assert.equal(rewritten.tokens.refresh_token, "rt-rotated");
|
|
238
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it("throws an honest re-login error on invalid_grant", async () => {
|
|
242
|
+
const auth: ChatGptAuth = { ...makeAuth({ refreshToken: "rt-dead" }) };
|
|
243
|
+
const refreshFetch = (async () => ({ status: 400, text: JSON.stringify({ error: "invalid_grant" }) })) as any;
|
|
244
|
+
try {
|
|
245
|
+
await refreshChatGptAuth(auth, { refreshFetch });
|
|
246
|
+
assert.fail("should throw");
|
|
247
|
+
} catch (e) {
|
|
248
|
+
assert.ok(e instanceof ChatGptAuthError);
|
|
249
|
+
assert.ok(includes((e as Error).message, "codex login"));
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it("refuses to refresh without a refresh token", async () => {
|
|
254
|
+
const auth: ChatGptAuth = { ...makeAuth({ expiresAt: Date.now() - 1000 }) };
|
|
255
|
+
try {
|
|
256
|
+
await refreshChatGptAuth(auth);
|
|
257
|
+
assert.fail("should throw");
|
|
258
|
+
} catch (e) {
|
|
259
|
+
assert.ok(e instanceof ChatGptAuthError);
|
|
260
|
+
assert.ok(includes((e as Error).message, "codex login"));
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it("loadChatGptAuth prefers a fresher stored token matching the refresh fingerprint", () => {
|
|
265
|
+
const storePath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-store-")), "store.json");
|
|
266
|
+
const freshToken = accessToken();
|
|
267
|
+
fs.writeFileSync(storePath, JSON.stringify({
|
|
268
|
+
refreshKey: createHash("sha256").update("rt-old").digest("hex").slice(0, 16),
|
|
269
|
+
accessToken: freshToken,
|
|
270
|
+
refreshToken: "rt-rotated",
|
|
271
|
+
expiresAt: Date.now() + 7200_000,
|
|
272
|
+
updatedAt: Date.now(),
|
|
273
|
+
}));
|
|
274
|
+
process.env.CHATGPT_WEB_AUTH_KEY = JSON.stringify({ access_token: accessToken({ exp: PAST_EXP }), refresh_token: "rt-old" });
|
|
275
|
+
const { auth } = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: "/nonexistent", storePath });
|
|
276
|
+
assert.equal(auth?.accessToken, freshToken);
|
|
277
|
+
assert.equal(auth?.refreshToken, "rt-rotated");
|
|
278
|
+
fs.rmSync(path.dirname(storePath), { recursive: true, force: true });
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
it("adopts the rotated token persisted by a previous session's refresh (prev-key match)", async () => {
|
|
282
|
+
const storePath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-store-")), "store.json");
|
|
283
|
+
process.env.CHATGPT_WEB_AUTH_KEY = JSON.stringify({ access_token: accessToken({ exp: PAST_EXP }), refresh_token: "rt-old" });
|
|
284
|
+
// previous session: refresh rotates rt-old → rt-rotated, persists the store
|
|
285
|
+
const first = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: "/nonexistent", storePath }).auth!;
|
|
286
|
+
await refreshChatGptAuth(first, { storePath, refreshFetch: refreshOkFetch(accessToken({ exp: FUTURE_EXP + 3600 })) });
|
|
287
|
+
const stored = JSON.parse(fs.readFileSync(storePath, "utf8"));
|
|
288
|
+
assert.equal(stored.prevRefreshKey, createHash("sha256").update("rt-old").digest("hex").slice(0, 16));
|
|
289
|
+
// next session: SAME env (still stale access + rt-old) must adopt the store
|
|
290
|
+
const next = loadChatGptAuth("/nonexistent", false, { codexAuthPath: "/nonexistent", piAuthPath: "/nonexistent", storePath }).auth!;
|
|
291
|
+
assert.equal(next!.refreshToken, "rt-rotated");
|
|
292
|
+
assert.equal(next!.accessToken, accessToken({ exp: FUTURE_EXP + 3600 }));
|
|
293
|
+
assert.ok((next!.expiresAt ?? 0) > Date.now());
|
|
294
|
+
fs.rmSync(path.dirname(storePath), { recursive: true, force: true });
|
|
295
|
+
});
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
// ---------------------------------------------------------------------------
|
|
299
|
+
// Chat
|
|
300
|
+
// ---------------------------------------------------------------------------
|
|
301
|
+
|
|
302
|
+
describe("chatgptWebChat", () => {
|
|
303
|
+
it("streams the answer from output_text deltas and sends the codex request shape", async () => {
|
|
304
|
+
const { fetch, calls } = sseFetch([
|
|
305
|
+
{ type: "response.created", response: { tools: [] } },
|
|
306
|
+
sseText("pon"),
|
|
307
|
+
sseText("g"),
|
|
308
|
+
{ type: "response.completed", response: { usage: { input_tokens: 5, output_tokens: 1, total_tokens: 6 }, output: [] } },
|
|
309
|
+
]);
|
|
310
|
+
const r = await chatgptWebChat({ auth: makeAuth(), prompt: "say pong", fetchImpl: fetch });
|
|
311
|
+
assert.equal(r.text, "pong");
|
|
312
|
+
assert.equal(r.model, "gpt-5.5");
|
|
313
|
+
assert.equal(r.usage?.totalTokens, 6);
|
|
314
|
+
const init = calls[0].init;
|
|
315
|
+
assert.equal(calls[0].url, "https://chatgpt.com/backend-api/codex/responses");
|
|
316
|
+
assert.match(String(init.headers.Authorization), /^Bearer eyJ/);
|
|
317
|
+
assert.equal(init.headers["chatgpt-account-id"], "acc-123");
|
|
318
|
+
assert.equal(init.headers.Accept, "text/event-stream");
|
|
319
|
+
assert.equal(init.headers["OpenAI-Beta"], "responses=experimental");
|
|
320
|
+
assert.equal(init.headers["session-id"], init.headers["x-client-request-id"]);
|
|
321
|
+
const body = JSON.parse(init.body);
|
|
322
|
+
assert.equal(body.stream, true);
|
|
323
|
+
assert.equal(body.store, false);
|
|
324
|
+
assert.equal(body.model, "gpt-5.5");
|
|
325
|
+
assert.equal(body.instructions, "You are a helpful assistant.");
|
|
326
|
+
assert.equal(body.input[0].content[0].text, "say pong");
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it("passes system through as instructions", async () => {
|
|
330
|
+
const { fetch, calls } = sseFetch([sseText("ok")]);
|
|
331
|
+
await chatgptWebChat({ auth: makeAuth(), prompt: "q", system: "be terse", fetchImpl: fetch });
|
|
332
|
+
assert.equal(JSON.parse(calls[0].init.body).instructions, "be terse");
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it("falls back to the completed response output when no deltas arrived", async () => {
|
|
336
|
+
const { fetch } = sseFetch([
|
|
337
|
+
{ type: "response.completed", response: { output: [{ type: "message", content: [{ type: "output_text", text: "final text" }] }] } },
|
|
338
|
+
]);
|
|
339
|
+
const r = await chatgptWebChat({ auth: makeAuth(), prompt: "q", fetchImpl: fetch });
|
|
340
|
+
assert.equal(r.text, "final text");
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
it("falls back to the fallback model on unknown-model errors", async () => {
|
|
344
|
+
const calls: any[] = [];
|
|
345
|
+
let n = 0;
|
|
346
|
+
const fetch: SSEFetchLike = (async (_url, init) => {
|
|
347
|
+
calls.push(init);
|
|
348
|
+
n++;
|
|
349
|
+
if (n === 1) return { ok: false, status: 400, text: async () => JSON.stringify({ error: { message: "Unknown model: bogus-model" } }) };
|
|
350
|
+
const encoder = new TextEncoder();
|
|
351
|
+
const bytes = encoder.encode(`data: ${JSON.stringify(sseText("ok"))}\n\ndata: [DONE]\n\n`);
|
|
352
|
+
async function* body() { yield bytes; }
|
|
353
|
+
return { ok: true, status: 200, body: body() };
|
|
354
|
+
}) as SSEFetchLike;
|
|
355
|
+
const r = await chatgptWebChat({ auth: makeAuth(), prompt: "q", model: "bogus-model", fetchImpl: fetch });
|
|
356
|
+
assert.equal(r.model, CHATGPT_MODEL_FALLBACK);
|
|
357
|
+
assert.equal(JSON.parse(calls[1].body).model, CHATGPT_MODEL_FALLBACK);
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
it("surfaces mid-stream failure details and empty completions", async () => {
|
|
361
|
+
const failed = sseFetch([{ type: "response.failed", response: { error: { message: "quota exceeded" } } }]);
|
|
362
|
+
try {
|
|
363
|
+
await chatgptWebChat({ auth: makeAuth(), prompt: "q", fetchImpl: failed.fetch });
|
|
364
|
+
assert.fail("should throw");
|
|
365
|
+
} catch (e) {
|
|
366
|
+
assert.ok(includes(describeChatGptError(e), "quota exceeded"));
|
|
367
|
+
}
|
|
368
|
+
const empty = sseFetch([{ type: "response.created", response: {} }]);
|
|
369
|
+
try {
|
|
370
|
+
await chatgptWebChat({ auth: makeAuth(), prompt: "q", fetchImpl: empty.fetch });
|
|
371
|
+
assert.fail("should throw");
|
|
372
|
+
} catch (e) {
|
|
373
|
+
assert.ok(includes((e as Error).message, "no usable output"));
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
// ---------------------------------------------------------------------------
|
|
379
|
+
// Auth retry
|
|
380
|
+
// ---------------------------------------------------------------------------
|
|
381
|
+
|
|
382
|
+
describe("auth retry", () => {
|
|
383
|
+
function makeFlow(authExpiryPast: boolean) {
|
|
384
|
+
// The API 401s exactly the STALE token; the refresh issues a fresh one, so
|
|
385
|
+
// a proactive refresh never hits the wire and a mid-session 401 retries once.
|
|
386
|
+
const apiCalls: string[] = [];
|
|
387
|
+
const staleToken = accessToken();
|
|
388
|
+
const staleAuth = (): ChatGptAuth => makeAuth({ accessToken: staleToken, expiresAt: authExpiryPast ? Date.now() - 1000 : FUTURE_EXP * 1000, refreshToken: "rt-old" });
|
|
389
|
+
let refreshed = false;
|
|
390
|
+
const refreshFetch = (async () => {
|
|
391
|
+
refreshed = true;
|
|
392
|
+
// the refreshed token must differ from the stale fixture, or the fake
|
|
393
|
+
// would 401 the post-refresh call too
|
|
394
|
+
return { status: 200, text: JSON.stringify({ access_token: accessToken({ exp: FUTURE_EXP + 3600 }), refresh_token: "rt-new" }) };
|
|
395
|
+
}) as any;
|
|
396
|
+
const encode = (obj: unknown) => new TextEncoder().encode(`data: ${JSON.stringify(obj)}\n\ndata: [DONE]\n\n`);
|
|
397
|
+
const okStream = async function* () { yield encode(sseText("recovered")); }();
|
|
398
|
+
const fetch: SSEFetchLike = (async (_url, init) => {
|
|
399
|
+
apiCalls.push(init!.headers!.Authorization);
|
|
400
|
+
if (init!.headers!.Authorization === `Bearer ${staleToken}`) return { ok: false, status: 401, text: async () => JSON.stringify({ error: { message: "expired" } }) };
|
|
401
|
+
return { ok: true, status: 200, body: okStream };
|
|
402
|
+
}) as SSEFetchLike;
|
|
403
|
+
return { staleAuth, refreshFetch, fetch, apiCalls, getRefreshed: () => refreshed };
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
it("proactively refreshes an expired token before the call", async () => {
|
|
407
|
+
const flow = makeFlow(true);
|
|
408
|
+
const r = await chatgptWebChat({ auth: flow.staleAuth(), prompt: "q", fetchImpl: flow.fetch, refreshFetch: flow.refreshFetch, storePath: "/nonexistent-store" });
|
|
409
|
+
assert.equal(r.text, "recovered");
|
|
410
|
+
assert.equal(flow.getRefreshed(), true);
|
|
411
|
+
assert.equal(flow.apiCalls.length, 1); // only the post-refresh call hit the API
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
it("retries once after a 401 mid-session", async () => {
|
|
415
|
+
const flow = makeFlow(false);
|
|
416
|
+
const r = await chatgptWebChat({ auth: flow.staleAuth(), prompt: "q", fetchImpl: flow.fetch, refreshFetch: flow.refreshFetch, storePath: "/nonexistent-store" });
|
|
417
|
+
assert.equal(r.text, "recovered");
|
|
418
|
+
assert.equal(flow.apiCalls.length, 2);
|
|
419
|
+
assert.notEqual(flow.apiCalls[0], flow.apiCalls[1]); // token changed
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it("wraps an expired token without refresh material in an honest error", async () => {
|
|
423
|
+
const auth = makeAuth({ refreshToken: undefined });
|
|
424
|
+
const fetch: SSEFetchLike = (async () => ({ ok: false, status: 401, text: async () => JSON.stringify({ error: { message: "expired" } }) })) as SSEFetchLike;
|
|
425
|
+
try {
|
|
426
|
+
await chatgptWebChat({ auth, prompt: "q", fetchImpl: fetch });
|
|
427
|
+
assert.fail("should throw");
|
|
428
|
+
} catch (e) {
|
|
429
|
+
assert.ok(e instanceof ChatGptAuthError);
|
|
430
|
+
assert.ok(includes((e as Error).message, "no refresh token"));
|
|
431
|
+
}
|
|
432
|
+
});
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
// ---------------------------------------------------------------------------
|
|
436
|
+
// Image generation
|
|
437
|
+
// ---------------------------------------------------------------------------
|
|
438
|
+
|
|
439
|
+
describe("chatgptWebGenerateImage", () => {
|
|
440
|
+
it("decodes the image_generation_call result into a PNG file", async () => {
|
|
441
|
+
const { fetch, calls } = sseFetch([
|
|
442
|
+
{ type: "response.image_generation_call.generating" },
|
|
443
|
+
sseImageDone(PNG_B64),
|
|
444
|
+
{ type: "response.completed", response: { usage: { total_tokens: 100 }, tools: [{ type: "image_generation", model: "gpt-image-2-codex", size: "auto" }] } },
|
|
445
|
+
]);
|
|
446
|
+
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-img-"));
|
|
447
|
+
const r = await chatgptWebGenerateImage({ auth: makeAuth(), prompt: "a red cube", outDir, fetchImpl: fetch });
|
|
448
|
+
assert.equal(r.paths.length, 1);
|
|
449
|
+
const buf = fs.readFileSync(r.paths[0]);
|
|
450
|
+
assert.equal(buf[0], 0x89);
|
|
451
|
+
assert.equal(buf[1], 0x50); // PNG magic
|
|
452
|
+
assert.ok(includes(r.note, "gpt-image-2-codex")); // server rewrote the model
|
|
453
|
+
const body = JSON.parse(calls[0].init.body);
|
|
454
|
+
assert.equal(body.instructions, "You are an image generation assistant.");
|
|
455
|
+
assert.equal(body.tools[0].type, "image_generation");
|
|
456
|
+
assert.equal(body.tools[0].output_format, "png");
|
|
457
|
+
assert.ok(includes(body.input[0].content[0].text, "a red cube"));
|
|
458
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
it("errors honestly when no image arrives", async () => {
|
|
462
|
+
const { fetch } = sseFetch([{ type: "response.completed", response: {} }]);
|
|
463
|
+
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-img-"));
|
|
464
|
+
try {
|
|
465
|
+
await chatgptWebGenerateImage({ auth: makeAuth(), prompt: "p", outDir, fetchImpl: fetch });
|
|
466
|
+
assert.fail("should throw");
|
|
467
|
+
} catch (e) {
|
|
468
|
+
assert.ok(e instanceof ChatGptApiError);
|
|
469
|
+
assert.ok(includes((e as Error).message, "no image returned"));
|
|
470
|
+
}
|
|
471
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
472
|
+
});
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
// ---------------------------------------------------------------------------
|
|
476
|
+
// Env trust boundaries (untrusted project cwd must not steer secrets/models)
|
|
477
|
+
// ---------------------------------------------------------------------------
|
|
478
|
+
|
|
479
|
+
describe("env trust boundaries", () => {
|
|
480
|
+
it("defaultChatGptAuthStorePath ignores untrusted cwd .env.local", () => {
|
|
481
|
+
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-untrusted-"));
|
|
482
|
+
const leak = path.join(cwd, "leak.json");
|
|
483
|
+
fs.writeFileSync(path.join(cwd, ".env.local"), `CHATGPT_WEB_AUTH_STORE=${leak}\n`);
|
|
484
|
+
const p = defaultChatGptAuthStorePath();
|
|
485
|
+
assert.notEqual(p, leak);
|
|
486
|
+
assert.equal(p.endsWith("chatgpt-web-auth.json"), true);
|
|
487
|
+
fs.rmSync(cwd, { recursive: true, force: true });
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
// ceulen: cwd .env files are NEVER read by the module — trust-gated file
|
|
491
|
+
// ingestion lives in the bundle env.ts (it loads trusted cwd values into
|
|
492
|
+
// process.env before any tool runs). So the module-level guarantee is: a
|
|
493
|
+
// repo's .env.local alone never changes the model; only process.env does.
|
|
494
|
+
it("CHATGPT_WEB_MODEL comes from process.env, never from cwd .env files", async () => {
|
|
495
|
+
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-untrusted-"));
|
|
496
|
+
fs.writeFileSync(path.join(cwd, ".env.local"), "CHATGPT_WEB_MODEL=gpt-from-untrusted-cwd\n");
|
|
497
|
+
const calls: any[] = [];
|
|
498
|
+
const fetch: SSEFetchLike = (async (_url, init) => {
|
|
499
|
+
calls.push(init);
|
|
500
|
+
const bytes = new TextEncoder().encode(`data: ${JSON.stringify(sseText("ok"))}\n\ndata: [DONE]\n\n`);
|
|
501
|
+
async function* body() { yield bytes; }
|
|
502
|
+
return { ok: true, status: 200, body: body() };
|
|
503
|
+
}) as SSEFetchLike;
|
|
504
|
+
const oldModel = process.env.CHATGPT_WEB_MODEL;
|
|
505
|
+
delete process.env.CHATGPT_WEB_MODEL;
|
|
506
|
+
try {
|
|
507
|
+
await chatgptWebChat({ auth: makeAuth(), prompt: "q", fetchImpl: fetch, cwd, includeCwdEnv: true });
|
|
508
|
+
assert.equal(JSON.parse(calls[0].body).model, "gpt-5.5"); // cwd file NOT consulted
|
|
509
|
+
process.env.CHATGPT_WEB_MODEL = "gpt-from-env";
|
|
510
|
+
await chatgptWebChat({ auth: makeAuth(), prompt: "q", fetchImpl: fetch, cwd, includeCwdEnv: true });
|
|
511
|
+
assert.equal(JSON.parse(calls[1].body).model, "gpt-from-env"); // process.env → honored
|
|
512
|
+
} finally {
|
|
513
|
+
if (oldModel === undefined) delete process.env.CHATGPT_WEB_MODEL;
|
|
514
|
+
else process.env.CHATGPT_WEB_MODEL = oldModel;
|
|
515
|
+
fs.rmSync(cwd, { recursive: true, force: true });
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
// ---------------------------------------------------------------------------
|
|
521
|
+
// web_image chain integration
|
|
522
|
+
// ---------------------------------------------------------------------------
|
|
523
|
+
|
|
524
|
+
describe("web_image chatgpt chain", () => {
|
|
525
|
+
const rateConfig = loadImageRateConfig("/nonexistent", false);
|
|
526
|
+
const base = {
|
|
527
|
+
prompt: "a red cube",
|
|
528
|
+
n: 1,
|
|
529
|
+
provider: "auto" as const,
|
|
530
|
+
geminiConfig: { psid: undefined, psidSource: undefined, proxy: undefined } as any,
|
|
531
|
+
apiConfig: {} as any,
|
|
532
|
+
rateConfig,
|
|
533
|
+
geminiFactory: (() => { throw new Error("gemini not configured in this test"); }) as any,
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
afterEach(() => __resetImageRate());
|
|
537
|
+
|
|
538
|
+
it("auto chain order is gemini → chatgpt → zai → custom with per-provider hints", async () => {
|
|
539
|
+
const { fetch } = sseFetch([sseImageDone(PNG_B64)]);
|
|
540
|
+
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-chain-"));
|
|
541
|
+
const r = await generateImageWithFallback({
|
|
542
|
+
...base,
|
|
543
|
+
outDir,
|
|
544
|
+
chatgptAuth: makeAuth(),
|
|
545
|
+
chatgptFetchImpl: fetch,
|
|
546
|
+
});
|
|
547
|
+
assert.equal(r.provider, "chatgpt"); // gemini refused → chatgpt picked up
|
|
548
|
+
assert.equal(r.paths.length, 1);
|
|
549
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
550
|
+
});
|
|
551
|
+
|
|
552
|
+
it("unconfigured chatgpt contributes a hint to the all-failed error", async () => {
|
|
553
|
+
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-chain-"));
|
|
554
|
+
try {
|
|
555
|
+
await generateImageWithFallback({
|
|
556
|
+
...base,
|
|
557
|
+
outDir,
|
|
558
|
+
chatgptProblem: "CHATGPT_WEB_AUTH_KEY is set but is not an OpenAI OAuth token",
|
|
559
|
+
});
|
|
560
|
+
assert.fail("should throw");
|
|
561
|
+
} catch (e) {
|
|
562
|
+
const msg = (e as Error).message;
|
|
563
|
+
assert.ok(includes(msg, "gemini: "));
|
|
564
|
+
assert.ok(includes(msg, "not an OpenAI OAuth token"));
|
|
565
|
+
assert.ok(includes(msg, "zai: not configured (set ZAI_API_KEY)"));
|
|
566
|
+
}
|
|
567
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
it("loops n images sequentially over the codex surface", async () => {
|
|
571
|
+
let n = 0;
|
|
572
|
+
const looping: SSEFetchLike = (async (url, init) => {
|
|
573
|
+
void url;
|
|
574
|
+
void init;
|
|
575
|
+
n++;
|
|
576
|
+
const bytes = new TextEncoder().encode(`data: ${JSON.stringify(sseImageDone(PNG_B64))}\n\ndata: [DONE]\n\n`);
|
|
577
|
+
async function* body() { yield bytes; }
|
|
578
|
+
return { ok: true, status: 200, body: body() };
|
|
579
|
+
}) as SSEFetchLike;
|
|
580
|
+
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-chain-"));
|
|
581
|
+
const r = await generateImageWithFallback({
|
|
582
|
+
...base,
|
|
583
|
+
n: 2,
|
|
584
|
+
outDir,
|
|
585
|
+
chatgptAuth: makeAuth(),
|
|
586
|
+
chatgptFetchImpl: looping,
|
|
587
|
+
});
|
|
588
|
+
assert.equal(n, 2);
|
|
589
|
+
assert.equal(r.paths.length, 2);
|
|
590
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
it("counts chatgpt against the daily soft cap", async () => {
|
|
594
|
+
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-chain-"));
|
|
595
|
+
const looping: SSEFetchLike = (async () => {
|
|
596
|
+
const bytes = new TextEncoder().encode(`data: ${JSON.stringify(sseImageDone(PNG_B64))}\n\ndata: [DONE]\n\n`);
|
|
597
|
+
async function* body() { yield bytes; }
|
|
598
|
+
return { ok: true, status: 200, body: body() };
|
|
599
|
+
}) as SSEFetchLike;
|
|
600
|
+
const cfg = { ...rateConfig, dailyCap: 1, minIntervalMs: 0 };
|
|
601
|
+
const ok = await generateImageWithFallback({ ...base, outDir, rateConfig: cfg, chatgptAuth: makeAuth(), chatgptFetchImpl: looping });
|
|
602
|
+
assert.equal(ok.provider, "chatgpt");
|
|
603
|
+
// next call: chatgpt is capped → gemini throws (test factory), zai/custom
|
|
604
|
+
// unconfigured → the aggregated error must show the cap, not a silent skip.
|
|
605
|
+
try {
|
|
606
|
+
await generateImageWithFallback({ ...base, outDir, rateConfig: cfg, chatgptAuth: makeAuth(), chatgptFetchImpl: looping });
|
|
607
|
+
assert.fail("should throw");
|
|
608
|
+
} catch (e) {
|
|
609
|
+
assert.ok(includes((e as Error).message, "daily soft cap reached"));
|
|
610
|
+
}
|
|
611
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
it("counts each metered chatgpt generation (n>1) against the cap", async () => {
|
|
615
|
+
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), "chatgpt-chain-"));
|
|
616
|
+
const looping: SSEFetchLike = (async () => {
|
|
617
|
+
const bytes = new TextEncoder().encode(`data: ${JSON.stringify(sseImageDone(PNG_B64))}\n\ndata: [DONE]\n\n`);
|
|
618
|
+
async function* body() { yield bytes; }
|
|
619
|
+
return { ok: true, status: 200, body: body() };
|
|
620
|
+
}) as SSEFetchLike;
|
|
621
|
+
const cfg = { ...rateConfig, dailyCap: 2, minIntervalMs: 0 };
|
|
622
|
+
// n=2 consumes the whole cap in ONE tool call (2 metered generations)
|
|
623
|
+
const first = await generateImageWithFallback({ ...base, n: 2, outDir, rateConfig: cfg, chatgptAuth: makeAuth(), chatgptFetchImpl: looping });
|
|
624
|
+
assert.equal(first.paths.length, 2);
|
|
625
|
+
try {
|
|
626
|
+
await generateImageWithFallback({ ...base, outDir, rateConfig: cfg, chatgptAuth: makeAuth(), chatgptFetchImpl: looping });
|
|
627
|
+
assert.fail("should throw");
|
|
628
|
+
} catch (e) {
|
|
629
|
+
assert.ok(includes((e as Error).message, "daily soft cap reached"));
|
|
630
|
+
}
|
|
631
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
632
|
+
});
|
|
633
|
+
});
|