@aexol/spectral 0.7.1 → 0.7.5

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 (219) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/dist/agent/agents.js +1 -1
  3. package/dist/agent/index.js +199 -184
  4. package/dist/commands/serve.js +0 -3
  5. package/dist/designer/data/systems/renault/DESIGN.md +1 -1
  6. package/dist/designer/philosophies.js +668 -0
  7. package/dist/mcp/sampling-handler.js +1 -1
  8. package/dist/memory/commands/status.js +1 -1
  9. package/dist/memory/compaction.js +2 -2
  10. package/dist/memory/config.js +1 -1
  11. package/dist/memory/debug-log.js +1 -1
  12. package/dist/memory/hooks/compaction-hook.js +29 -0
  13. package/dist/memory/index.js +2 -0
  14. package/dist/memory/observer.js +2 -2
  15. package/dist/memory/project-observations-store.js +14 -0
  16. package/dist/memory/tokens.js +1 -1
  17. package/dist/memory/tools/read-project-observations.js +82 -0
  18. package/dist/memory/tools/recall-observation.js +2 -2
  19. package/dist/pi/agent-core/agent-loop.js +501 -0
  20. package/dist/pi/agent-core/agent.js +401 -0
  21. package/dist/pi/agent-core/harness/agent-harness.js +899 -0
  22. package/dist/pi/agent-core/harness/compaction/branch-summarization.js +173 -0
  23. package/dist/pi/agent-core/harness/compaction/compaction.js +532 -0
  24. package/dist/pi/agent-core/harness/compaction/utils.js +130 -0
  25. package/dist/pi/agent-core/harness/env/nodejs.js +485 -0
  26. package/dist/pi/agent-core/harness/messages.js +101 -0
  27. package/dist/pi/agent-core/harness/prompt-templates.js +229 -0
  28. package/dist/pi/agent-core/harness/session/jsonl-repo.js +100 -0
  29. package/dist/pi/agent-core/harness/session/jsonl-storage.js +230 -0
  30. package/dist/pi/agent-core/harness/session/memory-repo.js +41 -0
  31. package/dist/pi/agent-core/harness/session/memory-storage.js +113 -0
  32. package/dist/pi/agent-core/harness/session/repo-utils.js +38 -0
  33. package/dist/pi/agent-core/harness/session/session.js +196 -0
  34. package/dist/pi/agent-core/harness/session/uuid.js +49 -0
  35. package/dist/pi/agent-core/harness/skills.js +310 -0
  36. package/dist/pi/agent-core/harness/system-prompt.js +29 -0
  37. package/dist/pi/agent-core/harness/types.js +93 -0
  38. package/dist/pi/agent-core/harness/utils/shell-output.js +125 -0
  39. package/dist/pi/agent-core/harness/utils/truncate.js +289 -0
  40. package/dist/pi/agent-core/index.js +24 -0
  41. package/dist/pi/agent-core/node.js +2 -0
  42. package/dist/pi/agent-core/proxy.js +277 -0
  43. package/dist/pi/agent-core/types.js +1 -0
  44. package/dist/pi/ai/api-registry.js +43 -0
  45. package/dist/pi/ai/cli.js +120 -0
  46. package/dist/pi/ai/env-api-keys.js +169 -0
  47. package/dist/pi/ai/image-models.generated.js +441 -0
  48. package/dist/pi/ai/image-models.js +22 -0
  49. package/dist/pi/ai/images-api-registry.js +21 -0
  50. package/dist/pi/ai/images.js +13 -0
  51. package/dist/pi/ai/index.js +18 -0
  52. package/dist/pi/ai/models.generated.js +16220 -0
  53. package/dist/pi/ai/models.js +70 -0
  54. package/dist/pi/ai/oauth.js +1 -0
  55. package/dist/pi/ai/providers/anthropic.js +945 -0
  56. package/dist/pi/ai/providers/faux.js +367 -0
  57. package/dist/pi/ai/providers/github-copilot-headers.js +28 -0
  58. package/dist/pi/ai/providers/openai-completions.js +945 -0
  59. package/dist/pi/ai/providers/openai-prompt-cache.js +9 -0
  60. package/dist/pi/ai/providers/register-builtins.js +97 -0
  61. package/dist/pi/ai/providers/simple-options.js +40 -0
  62. package/dist/pi/ai/providers/transform-messages.js +183 -0
  63. package/dist/pi/ai/session-resources.js +21 -0
  64. package/dist/pi/ai/stream.js +26 -0
  65. package/dist/pi/ai/types.js +1 -0
  66. package/dist/pi/ai/utils/diagnostics.js +24 -0
  67. package/dist/pi/ai/utils/event-stream.js +80 -0
  68. package/dist/pi/ai/utils/hash.js +13 -0
  69. package/dist/pi/ai/utils/headers.js +7 -0
  70. package/dist/pi/ai/utils/json-parse.js +112 -0
  71. package/dist/pi/ai/utils/node-http-proxy.js +96 -0
  72. package/dist/pi/ai/utils/oauth/anthropic.js +334 -0
  73. package/dist/pi/ai/utils/oauth/device-code.js +54 -0
  74. package/dist/pi/ai/utils/oauth/github-copilot.js +270 -0
  75. package/dist/pi/ai/utils/oauth/index.js +121 -0
  76. package/dist/pi/ai/utils/oauth/oauth-page.js +104 -0
  77. package/dist/pi/ai/utils/oauth/openai-codex.js +384 -0
  78. package/dist/pi/ai/utils/oauth/pkce.js +30 -0
  79. package/dist/pi/ai/utils/oauth/types.js +1 -0
  80. package/dist/pi/ai/utils/overflow.js +150 -0
  81. package/dist/pi/ai/utils/sanitize-unicode.js +25 -0
  82. package/dist/pi/ai/utils/typebox-helpers.js +20 -0
  83. package/dist/pi/ai/utils/validation.js +280 -0
  84. package/dist/pi/coding-agent/bun/cli.js +7 -0
  85. package/dist/pi/coding-agent/bun/restore-sandbox-env.js +31 -0
  86. package/dist/pi/coding-agent/cli/args.js +340 -0
  87. package/dist/pi/coding-agent/cli/file-processor.js +82 -0
  88. package/dist/pi/coding-agent/cli/initial-message.js +21 -0
  89. package/dist/pi/coding-agent/cli.js +17 -0
  90. package/dist/pi/coding-agent/config.js +414 -0
  91. package/dist/pi/coding-agent/core/agent-session-runtime.js +299 -0
  92. package/dist/pi/coding-agent/core/agent-session-services.js +117 -0
  93. package/dist/pi/coding-agent/core/agent-session.js +2498 -0
  94. package/dist/pi/coding-agent/core/auth-guidance.js +20 -0
  95. package/dist/pi/coding-agent/core/auth-storage.js +441 -0
  96. package/dist/pi/coding-agent/core/bash-executor.js +110 -0
  97. package/dist/pi/coding-agent/core/compaction/branch-summarization.js +242 -0
  98. package/dist/pi/coding-agent/core/compaction/compaction.js +624 -0
  99. package/dist/pi/coding-agent/core/compaction/index.js +6 -0
  100. package/dist/pi/coding-agent/core/compaction/utils.js +152 -0
  101. package/dist/pi/coding-agent/core/defaults.js +1 -0
  102. package/dist/pi/coding-agent/core/diagnostics.js +1 -0
  103. package/dist/pi/coding-agent/core/event-bus.js +24 -0
  104. package/dist/pi/coding-agent/core/exec.js +74 -0
  105. package/dist/pi/coding-agent/core/export-html/ansi-to-html.js +248 -0
  106. package/dist/pi/coding-agent/core/export-html/index.js +225 -0
  107. package/dist/pi/coding-agent/core/export-html/tool-renderer.js +107 -0
  108. package/dist/pi/coding-agent/core/extensions/index.js +8 -0
  109. package/dist/pi/coding-agent/core/extensions/loader.js +485 -0
  110. package/dist/pi/coding-agent/core/extensions/runner.js +824 -0
  111. package/dist/pi/coding-agent/core/extensions/types.js +44 -0
  112. package/dist/pi/coding-agent/core/extensions/wrapper.js +21 -0
  113. package/dist/pi/coding-agent/core/footer-data-provider.js +309 -0
  114. package/dist/pi/coding-agent/core/http-dispatcher.js +47 -0
  115. package/dist/pi/coding-agent/core/index.js +11 -0
  116. package/dist/pi/coding-agent/core/keybindings.js +294 -0
  117. package/dist/pi/coding-agent/core/messages.js +122 -0
  118. package/dist/pi/coding-agent/core/model-registry.js +728 -0
  119. package/dist/pi/coding-agent/core/model-resolver.js +494 -0
  120. package/dist/pi/coding-agent/core/output-guard.js +58 -0
  121. package/dist/pi/coding-agent/core/package-manager.js +2020 -0
  122. package/dist/pi/coding-agent/core/prompt-templates.js +237 -0
  123. package/dist/pi/coding-agent/core/provider-display-names.js +32 -0
  124. package/dist/pi/coding-agent/core/resolve-config-value.js +125 -0
  125. package/dist/pi/coding-agent/core/resource-loader.js +733 -0
  126. package/dist/pi/coding-agent/core/sdk.js +282 -0
  127. package/dist/pi/coding-agent/core/session-cwd.js +37 -0
  128. package/dist/pi/coding-agent/core/session-manager.js +1146 -0
  129. package/dist/pi/coding-agent/core/settings-manager.js +794 -0
  130. package/dist/pi/coding-agent/core/skills.js +386 -0
  131. package/dist/pi/coding-agent/core/slash-commands.js +24 -0
  132. package/dist/pi/coding-agent/core/source-info.js +18 -0
  133. package/dist/pi/coding-agent/core/system-prompt.js +122 -0
  134. package/dist/pi/coding-agent/core/telemetry.js +8 -0
  135. package/dist/pi/coding-agent/core/timings.js +30 -0
  136. package/dist/pi/coding-agent/core/tools/bash.js +341 -0
  137. package/dist/pi/coding-agent/core/tools/edit-diff.js +344 -0
  138. package/dist/pi/coding-agent/core/tools/edit.js +324 -0
  139. package/dist/pi/coding-agent/core/tools/file-mutation-queue.js +36 -0
  140. package/dist/pi/coding-agent/core/tools/find.js +297 -0
  141. package/dist/pi/coding-agent/core/tools/grep.js +303 -0
  142. package/dist/pi/coding-agent/core/tools/index.js +111 -0
  143. package/dist/pi/coding-agent/core/tools/ls.js +168 -0
  144. package/dist/pi/coding-agent/core/tools/output-accumulator.js +183 -0
  145. package/dist/pi/coding-agent/core/tools/path-utils.js +61 -0
  146. package/dist/pi/coding-agent/core/tools/read.js +288 -0
  147. package/dist/pi/coding-agent/core/tools/render-utils.js +48 -0
  148. package/dist/pi/coding-agent/core/tools/tool-definition-wrapper.js +33 -0
  149. package/dist/pi/coding-agent/core/tools/truncate.js +214 -0
  150. package/dist/pi/coding-agent/core/tools/write.js +212 -0
  151. package/dist/pi/coding-agent/index.js +41 -0
  152. package/dist/pi/coding-agent/main.js +5 -0
  153. package/dist/pi/coding-agent/migrations.js +280 -0
  154. package/dist/pi/coding-agent/modes/index.js +7 -0
  155. package/dist/pi/coding-agent/modes/interactive/components/diff.js +132 -0
  156. package/dist/pi/coding-agent/modes/interactive/components/keybinding-hints.js +35 -0
  157. package/dist/pi/coding-agent/modes/interactive/components/visual-truncate.js +32 -0
  158. package/dist/pi/coding-agent/modes/interactive/interactive-mode.js +3 -0
  159. package/dist/pi/coding-agent/modes/interactive/theme/theme.js +1023 -0
  160. package/dist/pi/coding-agent/modes/print-mode.js +130 -0
  161. package/dist/pi/coding-agent/modes/rpc/jsonl.js +48 -0
  162. package/dist/pi/coding-agent/modes/rpc/rpc-client.js +409 -0
  163. package/dist/pi/coding-agent/modes/rpc/rpc-mode.js +600 -0
  164. package/dist/pi/coding-agent/modes/rpc/rpc-types.js +7 -0
  165. package/dist/pi/coding-agent/utils/ansi.js +51 -0
  166. package/dist/pi/coding-agent/utils/changelog.js +86 -0
  167. package/dist/pi/coding-agent/utils/child-process.js +87 -0
  168. package/dist/pi/coding-agent/utils/clipboard-image.js +244 -0
  169. package/dist/pi/coding-agent/utils/clipboard-native.js +13 -0
  170. package/dist/pi/coding-agent/utils/clipboard.js +116 -0
  171. package/dist/pi/coding-agent/utils/exif-orientation.js +157 -0
  172. package/dist/pi/coding-agent/utils/frontmatter.js +25 -0
  173. package/dist/pi/coding-agent/utils/fs-watch.js +24 -0
  174. package/dist/pi/coding-agent/utils/git.js +162 -0
  175. package/dist/pi/coding-agent/utils/html.js +39 -0
  176. package/dist/pi/coding-agent/utils/image-convert.js +38 -0
  177. package/dist/pi/coding-agent/utils/image-resize.js +136 -0
  178. package/dist/pi/coding-agent/utils/mime.js +68 -0
  179. package/dist/pi/coding-agent/utils/paths.js +91 -0
  180. package/dist/pi/coding-agent/utils/photon.js +120 -0
  181. package/dist/pi/coding-agent/utils/pi-user-agent.js +4 -0
  182. package/dist/pi/coding-agent/utils/shell.js +194 -0
  183. package/dist/pi/coding-agent/utils/sleep.js +16 -0
  184. package/dist/pi/coding-agent/utils/syntax-highlight.js +117 -0
  185. package/dist/pi/coding-agent/utils/tools-manager.js +327 -0
  186. package/dist/pi/coding-agent/utils/version-check.js +81 -0
  187. package/dist/pi/coding-agent/utils/windows-self-update.js +76 -0
  188. package/dist/pi/tui/autocomplete.js +631 -0
  189. package/dist/pi/tui/components/box.js +103 -0
  190. package/dist/pi/tui/components/cancellable-loader.js +34 -0
  191. package/dist/pi/tui/components/editor.js +1915 -0
  192. package/dist/pi/tui/components/image.js +88 -0
  193. package/dist/pi/tui/components/input.js +425 -0
  194. package/dist/pi/tui/components/loader.js +68 -0
  195. package/dist/pi/tui/components/markdown.js +633 -0
  196. package/dist/pi/tui/components/select-list.js +158 -0
  197. package/dist/pi/tui/components/settings-list.js +184 -0
  198. package/dist/pi/tui/components/spacer.js +22 -0
  199. package/dist/pi/tui/components/text.js +88 -0
  200. package/dist/pi/tui/components/truncated-text.js +50 -0
  201. package/dist/pi/tui/editor-component.js +1 -0
  202. package/dist/pi/tui/fuzzy.js +109 -0
  203. package/dist/pi/tui/index.js +31 -0
  204. package/dist/pi/tui/keybindings.js +173 -0
  205. package/dist/pi/tui/keys.js +1172 -0
  206. package/dist/pi/tui/kill-ring.js +43 -0
  207. package/dist/pi/tui/stdin-buffer.js +360 -0
  208. package/dist/pi/tui/terminal-image.js +335 -0
  209. package/dist/pi/tui/terminal.js +324 -0
  210. package/dist/pi/tui/tui.js +1076 -0
  211. package/dist/pi/tui/undo-stack.js +24 -0
  212. package/dist/pi/tui/utils.js +1016 -0
  213. package/dist/relay/dispatcher.js +30 -0
  214. package/dist/server/handlers/queue.js +52 -0
  215. package/dist/server/pi-bridge.js +9 -1
  216. package/dist/server/session-stream.js +76 -111
  217. package/dist/server/storage.js +154 -2
  218. package/dist/server/title-generator.js +14 -153
  219. package/package.json +24 -6
@@ -0,0 +1,384 @@
1
+ /**
2
+ * OpenAI Codex (ChatGPT OAuth) flow
3
+ *
4
+ * NOTE: This module uses Node.js crypto and http for the OAuth callback.
5
+ * It is only intended for CLI use, not browser environments.
6
+ */
7
+ // NEVER convert to top-level imports - breaks browser/Vite builds
8
+ let _randomBytes = null;
9
+ let _http = null;
10
+ if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
11
+ import("node:crypto").then((m) => {
12
+ _randomBytes = m.randomBytes;
13
+ });
14
+ import("node:http").then((m) => {
15
+ _http = m;
16
+ });
17
+ }
18
+ import { oauthErrorHtml, oauthSuccessHtml } from "./oauth-page.js";
19
+ import { generatePKCE } from "./pkce.js";
20
+ const CALLBACK_HOST = process.env.PI_OAUTH_CALLBACK_HOST || "127.0.0.1";
21
+ const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
22
+ const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
23
+ const TOKEN_URL = "https://auth.openai.com/oauth/token";
24
+ const REDIRECT_URI = "http://localhost:1455/auth/callback";
25
+ const SCOPE = "openid profile email offline_access";
26
+ const JWT_CLAIM_PATH = "https://api.openai.com/auth";
27
+ function createState() {
28
+ if (!_randomBytes) {
29
+ throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
30
+ }
31
+ return _randomBytes(16).toString("hex");
32
+ }
33
+ function parseAuthorizationInput(input) {
34
+ const value = input.trim();
35
+ if (!value)
36
+ return {};
37
+ try {
38
+ const url = new URL(value);
39
+ return {
40
+ code: url.searchParams.get("code") ?? undefined,
41
+ state: url.searchParams.get("state") ?? undefined,
42
+ };
43
+ }
44
+ catch {
45
+ // not a URL
46
+ }
47
+ if (value.includes("#")) {
48
+ const [code, state] = value.split("#", 2);
49
+ return { code, state };
50
+ }
51
+ if (value.includes("code=")) {
52
+ const params = new URLSearchParams(value);
53
+ return {
54
+ code: params.get("code") ?? undefined,
55
+ state: params.get("state") ?? undefined,
56
+ };
57
+ }
58
+ return { code: value };
59
+ }
60
+ function decodeJwt(token) {
61
+ try {
62
+ const parts = token.split(".");
63
+ if (parts.length !== 3)
64
+ return null;
65
+ const payload = parts[1] ?? "";
66
+ const decoded = atob(payload);
67
+ return JSON.parse(decoded);
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ async function exchangeAuthorizationCode(code, verifier, redirectUri = REDIRECT_URI) {
74
+ const response = await fetch(TOKEN_URL, {
75
+ method: "POST",
76
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
77
+ body: new URLSearchParams({
78
+ grant_type: "authorization_code",
79
+ client_id: CLIENT_ID,
80
+ code,
81
+ code_verifier: verifier,
82
+ redirect_uri: redirectUri,
83
+ }),
84
+ });
85
+ if (!response.ok) {
86
+ const text = await response.text().catch(() => "");
87
+ return {
88
+ type: "failed",
89
+ status: response.status,
90
+ message: `OpenAI Codex token exchange failed (${response.status}): ${text || response.statusText}`,
91
+ };
92
+ }
93
+ const json = (await response.json());
94
+ if (!json.access_token || !json.refresh_token || typeof json.expires_in !== "number") {
95
+ return {
96
+ type: "failed",
97
+ message: `OpenAI Codex token exchange response missing fields: ${JSON.stringify(json)}`,
98
+ };
99
+ }
100
+ return {
101
+ type: "success",
102
+ access: json.access_token,
103
+ refresh: json.refresh_token,
104
+ expires: Date.now() + json.expires_in * 1000,
105
+ };
106
+ }
107
+ async function refreshAccessToken(refreshToken) {
108
+ try {
109
+ const response = await fetch(TOKEN_URL, {
110
+ method: "POST",
111
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
112
+ body: new URLSearchParams({
113
+ grant_type: "refresh_token",
114
+ refresh_token: refreshToken,
115
+ client_id: CLIENT_ID,
116
+ }),
117
+ });
118
+ if (!response.ok) {
119
+ const text = await response.text().catch(() => "");
120
+ return {
121
+ type: "failed",
122
+ status: response.status,
123
+ message: `OpenAI Codex token refresh failed (${response.status}): ${text || response.statusText}`,
124
+ };
125
+ }
126
+ const json = (await response.json());
127
+ if (!json.access_token || !json.refresh_token || typeof json.expires_in !== "number") {
128
+ return {
129
+ type: "failed",
130
+ message: `OpenAI Codex token refresh response missing fields: ${JSON.stringify(json)}`,
131
+ };
132
+ }
133
+ return {
134
+ type: "success",
135
+ access: json.access_token,
136
+ refresh: json.refresh_token,
137
+ expires: Date.now() + json.expires_in * 1000,
138
+ };
139
+ }
140
+ catch (error) {
141
+ return {
142
+ type: "failed",
143
+ message: `OpenAI Codex token refresh error: ${error instanceof Error ? error.message : String(error)}`,
144
+ };
145
+ }
146
+ }
147
+ async function createAuthorizationFlow(originator = "pi") {
148
+ const { verifier, challenge } = await generatePKCE();
149
+ const state = createState();
150
+ const url = new URL(AUTHORIZE_URL);
151
+ url.searchParams.set("response_type", "code");
152
+ url.searchParams.set("client_id", CLIENT_ID);
153
+ url.searchParams.set("redirect_uri", REDIRECT_URI);
154
+ url.searchParams.set("scope", SCOPE);
155
+ url.searchParams.set("code_challenge", challenge);
156
+ url.searchParams.set("code_challenge_method", "S256");
157
+ url.searchParams.set("state", state);
158
+ url.searchParams.set("id_token_add_organizations", "true");
159
+ url.searchParams.set("codex_cli_simplified_flow", "true");
160
+ url.searchParams.set("originator", originator);
161
+ return { verifier, state, url: url.toString() };
162
+ }
163
+ function startLocalOAuthServer(state) {
164
+ if (!_http) {
165
+ throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
166
+ }
167
+ let settleWait;
168
+ const waitForCodePromise = new Promise((resolve) => {
169
+ let settled = false;
170
+ settleWait = (value) => {
171
+ if (settled)
172
+ return;
173
+ settled = true;
174
+ resolve(value);
175
+ };
176
+ });
177
+ const server = _http.createServer((req, res) => {
178
+ try {
179
+ const url = new URL(req.url || "", "http://localhost");
180
+ if (url.pathname !== "/auth/callback") {
181
+ res.statusCode = 404;
182
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
183
+ res.end(oauthErrorHtml("Callback route not found."));
184
+ return;
185
+ }
186
+ if (url.searchParams.get("state") !== state) {
187
+ res.statusCode = 400;
188
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
189
+ res.end(oauthErrorHtml("State mismatch."));
190
+ return;
191
+ }
192
+ const code = url.searchParams.get("code");
193
+ if (!code) {
194
+ res.statusCode = 400;
195
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
196
+ res.end(oauthErrorHtml("Missing authorization code."));
197
+ return;
198
+ }
199
+ res.statusCode = 200;
200
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
201
+ res.end(oauthSuccessHtml("OpenAI authentication completed. You can close this window."));
202
+ settleWait?.({ code });
203
+ }
204
+ catch {
205
+ res.statusCode = 500;
206
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
207
+ res.end(oauthErrorHtml("Internal error while processing OAuth callback."));
208
+ }
209
+ });
210
+ return new Promise((resolve) => {
211
+ server
212
+ .listen(1455, CALLBACK_HOST, () => {
213
+ resolve({
214
+ close: () => server.close(),
215
+ cancelWait: () => {
216
+ settleWait?.(null);
217
+ },
218
+ waitForCode: () => waitForCodePromise,
219
+ });
220
+ })
221
+ .on("error", (_err) => {
222
+ settleWait?.(null);
223
+ resolve({
224
+ close: () => {
225
+ try {
226
+ server.close();
227
+ }
228
+ catch {
229
+ // ignore
230
+ }
231
+ },
232
+ cancelWait: () => { },
233
+ waitForCode: async () => null,
234
+ });
235
+ });
236
+ });
237
+ }
238
+ function getAccountId(accessToken) {
239
+ const payload = decodeJwt(accessToken);
240
+ const auth = payload?.[JWT_CLAIM_PATH];
241
+ const accountId = auth?.chatgpt_account_id;
242
+ return typeof accountId === "string" && accountId.length > 0 ? accountId : null;
243
+ }
244
+ /**
245
+ * Login with OpenAI Codex OAuth
246
+ *
247
+ * @param options.onAuth - Called with URL and instructions when auth starts
248
+ * @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)
249
+ * @param options.onProgress - Optional progress messages
250
+ * @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.
251
+ * Races with browser callback - whichever completes first wins.
252
+ * Useful for showing paste input immediately alongside browser flow.
253
+ * @param options.originator - OAuth originator parameter (defaults to "pi")
254
+ */
255
+ export async function loginOpenAICodex(options) {
256
+ const { verifier, state, url } = await createAuthorizationFlow(options.originator);
257
+ const server = await startLocalOAuthServer(state);
258
+ options.onAuth({ url, instructions: "A browser window should open. Complete login to finish." });
259
+ let code;
260
+ try {
261
+ if (options.onManualCodeInput) {
262
+ // Race between browser callback and manual input
263
+ let manualCode;
264
+ let manualError;
265
+ const manualPromise = options
266
+ .onManualCodeInput()
267
+ .then((input) => {
268
+ manualCode = input;
269
+ server.cancelWait();
270
+ })
271
+ .catch((err) => {
272
+ manualError = err instanceof Error ? err : new Error(String(err));
273
+ server.cancelWait();
274
+ });
275
+ const result = await server.waitForCode();
276
+ // If manual input was cancelled, throw that error
277
+ if (manualError) {
278
+ throw manualError;
279
+ }
280
+ if (result?.code) {
281
+ // Browser callback won
282
+ code = result.code;
283
+ }
284
+ else if (manualCode) {
285
+ // Manual input won (or callback timed out and user had entered code)
286
+ const parsed = parseAuthorizationInput(manualCode);
287
+ if (parsed.state && parsed.state !== state) {
288
+ throw new Error("State mismatch");
289
+ }
290
+ code = parsed.code;
291
+ }
292
+ // If still no code, wait for manual promise to complete and try that
293
+ if (!code) {
294
+ await manualPromise;
295
+ if (manualError) {
296
+ throw manualError;
297
+ }
298
+ if (manualCode) {
299
+ const parsed = parseAuthorizationInput(manualCode);
300
+ if (parsed.state && parsed.state !== state) {
301
+ throw new Error("State mismatch");
302
+ }
303
+ code = parsed.code;
304
+ }
305
+ }
306
+ }
307
+ else {
308
+ // Original flow: wait for callback, then prompt if needed
309
+ const result = await server.waitForCode();
310
+ if (result?.code) {
311
+ code = result.code;
312
+ }
313
+ }
314
+ // Fallback to onPrompt if still no code
315
+ if (!code) {
316
+ const input = await options.onPrompt({
317
+ message: "Paste the authorization code (or full redirect URL):",
318
+ });
319
+ const parsed = parseAuthorizationInput(input);
320
+ if (parsed.state && parsed.state !== state) {
321
+ throw new Error("State mismatch");
322
+ }
323
+ code = parsed.code;
324
+ }
325
+ if (!code) {
326
+ throw new Error("Missing authorization code");
327
+ }
328
+ const tokenResult = await exchangeAuthorizationCode(code, verifier);
329
+ if (tokenResult.type !== "success") {
330
+ throw new Error(tokenResult.message);
331
+ }
332
+ const accountId = getAccountId(tokenResult.access);
333
+ if (!accountId) {
334
+ throw new Error("Failed to extract accountId from token");
335
+ }
336
+ return {
337
+ access: tokenResult.access,
338
+ refresh: tokenResult.refresh,
339
+ expires: tokenResult.expires,
340
+ accountId,
341
+ };
342
+ }
343
+ finally {
344
+ server.close();
345
+ }
346
+ }
347
+ /**
348
+ * Refresh OpenAI Codex OAuth token
349
+ */
350
+ export async function refreshOpenAICodexToken(refreshToken) {
351
+ const result = await refreshAccessToken(refreshToken);
352
+ if (result.type !== "success") {
353
+ throw new Error(result.message);
354
+ }
355
+ const accountId = getAccountId(result.access);
356
+ if (!accountId) {
357
+ throw new Error("Failed to extract accountId from token");
358
+ }
359
+ return {
360
+ access: result.access,
361
+ refresh: result.refresh,
362
+ expires: result.expires,
363
+ accountId,
364
+ };
365
+ }
366
+ export const openaiCodexOAuthProvider = {
367
+ id: "openai-codex",
368
+ name: "ChatGPT Plus/Pro (Codex Subscription)",
369
+ usesCallbackServer: true,
370
+ async login(callbacks) {
371
+ return loginOpenAICodex({
372
+ onAuth: callbacks.onAuth,
373
+ onPrompt: callbacks.onPrompt,
374
+ onProgress: callbacks.onProgress,
375
+ onManualCodeInput: callbacks.onManualCodeInput,
376
+ });
377
+ },
378
+ async refreshToken(credentials) {
379
+ return refreshOpenAICodexToken(credentials.refresh);
380
+ },
381
+ getApiKey(credentials) {
382
+ return credentials.access;
383
+ },
384
+ };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * PKCE utilities using Web Crypto API.
3
+ * Works in both Node.js 20+ and browsers.
4
+ */
5
+ /**
6
+ * Encode bytes as base64url string.
7
+ */
8
+ function base64urlEncode(bytes) {
9
+ let binary = "";
10
+ for (const byte of bytes) {
11
+ binary += String.fromCharCode(byte);
12
+ }
13
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14
+ }
15
+ /**
16
+ * Generate PKCE code verifier and challenge.
17
+ * Uses Web Crypto API for cross-platform compatibility.
18
+ */
19
+ export async function generatePKCE() {
20
+ // Generate random verifier
21
+ const verifierBytes = new Uint8Array(32);
22
+ crypto.getRandomValues(verifierBytes);
23
+ const verifier = base64urlEncode(verifierBytes);
24
+ // Compute SHA-256 challenge
25
+ const encoder = new TextEncoder();
26
+ const data = encoder.encode(verifier);
27
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
28
+ const challenge = base64urlEncode(new Uint8Array(hashBuffer));
29
+ return { verifier, challenge };
30
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Regex patterns to detect context overflow errors from different providers.
3
+ *
4
+ * These patterns match error messages returned when the input exceeds
5
+ * the model's context window.
6
+ *
7
+ * Provider-specific patterns (with example error messages):
8
+ *
9
+ * - Anthropic: "prompt is too long: 213462 tokens > 200000 maximum"
10
+ * - Anthropic: "413 {\"error\":{\"type\":\"request_too_large\",\"message\":\"Request exceeds the maximum size\"}}"
11
+ * - OpenAI: "Your input exceeds the context window of this model"
12
+ * - OpenAI/LiteLLM: "Requested token count exceeds the model's maximum context length of 131072 tokens"
13
+ * - Google: "The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)"
14
+ * - xAI: "This model's maximum prompt length is 131072 but the request contains 537812 tokens"
15
+ * - Groq: "Please reduce the length of the messages or completion"
16
+ * - OpenRouter: "This endpoint's maximum context length is X tokens. However, you requested about Y tokens"
17
+ * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)."
18
+ * - llama.cpp: "the request exceeds the available context size, try increasing it"
19
+ * - LM Studio: "tokens to keep from the initial prompt is greater than the context length"
20
+ * - GitHub Copilot: "prompt token count of X exceeds the limit of Y"
21
+ * - MiniMax: "invalid params, context window exceeds limit"
22
+ * - Kimi For Coding: "Your request exceeded model token limit: X (requested: Y)"
23
+ * - Cerebras: "400/413 status code (no body)"
24
+ * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length"
25
+ * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow
26
+ * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason "length"
27
+ * with output=0 (no room left to generate). Detected via stopReason "length" + zero output +
28
+ * input filling the context window.
29
+ * - Ollama: Some deployments truncate silently, others return errors like "prompt too long; exceeded max context length by X tokens"
30
+ */
31
+ const OVERFLOW_PATTERNS = [
32
+ /prompt is too long/i, // Anthropic token overflow
33
+ /request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)
34
+ /input is too long for requested model/i, // Amazon Bedrock
35
+ /exceeds the context window/i, // OpenAI (Completions & Responses API)
36
+ /exceeds (?:the )?(?:model'?s )?maximum context length of [\d,]+ tokens?/i, // OpenAI-compatible proxies (LiteLLM)
37
+ /input token count.*exceeds the maximum/i, // Google (Gemini)
38
+ /maximum prompt length is \d+/i, // xAI (Grok)
39
+ /reduce the length of the messages/i, // Groq
40
+ /maximum context length is \d+ tokens/i, // OpenRouter (all backends)
41
+ /input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i, // Together AI
42
+ /exceeds the limit of \d+/i, // GitHub Copilot
43
+ /exceeds the available context size/i, // llama.cpp server
44
+ /greater than the context length/i, // LM Studio
45
+ /context window exceeds limit/i, // MiniMax
46
+ /exceeded model token limit/i, // Kimi For Coding
47
+ /too large for model with \d+ maximum context length/i, // Mistral
48
+ /model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text
49
+ /prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error
50
+ /context[_ ]length[_ ]exceeded/i, // Generic fallback
51
+ /too many tokens/i, // Generic fallback
52
+ /token limit exceeded/i, // Generic fallback
53
+ /^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i, // Cerebras: 400/413 with no body
54
+ ];
55
+ /**
56
+ * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).
57
+ * Error messages matching any of these are excluded from overflow detection
58
+ * even if they also match an OVERFLOW_PATTERN.
59
+ *
60
+ * Example: Bedrock formats throttling errors as "ThrottlingException: Too many tokens,
61
+ * please wait before trying again." which would match the /too many tokens/i overflow
62
+ * pattern without this exclusion.
63
+ */
64
+ const NON_OVERFLOW_PATTERNS = [
65
+ /^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)
66
+ /rate limit/i, // Generic rate limiting
67
+ /too many requests/i, // Generic HTTP 429 style
68
+ ];
69
+ /**
70
+ * Check if an assistant message represents a context overflow error.
71
+ *
72
+ * This handles two cases:
73
+ * 1. Error-based overflow: Most providers return stopReason "error" with a
74
+ * specific error message pattern.
75
+ * 2. Silent overflow: Some providers accept overflow requests and return
76
+ * successfully. For these, we check if usage.input exceeds the context window.
77
+ *
78
+ * ## Reliability by Provider
79
+ *
80
+ * **Reliable detection (returns error with detectable message):**
81
+ * - Anthropic: "prompt is too long: X tokens > Y maximum" or "request_too_large"
82
+ * - OpenAI (Completions & Responses): "exceeds the context window" or "exceeds the model's maximum context length of X tokens"
83
+ * - Google Gemini: "input token count exceeds the maximum"
84
+ * - xAI (Grok): "maximum prompt length is X but request contains Y"
85
+ * - Groq: "reduce the length of the messages"
86
+ * - Cerebras: 400/413 status code (no body)
87
+ * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length"
88
+ * - OpenRouter (all backends): "maximum context length is X tokens"
89
+ * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)."
90
+ * - llama.cpp: "exceeds the available context size"
91
+ * - LM Studio: "greater than the context length"
92
+ * - Kimi For Coding: "exceeded model token limit: X (requested: Y)"
93
+ *
94
+ * **Unreliable detection:**
95
+ * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),
96
+ * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.
97
+ * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason "length" with
98
+ * output=0. Pass contextWindow param to detect via the "filled context + zero output" signal.
99
+ * - Ollama: May truncate input silently for some setups, but may also return explicit
100
+ * overflow errors that match the patterns above. Silent truncation still cannot be
101
+ * detected here because we do not know the expected token count.
102
+ *
103
+ * ## Custom Providers
104
+ *
105
+ * If you've added custom models via settings.json, this function may not detect
106
+ * overflow errors from those providers. To add support:
107
+ *
108
+ * 1. Send a request that exceeds the model's context window
109
+ * 2. Check the errorMessage in the response
110
+ * 3. Create a regex pattern that matches the error
111
+ * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or
112
+ * check the errorMessage yourself before calling this function
113
+ *
114
+ * @param message - The assistant message to check
115
+ * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)
116
+ * @returns true if the message indicates a context overflow
117
+ */
118
+ export function isContextOverflow(message, contextWindow) {
119
+ // Case 1: Check error message patterns
120
+ if (message.stopReason === "error" && message.errorMessage) {
121
+ // Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)
122
+ const isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage));
123
+ if (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage))) {
124
+ return true;
125
+ }
126
+ }
127
+ // Case 2: Silent overflow (z.ai style) - successful but usage exceeds context
128
+ if (contextWindow && message.stopReason === "stop") {
129
+ const inputTokens = message.usage.input + message.usage.cacheRead;
130
+ if (inputTokens > contextWindow) {
131
+ return true;
132
+ }
133
+ }
134
+ // Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input
135
+ // to fit the context window, leaving no room for output. Returns stopReason "length"
136
+ // with output=0 and input+cacheRead filling the context window.
137
+ if (contextWindow && message.stopReason === "length" && message.usage.output === 0) {
138
+ const inputTokens = message.usage.input + message.usage.cacheRead;
139
+ if (inputTokens >= contextWindow * 0.99) {
140
+ return true;
141
+ }
142
+ }
143
+ return false;
144
+ }
145
+ /**
146
+ * Get the overflow patterns for testing purposes.
147
+ */
148
+ export function getOverflowPatterns() {
149
+ return [...OVERFLOW_PATTERNS];
150
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Removes unpaired Unicode surrogate characters from a string.
3
+ *
4
+ * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF,
5
+ * or vice versa) cause JSON serialization errors in many API providers.
6
+ *
7
+ * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired
8
+ * surrogates and will NOT be affected by this function.
9
+ *
10
+ * @param text - The text to sanitize
11
+ * @returns The sanitized text with unpaired surrogates removed
12
+ *
13
+ * @example
14
+ * // Valid emoji (properly paired surrogates) are preserved
15
+ * sanitizeSurrogates("Hello 🙈 World") // => "Hello 🙈 World"
16
+ *
17
+ * // Unpaired high surrogate is removed
18
+ * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low
19
+ * sanitizeSurrogates(`Text ${unpaired} here`) // => "Text here"
20
+ */
21
+ export function sanitizeSurrogates(text) {
22
+ // Replace unpaired high surrogates (0xD800-0xDBFF not followed by low surrogate)
23
+ // Replace unpaired low surrogates (0xDC00-0xDFFF not preceded by high surrogate)
24
+ return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
25
+ }
@@ -0,0 +1,20 @@
1
+ import { Type } from "typebox";
2
+ /**
3
+ * Creates a string enum schema compatible with Google's API and other providers
4
+ * that don't support anyOf/const patterns.
5
+ *
6
+ * @example
7
+ * const OperationSchema = StringEnum(["add", "subtract", "multiply", "divide"], {
8
+ * description: "The operation to perform"
9
+ * });
10
+ *
11
+ * type Operation = Static<typeof OperationSchema>; // "add" | "subtract" | "multiply" | "divide"
12
+ */
13
+ export function StringEnum(values, options) {
14
+ return Type.Unsafe({
15
+ type: "string",
16
+ enum: values,
17
+ ...(options?.description && { description: options.description }),
18
+ ...(options?.default && { default: options.default }),
19
+ });
20
+ }