@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,483 @@
1
+ /**
2
+ * Gemini CLI OAuth flow (Google Cloud Code Assist)
3
+ * Standard Gemini models only (gemini-2.0-flash, gemini-2.5-*)
4
+ *
5
+ * NOTE: This module uses Node.js http.createServer for the OAuth callback.
6
+ * It is only intended for CLI use, not browser environments.
7
+ */
8
+ /**
9
+ * [WHO]: geminiCliOAuthProvider
10
+ * [FROM]: Depends on ./pkce.js
11
+ * [TO]: Consumed by core/lib/ai/src/index.ts
12
+ * [HERE]: core/lib/ai/src/utils/oauth/google-gemini-cli.ts -
13
+ */
14
+ import { decodeOAuthCredentialSegment } from "./decode-credential.js";
15
+ import { generatePKCE } from "./pkce.js";
16
+ let _createServer = null;
17
+ let _httpImportPromise = null;
18
+ if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
19
+ _httpImportPromise = import("node:http").then((m) => {
20
+ _createServer = m.createServer;
21
+ });
22
+ }
23
+ const CLIENT_ID = decodeOAuthCredentialSegment("YOUR_CLIENT_ID_HERE");
24
+ const CLIENT_SECRET = decodeOAuthCredentialSegment("YOUR_CLIENT_SECRET_HERE");
25
+ const REDIRECT_URI = "http://localhost:8085/oauth2callback";
26
+ const SCOPES = [
27
+ "https://www.googleapis.com/auth/cloud-platform",
28
+ "https://www.googleapis.com/auth/userinfo.email",
29
+ "https://www.googleapis.com/auth/userinfo.profile",
30
+ ];
31
+ const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
32
+ const TOKEN_URL = "https://oauth2.googleapis.com/token";
33
+ const CODE_ASSIST_ENDPOINT = "https://cloudcode-pa.googleapis.com";
34
+ /**
35
+ * Start a local HTTP server to receive the OAuth callback
36
+ */
37
+ async function getNodeCreateServer() {
38
+ if (_createServer)
39
+ return _createServer;
40
+ if (_httpImportPromise) {
41
+ await _httpImportPromise;
42
+ }
43
+ if (_createServer)
44
+ return _createServer;
45
+ throw new Error("Gemini CLI OAuth is only available in Node.js environments");
46
+ }
47
+ async function startCallbackServer() {
48
+ const createServer = await getNodeCreateServer();
49
+ return new Promise((resolve, reject) => {
50
+ let result = null;
51
+ let cancelled = false;
52
+ const server = createServer((req, res) => {
53
+ const url = new URL(req.url || "", `http://localhost:8085`);
54
+ if (url.pathname === "/oauth2callback") {
55
+ const code = url.searchParams.get("code");
56
+ const state = url.searchParams.get("state");
57
+ const error = url.searchParams.get("error");
58
+ if (error) {
59
+ res.writeHead(400, { "Content-Type": "text/html" });
60
+ res.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${error}</p><p>You can close this window.</p></body></html>`);
61
+ return;
62
+ }
63
+ if (code && state) {
64
+ res.writeHead(200, { "Content-Type": "text/html" });
65
+ res.end(`<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>`);
66
+ result = { code, state };
67
+ }
68
+ else {
69
+ res.writeHead(400, { "Content-Type": "text/html" });
70
+ res.end(`<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>`);
71
+ }
72
+ }
73
+ else {
74
+ res.writeHead(404);
75
+ res.end();
76
+ }
77
+ });
78
+ server.on("error", (err) => {
79
+ reject(err);
80
+ });
81
+ server.listen(8085, "127.0.0.1", () => {
82
+ resolve({
83
+ server,
84
+ cancelWait: () => {
85
+ cancelled = true;
86
+ },
87
+ waitForCode: async () => {
88
+ const sleep = () => new Promise((r) => setTimeout(r, 100));
89
+ while (!result && !cancelled) {
90
+ await sleep();
91
+ }
92
+ return result;
93
+ },
94
+ });
95
+ });
96
+ });
97
+ }
98
+ /**
99
+ * Parse redirect URL to extract code and state
100
+ */
101
+ function parseRedirectUrl(input) {
102
+ const value = input.trim();
103
+ if (!value)
104
+ return {};
105
+ try {
106
+ const url = new URL(value);
107
+ return {
108
+ code: url.searchParams.get("code") ?? undefined,
109
+ state: url.searchParams.get("state") ?? undefined,
110
+ };
111
+ }
112
+ catch {
113
+ // Not a URL, return empty
114
+ return {};
115
+ }
116
+ }
117
+ // Tier IDs as used by the Cloud Code API
118
+ const TIER_FREE = "free-tier";
119
+ const TIER_LEGACY = "legacy-tier";
120
+ const TIER_STANDARD = "standard-tier";
121
+ /**
122
+ * Wait helper for onboarding retries
123
+ */
124
+ function wait(ms) {
125
+ return new Promise((resolve) => setTimeout(resolve, ms));
126
+ }
127
+ /**
128
+ * Get default tier from allowed tiers
129
+ */
130
+ function getDefaultTier(allowedTiers) {
131
+ if (!allowedTiers || allowedTiers.length === 0)
132
+ return { id: TIER_LEGACY };
133
+ const defaultTier = allowedTiers.find((t) => t.isDefault);
134
+ return defaultTier ?? { id: TIER_LEGACY };
135
+ }
136
+ function isVpcScAffectedUser(payload) {
137
+ if (!payload || typeof payload !== "object")
138
+ return false;
139
+ if (!("error" in payload))
140
+ return false;
141
+ const error = payload.error;
142
+ if (!error?.details || !Array.isArray(error.details))
143
+ return false;
144
+ return error.details.some((detail) => detail.reason === "SECURITY_POLICY_VIOLATED");
145
+ }
146
+ /**
147
+ * Poll a long-running operation until completion
148
+ */
149
+ async function pollOperation(operationName, headers, onProgress) {
150
+ let attempt = 0;
151
+ while (true) {
152
+ if (attempt > 0) {
153
+ onProgress?.(`Waiting for project provisioning (attempt ${attempt + 1})...`);
154
+ await wait(5000);
155
+ }
156
+ const response = await fetch(`${CODE_ASSIST_ENDPOINT}/v1internal/${operationName}`, {
157
+ method: "GET",
158
+ headers,
159
+ });
160
+ if (!response.ok) {
161
+ throw new Error(`Failed to poll operation: ${response.status} ${response.statusText}`);
162
+ }
163
+ const data = (await response.json());
164
+ if (data.done) {
165
+ return data;
166
+ }
167
+ attempt += 1;
168
+ }
169
+ }
170
+ /**
171
+ * Discover or provision a Google Cloud project for the user
172
+ */
173
+ async function discoverProject(accessToken, onProgress) {
174
+ // Check for user-provided project ID via environment variable
175
+ const envProjectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT_ID;
176
+ const headers = {
177
+ Authorization: `Bearer ${accessToken}`,
178
+ "Content-Type": "application/json",
179
+ "User-Agent": "google-api-nodejs-client/9.15.1",
180
+ "X-Goog-Api-Client": "gl-node/22.17.0",
181
+ };
182
+ // Try to load existing project via loadCodeAssist
183
+ onProgress?.("Checking for existing Cloud Code Assist project...");
184
+ const loadResponse = await fetch(`${CODE_ASSIST_ENDPOINT}/v1internal:loadCodeAssist`, {
185
+ method: "POST",
186
+ headers,
187
+ body: JSON.stringify({
188
+ cloudaicompanionProject: envProjectId,
189
+ metadata: {
190
+ ideType: "IDE_UNSPECIFIED",
191
+ platform: "PLATFORM_UNSPECIFIED",
192
+ pluginType: "GEMINI",
193
+ duetProject: envProjectId,
194
+ },
195
+ }),
196
+ });
197
+ let data;
198
+ if (!loadResponse.ok) {
199
+ let errorPayload;
200
+ try {
201
+ errorPayload = await loadResponse.clone().json();
202
+ }
203
+ catch {
204
+ errorPayload = undefined;
205
+ }
206
+ if (isVpcScAffectedUser(errorPayload)) {
207
+ data = { currentTier: { id: TIER_STANDARD } };
208
+ }
209
+ else {
210
+ const errorText = await loadResponse.text();
211
+ throw new Error(`loadCodeAssist failed: ${loadResponse.status} ${loadResponse.statusText}: ${errorText}`);
212
+ }
213
+ }
214
+ else {
215
+ data = (await loadResponse.json());
216
+ }
217
+ // If user already has a current tier and project, use it
218
+ if (data.currentTier) {
219
+ if (data.cloudaicompanionProject) {
220
+ return data.cloudaicompanionProject;
221
+ }
222
+ // User has a tier but no managed project - they need to provide one via env var
223
+ if (envProjectId) {
224
+ return envProjectId;
225
+ }
226
+ throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. " +
227
+ "See https://goo.gle/gemini-cli-auth-docs#workspace-gca");
228
+ }
229
+ // User needs to be onboarded - get the default tier
230
+ const tier = getDefaultTier(data.allowedTiers);
231
+ const tierId = tier?.id ?? TIER_FREE;
232
+ if (tierId !== TIER_FREE && !envProjectId) {
233
+ throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. " +
234
+ "See https://goo.gle/gemini-cli-auth-docs#workspace-gca");
235
+ }
236
+ onProgress?.("Provisioning Cloud Code Assist project (this may take a moment)...");
237
+ // Build onboard request - for free tier, don't include project ID (Google provisions one)
238
+ // For other tiers, include the user's project ID if available
239
+ const onboardBody = {
240
+ tierId,
241
+ metadata: {
242
+ ideType: "IDE_UNSPECIFIED",
243
+ platform: "PLATFORM_UNSPECIFIED",
244
+ pluginType: "GEMINI",
245
+ },
246
+ };
247
+ if (tierId !== TIER_FREE && envProjectId) {
248
+ onboardBody.cloudaicompanionProject = envProjectId;
249
+ onboardBody.metadata.duetProject = envProjectId;
250
+ }
251
+ // Start onboarding - this returns a long-running operation
252
+ const onboardResponse = await fetch(`${CODE_ASSIST_ENDPOINT}/v1internal:onboardUser`, {
253
+ method: "POST",
254
+ headers,
255
+ body: JSON.stringify(onboardBody),
256
+ });
257
+ if (!onboardResponse.ok) {
258
+ const errorText = await onboardResponse.text();
259
+ throw new Error(`onboardUser failed: ${onboardResponse.status} ${onboardResponse.statusText}: ${errorText}`);
260
+ }
261
+ let lroData = (await onboardResponse.json());
262
+ // If the operation isn't done yet, poll until completion
263
+ if (!lroData.done && lroData.name) {
264
+ lroData = await pollOperation(lroData.name, headers, onProgress);
265
+ }
266
+ // Try to get project ID from the response
267
+ const projectId = lroData.response?.cloudaicompanionProject?.id;
268
+ if (projectId) {
269
+ return projectId;
270
+ }
271
+ // If no project ID from onboarding, fall back to env var
272
+ if (envProjectId) {
273
+ return envProjectId;
274
+ }
275
+ throw new Error("Could not discover or provision a Google Cloud project. " +
276
+ "Try setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. " +
277
+ "See https://goo.gle/gemini-cli-auth-docs#workspace-gca");
278
+ }
279
+ /**
280
+ * Get user email from the access token
281
+ */
282
+ async function getUserEmail(accessToken) {
283
+ try {
284
+ const response = await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json", {
285
+ headers: {
286
+ Authorization: `Bearer ${accessToken}`,
287
+ },
288
+ });
289
+ if (response.ok) {
290
+ const data = (await response.json());
291
+ return data.email;
292
+ }
293
+ }
294
+ catch {
295
+ // Ignore errors, email is optional
296
+ }
297
+ return undefined;
298
+ }
299
+ /**
300
+ * Refresh Google Cloud Code Assist token
301
+ */
302
+ export async function refreshGoogleCloudToken(refreshToken, projectId) {
303
+ const response = await fetch(TOKEN_URL, {
304
+ method: "POST",
305
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
306
+ body: new URLSearchParams({
307
+ client_id: CLIENT_ID,
308
+ client_secret: CLIENT_SECRET,
309
+ refresh_token: refreshToken,
310
+ grant_type: "refresh_token",
311
+ }),
312
+ });
313
+ if (!response.ok) {
314
+ const error = await response.text();
315
+ throw new Error(`Google Cloud token refresh failed: ${error}`);
316
+ }
317
+ const data = (await response.json());
318
+ return {
319
+ refresh: data.refresh_token || refreshToken,
320
+ access: data.access_token,
321
+ expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,
322
+ projectId,
323
+ };
324
+ }
325
+ /**
326
+ * Login with Gemini CLI (Google Cloud Code Assist) OAuth
327
+ *
328
+ * @param onAuth - Callback with URL and optional instructions
329
+ * @param onProgress - Optional progress callback
330
+ * @param onManualCodeInput - Optional promise that resolves with user-pasted redirect URL.
331
+ * Races with browser callback - whichever completes first wins.
332
+ */
333
+ export async function loginGeminiCli(onAuth, onProgress, onManualCodeInput) {
334
+ const { verifier, challenge } = await generatePKCE();
335
+ // Start local server for callback
336
+ onProgress?.("Starting local server for OAuth callback...");
337
+ const server = await startCallbackServer();
338
+ let code;
339
+ try {
340
+ // Build authorization URL
341
+ const authParams = new URLSearchParams({
342
+ client_id: CLIENT_ID,
343
+ response_type: "code",
344
+ redirect_uri: REDIRECT_URI,
345
+ scope: SCOPES.join(" "),
346
+ code_challenge: challenge,
347
+ code_challenge_method: "S256",
348
+ state: verifier,
349
+ access_type: "offline",
350
+ prompt: "consent",
351
+ });
352
+ const authUrl = `${AUTH_URL}?${authParams.toString()}`;
353
+ // Notify caller with URL to open
354
+ onAuth({
355
+ url: authUrl,
356
+ instructions: "Complete the sign-in in your browser.",
357
+ });
358
+ // Wait for the callback, racing with manual input if provided
359
+ onProgress?.("Waiting for OAuth callback...");
360
+ if (onManualCodeInput) {
361
+ // Race between browser callback and manual input
362
+ let manualInput;
363
+ let manualError;
364
+ const manualPromise = onManualCodeInput()
365
+ .then((input) => {
366
+ manualInput = input;
367
+ server.cancelWait();
368
+ })
369
+ .catch((err) => {
370
+ manualError = err instanceof Error ? err : new Error(String(err));
371
+ server.cancelWait();
372
+ });
373
+ const result = await server.waitForCode();
374
+ // If manual input was cancelled, throw that error
375
+ if (manualError) {
376
+ throw manualError;
377
+ }
378
+ if (result?.code) {
379
+ // Browser callback won - verify state
380
+ if (result.state !== verifier) {
381
+ throw new Error("OAuth state mismatch - possible CSRF attack");
382
+ }
383
+ code = result.code;
384
+ }
385
+ else if (manualInput) {
386
+ // Manual input won
387
+ const parsed = parseRedirectUrl(manualInput);
388
+ if (parsed.state && parsed.state !== verifier) {
389
+ throw new Error("OAuth state mismatch - possible CSRF attack");
390
+ }
391
+ code = parsed.code;
392
+ }
393
+ // If still no code, wait for manual promise and try that
394
+ if (!code) {
395
+ await manualPromise;
396
+ if (manualError) {
397
+ throw manualError;
398
+ }
399
+ if (manualInput) {
400
+ const parsed = parseRedirectUrl(manualInput);
401
+ if (parsed.state && parsed.state !== verifier) {
402
+ throw new Error("OAuth state mismatch - possible CSRF attack");
403
+ }
404
+ code = parsed.code;
405
+ }
406
+ }
407
+ }
408
+ else {
409
+ // Original flow: just wait for callback
410
+ const result = await server.waitForCode();
411
+ if (result?.code) {
412
+ if (result.state !== verifier) {
413
+ throw new Error("OAuth state mismatch - possible CSRF attack");
414
+ }
415
+ code = result.code;
416
+ }
417
+ }
418
+ if (!code) {
419
+ throw new Error("No authorization code received");
420
+ }
421
+ // Exchange code for tokens
422
+ onProgress?.("Exchanging authorization code for tokens...");
423
+ const tokenResponse = await fetch(TOKEN_URL, {
424
+ method: "POST",
425
+ headers: {
426
+ "Content-Type": "application/x-www-form-urlencoded",
427
+ },
428
+ body: new URLSearchParams({
429
+ client_id: CLIENT_ID,
430
+ client_secret: CLIENT_SECRET,
431
+ code,
432
+ grant_type: "authorization_code",
433
+ redirect_uri: REDIRECT_URI,
434
+ code_verifier: verifier,
435
+ }),
436
+ });
437
+ if (!tokenResponse.ok) {
438
+ const error = await tokenResponse.text();
439
+ throw new Error(`Token exchange failed: ${error}`);
440
+ }
441
+ const tokenData = (await tokenResponse.json());
442
+ if (!tokenData.refresh_token) {
443
+ throw new Error("No refresh token received. Please try again.");
444
+ }
445
+ // Get user email
446
+ onProgress?.("Getting user info...");
447
+ const email = await getUserEmail(tokenData.access_token);
448
+ // Discover project
449
+ const projectId = await discoverProject(tokenData.access_token, onProgress);
450
+ // Calculate expiry time (current time + expires_in seconds - 5 min buffer)
451
+ const expiresAt = Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000;
452
+ const credentials = {
453
+ refresh: tokenData.refresh_token,
454
+ access: tokenData.access_token,
455
+ expires: expiresAt,
456
+ projectId,
457
+ email,
458
+ };
459
+ return credentials;
460
+ }
461
+ finally {
462
+ server.server.close();
463
+ }
464
+ }
465
+ export const geminiCliOAuthProvider = {
466
+ id: "google-gemini-cli",
467
+ name: "Google Cloud Code Assist (Gemini CLI)",
468
+ usesCallbackServer: true,
469
+ async login(callbacks) {
470
+ return loginGeminiCli(callbacks.onAuth, callbacks.onProgress, callbacks.onManualCodeInput);
471
+ },
472
+ async refreshToken(credentials) {
473
+ const creds = credentials;
474
+ if (!creds.projectId) {
475
+ throw new Error("Google Cloud credentials missing projectId");
476
+ }
477
+ return refreshGoogleCloudToken(creds.refresh, creds.projectId);
478
+ },
479
+ getApiKey(credentials) {
480
+ const creds = credentials;
481
+ return JSON.stringify({ token: creds.access, projectId: creds.projectId });
482
+ },
483
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * [WHO]: OAuth credential management - loginAnthropic, refreshAnthropicToken, loginGitHubCopilot, loginGoogleGeminiCli, loginOpenAICodex
3
+ * [FROM]: Depends on ./anthropic, ./github-copilot, ./google-antigravity, ./google-gemini-cli, ./openai-codex, ../http-proxy
4
+ * [TO]: Consumed by core/lib/ai/src/index.ts, AI providers
5
+ * [HERE]: core/lib/ai/src/utils/oauth/index.ts - OAuth credential management for AI providers
6
+ *
7
+ * Handles login, token refresh, and credential storage for:
8
+ * Anthropic, GitHub Copilot, Google Cloud Code Assist, Antigravity
9
+ */
10
+ import "../http-proxy.js";
11
+ export { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from "./anthropic.js";
12
+ export { getGitHubCopilotBaseUrl, githubCopilotOAuthProvider, loginGitHubCopilot, normalizeDomain, refreshGitHubCopilotToken, } from "./github-copilot.js";
13
+ export { antigravityOAuthProvider, loginAntigravity, refreshAntigravityToken } from "./google-antigravity.js";
14
+ export { geminiCliOAuthProvider, loginGeminiCli, refreshGoogleCloudToken } from "./google-gemini-cli.js";
15
+ export { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from "./openai-codex.js";
16
+ export * from "./types.js";
17
+ import type { OAuthCredentials, OAuthProviderId, OAuthProviderInfo, OAuthProviderInterface } from "./types.js";
18
+ /**
19
+ * Get an OAuth provider by ID
20
+ */
21
+ export declare function getOAuthProvider(id: OAuthProviderId): OAuthProviderInterface | undefined;
22
+ /**
23
+ * Register a custom OAuth provider
24
+ */
25
+ export declare function registerOAuthProvider(provider: OAuthProviderInterface): void;
26
+ /**
27
+ * Unregister an OAuth provider.
28
+ *
29
+ * If the provider is built-in, restores the built-in implementation.
30
+ * Custom providers are removed completely.
31
+ */
32
+ export declare function unregisterOAuthProvider(id: string): void;
33
+ /**
34
+ * Reset OAuth providers to built-ins.
35
+ */
36
+ export declare function resetOAuthProviders(): void;
37
+ /**
38
+ * Get all registered OAuth providers
39
+ */
40
+ export declare function getOAuthProviders(): OAuthProviderInterface[];
41
+ /**
42
+ * @deprecated Use getOAuthProviders() which returns OAuthProviderInterface[]
43
+ */
44
+ export declare function getOAuthProviderInfoList(): OAuthProviderInfo[];
45
+ /**
46
+ * Refresh token for any OAuth provider.
47
+ * @deprecated Use getOAuthProvider(id).refreshToken() instead
48
+ */
49
+ export declare function refreshOAuthToken(providerId: OAuthProviderId, credentials: OAuthCredentials): Promise<OAuthCredentials>;
50
+ /**
51
+ * Get API key for a provider from OAuth credentials.
52
+ * Automatically refreshes expired tokens.
53
+ *
54
+ * @returns API key string and updated credentials, or null if no credentials
55
+ * @throws Error if refresh fails
56
+ */
57
+ export declare function getOAuthApiKey(providerId: OAuthProviderId, credentials: Record<string, OAuthCredentials>): Promise<{
58
+ newCredentials: OAuthCredentials;
59
+ apiKey: string;
60
+ } | null>;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * [WHO]: OAuth credential management - loginAnthropic, refreshAnthropicToken, loginGitHubCopilot, loginGoogleGeminiCli, loginOpenAICodex
3
+ * [FROM]: Depends on ./anthropic, ./github-copilot, ./google-antigravity, ./google-gemini-cli, ./openai-codex, ../http-proxy
4
+ * [TO]: Consumed by core/lib/ai/src/index.ts, AI providers
5
+ * [HERE]: core/lib/ai/src/utils/oauth/index.ts - OAuth credential management for AI providers
6
+ *
7
+ * Handles login, token refresh, and credential storage for:
8
+ * Anthropic, GitHub Copilot, Google Cloud Code Assist, Antigravity
9
+ */
10
+ // Set up HTTP proxy for fetch() calls (respects HTTP_PROXY, HTTPS_PROXY env vars)
11
+ import "../http-proxy.js";
12
+ // Anthropic
13
+ export { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from "./anthropic.js";
14
+ // GitHub Copilot
15
+ export { getGitHubCopilotBaseUrl, githubCopilotOAuthProvider, loginGitHubCopilot, normalizeDomain, refreshGitHubCopilotToken, } from "./github-copilot.js";
16
+ // Google Antigravity
17
+ export { antigravityOAuthProvider, loginAntigravity, refreshAntigravityToken } from "./google-antigravity.js";
18
+ // Google Gemini CLI
19
+ export { geminiCliOAuthProvider, loginGeminiCli, refreshGoogleCloudToken } from "./google-gemini-cli.js";
20
+ // OpenAI Codex (ChatGPT OAuth)
21
+ export { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from "./openai-codex.js";
22
+ export * from "./types.js";
23
+ // ============================================================================
24
+ // Provider Registry
25
+ // ============================================================================
26
+ import { anthropicOAuthProvider } from "./anthropic.js";
27
+ import { githubCopilotOAuthProvider } from "./github-copilot.js";
28
+ import { antigravityOAuthProvider } from "./google-antigravity.js";
29
+ import { geminiCliOAuthProvider } from "./google-gemini-cli.js";
30
+ import { openaiCodexOAuthProvider } from "./openai-codex.js";
31
+ const BUILT_IN_OAUTH_PROVIDERS = [
32
+ anthropicOAuthProvider,
33
+ githubCopilotOAuthProvider,
34
+ geminiCliOAuthProvider,
35
+ antigravityOAuthProvider,
36
+ openaiCodexOAuthProvider,
37
+ ];
38
+ const oauthProviderRegistry = new Map(BUILT_IN_OAUTH_PROVIDERS.map((provider) => [provider.id, provider]));
39
+ /**
40
+ * Get an OAuth provider by ID
41
+ */
42
+ export function getOAuthProvider(id) {
43
+ return oauthProviderRegistry.get(id);
44
+ }
45
+ /**
46
+ * Register a custom OAuth provider
47
+ */
48
+ export function registerOAuthProvider(provider) {
49
+ oauthProviderRegistry.set(provider.id, provider);
50
+ }
51
+ /**
52
+ * Unregister an OAuth provider.
53
+ *
54
+ * If the provider is built-in, restores the built-in implementation.
55
+ * Custom providers are removed completely.
56
+ */
57
+ export function unregisterOAuthProvider(id) {
58
+ const builtInProvider = BUILT_IN_OAUTH_PROVIDERS.find((provider) => provider.id === id);
59
+ if (builtInProvider) {
60
+ oauthProviderRegistry.set(id, builtInProvider);
61
+ return;
62
+ }
63
+ oauthProviderRegistry.delete(id);
64
+ }
65
+ /**
66
+ * Reset OAuth providers to built-ins.
67
+ */
68
+ export function resetOAuthProviders() {
69
+ oauthProviderRegistry.clear();
70
+ for (const provider of BUILT_IN_OAUTH_PROVIDERS) {
71
+ oauthProviderRegistry.set(provider.id, provider);
72
+ }
73
+ }
74
+ /**
75
+ * Get all registered OAuth providers
76
+ */
77
+ export function getOAuthProviders() {
78
+ return Array.from(oauthProviderRegistry.values());
79
+ }
80
+ /**
81
+ * @deprecated Use getOAuthProviders() which returns OAuthProviderInterface[]
82
+ */
83
+ export function getOAuthProviderInfoList() {
84
+ return getOAuthProviders().map((p) => ({
85
+ id: p.id,
86
+ name: p.name,
87
+ available: true,
88
+ }));
89
+ }
90
+ // ============================================================================
91
+ // High-level API (uses provider registry)
92
+ // ============================================================================
93
+ /**
94
+ * Refresh token for any OAuth provider.
95
+ * @deprecated Use getOAuthProvider(id).refreshToken() instead
96
+ */
97
+ export async function refreshOAuthToken(providerId, credentials) {
98
+ const provider = getOAuthProvider(providerId);
99
+ if (!provider) {
100
+ throw new Error(`Unknown OAuth provider: ${providerId}`);
101
+ }
102
+ return provider.refreshToken(credentials);
103
+ }
104
+ /**
105
+ * Get API key for a provider from OAuth credentials.
106
+ * Automatically refreshes expired tokens.
107
+ *
108
+ * @returns API key string and updated credentials, or null if no credentials
109
+ * @throws Error if refresh fails
110
+ */
111
+ export async function getOAuthApiKey(providerId, credentials) {
112
+ const provider = getOAuthProvider(providerId);
113
+ if (!provider) {
114
+ throw new Error(`Unknown OAuth provider: ${providerId}`);
115
+ }
116
+ let creds = credentials[providerId];
117
+ if (!creds) {
118
+ return null;
119
+ }
120
+ // Refresh if expired
121
+ if (Date.now() >= creds.expires) {
122
+ try {
123
+ creds = await provider.refreshToken(creds);
124
+ }
125
+ catch (_error) {
126
+ throw new Error(`Failed to refresh OAuth token for ${providerId}`);
127
+ }
128
+ }
129
+ const apiKey = provider.getApiKey(creds);
130
+ return { newCredentials: creds, apiKey };
131
+ }