@pencil-agent/nano-pencil 2.0.0-beta.2 → 2.0.0-beta.3

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 (179) hide show
  1. package/dist/build-meta.json +3 -3
  2. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-continuations.d.ts +17 -0
  3. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-continuations.js +60 -0
  4. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-stream-events.d.ts +19 -0
  5. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-stream-events.js +55 -0
  6. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-tool-results.d.ts +10 -0
  7. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-tool-results.js +137 -0
  8. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-tool-summaries.d.ts +22 -0
  9. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-tool-summaries.js +64 -0
  10. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop.d.ts +26 -0
  11. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop.js +913 -0
  12. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-run-result.d.ts +9 -0
  13. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-run-result.js +32 -0
  14. package/dist/node_modules/@pencil-agent/agent-core/dist/agent.d.ts +215 -0
  15. package/dist/node_modules/@pencil-agent/agent-core/dist/agent.js +522 -0
  16. package/dist/node_modules/@pencil-agent/agent-core/dist/errors.d.ts +62 -0
  17. package/dist/node_modules/@pencil-agent/agent-core/dist/errors.js +146 -0
  18. package/dist/node_modules/@pencil-agent/agent-core/dist/index.d.ts +14 -0
  19. package/dist/node_modules/@pencil-agent/agent-core/dist/index.js +19 -0
  20. package/dist/node_modules/@pencil-agent/agent-core/dist/proxy.d.ts +91 -0
  21. package/dist/node_modules/@pencil-agent/agent-core/dist/proxy.js +279 -0
  22. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-agent-loop.d.ts +15 -0
  23. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-agent-loop.js +625 -0
  24. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-streaming-tool-executor.d.ts +33 -0
  25. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-streaming-tool-executor.js +189 -0
  26. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-tool-orchestration.d.ts +35 -0
  27. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-tool-orchestration.js +319 -0
  28. package/dist/node_modules/@pencil-agent/agent-core/dist/types.d.ts +417 -0
  29. package/dist/node_modules/@pencil-agent/agent-core/dist/types.js +13 -0
  30. package/dist/node_modules/@pencil-agent/agent-core/package.json +28 -0
  31. package/dist/node_modules/@pencil-agent/ai/dist/api-registry.d.ts +27 -0
  32. package/dist/node_modules/@pencil-agent/ai/dist/api-registry.js +152 -0
  33. package/dist/node_modules/@pencil-agent/ai/dist/cli.d.ts +2 -0
  34. package/dist/node_modules/@pencil-agent/ai/dist/cli.js +121 -0
  35. package/dist/node_modules/@pencil-agent/ai/dist/config-path.d.ts +1 -0
  36. package/dist/node_modules/@pencil-agent/ai/dist/config-path.js +17 -0
  37. package/dist/node_modules/@pencil-agent/ai/dist/debug-logger.d.ts +94 -0
  38. package/dist/node_modules/@pencil-agent/ai/dist/debug-logger.js +218 -0
  39. package/dist/node_modules/@pencil-agent/ai/dist/env-api-keys.d.ts +8 -0
  40. package/dist/node_modules/@pencil-agent/ai/dist/env-api-keys.js +107 -0
  41. package/dist/node_modules/@pencil-agent/ai/dist/env.d.ts +7 -0
  42. package/dist/node_modules/@pencil-agent/ai/dist/env.js +7 -0
  43. package/dist/node_modules/@pencil-agent/ai/dist/events.d.ts +8 -0
  44. package/dist/node_modules/@pencil-agent/ai/dist/events.js +7 -0
  45. package/dist/node_modules/@pencil-agent/ai/dist/index.d.ts +27 -0
  46. package/dist/node_modules/@pencil-agent/ai/dist/index.js +20 -0
  47. package/dist/node_modules/@pencil-agent/ai/dist/json.d.ts +7 -0
  48. package/dist/node_modules/@pencil-agent/ai/dist/json.js +7 -0
  49. package/dist/node_modules/@pencil-agent/ai/dist/models.d.ts +31 -0
  50. package/dist/node_modules/@pencil-agent/ai/dist/models.generated.d.ts +15159 -0
  51. package/dist/node_modules/@pencil-agent/ai/dist/models.generated.js +14928 -0
  52. package/dist/node_modules/@pencil-agent/ai/dist/models.js +60 -0
  53. package/dist/node_modules/@pencil-agent/ai/dist/overflow.d.ts +7 -0
  54. package/dist/node_modules/@pencil-agent/ai/dist/overflow.js +7 -0
  55. package/dist/node_modules/@pencil-agent/ai/dist/providers/amazon-bedrock.d.ts +20 -0
  56. package/dist/node_modules/@pencil-agent/ai/dist/providers/amazon-bedrock.js +606 -0
  57. package/dist/node_modules/@pencil-agent/ai/dist/providers/anthropic.d.ts +38 -0
  58. package/dist/node_modules/@pencil-agent/ai/dist/providers/anthropic.js +737 -0
  59. package/dist/node_modules/@pencil-agent/ai/dist/providers/azure-openai-responses.d.ts +21 -0
  60. package/dist/node_modules/@pencil-agent/ai/dist/providers/azure-openai-responses.js +193 -0
  61. package/dist/node_modules/@pencil-agent/ai/dist/providers/github-copilot-headers.d.ts +13 -0
  62. package/dist/node_modules/@pencil-agent/ai/dist/providers/github-copilot-headers.js +34 -0
  63. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-gemini-cli.d.ts +79 -0
  64. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-gemini-cli.js +753 -0
  65. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-shared.d.ts +70 -0
  66. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-shared.js +311 -0
  67. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-vertex.d.ts +20 -0
  68. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-vertex.js +380 -0
  69. package/dist/node_modules/@pencil-agent/ai/dist/providers/google.d.ts +18 -0
  70. package/dist/node_modules/@pencil-agent/ai/dist/providers/google.js +360 -0
  71. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-codex-responses.d.ts +8 -0
  72. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-codex-responses.js +704 -0
  73. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-completions.d.ts +20 -0
  74. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-completions.js +870 -0
  75. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-responses-shared.d.ts +22 -0
  76. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-responses-shared.js +432 -0
  77. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-responses.d.ts +19 -0
  78. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-responses.js +207 -0
  79. package/dist/node_modules/@pencil-agent/ai/dist/providers/register-builtins.d.ts +8 -0
  80. package/dist/node_modules/@pencil-agent/ai/dist/providers/register-builtins.js +86 -0
  81. package/dist/node_modules/@pencil-agent/ai/dist/providers/simple-options.d.ts +13 -0
  82. package/dist/node_modules/@pencil-agent/ai/dist/providers/simple-options.js +40 -0
  83. package/dist/node_modules/@pencil-agent/ai/dist/providers/transform-messages.d.ts +13 -0
  84. package/dist/node_modules/@pencil-agent/ai/dist/providers/transform-messages.js +175 -0
  85. package/dist/node_modules/@pencil-agent/ai/dist/registry.d.ts +8 -0
  86. package/dist/node_modules/@pencil-agent/ai/dist/registry.js +8 -0
  87. package/dist/node_modules/@pencil-agent/ai/dist/schema.d.ts +10 -0
  88. package/dist/node_modules/@pencil-agent/ai/dist/schema.js +9 -0
  89. package/dist/node_modules/@pencil-agent/ai/dist/stream.d.ts +25 -0
  90. package/dist/node_modules/@pencil-agent/ai/dist/stream.js +324 -0
  91. package/dist/node_modules/@pencil-agent/ai/dist/types.d.ts +306 -0
  92. package/dist/node_modules/@pencil-agent/ai/dist/types.js +7 -0
  93. package/dist/node_modules/@pencil-agent/ai/dist/utils/event-stream-types.d.ts +12 -0
  94. package/dist/node_modules/@pencil-agent/ai/dist/utils/event-stream-types.js +7 -0
  95. package/dist/node_modules/@pencil-agent/ai/dist/utils/event-stream.d.ts +31 -0
  96. package/dist/node_modules/@pencil-agent/ai/dist/utils/event-stream.js +98 -0
  97. package/dist/node_modules/@pencil-agent/ai/dist/utils/http-proxy.d.ts +13 -0
  98. package/dist/node_modules/@pencil-agent/ai/dist/utils/http-proxy.js +20 -0
  99. package/dist/node_modules/@pencil-agent/ai/dist/utils/json-parse.d.ts +14 -0
  100. package/dist/node_modules/@pencil-agent/ai/dist/utils/json-parse.js +34 -0
  101. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/anthropic.d.ts +22 -0
  102. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/anthropic.js +109 -0
  103. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/decode-credential.d.ts +12 -0
  104. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/decode-credential.js +25 -0
  105. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/github-copilot.d.ts +35 -0
  106. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/github-copilot.js +286 -0
  107. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/google-antigravity.d.ts +31 -0
  108. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/google-antigravity.js +378 -0
  109. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/google-gemini-cli.d.ts +31 -0
  110. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/google-gemini-cli.js +483 -0
  111. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/index.d.ts +60 -0
  112. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/index.js +131 -0
  113. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/openai-codex.d.ts +39 -0
  114. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/openai-codex.js +385 -0
  115. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/pkce.d.ts +18 -0
  116. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/pkce.js +36 -0
  117. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/types.d.ts +52 -0
  118. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/types.js +7 -0
  119. package/dist/node_modules/@pencil-agent/ai/dist/utils/overflow.d.ts +57 -0
  120. package/dist/node_modules/@pencil-agent/ai/dist/utils/overflow.js +120 -0
  121. package/dist/node_modules/@pencil-agent/ai/dist/utils/sanitize-unicode.d.ts +16 -0
  122. package/dist/node_modules/@pencil-agent/ai/dist/utils/sanitize-unicode.js +20 -0
  123. package/dist/node_modules/@pencil-agent/ai/dist/utils/typebox-helpers.d.ts +22 -0
  124. package/dist/node_modules/@pencil-agent/ai/dist/utils/typebox-helpers.js +26 -0
  125. package/dist/node_modules/@pencil-agent/ai/dist/utils/validation.d.ts +23 -0
  126. package/dist/node_modules/@pencil-agent/ai/dist/utils/validation.js +78 -0
  127. package/dist/node_modules/@pencil-agent/ai/package.json +94 -0
  128. package/dist/node_modules/@pencil-agent/tui/dist/autocomplete.d.ts +62 -0
  129. package/dist/node_modules/@pencil-agent/tui/dist/autocomplete.js +624 -0
  130. package/dist/node_modules/@pencil-agent/tui/dist/components/box.d.ts +27 -0
  131. package/dist/node_modules/@pencil-agent/tui/dist/components/box.js +109 -0
  132. package/dist/node_modules/@pencil-agent/tui/dist/components/cancellable-loader.d.ts +27 -0
  133. package/dist/node_modules/@pencil-agent/tui/dist/components/cancellable-loader.js +40 -0
  134. package/dist/node_modules/@pencil-agent/tui/dist/components/editor.d.ts +218 -0
  135. package/dist/node_modules/@pencil-agent/tui/dist/components/editor.js +1697 -0
  136. package/dist/node_modules/@pencil-agent/tui/dist/components/image.d.ts +33 -0
  137. package/dist/node_modules/@pencil-agent/tui/dist/components/image.js +74 -0
  138. package/dist/node_modules/@pencil-agent/tui/dist/components/input.d.ts +42 -0
  139. package/dist/node_modules/@pencil-agent/tui/dist/components/input.js +438 -0
  140. package/dist/node_modules/@pencil-agent/tui/dist/components/loader.d.ts +26 -0
  141. package/dist/node_modules/@pencil-agent/tui/dist/components/loader.js +54 -0
  142. package/dist/node_modules/@pencil-agent/tui/dist/components/markdown.d.ts +100 -0
  143. package/dist/node_modules/@pencil-agent/tui/dist/components/markdown.js +634 -0
  144. package/dist/node_modules/@pencil-agent/tui/dist/components/select-list.d.ts +37 -0
  145. package/dist/node_modules/@pencil-agent/tui/dist/components/select-list.js +157 -0
  146. package/dist/node_modules/@pencil-agent/tui/dist/components/settings-list.d.ts +55 -0
  147. package/dist/node_modules/@pencil-agent/tui/dist/components/settings-list.js +190 -0
  148. package/dist/node_modules/@pencil-agent/tui/dist/components/spacer.d.ts +17 -0
  149. package/dist/node_modules/@pencil-agent/tui/dist/components/spacer.js +28 -0
  150. package/dist/node_modules/@pencil-agent/tui/dist/components/text.d.ts +24 -0
  151. package/dist/node_modules/@pencil-agent/tui/dist/components/text.js +94 -0
  152. package/dist/node_modules/@pencil-agent/tui/dist/components/truncated-text.d.ts +18 -0
  153. package/dist/node_modules/@pencil-agent/tui/dist/components/truncated-text.js +56 -0
  154. package/dist/node_modules/@pencil-agent/tui/dist/editor-component.d.ts +51 -0
  155. package/dist/node_modules/@pencil-agent/tui/dist/editor-component.js +7 -0
  156. package/dist/node_modules/@pencil-agent/tui/dist/fuzzy.d.ts +32 -0
  157. package/dist/node_modules/@pencil-agent/tui/dist/fuzzy.js +152 -0
  158. package/dist/node_modules/@pencil-agent/tui/dist/index.d.ts +28 -0
  159. package/dist/node_modules/@pencil-agent/tui/dist/index.js +37 -0
  160. package/dist/node_modules/@pencil-agent/tui/dist/keybindings.d.ts +44 -0
  161. package/dist/node_modules/@pencil-agent/tui/dist/keybindings.js +119 -0
  162. package/dist/node_modules/@pencil-agent/tui/dist/keys.d.ts +149 -0
  163. package/dist/node_modules/@pencil-agent/tui/dist/keys.js +948 -0
  164. package/dist/node_modules/@pencil-agent/tui/dist/kill-ring.d.ts +33 -0
  165. package/dist/node_modules/@pencil-agent/tui/dist/kill-ring.js +49 -0
  166. package/dist/node_modules/@pencil-agent/tui/dist/stdin-buffer.d.ts +38 -0
  167. package/dist/node_modules/@pencil-agent/tui/dist/stdin-buffer.js +307 -0
  168. package/dist/node_modules/@pencil-agent/tui/dist/terminal-image.d.ts +73 -0
  169. package/dist/node_modules/@pencil-agent/tui/dist/terminal-image.js +287 -0
  170. package/dist/node_modules/@pencil-agent/tui/dist/terminal.d.ts +86 -0
  171. package/dist/node_modules/@pencil-agent/tui/dist/terminal.js +266 -0
  172. package/dist/node_modules/@pencil-agent/tui/dist/tui.d.ts +219 -0
  173. package/dist/node_modules/@pencil-agent/tui/dist/tui.js +1001 -0
  174. package/dist/node_modules/@pencil-agent/tui/dist/undo-stack.d.ts +22 -0
  175. package/dist/node_modules/@pencil-agent/tui/dist/undo-stack.js +30 -0
  176. package/dist/node_modules/@pencil-agent/tui/dist/utils.d.ts +83 -0
  177. package/dist/node_modules/@pencil-agent/tui/dist/utils.js +811 -0
  178. package/dist/node_modules/@pencil-agent/tui/package.json +37 -0
  179. package/package.json +3 -2
@@ -0,0 +1,39 @@
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
+ /**
8
+ * [WHO]: openaiCodexOAuthProvider
9
+ * [FROM]: Depends on ./pkce.js
10
+ * [TO]: Consumed by core/lib/ai/src/index.ts
11
+ * [HERE]: core/lib/ai/src/utils/oauth/openai-codex.ts -
12
+ */
13
+ import type { OAuthCredentials, OAuthPrompt, OAuthProviderInterface } from "./types.js";
14
+ /**
15
+ * Login with OpenAI Codex OAuth
16
+ *
17
+ * @param options.onAuth - Called with URL and instructions when auth starts
18
+ * @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)
19
+ * @param options.onProgress - Optional progress messages
20
+ * @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.
21
+ * Races with browser callback - whichever completes first wins.
22
+ * Useful for showing paste input immediately alongside browser flow.
23
+ * @param options.originator - OAuth originator parameter (defaults to "nanopencil")
24
+ */
25
+ export declare function loginOpenAICodex(options: {
26
+ onAuth: (info: {
27
+ url: string;
28
+ instructions?: string;
29
+ }) => void;
30
+ onPrompt: (prompt: OAuthPrompt) => Promise<string>;
31
+ onProgress?: (message: string) => void;
32
+ onManualCodeInput?: () => Promise<string>;
33
+ originator?: string;
34
+ }): Promise<OAuthCredentials>;
35
+ /**
36
+ * Refresh OpenAI Codex OAuth token
37
+ */
38
+ export declare function refreshOpenAICodexToken(refreshToken: string): Promise<OAuthCredentials>;
39
+ export declare const openaiCodexOAuthProvider: OAuthProviderInterface;
@@ -0,0 +1,385 @@
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
+ /**
8
+ * [WHO]: openaiCodexOAuthProvider
9
+ * [FROM]: Depends on ./pkce.js
10
+ * [TO]: Consumed by core/lib/ai/src/index.ts
11
+ * [HERE]: core/lib/ai/src/utils/oauth/openai-codex.ts -
12
+ */
13
+ // NEVER convert to top-level imports - breaks browser/Vite builds (web-ui)
14
+ let _randomBytes = null;
15
+ let _http = null;
16
+ if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
17
+ import("node:crypto").then((m) => {
18
+ _randomBytes = m.randomBytes;
19
+ });
20
+ import("node:http").then((m) => {
21
+ _http = m;
22
+ });
23
+ }
24
+ import { generatePKCE } from "./pkce.js";
25
+ const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
26
+ const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
27
+ const TOKEN_URL = "https://auth.openai.com/oauth/token";
28
+ const REDIRECT_URI = "http://localhost:1455/auth/callback";
29
+ const SCOPE = "openid profile email offline_access";
30
+ const JWT_CLAIM_PATH = "https://api.openai.com/auth";
31
+ const SUCCESS_HTML = `<!doctype html>
32
+ <html lang="en">
33
+ <head>
34
+ <meta charset="utf-8" />
35
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
36
+ <title>Authentication successful</title>
37
+ </head>
38
+ <body>
39
+ <p>Authentication successful. Return to your terminal to continue.</p>
40
+ </body>
41
+ </html>`;
42
+ function createState() {
43
+ if (!_randomBytes) {
44
+ throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
45
+ }
46
+ return _randomBytes(16).toString("hex");
47
+ }
48
+ function parseAuthorizationInput(input) {
49
+ const value = input.trim();
50
+ if (!value)
51
+ return {};
52
+ try {
53
+ const url = new URL(value);
54
+ return {
55
+ code: url.searchParams.get("code") ?? undefined,
56
+ state: url.searchParams.get("state") ?? undefined,
57
+ };
58
+ }
59
+ catch {
60
+ // not a URL
61
+ }
62
+ if (value.includes("#")) {
63
+ const [code, state] = value.split("#", 2);
64
+ return { code, state };
65
+ }
66
+ if (value.includes("code=")) {
67
+ const params = new URLSearchParams(value);
68
+ return {
69
+ code: params.get("code") ?? undefined,
70
+ state: params.get("state") ?? undefined,
71
+ };
72
+ }
73
+ return { code: value };
74
+ }
75
+ function decodeJwt(token) {
76
+ try {
77
+ const parts = token.split(".");
78
+ if (parts.length !== 3)
79
+ return null;
80
+ const payload = parts[1] ?? "";
81
+ const decoded = atob(payload);
82
+ return JSON.parse(decoded);
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ async function exchangeAuthorizationCode(code, verifier, redirectUri = REDIRECT_URI) {
89
+ const response = await fetch(TOKEN_URL, {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
92
+ body: new URLSearchParams({
93
+ grant_type: "authorization_code",
94
+ client_id: CLIENT_ID,
95
+ code,
96
+ code_verifier: verifier,
97
+ redirect_uri: redirectUri,
98
+ }),
99
+ });
100
+ if (!response.ok) {
101
+ const text = await response.text().catch(() => "");
102
+ console.error("[openai-codex] code->token failed:", response.status, text);
103
+ return { type: "failed" };
104
+ }
105
+ const json = (await response.json());
106
+ if (!json.access_token || !json.refresh_token || typeof json.expires_in !== "number") {
107
+ console.error("[openai-codex] token response missing fields:", json);
108
+ return { type: "failed" };
109
+ }
110
+ return {
111
+ type: "success",
112
+ access: json.access_token,
113
+ refresh: json.refresh_token,
114
+ expires: Date.now() + json.expires_in * 1000,
115
+ };
116
+ }
117
+ async function refreshAccessToken(refreshToken) {
118
+ try {
119
+ const response = await fetch(TOKEN_URL, {
120
+ method: "POST",
121
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
122
+ body: new URLSearchParams({
123
+ grant_type: "refresh_token",
124
+ refresh_token: refreshToken,
125
+ client_id: CLIENT_ID,
126
+ }),
127
+ });
128
+ if (!response.ok) {
129
+ const text = await response.text().catch(() => "");
130
+ console.error("[openai-codex] Token refresh failed:", response.status, text);
131
+ return { type: "failed" };
132
+ }
133
+ const json = (await response.json());
134
+ if (!json.access_token || !json.refresh_token || typeof json.expires_in !== "number") {
135
+ console.error("[openai-codex] Token refresh response missing fields:", json);
136
+ return { type: "failed" };
137
+ }
138
+ return {
139
+ type: "success",
140
+ access: json.access_token,
141
+ refresh: json.refresh_token,
142
+ expires: Date.now() + json.expires_in * 1000,
143
+ };
144
+ }
145
+ catch (error) {
146
+ console.error("[openai-codex] Token refresh error:", error);
147
+ return { type: "failed" };
148
+ }
149
+ }
150
+ async function createAuthorizationFlow(originator = "nanopencil") {
151
+ const { verifier, challenge } = await generatePKCE();
152
+ const state = createState();
153
+ const url = new URL(AUTHORIZE_URL);
154
+ url.searchParams.set("response_type", "code");
155
+ url.searchParams.set("client_id", CLIENT_ID);
156
+ url.searchParams.set("redirect_uri", REDIRECT_URI);
157
+ url.searchParams.set("scope", SCOPE);
158
+ url.searchParams.set("code_challenge", challenge);
159
+ url.searchParams.set("code_challenge_method", "S256");
160
+ url.searchParams.set("state", state);
161
+ url.searchParams.set("id_token_add_organizations", "true");
162
+ url.searchParams.set("codex_cli_simplified_flow", "true");
163
+ url.searchParams.set("originator", originator);
164
+ return { verifier, state, url: url.toString() };
165
+ }
166
+ function startLocalOAuthServer(state) {
167
+ if (!_http) {
168
+ throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
169
+ }
170
+ let lastCode = null;
171
+ let cancelled = false;
172
+ const server = _http.createServer((req, res) => {
173
+ try {
174
+ const url = new URL(req.url || "", "http://localhost");
175
+ if (url.pathname !== "/auth/callback") {
176
+ res.statusCode = 404;
177
+ res.end("Not found");
178
+ return;
179
+ }
180
+ if (url.searchParams.get("state") !== state) {
181
+ res.statusCode = 400;
182
+ res.end("State mismatch");
183
+ return;
184
+ }
185
+ const code = url.searchParams.get("code");
186
+ if (!code) {
187
+ res.statusCode = 400;
188
+ res.end("Missing authorization code");
189
+ return;
190
+ }
191
+ res.statusCode = 200;
192
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
193
+ res.end(SUCCESS_HTML);
194
+ lastCode = code;
195
+ }
196
+ catch {
197
+ res.statusCode = 500;
198
+ res.end("Internal error");
199
+ }
200
+ });
201
+ return new Promise((resolve) => {
202
+ server
203
+ .listen(1455, "127.0.0.1", () => {
204
+ resolve({
205
+ close: () => server.close(),
206
+ cancelWait: () => {
207
+ cancelled = true;
208
+ },
209
+ waitForCode: async () => {
210
+ const sleep = () => new Promise((r) => setTimeout(r, 100));
211
+ for (let i = 0; i < 600; i += 1) {
212
+ if (lastCode)
213
+ return { code: lastCode };
214
+ if (cancelled)
215
+ return null;
216
+ await sleep();
217
+ }
218
+ return null;
219
+ },
220
+ });
221
+ })
222
+ .on("error", (err) => {
223
+ console.error("[openai-codex] Failed to bind http://127.0.0.1:1455 (", err.code, ") Falling back to manual paste.");
224
+ resolve({
225
+ close: () => {
226
+ try {
227
+ server.close();
228
+ }
229
+ catch {
230
+ // ignore
231
+ }
232
+ },
233
+ cancelWait: () => { },
234
+ waitForCode: async () => null,
235
+ });
236
+ });
237
+ });
238
+ }
239
+ function getAccountId(accessToken) {
240
+ const payload = decodeJwt(accessToken);
241
+ const auth = payload?.[JWT_CLAIM_PATH];
242
+ const accountId = auth?.chatgpt_account_id;
243
+ return typeof accountId === "string" && accountId.length > 0 ? accountId : null;
244
+ }
245
+ /**
246
+ * Login with OpenAI Codex OAuth
247
+ *
248
+ * @param options.onAuth - Called with URL and instructions when auth starts
249
+ * @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)
250
+ * @param options.onProgress - Optional progress messages
251
+ * @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.
252
+ * Races with browser callback - whichever completes first wins.
253
+ * Useful for showing paste input immediately alongside browser flow.
254
+ * @param options.originator - OAuth originator parameter (defaults to "nanopencil")
255
+ */
256
+ export async function loginOpenAICodex(options) {
257
+ const { verifier, state, url } = await createAuthorizationFlow(options.originator);
258
+ const server = await startLocalOAuthServer(state);
259
+ options.onAuth({ url, instructions: "A browser window should open. Complete login to finish." });
260
+ let code;
261
+ try {
262
+ if (options.onManualCodeInput) {
263
+ // Race between browser callback and manual input
264
+ let manualCode;
265
+ let manualError;
266
+ const manualPromise = options
267
+ .onManualCodeInput()
268
+ .then((input) => {
269
+ manualCode = input;
270
+ server.cancelWait();
271
+ })
272
+ .catch((err) => {
273
+ manualError = err instanceof Error ? err : new Error(String(err));
274
+ server.cancelWait();
275
+ });
276
+ const result = await server.waitForCode();
277
+ // If manual input was cancelled, throw that error
278
+ if (manualError) {
279
+ throw manualError;
280
+ }
281
+ if (result?.code) {
282
+ // Browser callback won
283
+ code = result.code;
284
+ }
285
+ else if (manualCode) {
286
+ // Manual input won (or callback timed out and user had entered code)
287
+ const parsed = parseAuthorizationInput(manualCode);
288
+ if (parsed.state && parsed.state !== state) {
289
+ throw new Error("State mismatch");
290
+ }
291
+ code = parsed.code;
292
+ }
293
+ // If still no code, wait for manual promise to complete and try that
294
+ if (!code) {
295
+ await manualPromise;
296
+ if (manualError) {
297
+ throw manualError;
298
+ }
299
+ if (manualCode) {
300
+ const parsed = parseAuthorizationInput(manualCode);
301
+ if (parsed.state && parsed.state !== state) {
302
+ throw new Error("State mismatch");
303
+ }
304
+ code = parsed.code;
305
+ }
306
+ }
307
+ }
308
+ else {
309
+ // Original flow: wait for callback, then prompt if needed
310
+ const result = await server.waitForCode();
311
+ if (result?.code) {
312
+ code = result.code;
313
+ }
314
+ }
315
+ // Fallback to onPrompt if still no code
316
+ if (!code) {
317
+ const input = await options.onPrompt({
318
+ message: "Paste the authorization code (or full redirect URL):",
319
+ });
320
+ const parsed = parseAuthorizationInput(input);
321
+ if (parsed.state && parsed.state !== state) {
322
+ throw new Error("State mismatch");
323
+ }
324
+ code = parsed.code;
325
+ }
326
+ if (!code) {
327
+ throw new Error("Missing authorization code");
328
+ }
329
+ const tokenResult = await exchangeAuthorizationCode(code, verifier);
330
+ if (tokenResult.type !== "success") {
331
+ throw new Error("Token exchange failed");
332
+ }
333
+ const accountId = getAccountId(tokenResult.access);
334
+ if (!accountId) {
335
+ throw new Error("Failed to extract accountId from token");
336
+ }
337
+ return {
338
+ access: tokenResult.access,
339
+ refresh: tokenResult.refresh,
340
+ expires: tokenResult.expires,
341
+ accountId,
342
+ };
343
+ }
344
+ finally {
345
+ server.close();
346
+ }
347
+ }
348
+ /**
349
+ * Refresh OpenAI Codex OAuth token
350
+ */
351
+ export async function refreshOpenAICodexToken(refreshToken) {
352
+ const result = await refreshAccessToken(refreshToken);
353
+ if (result.type !== "success") {
354
+ throw new Error("Failed to refresh OpenAI Codex token");
355
+ }
356
+ const accountId = getAccountId(result.access);
357
+ if (!accountId) {
358
+ throw new Error("Failed to extract accountId from token");
359
+ }
360
+ return {
361
+ access: result.access,
362
+ refresh: result.refresh,
363
+ expires: result.expires,
364
+ accountId,
365
+ };
366
+ }
367
+ export const openaiCodexOAuthProvider = {
368
+ id: "openai-codex",
369
+ name: "ChatGPT Plus/Pro (Codex Subscription)",
370
+ usesCallbackServer: true,
371
+ async login(callbacks) {
372
+ return loginOpenAICodex({
373
+ onAuth: callbacks.onAuth,
374
+ onPrompt: callbacks.onPrompt,
375
+ onProgress: callbacks.onProgress,
376
+ onManualCodeInput: callbacks.onManualCodeInput,
377
+ });
378
+ },
379
+ async refreshToken(credentials) {
380
+ return refreshOpenAICodexToken(credentials.refresh);
381
+ },
382
+ getApiKey(credentials) {
383
+ return credentials.access;
384
+ },
385
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * PKCE utilities using Web Crypto API.
3
+ * Works in both Node.js 20+ and browsers.
4
+ */
5
+ /**
6
+ * [WHO]: Extension interface
7
+ * [FROM]: No external dependencies
8
+ * [TO]: Consumed by core/lib/ai/src/index.ts
9
+ * [HERE]: core/lib/ai/src/utils/oauth/pkce.ts -
10
+ */
11
+ /**
12
+ * Generate PKCE code verifier and challenge.
13
+ * Uses Web Crypto API for cross-platform compatibility.
14
+ */
15
+ export declare function generatePKCE(): Promise<{
16
+ verifier: string;
17
+ challenge: string;
18
+ }>;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * PKCE utilities using Web Crypto API.
3
+ * Works in both Node.js 20+ and browsers.
4
+ */
5
+ /**
6
+ * [WHO]: Extension interface
7
+ * [FROM]: No external dependencies
8
+ * [TO]: Consumed by core/lib/ai/src/index.ts
9
+ * [HERE]: core/lib/ai/src/utils/oauth/pkce.ts -
10
+ */
11
+ /**
12
+ * Encode bytes as base64url string.
13
+ */
14
+ function base64urlEncode(bytes) {
15
+ let binary = "";
16
+ for (const byte of bytes) {
17
+ binary += String.fromCharCode(byte);
18
+ }
19
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
20
+ }
21
+ /**
22
+ * Generate PKCE code verifier and challenge.
23
+ * Uses Web Crypto API for cross-platform compatibility.
24
+ */
25
+ export async function generatePKCE() {
26
+ // Generate random verifier
27
+ const verifierBytes = new Uint8Array(32);
28
+ crypto.getRandomValues(verifierBytes);
29
+ const verifier = base64urlEncode(verifierBytes);
30
+ // Compute SHA-256 challenge
31
+ const encoder = new TextEncoder();
32
+ const data = encoder.encode(verifier);
33
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
34
+ const challenge = base64urlEncode(new Uint8Array(hashBuffer));
35
+ return { verifier, challenge };
36
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * [WHO]: OAuthLoginCallbacks, OAuthProviderInterface, OAuthProviderInfo
3
+ * [FROM]: No external dependencies
4
+ * [TO]: Consumed by core/lib/ai/src/index.ts
5
+ * [HERE]: core/lib/ai/src/utils/oauth/types.ts -
6
+ */
7
+ import type { Api, Model } from "../../types.js";
8
+ export type OAuthCredentials = {
9
+ refresh: string;
10
+ access: string;
11
+ expires: number;
12
+ [key: string]: unknown;
13
+ };
14
+ export type OAuthProviderId = string;
15
+ /** @deprecated Use OAuthProviderId instead */
16
+ export type OAuthProvider = OAuthProviderId;
17
+ export type OAuthPrompt = {
18
+ message: string;
19
+ placeholder?: string;
20
+ allowEmpty?: boolean;
21
+ };
22
+ export type OAuthAuthInfo = {
23
+ url: string;
24
+ instructions?: string;
25
+ };
26
+ export interface OAuthLoginCallbacks {
27
+ onAuth: (info: OAuthAuthInfo) => void;
28
+ onPrompt: (prompt: OAuthPrompt) => Promise<string>;
29
+ onProgress?: (message: string) => void;
30
+ onManualCodeInput?: () => Promise<string>;
31
+ signal?: AbortSignal;
32
+ }
33
+ export interface OAuthProviderInterface {
34
+ readonly id: OAuthProviderId;
35
+ readonly name: string;
36
+ /** Run the login flow, return credentials to persist */
37
+ login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;
38
+ /** Whether login uses a local callback server and supports manual code input. */
39
+ usesCallbackServer?: boolean;
40
+ /** Refresh expired credentials, return updated credentials to persist */
41
+ refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;
42
+ /** Convert credentials to API key string for the provider */
43
+ getApiKey(credentials: OAuthCredentials): string;
44
+ /** Optional: modify models for this provider (e.g., update baseUrl) */
45
+ modifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];
46
+ }
47
+ /** @deprecated Use OAuthProviderInterface instead */
48
+ export interface OAuthProviderInfo {
49
+ id: OAuthProviderId;
50
+ name: string;
51
+ available: boolean;
52
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * [WHO]: OAuthLoginCallbacks, OAuthProviderInterface, OAuthProviderInfo
3
+ * [FROM]: No external dependencies
4
+ * [TO]: Consumed by core/lib/ai/src/index.ts
5
+ * [HERE]: core/lib/ai/src/utils/oauth/types.ts -
6
+ */
7
+ export {};
@@ -0,0 +1,57 @@
1
+ /**
2
+ * [WHO]: isContextOverflow, getOverflowPatterns
3
+ * [FROM]: No external dependencies
4
+ * [TO]: Consumed by core/lib/ai/src/index.ts
5
+ * [HERE]: core/lib/ai/src/utils/overflow.ts -
6
+ */
7
+ import type { AssistantMessage } from "../types.js";
8
+ /**
9
+ * Check if an assistant message represents a context overflow error.
10
+ *
11
+ * This handles two cases:
12
+ * 1. Error-based overflow: Most providers return stopReason "error" with a
13
+ * specific error message pattern.
14
+ * 2. Silent overflow: Some providers accept overflow requests and return
15
+ * successfully. For these, we check if usage.input exceeds the context window.
16
+ *
17
+ * ## Reliability by Provider
18
+ *
19
+ * **Reliable detection (returns error with detectable message):**
20
+ * - Anthropic: "prompt is too long: X tokens > Y maximum"
21
+ * - OpenAI (Completions & Responses): "exceeds the context window"
22
+ * - Google Gemini: "input token count exceeds the maximum"
23
+ * - xAI (Grok): "maximum prompt length is X but request contains Y"
24
+ * - Groq: "reduce the length of the messages"
25
+ * - Cerebras: 400/413 status code (no body)
26
+ * - Mistral: 400/413 status code (no body)
27
+ * - OpenRouter (all backends): "maximum context length is X tokens"
28
+ * - llama.cpp: "exceeds the available context size"
29
+ * - LM Studio: "greater than the context length"
30
+ * - Kimi For Coding: "exceeded model token limit: X (requested: Y)"
31
+ *
32
+ * **Unreliable detection:**
33
+ * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),
34
+ * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.
35
+ * - Ollama: Silently truncates input without error. Cannot be detected via this function.
36
+ * The response will have usage.input < expected, but we don't know the expected value.
37
+ *
38
+ * ## Custom Providers
39
+ *
40
+ * If you've added custom models via settings.json, this function may not detect
41
+ * overflow errors from those providers. To add support:
42
+ *
43
+ * 1. Send a request that exceeds the model's context window
44
+ * 2. Check the errorMessage in the response
45
+ * 3. Create a regex pattern that matches the error
46
+ * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or
47
+ * check the errorMessage yourself before calling this function
48
+ *
49
+ * @param message - The assistant message to check
50
+ * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)
51
+ * @returns true if the message indicates a context overflow
52
+ */
53
+ export declare function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean;
54
+ /**
55
+ * Get the overflow patterns for testing purposes.
56
+ */
57
+ export declare function getOverflowPatterns(): RegExp[];