@theia/ai-copilot 1.75.0 → 1.76.0-next.10

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 (150) hide show
  1. package/README.md +86 -14
  2. package/lib/browser/copilot-auth-dialog.d.ts.map +1 -1
  3. package/lib/browser/copilot-auth-dialog.js +12 -4
  4. package/lib/browser/copilot-auth-dialog.js.map +1 -1
  5. package/lib/browser/copilot-frontend-application-contribution.d.ts +15 -1
  6. package/lib/browser/copilot-frontend-application-contribution.d.ts.map +1 -1
  7. package/lib/browser/copilot-frontend-application-contribution.js +52 -24
  8. package/lib/browser/copilot-frontend-application-contribution.js.map +1 -1
  9. package/lib/common/copilot-auth-service.d.ts +27 -24
  10. package/lib/common/copilot-auth-service.d.ts.map +1 -1
  11. package/lib/common/copilot-language-models-manager.d.ts +3 -21
  12. package/lib/common/copilot-language-models-manager.d.ts.map +1 -1
  13. package/lib/common/copilot-language-models-manager.js +1 -13
  14. package/lib/common/copilot-language-models-manager.js.map +1 -1
  15. package/lib/common/copilot-preferences.d.ts +1 -0
  16. package/lib/common/copilot-preferences.d.ts.map +1 -1
  17. package/lib/common/copilot-preferences.js +24 -6
  18. package/lib/common/copilot-preferences.js.map +1 -1
  19. package/lib/common/index.d.ts +0 -1
  20. package/lib/common/index.d.ts.map +1 -1
  21. package/lib/common/index.js +0 -1
  22. package/lib/common/index.js.map +1 -1
  23. package/lib/node/copilot-auth-service-impl.d.ts +25 -16
  24. package/lib/node/copilot-auth-service-impl.d.ts.map +1 -1
  25. package/lib/node/copilot-auth-service-impl.js +67 -183
  26. package/lib/node/copilot-auth-service-impl.js.map +1 -1
  27. package/lib/node/copilot-auth-service-impl.spec.js +104 -168
  28. package/lib/node/copilot-auth-service-impl.spec.js.map +1 -1
  29. package/lib/node/copilot-backend-module.d.ts.map +1 -1
  30. package/lib/node/copilot-backend-module.js +10 -2
  31. package/lib/node/copilot-backend-module.js.map +1 -1
  32. package/lib/node/copilot-cli-auth-provider.d.ts +146 -0
  33. package/lib/node/copilot-cli-auth-provider.d.ts.map +1 -0
  34. package/lib/node/copilot-cli-auth-provider.js +430 -0
  35. package/lib/node/copilot-cli-auth-provider.js.map +1 -0
  36. package/lib/node/copilot-cli-auth-provider.spec.d.ts +2 -0
  37. package/lib/node/copilot-cli-auth-provider.spec.d.ts.map +1 -0
  38. package/lib/node/copilot-cli-auth-provider.spec.js +249 -0
  39. package/lib/node/copilot-cli-auth-provider.spec.js.map +1 -0
  40. package/lib/node/copilot-cli-locator.d.ts +120 -0
  41. package/lib/node/copilot-cli-locator.d.ts.map +1 -0
  42. package/lib/node/copilot-cli-locator.js +348 -0
  43. package/lib/node/copilot-cli-locator.js.map +1 -0
  44. package/lib/node/copilot-cli-locator.spec.d.ts +2 -0
  45. package/lib/node/copilot-cli-locator.spec.d.ts.map +1 -0
  46. package/lib/node/copilot-cli-locator.spec.js +327 -0
  47. package/lib/node/copilot-cli-locator.spec.js.map +1 -0
  48. package/lib/node/copilot-credential-store.d.ts +45 -0
  49. package/lib/node/copilot-credential-store.d.ts.map +1 -0
  50. package/lib/node/copilot-credential-store.js +96 -0
  51. package/lib/node/copilot-credential-store.js.map +1 -0
  52. package/lib/node/copilot-credential-store.spec.d.ts +2 -0
  53. package/lib/node/copilot-credential-store.spec.d.ts.map +1 -0
  54. package/lib/node/copilot-credential-store.spec.js +93 -0
  55. package/lib/node/copilot-credential-store.spec.js.map +1 -0
  56. package/lib/node/copilot-language-models-manager-impl.d.ts +20 -18
  57. package/lib/node/copilot-language-models-manager-impl.d.ts.map +1 -1
  58. package/lib/node/copilot-language-models-manager-impl.js +39 -67
  59. package/lib/node/copilot-language-models-manager-impl.js.map +1 -1
  60. package/lib/node/copilot-language-models-manager-impl.spec.d.ts +2 -0
  61. package/lib/node/copilot-language-models-manager-impl.spec.d.ts.map +1 -0
  62. package/lib/node/copilot-language-models-manager-impl.spec.js +119 -0
  63. package/lib/node/copilot-language-models-manager-impl.spec.js.map +1 -0
  64. package/lib/node/copilot-runtime-env.d.ts +20 -0
  65. package/lib/node/copilot-runtime-env.d.ts.map +1 -0
  66. package/lib/node/copilot-runtime-env.js +49 -0
  67. package/lib/node/copilot-runtime-env.js.map +1 -0
  68. package/lib/node/copilot-sdk-client-provider.d.ts +103 -0
  69. package/lib/node/copilot-sdk-client-provider.d.ts.map +1 -0
  70. package/lib/node/copilot-sdk-client-provider.js +247 -0
  71. package/lib/node/copilot-sdk-client-provider.js.map +1 -0
  72. package/lib/node/copilot-sdk-client-provider.spec.d.ts +2 -0
  73. package/lib/node/copilot-sdk-client-provider.spec.d.ts.map +1 -0
  74. package/lib/node/copilot-sdk-client-provider.spec.js +215 -0
  75. package/lib/node/copilot-sdk-client-provider.spec.js.map +1 -0
  76. package/lib/node/copilot-sdk-language-model.d.ts +85 -0
  77. package/lib/node/copilot-sdk-language-model.d.ts.map +1 -0
  78. package/lib/node/copilot-sdk-language-model.js +301 -0
  79. package/lib/node/copilot-sdk-language-model.js.map +1 -0
  80. package/lib/node/copilot-sdk-language-model.spec.d.ts +2 -0
  81. package/lib/node/copilot-sdk-language-model.spec.d.ts.map +1 -0
  82. package/lib/node/copilot-sdk-language-model.spec.js +302 -0
  83. package/lib/node/copilot-sdk-language-model.spec.js.map +1 -0
  84. package/lib/node/copilot-sdk-loader.d.ts +57 -0
  85. package/lib/node/copilot-sdk-loader.d.ts.map +1 -0
  86. package/lib/node/copilot-sdk-loader.js +133 -0
  87. package/lib/node/copilot-sdk-loader.js.map +1 -0
  88. package/lib/node/copilot-sdk-loader.spec.d.ts +2 -0
  89. package/lib/node/copilot-sdk-loader.spec.d.ts.map +1 -0
  90. package/lib/node/copilot-sdk-loader.spec.js +113 -0
  91. package/lib/node/copilot-sdk-loader.spec.js.map +1 -0
  92. package/lib/node/copilot-sdk-mappers.d.ts +49 -0
  93. package/lib/node/copilot-sdk-mappers.d.ts.map +1 -0
  94. package/lib/node/copilot-sdk-mappers.js +147 -0
  95. package/lib/node/copilot-sdk-mappers.js.map +1 -0
  96. package/lib/node/copilot-sdk-mappers.spec.d.ts +2 -0
  97. package/lib/node/copilot-sdk-mappers.spec.d.ts.map +1 -0
  98. package/lib/node/copilot-sdk-mappers.spec.js +133 -0
  99. package/lib/node/copilot-sdk-mappers.spec.js.map +1 -0
  100. package/lib/node/copilot-sdk-types.d.ts +198 -0
  101. package/lib/node/copilot-sdk-types.d.ts.map +1 -0
  102. package/lib/{common/copilot-oauth-config.js → node/copilot-sdk-types.js} +2 -13
  103. package/lib/node/copilot-sdk-types.js.map +1 -0
  104. package/lib/node/index.d.ts +9 -1
  105. package/lib/node/index.d.ts.map +1 -1
  106. package/lib/node/index.js +9 -1
  107. package/lib/node/index.js.map +1 -1
  108. package/package.json +4 -6
  109. package/src/browser/copilot-auth-dialog.tsx +12 -8
  110. package/src/browser/copilot-frontend-application-contribution.ts +62 -29
  111. package/src/common/copilot-auth-service.ts +28 -24
  112. package/src/common/copilot-language-models-manager.ts +3 -28
  113. package/src/common/copilot-preferences.ts +24 -5
  114. package/src/common/index.ts +0 -1
  115. package/src/node/copilot-auth-service-impl.spec.ts +122 -207
  116. package/src/node/copilot-auth-service-impl.ts +63 -218
  117. package/src/node/copilot-backend-module.ts +11 -2
  118. package/src/node/copilot-cli-auth-provider.spec.ts +315 -0
  119. package/src/node/copilot-cli-auth-provider.ts +444 -0
  120. package/src/node/copilot-cli-locator.spec.ts +386 -0
  121. package/src/node/copilot-cli-locator.ts +363 -0
  122. package/src/node/copilot-credential-store.spec.ts +106 -0
  123. package/src/node/copilot-credential-store.ts +99 -0
  124. package/src/node/copilot-language-models-manager-impl.spec.ts +137 -0
  125. package/src/node/copilot-language-models-manager-impl.ts +51 -85
  126. package/src/node/copilot-runtime-env.ts +46 -0
  127. package/src/node/copilot-sdk-client-provider.spec.ts +253 -0
  128. package/src/node/copilot-sdk-client-provider.ts +241 -0
  129. package/src/node/copilot-sdk-language-model.spec.ts +363 -0
  130. package/src/node/copilot-sdk-language-model.ts +329 -0
  131. package/src/node/copilot-sdk-loader.spec.ts +126 -0
  132. package/src/node/copilot-sdk-loader.ts +142 -0
  133. package/src/node/copilot-sdk-mappers.spec.ts +151 -0
  134. package/src/node/copilot-sdk-mappers.ts +161 -0
  135. package/src/node/copilot-sdk-types.ts +276 -0
  136. package/src/node/index.ts +9 -1
  137. package/lib/common/copilot-oauth-config.d.ts +0 -33
  138. package/lib/common/copilot-oauth-config.d.ts.map +0 -1
  139. package/lib/common/copilot-oauth-config.js.map +0 -1
  140. package/lib/node/copilot-language-model.d.ts +0 -34
  141. package/lib/node/copilot-language-model.d.ts.map +0 -1
  142. package/lib/node/copilot-language-model.js +0 -236
  143. package/lib/node/copilot-language-model.js.map +0 -1
  144. package/lib/node/copilot-language-model.spec.d.ts +0 -2
  145. package/lib/node/copilot-language-model.spec.d.ts.map +0 -1
  146. package/lib/node/copilot-language-model.spec.js +0 -89
  147. package/lib/node/copilot-language-model.spec.js.map +0 -1
  148. package/src/common/copilot-oauth-config.ts +0 -55
  149. package/src/node/copilot-language-model.spec.ts +0 -106
  150. package/src/node/copilot-language-model.ts +0 -273
@@ -0,0 +1,444 @@
1
+ // *****************************************************************************
2
+ // Copyright (C) 2026 EclipseSource GmbH and others.
3
+ //
4
+ // This program and the accompanying materials are made available under the
5
+ // terms of the Eclipse Public License v. 2.0 which is available at
6
+ // http://www.eclipse.org/legal/epl-2.0.
7
+ //
8
+ // This Source Code may also be made available under the following Secondary
9
+ // Licenses when the conditions for such availability set forth in the Eclipse
10
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
+ // with the GNU Classpath Exception which is available at
12
+ // https://www.gnu.org/software/classpath/license.html.
13
+ //
14
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
+ // *****************************************************************************
16
+
17
+ import { ChildProcess, spawn } from 'child_process';
18
+ import { promises as fs } from 'fs';
19
+ import * as os from 'os';
20
+ import { join } from 'path';
21
+ import { inject, injectable, named, preDestroy } from '@theia/core/shared/inversify';
22
+ import { Deferred } from '@theia/core/lib/common/promise-util';
23
+ import { ILogger, nls } from '@theia/core';
24
+ import { CopilotAuthState, DeviceCodeResponse } from '../common/copilot-auth-service';
25
+ import { CopilotCliLocator } from './copilot-cli-locator';
26
+ import { CopilotCredentialStore } from './copilot-credential-store';
27
+ import { CopilotRuntimeEnv } from './copilot-runtime-env';
28
+ import { CopilotSdkClientProvider } from './copilot-sdk-client-provider';
29
+
30
+ /**
31
+ * Time after which a login that never reports a code is given up on.
32
+ */
33
+ const LOGIN_CODE_TIMEOUT_MS = 30_000;
34
+
35
+ /**
36
+ * Shape of the GitHub tokens the CLI persists, used to recognize one in the files it wrote.
37
+ */
38
+ const TOKEN_PATTERN = /\bgh[a-z]_[A-Za-z0-9_]{16,}\b/;
39
+
40
+ /**
41
+ * Upper bound for the files inspected for the token, so that a stray large file is not read.
42
+ */
43
+ const MAX_INSPECTED_FILE_BYTES = 1024 * 1024;
44
+
45
+ /**
46
+ * Authentication against GitHub Copilot, performed by the official Copilot CLI on our behalf.
47
+ *
48
+ * Access to the Copilot features is granted per OAuth application and the built-in Theia OAuth app
49
+ * is not entitled for them, whereas the Copilot CLI is. This provider therefore does not run an
50
+ * OAuth flow of its own but drives `copilot login --device-code` and reports its progress, so that
51
+ * the familiar sign-in dialog can be used.
52
+ *
53
+ * The credentials end up owned by this application rather than by the CLI: the login is run against
54
+ * a private, temporary Copilot home with the system keychain disabled, so that the CLI writes its
55
+ * token there instead of into the user's keyring. The token is then moved into
56
+ * {@link CopilotCredentialStore} and the temporary home is removed. Signing out consequently only
57
+ * has to delete our own entry, and never touches credentials of the user's machine such as their
58
+ * keyring entries or their GitHub CLI sign-in.
59
+ */
60
+ @injectable()
61
+ export class CopilotCliAuthProvider {
62
+
63
+ @inject(CopilotSdkClientProvider)
64
+ protected readonly sdkClientProvider: CopilotSdkClientProvider;
65
+
66
+ @inject(CopilotCliLocator)
67
+ protected readonly cliLocator: CopilotCliLocator;
68
+
69
+ @inject(CopilotCredentialStore)
70
+ protected readonly credentialStore: CopilotCredentialStore;
71
+
72
+ @inject(ILogger) @named('ai-copilot:CopilotCliAuthProvider')
73
+ protected readonly logger: ILogger;
74
+
75
+ protected loginProcess: ChildProcess | undefined;
76
+ protected loginResult: Deferred<boolean> | undefined;
77
+ protected loginHome: string | undefined;
78
+ protected loginEnterpriseUrl: string | undefined;
79
+ protected loginAccountLabel: string | undefined;
80
+
81
+ /**
82
+ * Stops a sign-in that is still in progress when the connection this provider belongs to closes.
83
+ * Unbinding a container runs `@preDestroy` rather than `dispose`, matching the client provider.
84
+ * Without this, the `copilot login` child process and the temporary home holding its token would
85
+ * be left behind.
86
+ */
87
+ @preDestroy()
88
+ protected stop(): void {
89
+ this.cancelLogin().catch(error => this.logger.warn('Copilot: failed to cancel the sign-in on shutdown:', error));
90
+ }
91
+
92
+ /**
93
+ * Starts `copilot login --device-code` and resolves once it reported the code the user has to
94
+ * enter. The process keeps running and polls GitHub itself until {@link waitForLogin} is awaited.
95
+ */
96
+ async startLogin(enterpriseUrl?: string): Promise<DeviceCodeResponse> {
97
+ await this.cancelLogin();
98
+ this.loginAccountLabel = undefined;
99
+
100
+ const args = ['login', '--device-code'];
101
+ if (enterpriseUrl) {
102
+ args.push('--host', this.toHostUrl(enterpriseUrl));
103
+ }
104
+
105
+ // Resolved before anything is written, so that a missing CLI does not leave a directory behind.
106
+ const cli = await this.cliLocator.resolve();
107
+ const home = await this.createLoginHome();
108
+ const noopBrowser = await this.createNoopBrowser(home);
109
+ this.loginHome = home;
110
+ this.loginEnterpriseUrl = enterpriseUrl;
111
+
112
+ // The device code flow is requested explicitly so that the CLI reports a code for the dialog
113
+ // instead of opening a browser on the backend host, which is not where the user is sitting.
114
+ const child = spawn(cli, args, {
115
+ stdio: ['ignore', 'pipe', 'pipe'],
116
+ env: this.createLoginEnv(home, noopBrowser)
117
+ });
118
+ this.loginProcess = child;
119
+
120
+ const result = new Deferred<boolean>();
121
+ this.loginResult = result;
122
+ // The outcome may settle before anyone awaits it, e.g. when the authorization is denied while
123
+ // the dialog still shows the code. Observe it here so that such a rejection is never unhandled;
124
+ // `waitForLogin` still sees the outcome through its own await of the same promise.
125
+ result.promise.catch(() => { /* observed in waitForLogin */ });
126
+ const code = new Deferred<DeviceCodeResponse>();
127
+ let output = '';
128
+
129
+ const onOutput = (chunk: Buffer | string) => {
130
+ output += String(chunk);
131
+ const parsed = this.parseDeviceCode(output);
132
+ if (parsed) {
133
+ code.resolve(parsed);
134
+ }
135
+ this.loginAccountLabel = this.parseAccountLabel(output) ?? this.loginAccountLabel;
136
+ };
137
+ child.stdout?.on('data', onOutput);
138
+ child.stderr?.on('data', onOutput);
139
+
140
+ // A login that was given up on has no one waiting for its outcome anymore, and rejecting it
141
+ // would surface as an unhandled rejection. Only the login that is still the current one is
142
+ // reported to, because that is the one `waitForLogin` can be awaiting.
143
+ const rejectResult = (error: Error) => {
144
+ if (this.loginResult === result) {
145
+ result.reject(error);
146
+ }
147
+ };
148
+
149
+ child.on('error', error => {
150
+ code.reject(error);
151
+ rejectResult(error);
152
+ });
153
+ child.on('close', exitCode => {
154
+ if (this.loginProcess === child) {
155
+ this.loginProcess = undefined;
156
+ }
157
+ if (exitCode === 0) {
158
+ code.reject(new Error('The Copilot CLI finished before reporting a device code.'));
159
+ result.resolve(true);
160
+ } else {
161
+ const message = this.extractFailure(output) ?? `The Copilot CLI login exited with code ${exitCode}.`;
162
+ code.reject(new Error(message));
163
+ rejectResult(new Error(message));
164
+ }
165
+ });
166
+
167
+ const timeout = setTimeout(() => code.reject(new Error('Timed out waiting for the Copilot CLI to report a device code.')), LOGIN_CODE_TIMEOUT_MS);
168
+ try {
169
+ return await code.promise;
170
+ } catch (error) {
171
+ await this.cancelLogin();
172
+ throw error;
173
+ } finally {
174
+ clearTimeout(timeout);
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Waits for the login started by {@link startLogin} to complete.
180
+ * Resolves `false` when the authorization was denied or expired.
181
+ */
182
+ async waitForLogin(): Promise<boolean> {
183
+ const result = this.loginResult;
184
+ const home = this.loginHome;
185
+ if (!result || !home) {
186
+ throw new Error(nls.localize('theia/ai/copilot/noLoginInProgress', 'No Copilot CLI login is in progress. Please start the sign-in again.'));
187
+ }
188
+ try {
189
+ if (!await result.promise) {
190
+ return false;
191
+ }
192
+ await this.storeCredentials(home);
193
+ return true;
194
+ } finally {
195
+ this.loginResult = undefined;
196
+ this.loginHome = undefined;
197
+ // The token was moved into our own store, so the plain copy must not linger.
198
+ await this.removeLoginHome(home);
199
+ // The runtime caches the credentials it started with, so pick up the new ones.
200
+ await this.sdkClientProvider.reset();
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Moves the token the CLI just persisted into our own credential store.
206
+ */
207
+ protected async storeCredentials(home: string): Promise<void> {
208
+ const token = await this.findStoredToken(home);
209
+ if (!token) {
210
+ throw new Error(nls.localize('theia/ai/copilot/tokenNotPersisted',
211
+ 'The Copilot CLI reported a successful sign-in but did not persist a token where it was expected. '
212
+ + 'This can happen when the Copilot CLI changes how it stores credentials.'));
213
+ }
214
+ await this.credentialStore.set({
215
+ token,
216
+ accountLabel: this.loginAccountLabel,
217
+ enterpriseUrl: this.loginEnterpriseUrl
218
+ });
219
+ }
220
+
221
+ /**
222
+ * Terminates a login that is still in progress, if any.
223
+ *
224
+ * Resolves once the token the CLI may already have written has been removed again, so that a
225
+ * caller which cancels a sign-in can rely on nothing being left behind in plain text.
226
+ */
227
+ async cancelLogin(): Promise<void> {
228
+ // Settle a login that may be awaited in `waitForLogin`, so that closing the dialog while it is
229
+ // still polling does not leave that request pending for the rest of the session.
230
+ this.loginResult?.resolve(false);
231
+ this.loginResult = undefined;
232
+ // Killing an already exited process is a no-op, so the state does not have to be tracked.
233
+ this.loginProcess?.kill();
234
+ this.loginProcess = undefined;
235
+ const home = this.loginHome;
236
+ this.loginHome = undefined;
237
+ if (home) {
238
+ await this.removeLoginHome(home);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Reports whether this application holds Copilot credentials.
244
+ *
245
+ * Deliberately based on our own store rather than on what the Copilot CLI reports: the CLI also
246
+ * accepts a token from the environment or the sign-in of the GitHub CLI, and neither of those is
247
+ * a sign-in of this application, so neither may make it appear signed in.
248
+ */
249
+ async getAuthState(): Promise<CopilotAuthState> {
250
+ const credentials = await this.credentialStore.get();
251
+ if (!credentials) {
252
+ return { isAuthenticated: false };
253
+ }
254
+ return {
255
+ isAuthenticated: true,
256
+ accountLabel: credentials.accountLabel,
257
+ enterpriseUrl: credentials.enterpriseUrl
258
+ };
259
+ }
260
+
261
+ /**
262
+ * Discards the credentials of this application. Nothing outside of it is touched.
263
+ */
264
+ async signOut(): Promise<void> {
265
+ await this.cancelLogin();
266
+ await this.credentialStore.delete();
267
+ await this.sdkClientProvider.reset();
268
+ }
269
+
270
+ /**
271
+ * Creates the private Copilot home the login is run against.
272
+ */
273
+ protected async createLoginHome(): Promise<string> {
274
+ const home = await fs.mkdtemp(join(os.tmpdir(), 'theia-copilot-login-'));
275
+ // With the keychain disabled, the CLI only persists the token when it is allowed to write it
276
+ // plainly. It lands in this private directory and is removed again right after it was taken over.
277
+ await fs.writeFile(join(home, 'settings.json'), JSON.stringify({ storeTokenPlaintext: true }, undefined, 2), 'utf8');
278
+ return home;
279
+ }
280
+
281
+ /**
282
+ * Writes the opener the CLI is pointed at instead of a real browser, and returns its path.
283
+ *
284
+ * The CLI opens a browser whenever it believes one is available, even for the device code flow, and
285
+ * prefers the command in `BROWSER` over the opener of the platform. Pointing it at a script that
286
+ * does nothing is therefore the reliable way to keep the flow in the dialog, where the user can read
287
+ * and copy the code. Opening a browser would also be wrong whenever the backend does not run on the
288
+ * user's own machine.
289
+ */
290
+ protected async createNoopBrowser(home: string): Promise<string> {
291
+ if (process.platform === 'win32') {
292
+ const batch = join(home, 'no-browser.cmd');
293
+ await fs.writeFile(batch, '@exit /b 0\r\n', 'utf8');
294
+ return batch;
295
+ }
296
+ const shell = join(home, 'no-browser.sh');
297
+ await fs.writeFile(shell, '#!/bin/sh\nexit 0\n', { encoding: 'utf8', mode: 0o755 });
298
+ return shell;
299
+ }
300
+
301
+ /**
302
+ * Removes the private Copilot home, including the token the CLI wrote into it.
303
+ */
304
+ protected async removeLoginHome(home: string): Promise<void> {
305
+ try {
306
+ await fs.rm(home, { recursive: true, force: true });
307
+ } catch (error) {
308
+ this.logger.warn(`Copilot: failed to remove the temporary sign-in directory ${home}:`, error);
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Builds the environment for the login process.
314
+ *
315
+ * The CLI is pointed at a private home and its use of the system keychain is disabled, so that
316
+ * it persists the token where we can take it over instead of in the keyring of the user. Tokens
317
+ * from the environment are removed so that a sign-in always establishes fresh credentials rather
318
+ * than silently succeeding with something the user configured elsewhere.
319
+ */
320
+ protected createLoginEnv(home: string, noopBrowser: string): Record<string, string | undefined> {
321
+ return {
322
+ ...CopilotRuntimeEnv.withoutTokens(process.env),
323
+ COPILOT_HOME: home,
324
+ COPILOT_DISABLE_KEYTAR: '1',
325
+ // Keep the flow in the dialog, see createNoopBrowser. The display variables are dropped as
326
+ // well so that nothing can open a window even if the opener were ignored.
327
+ BROWSER: noopBrowser,
328
+ DISPLAY: undefined,
329
+ WAYLAND_DISPLAY: undefined
330
+ };
331
+ }
332
+
333
+ /**
334
+ * Searches the configuration the CLI wrote in its private home for the persisted token.
335
+ *
336
+ * The file and the field the CLI uses are not part of its public interface, so every JSON file it
337
+ * wrote is searched for a value shaped like a GitHub token rather than relying on a fixed layout.
338
+ */
339
+ protected async findStoredToken(home: string): Promise<string | undefined> {
340
+ for (const file of await this.listCandidateFiles(home)) {
341
+ try {
342
+ // Checked before reading, so that a stray large file is never held in memory.
343
+ if ((await fs.stat(file)).size > MAX_INSPECTED_FILE_BYTES) {
344
+ continue;
345
+ }
346
+ const token = this.findTokenInText(await fs.readFile(file, 'utf8'));
347
+ if (token) {
348
+ return token;
349
+ }
350
+ } catch (error) {
351
+ this.logger.warn(`Copilot: failed to inspect ${file} for the persisted token:`, error);
352
+ }
353
+ }
354
+ return undefined;
355
+ }
356
+
357
+ /**
358
+ * The files of the private home that are inspected for the token.
359
+ *
360
+ * The logs are skipped, and the configuration the CLI writes is not plain JSON but carries
361
+ * comments, so the files are searched as text rather than parsed.
362
+ */
363
+ protected async listCandidateFiles(home: string): Promise<string[]> {
364
+ try {
365
+ const entries = await fs.readdir(home, { withFileTypes: true });
366
+ return entries
367
+ .filter(entry => entry.isFile() && entry.name !== 'settings.json' && !entry.name.startsWith('no-browser.'))
368
+ .map(entry => join(home, entry.name));
369
+ } catch (error) {
370
+ this.logger.warn(`Copilot: failed to list ${home}:`, error);
371
+ return [];
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Searches text for a value shaped like a GitHub token.
377
+ *
378
+ * Only the files the CLI wrote into the private home of this sign-in are searched, so anything
379
+ * shaped like a token in them is the token that was just obtained.
380
+ */
381
+ protected findTokenInText(text: string): string | undefined {
382
+ return text.match(TOKEN_PATTERN)?.[0];
383
+ }
384
+
385
+ /**
386
+ * Extracts the login the CLI reported for the account that signed in, if it reported one.
387
+ */
388
+ protected parseAccountLabel(output: string): string | undefined {
389
+ return output.match(/Signed in successfully as\s+([^\s.]+)/)?.[1];
390
+ }
391
+
392
+ /**
393
+ * Extracts the verification URL and the user code from the output of the CLI.
394
+ * Returns `undefined` while the output does not contain both yet.
395
+ */
396
+ protected parseDeviceCode(output: string): DeviceCodeResponse | undefined {
397
+ const url = output.match(/https?:\/\/\S*\/login\/device\b/)?.[0];
398
+ const userCode = output.match(/\b([A-Z0-9]{4}-[A-Z0-9]{4})\b/)?.[1];
399
+ if (!url || !userCode) {
400
+ return undefined;
401
+ }
402
+ return {
403
+ verification_uri: url,
404
+ user_code: userCode
405
+ };
406
+ }
407
+
408
+ /**
409
+ * Describes why a login failed, based on what the CLI reported.
410
+ *
411
+ * A line that names the problem is preferred, and the tail of the output is used otherwise, since
412
+ * the wording of the CLI is not stable enough to rely on and a bare exit code is not diagnosable.
413
+ */
414
+ protected extractFailure(output: string): string | undefined {
415
+ const lines = output.split('\n').map(entry => entry.trim())
416
+ // The CLI reports a failure to copy the code to the clipboard even on a healthy login,
417
+ // which must not be mistaken for the reason a login failed.
418
+ .filter(entry => entry.length > 0 && !/clipboard/i.test(entry));
419
+ const reported = [...lines].reverse().find(entry => /error|denied|failed|unauthorized|policy/i.test(entry));
420
+ if (reported) {
421
+ return reported;
422
+ }
423
+ const tail = lines.slice(-3).join(' ');
424
+ return tail.length > 0 ? `The Copilot CLI login failed: ${tail}` : undefined;
425
+ }
426
+
427
+ /**
428
+ * Turns the configured GitHub Enterprise deployment into the URL the CLI is pointed at.
429
+ *
430
+ * A bare domain is the expected form and gets a scheme. Plain HTTP is upgraded rather than passed
431
+ * on: the sign-in carries credentials, and a host that only matched "http" at the start of its
432
+ * name, such as `httpbin.example.com`, must not be mistaken for a URL that already has a scheme.
433
+ */
434
+ protected toHostUrl(enterpriseUrl: string): string {
435
+ const url = enterpriseUrl.trim();
436
+ if (/^https:\/\//i.test(url)) {
437
+ return url;
438
+ }
439
+ if (/^http:\/\//i.test(url)) {
440
+ return url.replace(/^http:\/\//i, 'https://');
441
+ }
442
+ return `https://${url}`;
443
+ }
444
+ }