@theia/ai-copilot 1.76.0-next.4 → 1.76.0-next.42

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 +87 -14
  2. package/lib/browser/copilot-auth-dialog.d.ts.map +1 -1
  3. package/lib/browser/copilot-auth-dialog.js +19 -11
  4. package/lib/browser/copilot-auth-dialog.js.map +1 -1
  5. package/lib/browser/copilot-frontend-application-contribution.d.ts +21 -1
  6. package/lib/browser/copilot-frontend-application-contribution.d.ts.map +1 -1
  7. package/lib/browser/copilot-frontend-application-contribution.js +129 -26
  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 +6 -22
  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 +44 -20
  57. package/lib/node/copilot-language-models-manager-impl.d.ts.map +1 -1
  58. package/lib/node/copilot-language-models-manager-impl.js +112 -65
  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 +162 -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 +315 -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 +54 -0
  93. package/lib/node/copilot-sdk-mappers.d.ts.map +1 -0
  94. package/lib/node/copilot-sdk-mappers.js +158 -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 +168 -0
  99. package/lib/node/copilot-sdk-mappers.spec.js.map +1 -0
  100. package/lib/node/copilot-sdk-types.d.ts +208 -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 +20 -16
  110. package/src/browser/copilot-frontend-application-contribution.ts +144 -31
  111. package/src/common/copilot-auth-service.ts +28 -24
  112. package/src/common/copilot-language-models-manager.ts +6 -29
  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 +188 -0
  125. package/src/node/copilot-language-models-manager-impl.ts +131 -84
  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 +377 -0
  130. package/src/node/copilot-sdk-language-model.ts +330 -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 +190 -0
  134. package/src/node/copilot-sdk-mappers.ts +172 -0
  135. package/src/node/copilot-sdk-types.ts +290 -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,253 @@
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 { expect } from 'chai';
18
+ import { promises as fs } from 'fs';
19
+ import * as os from 'os';
20
+ import { join } from 'path';
21
+ import { MockLogger } from '@theia/core/lib/common/test/mock-logger';
22
+ import { FileUri } from '@theia/core/lib/common/file-uri';
23
+ import { CopilotCredentials } from './copilot-credential-store';
24
+ import { CopilotSdkClientProvider } from './copilot-sdk-client-provider';
25
+ import type { CopilotClient, CopilotClientOptions } from './copilot-sdk-types';
26
+
27
+ interface SdkStub {
28
+ api: {
29
+ CopilotClient: new (options?: CopilotClientOptions) => CopilotClient,
30
+ RuntimeConnection: { forStdio: (options: { path: string }) => unknown }
31
+ };
32
+ started: string[];
33
+ stopped: string[];
34
+ }
35
+
36
+ /** The SDK as the provider uses it: a client constructor and the stdio connection factory. */
37
+ function sdkStub(): SdkStub {
38
+ const started: string[] = [];
39
+ const stopped: string[] = [];
40
+ class StubClient {
41
+ constructor(readonly options?: CopilotClientOptions) { }
42
+ async start(): Promise<void> {
43
+ started.push(String(this.options?.gitHubToken));
44
+ }
45
+ async stop(): Promise<Error[]> {
46
+ stopped.push(String(this.options?.gitHubToken));
47
+ return [];
48
+ }
49
+ async listModels(): Promise<[]> {
50
+ return [];
51
+ }
52
+ }
53
+ return {
54
+ api: {
55
+ CopilotClient: StubClient as unknown as new (options?: CopilotClientOptions) => CopilotClient,
56
+ RuntimeConnection: { forStdio: (options: { path: string }) => ({ kind: 'stdio', ...options }) }
57
+ },
58
+ started,
59
+ stopped
60
+ };
61
+ }
62
+
63
+ class TestableCopilotSdkClientProvider extends CopilotSdkClientProvider {
64
+
65
+ credentials: CopilotCredentials | undefined = { token: 'gho_first' };
66
+
67
+ constructor(sdk: SdkStub['api'], configDirectory: string, cli = join('/opt', 'copilot', 'copilot')) {
68
+ super();
69
+ Object.assign(this, {
70
+ logger: new MockLogger(),
71
+ credentialStore: { get: async () => this.credentials },
72
+ cliLocator: { resolve: async () => cli },
73
+ sdkLoader: { load: async () => sdk },
74
+ envVariablesServer: { getConfigDirUri: async () => FileUri.create(configDirectory).toString() }
75
+ });
76
+ }
77
+
78
+ callCreateRuntimeEnv(credentials: CopilotCredentials): Record<string, string | undefined> {
79
+ return this.createRuntimeEnv(credentials);
80
+ }
81
+
82
+ callEnrichEntitlementError(error: unknown): unknown {
83
+ return this.enrichEntitlementError(error);
84
+ }
85
+
86
+ clientOptions(client: CopilotClient): CopilotClientOptions | undefined {
87
+ return (client as unknown as { options?: CopilotClientOptions }).options;
88
+ }
89
+ }
90
+
91
+ describe('CopilotSdkClientProvider - client options', () => {
92
+
93
+ let configDirectory: string;
94
+ let sdk: ReturnType<typeof sdkStub>;
95
+
96
+ beforeEach(async () => {
97
+ configDirectory = await fs.mkdtemp(join(os.tmpdir(), 'theia-copilot-config-'));
98
+ sdk = sdkStub();
99
+ });
100
+
101
+ afterEach(async () => {
102
+ await fs.rm(configDirectory, { recursive: true, force: true });
103
+ });
104
+
105
+ it('should hand the located CLI and the token of this application to the runtime', async () => {
106
+ const provider = new TestableCopilotSdkClientProvider(sdk.api, configDirectory);
107
+ const options = provider.clientOptions(await provider.getClient());
108
+ expect(options?.connection).to.deep.equal({ kind: 'stdio', path: join('/opt', 'copilot', 'copilot') });
109
+ expect(options?.gitHubToken).to.equal('gho_first');
110
+ // Nothing the runtime finds on the host may make it appear signed in.
111
+ expect(options?.useLoggedInUser).to.be.false;
112
+ });
113
+
114
+ it('should keep the runtime out of the ambient behaviour of the CLI', async () => {
115
+ const provider = new TestableCopilotSdkClientProvider(sdk.api, configDirectory);
116
+ const options = provider.clientOptions(await provider.getClient());
117
+ expect(options?.mode).to.equal('empty');
118
+ });
119
+
120
+ it('should point the runtime at a Copilot home of the application and create it', async () => {
121
+ const provider = new TestableCopilotSdkClientProvider(sdk.api, configDirectory);
122
+ const options = provider.clientOptions(await provider.getClient());
123
+ const home = join(configDirectory, 'copilot');
124
+ // Compared without case, because the URI of the configuration directory lowercases the drive
125
+ // letter on Windows, which addresses the same location.
126
+ expect(options?.baseDirectory?.toLowerCase()).to.equal(home.toLowerCase());
127
+ expect((await fs.stat(home)).isDirectory()).to.be.true;
128
+ });
129
+ });
130
+
131
+ describe('CopilotSdkClientProvider - runtime environment', () => {
132
+
133
+ const provider = new TestableCopilotSdkClientProvider(sdkStub().api, os.tmpdir());
134
+
135
+ it('should remove tokens of the environment, which are not a sign-in of this application', () => {
136
+ const previous = { ...process.env };
137
+ try {
138
+ process.env.GITHUB_TOKEN = 'gho_environment';
139
+ process.env.GH_TOKEN = 'gho_environment';
140
+ process.env.COPILOT_GITHUB_TOKEN = 'gho_environment';
141
+ const env = provider.callCreateRuntimeEnv({ token: 'gho_ours' });
142
+ expect(env.GITHUB_TOKEN).to.be.undefined;
143
+ expect(env.GH_TOKEN).to.be.undefined;
144
+ expect(env.COPILOT_GITHUB_TOKEN).to.be.undefined;
145
+ } finally {
146
+ process.env = previous;
147
+ }
148
+ });
149
+
150
+ it('should remove a token variable whatever its case, since Windows ignores it', () => {
151
+ const previous = { ...process.env };
152
+ try {
153
+ process.env.Gh_Token = 'gho_environment';
154
+ const env = provider.callCreateRuntimeEnv({ token: 'gho_ours' });
155
+ expect(Object.keys(env).some(name => name.toLowerCase() === 'gh_token')).to.be.false;
156
+ } finally {
157
+ process.env = previous;
158
+ }
159
+ });
160
+
161
+ it('should point the runtime at the deployment that was signed in to', () => {
162
+ const env = provider.callCreateRuntimeEnv({ token: 'gho_ours', enterpriseUrl: 'company.ghe.com' });
163
+ expect(env.COPILOT_GH_HOST).to.equal('company.ghe.com');
164
+ });
165
+
166
+ it('should leave the host alone for a sign-in against GitHub.com', () => {
167
+ expect(provider.callCreateRuntimeEnv({ token: 'gho_ours' })).to.not.have.property('COPILOT_GH_HOST');
168
+ });
169
+ });
170
+
171
+ describe('CopilotSdkClientProvider - lifecycle', () => {
172
+
173
+ let configDirectory: string;
174
+ let sdk: ReturnType<typeof sdkStub>;
175
+ let provider: TestableCopilotSdkClientProvider;
176
+
177
+ beforeEach(async () => {
178
+ configDirectory = await fs.mkdtemp(join(os.tmpdir(), 'theia-copilot-config-'));
179
+ sdk = sdkStub();
180
+ provider = new TestableCopilotSdkClientProvider(sdk.api, configDirectory);
181
+ });
182
+
183
+ afterEach(async () => {
184
+ await fs.rm(configDirectory, { recursive: true, force: true });
185
+ });
186
+
187
+ it('should reject when the application is not signed in', async () => {
188
+ provider.credentials = undefined;
189
+ try {
190
+ await provider.getClient();
191
+ expect.fail('should have rejected');
192
+ } catch (error) {
193
+ expect(String(error)).to.contain('sign in');
194
+ }
195
+ });
196
+
197
+ it('should start one CLI and share it, also for concurrent callers', async () => {
198
+ const [first, second] = await Promise.all([provider.getClient(), provider.getClient()]);
199
+ expect(first).to.equal(second);
200
+ expect(await provider.getClient()).to.equal(first);
201
+ expect(sdk.started).to.deep.equal(['gho_first']);
202
+ });
203
+
204
+ it('should replace the client when the credentials changed, stopping the previous one', async () => {
205
+ const first = await provider.getClient();
206
+ provider.credentials = { token: 'gho_second' };
207
+ const second = await provider.getClient();
208
+ expect(second).to.not.equal(first);
209
+ expect(sdk.started).to.deep.equal(['gho_first', 'gho_second']);
210
+ expect(sdk.stopped).to.deep.equal(['gho_first']);
211
+ });
212
+
213
+ it('should stop the CLI on reset and start a new one afterwards', async () => {
214
+ await provider.getClient();
215
+ await provider.reset();
216
+ expect(sdk.stopped).to.deep.equal(['gho_first']);
217
+ await provider.getClient();
218
+ expect(sdk.started).to.deep.equal(['gho_first', 'gho_first']);
219
+ });
220
+
221
+ it('should not cache a client whose runtime failed to start', async () => {
222
+ const failing = sdkStub();
223
+ failing.api.CopilotClient = class {
224
+ async start(): Promise<void> {
225
+ throw new Error('runtime did not come up');
226
+ }
227
+ } as unknown as new () => CopilotClient;
228
+ const other = new TestableCopilotSdkClientProvider(failing.api, configDirectory);
229
+ await other.getClient().catch(() => { /* expected */ });
230
+ // A cached rejection would keep replaying instead of trying again.
231
+ await other.getClient().catch(error => expect(String(error)).to.contain('did not come up'));
232
+ });
233
+ });
234
+
235
+ describe('CopilotSdkClientProvider - entitlement errors', () => {
236
+
237
+ const provider = new TestableCopilotSdkClientProvider(sdkStub().api, os.tmpdir());
238
+
239
+ it('should explain what an authorization failure of the runtime can mean', () => {
240
+ const enriched = provider.callEnrichEntitlementError(new Error('user is not authorized to use this Copilot feature'));
241
+ expect(String(enriched)).to.contain('subscription');
242
+ expect(String(enriched)).to.contain('not authorized to use this Copilot feature');
243
+ });
244
+
245
+ it('should explain a policy rejection the same way', () => {
246
+ expect(String(provider.callEnrichEntitlementError(new Error('Access denied by policy settings')))).to.contain('administrator');
247
+ });
248
+
249
+ it('should pass an unrelated failure through unchanged', () => {
250
+ const error = new Error('socket hang up');
251
+ expect(provider.callEnrichEntitlementError(error)).to.equal(error);
252
+ });
253
+ });
@@ -0,0 +1,241 @@
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 { promises as fs } from 'fs';
18
+ import { join } from 'path';
19
+ import { inject, injectable, named, preDestroy } from '@theia/core/shared/inversify';
20
+ import { ILogger, nls, URI } from '@theia/core';
21
+ import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
22
+ import { FileUri } from '@theia/core/lib/common/file-uri';
23
+ import type { CopilotClient, CopilotClientOptions } from './copilot-sdk-types';
24
+ import { CopilotCredentials, CopilotCredentialStore } from './copilot-credential-store';
25
+ import { CopilotCliLocator } from './copilot-cli-locator';
26
+ import { CopilotRuntimeEnv } from './copilot-runtime-env';
27
+ import { CopilotSdkApi, CopilotSdkLoader } from './copilot-sdk-loader';
28
+ import { selectSdkModelIds } from './copilot-sdk-mappers';
29
+
30
+ /**
31
+ * Manages the lifecycle of a {@link CopilotClient}, which spawns and talks to the
32
+ * official Copilot CLI over JSON-RPC.
33
+ *
34
+ * The runtime is given the token this application holds, and nothing else: credentials the CLI could
35
+ * otherwise pick up on its own, from the environment or from the sign-in of the GitHub CLI, are not a
36
+ * sign-in of this application and are deliberately kept out of reach. The token is established by
37
+ * {@link CopilotCliAuthProvider} and kept in {@link CopilotCredentialStore}.
38
+ *
39
+ * A single client is started lazily and shared for the lifetime of the (connection-scoped) backend
40
+ * container. It is recreated when the host configuration changes.
41
+ *
42
+ * Note: this provider is bound in the per-connection container, so each frontend connection runs
43
+ * its own CLI process, authenticated with the credentials of the backend host. This is not suitable
44
+ * for multi-user backend deployments, where every connected frontend would share a single identity.
45
+ */
46
+ @injectable()
47
+ export class CopilotSdkClientProvider {
48
+
49
+ @inject(CopilotCredentialStore)
50
+ protected readonly credentialStore: CopilotCredentialStore;
51
+
52
+ @inject(CopilotCliLocator)
53
+ protected readonly cliLocator: CopilotCliLocator;
54
+
55
+ @inject(CopilotSdkLoader)
56
+ protected readonly sdkLoader: CopilotSdkLoader;
57
+
58
+ @inject(EnvVariablesServer)
59
+ protected readonly envVariablesServer: EnvVariablesServer;
60
+
61
+ @inject(ILogger) @named('ai-copilot:CopilotSdkClientProvider')
62
+ protected readonly logger: ILogger;
63
+
64
+ protected clientPromise: Promise<CopilotClient> | undefined;
65
+ protected clientConfigKey: string | undefined;
66
+
67
+ /**
68
+ * Returns a started {@link CopilotClient}, creating (or recreating, if the
69
+ * configuration changed) one on demand.
70
+ */
71
+ async getClient(): Promise<CopilotClient> {
72
+ const credentials = await this.credentialStore.get();
73
+ if (!credentials) {
74
+ throw new Error(nls.localize('theia/ai/copilot/notSignedInSignInFirst', 'Not signed in to GitHub Copilot. Please sign in first.'));
75
+ }
76
+ const configKey = this.getConfigKey(credentials);
77
+ if (this.clientPromise && this.clientConfigKey === configKey) {
78
+ return this.clientPromise;
79
+ }
80
+ // First use or changed credentials: (re)create the client. Capture the
81
+ // previous client and assign synchronously so concurrent callers share
82
+ // the same promise instead of spawning multiple CLI processes.
83
+ const previous = this.clientPromise;
84
+ this.clientConfigKey = configKey;
85
+ this.clientPromise = this.recreate(configKey, credentials, previous);
86
+ return this.clientPromise;
87
+ }
88
+
89
+ /**
90
+ * Lists the model IDs available to the authenticated user via the Copilot CLI.
91
+ * Because the CLI runs under an entitled identity, this returns the full current model lineup
92
+ * rather than the baseline set that the direct REST API exposes to an unentitled OAuth app.
93
+ */
94
+ async listModelIds(): Promise<string[]> {
95
+ const client = await this.getClient();
96
+ try {
97
+ const models = await client.listModels();
98
+ return selectSdkModelIds(models);
99
+ } catch (error) {
100
+ throw this.enrichEntitlementError(error);
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Replaces the bare authorization failure of the Copilot runtime with an explanation of the
106
+ * possible causes, because the runtime only reports that the feature is not authorized.
107
+ */
108
+ protected enrichEntitlementError(error: unknown): unknown {
109
+ const message = error instanceof Error ? error.message : String(error);
110
+ if (!message.includes('not authorized to use this Copilot feature') && !message.includes('Access denied by policy settings')) {
111
+ return error;
112
+ }
113
+ return new Error(nls.localize('theia/ai/copilot/notAuthorized',
114
+ 'GitHub Copilot rejected the request as not authorized for this account. Either the account has no Copilot subscription, or '
115
+ + 'access has to be enabled by an administrator through an organization or enterprise policy. Signing out and in again also '
116
+ + 'renews credentials that were revoked. GitHub reports requests sent to an API host that does not match the subscription the '
117
+ + 'same way, so as a last resort the host can be set explicitly with the `COPILOT_API_URL` environment variable of the backend. '
118
+ + 'Reported by the Copilot runtime: {0}', message));
119
+ }
120
+
121
+ protected getConfigKey(credentials: CopilotCredentials): string {
122
+ return `${credentials.enterpriseUrl ?? ''}|${credentials.token}`;
123
+ }
124
+
125
+ protected async recreate(configKey: string, credentials: CopilotCredentials, previous: Promise<CopilotClient> | undefined): Promise<CopilotClient> {
126
+ if (previous) {
127
+ try {
128
+ const previousClient = await previous;
129
+ await previousClient.stop();
130
+ } catch (error) {
131
+ this.logger.warn('Copilot SDK: failed to stop previous client:', error);
132
+ }
133
+ }
134
+ const sdk = await this.sdkLoader.load();
135
+ const client = new sdk.CopilotClient(this.createClientOptions(sdk, credentials, await this.cliLocator.resolve(), await this.getCopilotHome()));
136
+ try {
137
+ await client.start();
138
+ } catch (error) {
139
+ // Don't cache a failed start, otherwise every later call replays the rejection.
140
+ if (this.clientConfigKey === configKey) {
141
+ this.clientPromise = undefined;
142
+ this.clientConfigKey = undefined;
143
+ }
144
+ throw error;
145
+ }
146
+ return client;
147
+ }
148
+
149
+ /**
150
+ * Builds the options of the {@link CopilotClient}.
151
+ *
152
+ * The token of this application is passed explicitly and the resolution of a logged-in user is
153
+ * switched off, so that the runtime cannot fall back to credentials this application does not own.
154
+ *
155
+ * The CLI is passed explicitly as well, see {@link CopilotCliLocator}: the SDK would otherwise look
156
+ * for the JavaScript entry point of a platform package installed next to itself and spawn it with
157
+ * `process.execPath`, which is the Electron binary rather than Node.js in an Electron application.
158
+ *
159
+ * The runtime is configured in `empty` mode rather than in the `copilot-cli` mode the SDK defaults
160
+ * to. That mode brings the ambient behaviour of the CLI along, which the SDK documents as unsuitable
161
+ * for an application serving requests on a backend: instructions and skills found on the host,
162
+ * session and memory stores, host git operations and plugins. Theia drives the conversation itself
163
+ * and declares the tools of each request, so none of that applies, and `empty` mode additionally
164
+ * keeps the runtime away from the system keychain. Its two requirements are met here, a persistence
165
+ * location ({@link getCopilotHome}) and an explicit tool list per session.
166
+ */
167
+ protected createClientOptions(sdk: CopilotSdkApi, credentials: CopilotCredentials, cliPath: string, baseDirectory: string): CopilotClientOptions {
168
+ return {
169
+ connection: sdk.RuntimeConnection.forStdio({ path: cliPath }),
170
+ mode: 'empty',
171
+ baseDirectory,
172
+ gitHubToken: credentials.token,
173
+ useLoggedInUser: false,
174
+ logLevel: 'error',
175
+ env: this.createRuntimeEnv(credentials)
176
+ };
177
+ }
178
+
179
+ /**
180
+ * The Copilot home the runtime is pointed at, below the configuration directory of Theia.
181
+ *
182
+ * Requests are served in sessions that the runtime persists in its home, and the default home is
183
+ * the one the user's own Copilot CLI uses. Prompts sent from Theia would end up listed among the
184
+ * conversations the user started themselves, so this application keeps its own.
185
+ */
186
+ protected async getCopilotHome(): Promise<string> {
187
+ const configDirectory = FileUri.fsPath(new URI(await this.envVariablesServer.getConfigDirUri()));
188
+ const home = join(configDirectory, 'copilot');
189
+ await fs.mkdir(home, { recursive: true });
190
+ return home;
191
+ }
192
+
193
+ /**
194
+ * Returns the environment for the runtime process.
195
+ *
196
+ * Tokens from the environment are removed: the runtime accepts them even when a token is passed
197
+ * explicitly, and they are not a sign-in of this application. The GitHub host is taken from the
198
+ * credentials, so that the runtime always talks to the deployment that was signed in to.
199
+ *
200
+ * The Copilot API endpoint is deliberately not set: the runtime resolves the one belonging to the
201
+ * subscription from the token, including for Business and Enterprise seats. The environment of the
202
+ * backend is inherited as-is, so an operator can still override it with `COPILOT_API_URL` should
203
+ * that resolution ever fail for a deployment.
204
+ */
205
+ protected createRuntimeEnv(credentials: CopilotCredentials): Record<string, string | undefined> {
206
+ return {
207
+ ...CopilotRuntimeEnv.withoutTokens(process.env),
208
+ ...(credentials.enterpriseUrl ? { COPILOT_GH_HOST: credentials.enterpriseUrl } : {})
209
+ };
210
+ }
211
+
212
+ /**
213
+ * Stops and clears the current client. Safe to call when no client exists.
214
+ */
215
+ async reset(): Promise<void> {
216
+ const previous = this.clientPromise;
217
+ this.clientPromise = undefined;
218
+ this.clientConfigKey = undefined;
219
+ if (previous) {
220
+ try {
221
+ const client = await previous;
222
+ await client.stop();
223
+ } catch (error) {
224
+ this.logger.warn('Copilot SDK: failed to stop client during reset:', error);
225
+ }
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Stops the CLI when the container this provider lives in goes away, which happens when the
231
+ * frontend connection it belongs to is closed.
232
+ *
233
+ * A closing connection unbinds its container, and unbinding runs `@preDestroy` rather than
234
+ * `dispose`. Without this hook the CLI of every closed connection would keep running for the rest
235
+ * of the lifetime of the backend.
236
+ */
237
+ @preDestroy()
238
+ protected async stop(): Promise<void> {
239
+ await this.reset();
240
+ }
241
+ }