@microsoft/copilot-sdk 0.0.0-stage → 2.0.0-preview.0
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.
- package/README.md +2531 -2
- package/dist/canvas.d.ts +135 -0
- package/dist/canvas.js +51 -0
- package/dist/cjs/canvas.js +77 -0
- package/dist/cjs/cliVersion.js +31 -0
- package/dist/cjs/client.js +3941 -0
- package/dist/cjs/copilotRequestHandler.js +815 -0
- package/dist/cjs/decisions.js +139 -0
- package/dist/cjs/entra.js +83 -0
- package/dist/cjs/extension.js +79 -0
- package/dist/cjs/ffiRuntimeHost.js +400 -0
- package/dist/cjs/generated/lifecycle-diagnostics.js +16 -0
- package/dist/cjs/generated/rpc.js +5883 -0
- package/dist/cjs/generated/session-events.js +16 -0
- package/dist/cjs/host.js +83 -0
- package/dist/cjs/index.js +100 -0
- package/dist/cjs/installationConfirmation.js +98 -0
- package/dist/cjs/jsonrpcTypes.js +41 -0
- package/dist/cjs/localModelJson.js +103 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/providerConfiguration.js +39 -0
- package/dist/cjs/rpcCancellation.js +49 -0
- package/dist/cjs/runtimeArtifacts.js +255 -0
- package/dist/cjs/schema.js +40 -0
- package/dist/cjs/sdkProtocolVersion.js +33 -0
- package/dist/cjs/session.js +2764 -0
- package/dist/cjs/sessionFsProvider.js +283 -0
- package/dist/cjs/taskAnalyticsJson.js +47 -0
- package/dist/cjs/telemetry.js +35 -0
- package/dist/cjs/toolSet.js +107 -0
- package/dist/cjs/types.js +204 -0
- package/dist/cjs/workflow.js +278 -0
- package/dist/cliVersion.d.ts +2 -0
- package/dist/cliVersion.js +6 -0
- package/dist/client.d.ts +576 -0
- package/dist/client.js +3924 -0
- package/dist/copilotRequestHandler.d.ts +91 -0
- package/dist/copilotRequestHandler.js +787 -0
- package/dist/decisions.d.ts +65 -0
- package/dist/decisions.js +113 -0
- package/dist/entra.d.ts +3 -0
- package/dist/entra.js +59 -0
- package/dist/extension.d.ts +69 -0
- package/dist/extension.js +59 -0
- package/dist/ffiRuntimeHost.d.ts +44 -0
- package/dist/ffiRuntimeHost.js +366 -0
- package/dist/generated/lifecycle-diagnostics.d.ts +232 -0
- package/dist/generated/lifecycle-diagnostics.js +0 -0
- package/dist/generated/rpc.d.ts +47706 -0
- package/dist/generated/rpc.js +5854 -0
- package/dist/generated/session-events.d.ts +17349 -0
- package/dist/generated/session-events.js +0 -0
- package/dist/host.d.ts +143 -0
- package/dist/host.js +59 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +74 -0
- package/dist/installationConfirmation.d.ts +19 -0
- package/dist/installationConfirmation.js +74 -0
- package/dist/jsonrpcTypes.d.ts +16 -0
- package/dist/jsonrpcTypes.js +17 -0
- package/dist/localModelJson.d.ts +1 -0
- package/dist/localModelJson.js +69 -0
- package/dist/providerConfiguration.d.ts +3 -0
- package/dist/providerConfiguration.js +15 -0
- package/dist/rpcCancellation.d.ts +3 -0
- package/dist/rpcCancellation.js +25 -0
- package/dist/runtimeArtifacts.d.ts +18 -0
- package/dist/runtimeArtifacts.js +233 -0
- package/dist/schema.d.ts +4 -0
- package/dist/schema.js +14 -0
- package/dist/sdkProtocolVersion.d.ts +10 -0
- package/dist/sdkProtocolVersion.js +8 -0
- package/dist/session.d.ts +524 -0
- package/dist/session.js +2751 -0
- package/dist/sessionFsProvider.d.ts +130 -0
- package/dist/sessionFsProvider.js +257 -0
- package/dist/taskAnalyticsJson.d.ts +8 -0
- package/dist/taskAnalyticsJson.js +12 -0
- package/dist/telemetry.d.ts +14 -0
- package/dist/telemetry.js +11 -0
- package/dist/toolSet.d.ts +75 -0
- package/dist/toolSet.js +82 -0
- package/dist/types.d.ts +3864 -0
- package/dist/types.js +169 -0
- package/dist/workflow.d.ts +413 -0
- package/dist/workflow.js +248 -0
- package/docs/agent-author.md +372 -0
- package/docs/examples.md +747 -0
- package/docs/extensions.md +121 -0
- package/docs/workflows.md +303 -0
- package/package.json +135 -5
package/dist/client.js
ADDED
|
@@ -0,0 +1,3924 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { accessSync, constants, existsSync, statSync } from "node:fs";
|
|
5
|
+
import { isIPv6, Socket } from "node:net";
|
|
6
|
+
import { dirname, isAbsolute, join, resolve, win32 } from "node:path";
|
|
7
|
+
import {
|
|
8
|
+
CancellationTokenSource,
|
|
9
|
+
createMessageConnection as createRpcMessageConnection,
|
|
10
|
+
ErrorCodes,
|
|
11
|
+
Message,
|
|
12
|
+
ResponseError,
|
|
13
|
+
StreamMessageReader,
|
|
14
|
+
StreamMessageWriter
|
|
15
|
+
} from "vscode-jsonrpc/node";
|
|
16
|
+
import {
|
|
17
|
+
createServerRpc,
|
|
18
|
+
createInternalServerRpc,
|
|
19
|
+
registerClientGlobalApiHandlers,
|
|
20
|
+
registerClientSessionApiHandlers
|
|
21
|
+
} from "./generated/rpc.js";
|
|
22
|
+
import { CopilotDecisions } from "./decisions.js";
|
|
23
|
+
import { getSdkProtocolVersion } from "./sdkProtocolVersion.js";
|
|
24
|
+
import { CopilotSession } from "./session.js";
|
|
25
|
+
import {
|
|
26
|
+
AhpHost
|
|
27
|
+
} from "./host.js";
|
|
28
|
+
import { ensureRuntimeBundle } from "./runtimeArtifacts.js";
|
|
29
|
+
import { createLocalModelJsonCodec } from "./localModelJson.js";
|
|
30
|
+
import { COPILOT_CLI_VERSION } from "./cliVersion.js";
|
|
31
|
+
import { createSessionFsAdapter } from "./sessionFsProvider.js";
|
|
32
|
+
import { createCopilotRequestAdapter } from "./copilotRequestHandler.js";
|
|
33
|
+
import {
|
|
34
|
+
createInstallationConfirmationAdapter
|
|
35
|
+
} from "./installationConfirmation.js";
|
|
36
|
+
import { registerEntraTokenProvider } from "./entra.js";
|
|
37
|
+
import { getTraceContext } from "./telemetry.js";
|
|
38
|
+
import { toJsonSchema } from "./schema.js";
|
|
39
|
+
import { ToolSet } from "./toolSet.js";
|
|
40
|
+
import { defaultJoinSessionPermissionHandler } from "./types.js";
|
|
41
|
+
import { getWorkflowRegistration } from "./workflow.js";
|
|
42
|
+
const MIN_PROTOCOL_VERSION = 3;
|
|
43
|
+
const RUNTIME_SHUTDOWN_TIMEOUT_MS = 1e4;
|
|
44
|
+
const CLOUD_SESSION_CLEANUP_TIMEOUT_MS = 1e4;
|
|
45
|
+
const AUTO_MODE_RECOVERY_CLEANUP_TIMEOUT_MS = 1e4;
|
|
46
|
+
function sessionIdsOverlap(left, right) {
|
|
47
|
+
if (left === right) return true;
|
|
48
|
+
if (!isUuidSessionId(left) || !isUuidSessionId(right)) return false;
|
|
49
|
+
const normalizedLeft = left.toLowerCase();
|
|
50
|
+
const normalizedRight = right.toLowerCase();
|
|
51
|
+
return normalizedLeft.startsWith(normalizedRight) || normalizedRight.startsWith(normalizedLeft);
|
|
52
|
+
}
|
|
53
|
+
function isAbbreviatedUuidPrefix(sessionId) {
|
|
54
|
+
return /^[0-9a-f]{7}[0-9a-f-]{0,28}$/i.test(sessionId);
|
|
55
|
+
}
|
|
56
|
+
function isUuidSessionId(sessionId) {
|
|
57
|
+
return isAbbreviatedUuidPrefix(sessionId) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId);
|
|
58
|
+
}
|
|
59
|
+
const messageEncodeErrors = /* @__PURE__ */ new WeakSet();
|
|
60
|
+
function jsonMessageEncoder(codec) {
|
|
61
|
+
return {
|
|
62
|
+
name: "application/json",
|
|
63
|
+
encode: async (msg, options) => {
|
|
64
|
+
try {
|
|
65
|
+
return Buffer.from(await codec.encode(msg), options.charset);
|
|
66
|
+
} catch (thrown) {
|
|
67
|
+
const error = thrown instanceof Error ? thrown : new Error(String(thrown));
|
|
68
|
+
messageEncodeErrors.add(error);
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function createMessageConnection(reader, writer, sessionInitializationContext) {
|
|
75
|
+
let dispatch;
|
|
76
|
+
let finishDrain;
|
|
77
|
+
let drained;
|
|
78
|
+
let disposed = false;
|
|
79
|
+
const callbacks = /* @__PURE__ */ new Map();
|
|
80
|
+
const barrier = { jsonrpc: "2.0", method: "$/sdkDrain" };
|
|
81
|
+
const connection = createRpcMessageConnection(
|
|
82
|
+
{
|
|
83
|
+
onError: reader.onError,
|
|
84
|
+
onClose: reader.onClose,
|
|
85
|
+
onPartialMessage: reader.onPartialMessage,
|
|
86
|
+
listen: (callback) => {
|
|
87
|
+
dispatch = callback;
|
|
88
|
+
return reader.listen(callback);
|
|
89
|
+
},
|
|
90
|
+
dispose: () => reader.dispose()
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
onError: writer.onError,
|
|
94
|
+
onClose: writer.onClose,
|
|
95
|
+
write: (message) => {
|
|
96
|
+
if (Message.isResponse(message)) {
|
|
97
|
+
const context = callbacks.get(message.id);
|
|
98
|
+
if (context) {
|
|
99
|
+
context.active = false;
|
|
100
|
+
callbacks.delete(message.id);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return writer.write(message);
|
|
104
|
+
},
|
|
105
|
+
end: () => writer.end(),
|
|
106
|
+
dispose: () => writer.dispose()
|
|
107
|
+
},
|
|
108
|
+
void 0,
|
|
109
|
+
{
|
|
110
|
+
messageStrategy: {
|
|
111
|
+
handleMessage: (message, next) => {
|
|
112
|
+
if (message === barrier) {
|
|
113
|
+
finishDrain?.();
|
|
114
|
+
} else {
|
|
115
|
+
const request = Message.isRequest(message) ? message : void 0;
|
|
116
|
+
const params = request?.params;
|
|
117
|
+
const sessionId = params && typeof params === "object" && "sessionId" in params && typeof params.sessionId === "string" ? params.sessionId : void 0;
|
|
118
|
+
const context = sessionId === void 0 ? void 0 : { sessionId, active: true };
|
|
119
|
+
if (request && context) {
|
|
120
|
+
callbacks.set(request.id, context);
|
|
121
|
+
}
|
|
122
|
+
sessionInitializationContext.run(context, next, message);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
);
|
|
128
|
+
connection.onDispose(() => {
|
|
129
|
+
disposed = true;
|
|
130
|
+
for (const context of callbacks.values()) {
|
|
131
|
+
context.active = false;
|
|
132
|
+
}
|
|
133
|
+
callbacks.clear();
|
|
134
|
+
finishDrain?.();
|
|
135
|
+
});
|
|
136
|
+
return Object.assign(connection, {
|
|
137
|
+
drain: () => {
|
|
138
|
+
if (!drained) {
|
|
139
|
+
drained = new Promise((resolve2) => {
|
|
140
|
+
finishDrain = resolve2;
|
|
141
|
+
if (disposed || !dispatch) {
|
|
142
|
+
resolve2();
|
|
143
|
+
} else {
|
|
144
|
+
dispatch(barrier);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return drained;
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
async function withTimeout(promise, timeoutMs, message) {
|
|
153
|
+
let timeout;
|
|
154
|
+
try {
|
|
155
|
+
return await Promise.race([
|
|
156
|
+
promise,
|
|
157
|
+
new Promise((_, reject) => {
|
|
158
|
+
timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
|
|
159
|
+
})
|
|
160
|
+
]);
|
|
161
|
+
} finally {
|
|
162
|
+
if (timeout !== void 0) {
|
|
163
|
+
clearTimeout(timeout);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
async function waitForChildExit(child, timeoutMs) {
|
|
168
|
+
if (child.exitCode != null || child.signalCode != null) {
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
return new Promise((resolve2) => {
|
|
172
|
+
let timeout;
|
|
173
|
+
let settled = false;
|
|
174
|
+
const onExit = () => {
|
|
175
|
+
if (settled) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
settled = true;
|
|
179
|
+
clearTimeout(timeout);
|
|
180
|
+
resolve2(true);
|
|
181
|
+
};
|
|
182
|
+
timeout = setTimeout(() => {
|
|
183
|
+
if (settled) {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
settled = true;
|
|
187
|
+
child.off("exit", onExit);
|
|
188
|
+
resolve2(false);
|
|
189
|
+
}, timeoutMs);
|
|
190
|
+
child.once("exit", onExit);
|
|
191
|
+
if (child.exitCode != null || child.signalCode != null) {
|
|
192
|
+
onExit();
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
async function runCancellableCallback(connection, label, token, invoke) {
|
|
197
|
+
const ended = () => token.isCancellationRequested ? new ResponseError(-32800, `${label} request cancelled`) : new Error(`${label} connection closed`);
|
|
198
|
+
if (token.isCancellationRequested) {
|
|
199
|
+
throw ended();
|
|
200
|
+
}
|
|
201
|
+
const controller = new AbortController();
|
|
202
|
+
const abandoned = new Promise((_resolve, reject) => {
|
|
203
|
+
controller.signal.addEventListener("abort", () => reject(ended()), { once: true });
|
|
204
|
+
});
|
|
205
|
+
const abort = () => controller.abort();
|
|
206
|
+
const subscriptions = [
|
|
207
|
+
token.onCancellationRequested(abort),
|
|
208
|
+
connection.onClose(abort),
|
|
209
|
+
connection.onDispose(abort)
|
|
210
|
+
];
|
|
211
|
+
try {
|
|
212
|
+
const lookup = Promise.resolve().then(() => {
|
|
213
|
+
if (controller.signal.aborted) {
|
|
214
|
+
throw ended();
|
|
215
|
+
}
|
|
216
|
+
return invoke(controller.signal);
|
|
217
|
+
});
|
|
218
|
+
return await Promise.race([lookup, abandoned]);
|
|
219
|
+
} finally {
|
|
220
|
+
for (const subscription of subscriptions) {
|
|
221
|
+
subscription.dispose();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function snapshotNetworkConfig(network) {
|
|
226
|
+
const { scope, resolveProxy, authenticateNegotiate, authenticateBasic } = network;
|
|
227
|
+
return {
|
|
228
|
+
scope,
|
|
229
|
+
resolveProxy: resolveProxy && ((request, signal) => resolveProxy.call(network, request, signal)),
|
|
230
|
+
authenticateNegotiate: authenticateNegotiate && ((request, signal) => authenticateNegotiate.call(network, request, signal)),
|
|
231
|
+
authenticateBasic: authenticateBasic && ((request, signal) => authenticateBasic.call(network, request, signal))
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
async function resolveClientProxy(connection, callback, request, token) {
|
|
235
|
+
return {
|
|
236
|
+
proxy: await runCancellableCallback(
|
|
237
|
+
connection,
|
|
238
|
+
"Proxy resolution",
|
|
239
|
+
token,
|
|
240
|
+
(signal) => callback(request, signal)
|
|
241
|
+
)
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
async function authenticateClientNegotiate(connection, callback, request, token) {
|
|
245
|
+
return {
|
|
246
|
+
token: await runCancellableCallback(
|
|
247
|
+
connection,
|
|
248
|
+
"Negotiate authentication",
|
|
249
|
+
token,
|
|
250
|
+
(signal) => callback(request, signal)
|
|
251
|
+
)
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
async function authenticateClientBasic(connection, callback, request, token) {
|
|
255
|
+
const credentials = await runCancellableCallback(
|
|
256
|
+
connection,
|
|
257
|
+
"Basic authentication",
|
|
258
|
+
token,
|
|
259
|
+
(signal) => callback(request, signal)
|
|
260
|
+
);
|
|
261
|
+
return credentials ? { username: credentials.username, password: credentials.password } : {};
|
|
262
|
+
}
|
|
263
|
+
const DEFAULT_PROVIDER_NAME = "default";
|
|
264
|
+
function extractBearerTokenProviders(provider, providers) {
|
|
265
|
+
const callbacks = /* @__PURE__ */ new Map();
|
|
266
|
+
let wireProvider = provider;
|
|
267
|
+
if (provider?.bearerTokenProvider) {
|
|
268
|
+
const { bearerTokenProvider, ...rest } = provider;
|
|
269
|
+
callbacks.set(DEFAULT_PROVIDER_NAME, bearerTokenProvider);
|
|
270
|
+
wireProvider = {
|
|
271
|
+
...rest,
|
|
272
|
+
hasBearerTokenProvider: true
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
let wireProviders = providers;
|
|
276
|
+
if (providers?.some((p) => p.bearerTokenProvider)) {
|
|
277
|
+
wireProviders = providers.map((p) => {
|
|
278
|
+
if (!p.bearerTokenProvider) return p;
|
|
279
|
+
const { bearerTokenProvider, ...rest } = p;
|
|
280
|
+
callbacks.set(p.name, bearerTokenProvider);
|
|
281
|
+
return {
|
|
282
|
+
...rest,
|
|
283
|
+
hasBearerTokenProvider: true
|
|
284
|
+
};
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
return { wireProvider, wireProviders, callbacks };
|
|
288
|
+
}
|
|
289
|
+
function toWireMcpServers(mcpServers) {
|
|
290
|
+
if (!mcpServers) return void 0;
|
|
291
|
+
return Object.fromEntries(
|
|
292
|
+
Object.entries(mcpServers).map(([name, server]) => {
|
|
293
|
+
if ("workingDirectory" in server) {
|
|
294
|
+
const { workingDirectory, ...rest } = server;
|
|
295
|
+
return [name, { ...rest, cwd: workingDirectory }];
|
|
296
|
+
}
|
|
297
|
+
return [name, server];
|
|
298
|
+
})
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
function requestedMemoryStore(memory) {
|
|
302
|
+
if (!memory?.storeMemory) return void 0;
|
|
303
|
+
if (memory.enabled !== true) {
|
|
304
|
+
throw new Error("memory.storeMemory requires memory.enabled to be true.");
|
|
305
|
+
}
|
|
306
|
+
return memory.storeMemory;
|
|
307
|
+
}
|
|
308
|
+
function toWireMemoryConfiguration(memory) {
|
|
309
|
+
if (!memory) return memory;
|
|
310
|
+
const { storeMemory: _storeMemory, ...wire } = memory;
|
|
311
|
+
return wire;
|
|
312
|
+
}
|
|
313
|
+
function toWireCustomAgents(agents) {
|
|
314
|
+
if (!agents) return void 0;
|
|
315
|
+
return agents.map((agent) => {
|
|
316
|
+
if (!agent.mcpServers) return agent;
|
|
317
|
+
const { mcpServers, ...rest } = agent;
|
|
318
|
+
return { ...rest, mcpServers: toWireMcpServers(mcpServers) };
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
async function sendPing(connection, message) {
|
|
322
|
+
return await connection.sendRequest("ping", { message });
|
|
323
|
+
}
|
|
324
|
+
function clientInfoToWire(info) {
|
|
325
|
+
if (info == null) return void 0;
|
|
326
|
+
const wire = {};
|
|
327
|
+
if (info.applicationName) wire.editorName = info.applicationName;
|
|
328
|
+
if (info.applicationVersion) wire.editorVersion = info.applicationVersion;
|
|
329
|
+
if (info.integrationName) wire.extensionName = info.integrationName;
|
|
330
|
+
if (info.integrationVersion) wire.extensionVersion = info.integrationVersion;
|
|
331
|
+
return Object.keys(wire).length > 0 ? wire : void 0;
|
|
332
|
+
}
|
|
333
|
+
function toWireLargeOutput(config) {
|
|
334
|
+
if (!config) return void 0;
|
|
335
|
+
const { outputDirectory, ...rest } = config;
|
|
336
|
+
const wire = { ...rest };
|
|
337
|
+
if (outputDirectory !== void 0) {
|
|
338
|
+
wire.outputDir = outputDirectory;
|
|
339
|
+
}
|
|
340
|
+
return wire;
|
|
341
|
+
}
|
|
342
|
+
function toolFilterListToArray(value) {
|
|
343
|
+
if (value === void 0) {
|
|
344
|
+
return void 0;
|
|
345
|
+
}
|
|
346
|
+
return value instanceof ToolSet ? value.toArray() : value;
|
|
347
|
+
}
|
|
348
|
+
function validateToolFilterList(field, list) {
|
|
349
|
+
if (!list) {
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
for (const entry of list) {
|
|
353
|
+
if (entry === "*") {
|
|
354
|
+
throw new Error(
|
|
355
|
+
`Invalid ${field} entry '*': there is no bare wildcard. Use one or more of \`new ToolSet().addBuiltIn('*')\`, \`.addMcp('*')\`, or \`.addCustom('*')\` to target a specific source.`
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function extractTransformCallbacks(systemMessage) {
|
|
361
|
+
if (!systemMessage || systemMessage.mode !== "customize" || !systemMessage.sections) {
|
|
362
|
+
return { wirePayload: systemMessage, transformCallbacks: void 0 };
|
|
363
|
+
}
|
|
364
|
+
const transformCallbacks = /* @__PURE__ */ new Map();
|
|
365
|
+
const wireSections = {};
|
|
366
|
+
for (const [sectionId, override] of Object.entries(systemMessage.sections)) {
|
|
367
|
+
if (!override) continue;
|
|
368
|
+
if (typeof override.action === "function") {
|
|
369
|
+
transformCallbacks.set(sectionId, override.action);
|
|
370
|
+
wireSections[sectionId] = { action: "transform" };
|
|
371
|
+
} else {
|
|
372
|
+
wireSections[sectionId] = { action: override.action, content: override.content };
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
if (transformCallbacks.size === 0) {
|
|
376
|
+
return { wirePayload: systemMessage, transformCallbacks: void 0 };
|
|
377
|
+
}
|
|
378
|
+
const wirePayload = {
|
|
379
|
+
...systemMessage,
|
|
380
|
+
sections: wireSections
|
|
381
|
+
};
|
|
382
|
+
return { wirePayload, transformCallbacks };
|
|
383
|
+
}
|
|
384
|
+
function getNodeExecPath() {
|
|
385
|
+
if (process.versions.bun) {
|
|
386
|
+
return "node";
|
|
387
|
+
}
|
|
388
|
+
return process.execPath;
|
|
389
|
+
}
|
|
390
|
+
function getBundledRuntimePath() {
|
|
391
|
+
return ensureRuntimeBundle(COPILOT_CLI_VERSION);
|
|
392
|
+
}
|
|
393
|
+
async function getSpawnableBundledRuntimePath() {
|
|
394
|
+
const runtimePath = await getBundledRuntimePath();
|
|
395
|
+
return process.platform === "win32" ? win32.toNamespacedPath(runtimePath) : runtimePath;
|
|
396
|
+
}
|
|
397
|
+
class TeardownResilientStreamMessageWriter extends StreamMessageWriter {
|
|
398
|
+
suppressWriteErrors = false;
|
|
399
|
+
constructor(writable, codec) {
|
|
400
|
+
super(writable, { contentTypeEncoder: jsonMessageEncoder(codec) });
|
|
401
|
+
}
|
|
402
|
+
async write(msg) {
|
|
403
|
+
try {
|
|
404
|
+
await super.write(msg);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
if (!this.suppressWriteErrors) {
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
class CopilotClient {
|
|
413
|
+
cliStartTimeout = null;
|
|
414
|
+
cliProcess = null;
|
|
415
|
+
ffiHost = null;
|
|
416
|
+
connection = null;
|
|
417
|
+
requestAdapter = null;
|
|
418
|
+
pendingMemoryStores = /* @__PURE__ */ new Set();
|
|
419
|
+
messageWriter = null;
|
|
420
|
+
connectionClosed = false;
|
|
421
|
+
// Disconnects the current connection without waiting for its reader to reach EOF.
|
|
422
|
+
retireClosedConnection = null;
|
|
423
|
+
connectionEpoch = 0;
|
|
424
|
+
socket = null;
|
|
425
|
+
runtimePort = null;
|
|
426
|
+
actualHost = "localhost";
|
|
427
|
+
state = "disconnected";
|
|
428
|
+
/** Shared in-flight start; concurrent callers await the same runtime startup. */
|
|
429
|
+
startPromise = null;
|
|
430
|
+
shutdownCanceledStartup = null;
|
|
431
|
+
stopPromise = null;
|
|
432
|
+
forceStopPromise = null;
|
|
433
|
+
sessions = /* @__PURE__ */ new Map();
|
|
434
|
+
/**
|
|
435
|
+
* Open secret prompts by session ID, then request ID. Tracked here rather
|
|
436
|
+
* than on a session object, which a resume can replace while a prompt is open.
|
|
437
|
+
*/
|
|
438
|
+
pendingShellAuthenticationRequests = /* @__PURE__ */ new Map();
|
|
439
|
+
pendingSessionResumes = /* @__PURE__ */ new Map();
|
|
440
|
+
sessionInitializations = /* @__PURE__ */ new Map();
|
|
441
|
+
failedAutoModeRecoveryCleanups = /* @__PURE__ */ new WeakMap();
|
|
442
|
+
sessionInitializationContext = new AsyncLocalStorage();
|
|
443
|
+
sessionInitializationLifetime = new AbortController();
|
|
444
|
+
sessionInitializationGeneration = 0;
|
|
445
|
+
hostExitCallbacks = /* @__PURE__ */ new Map();
|
|
446
|
+
hostSessionFactories = /* @__PURE__ */ new Map();
|
|
447
|
+
hostAuthenticators = /* @__PURE__ */ new Map();
|
|
448
|
+
hostAuthentications = /* @__PURE__ */ new Map();
|
|
449
|
+
hostHandoffs = /* @__PURE__ */ new Map();
|
|
450
|
+
stderrBuffer = "";
|
|
451
|
+
// Captures CLI stderr for error messages
|
|
452
|
+
/** Resolved connection mode chosen in the constructor. */
|
|
453
|
+
connectionConfig;
|
|
454
|
+
/** Resolved path to the runtime executable (only used for child-process kinds). */
|
|
455
|
+
resolvedCliPath;
|
|
456
|
+
/** Resolved environment passed to the spawned runtime. */
|
|
457
|
+
resolvedEnv;
|
|
458
|
+
options;
|
|
459
|
+
isExternalServer = false;
|
|
460
|
+
forceStopping = false;
|
|
461
|
+
/** Token sent in `connect`; auto-generated when the SDK spawns its own CLI in TCP mode. */
|
|
462
|
+
effectiveConnectionToken;
|
|
463
|
+
onListModels;
|
|
464
|
+
onGetTraceContext;
|
|
465
|
+
modelsCache = {
|
|
466
|
+
models: null,
|
|
467
|
+
lock: Promise.resolve()
|
|
468
|
+
};
|
|
469
|
+
sessionLifecycleHandlers = /* @__PURE__ */ new Set();
|
|
470
|
+
typedLifecycleHandlers = /* @__PURE__ */ new Map();
|
|
471
|
+
_rpc = null;
|
|
472
|
+
_internalRpc = null;
|
|
473
|
+
_decisions;
|
|
474
|
+
processExitPromise = null;
|
|
475
|
+
// Rejects when CLI process exits
|
|
476
|
+
processTransportError = null;
|
|
477
|
+
negotiatedProtocolVersion = null;
|
|
478
|
+
/** Connection-level session filesystem config, set via constructor option. */
|
|
479
|
+
sessionFsConfig = null;
|
|
480
|
+
requestHandler = null;
|
|
481
|
+
extensionLaunchProvider;
|
|
482
|
+
network;
|
|
483
|
+
installationConfirmationHandler;
|
|
484
|
+
builtinPluginDirectories = [];
|
|
485
|
+
onGitHubTelemetry;
|
|
486
|
+
clientGlobalHandlers = {};
|
|
487
|
+
githubTokenProviders = /* @__PURE__ */ new Map();
|
|
488
|
+
/**
|
|
489
|
+
* Typed server-scoped RPC methods.
|
|
490
|
+
* @throws Error if the client is not connected
|
|
491
|
+
*/
|
|
492
|
+
get rpc() {
|
|
493
|
+
if (!this.connection) {
|
|
494
|
+
throw new Error("Client is not connected. Call start() first.");
|
|
495
|
+
}
|
|
496
|
+
if (!this._rpc) {
|
|
497
|
+
this._rpc = createServerRpc(this.connection);
|
|
498
|
+
}
|
|
499
|
+
return this._rpc;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* One-off yes/no, pick-one and rating questions answered by Copilot decision
|
|
503
|
+
* models. Requires the runtime's `DECISIONS_API` feature flag.
|
|
504
|
+
*
|
|
505
|
+
* @experimental
|
|
506
|
+
*/
|
|
507
|
+
get decisions() {
|
|
508
|
+
this._decisions ??= new CopilotDecisions(() => this.rpc);
|
|
509
|
+
return this._decisions;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Internal RPC surface (e.g. handshake helpers). Not part of the public API.
|
|
513
|
+
* @internal
|
|
514
|
+
*/
|
|
515
|
+
get internalRpc() {
|
|
516
|
+
if (!this.connection) {
|
|
517
|
+
throw new Error("Client is not connected. Call start() first.");
|
|
518
|
+
}
|
|
519
|
+
if (!this._internalRpc) {
|
|
520
|
+
this._internalRpc = createInternalServerRpc(this.connection);
|
|
521
|
+
}
|
|
522
|
+
return this._internalRpc;
|
|
523
|
+
}
|
|
524
|
+
logDebugTiming(message, startMs) {
|
|
525
|
+
const level = this.options.logLevel?.toLowerCase();
|
|
526
|
+
if (level === "debug" || level === "all") {
|
|
527
|
+
process.stderr.write(`[copilot-sdk] ${message}. Elapsed=${Date.now() - startMs}ms
|
|
528
|
+
`);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
logDebug(message) {
|
|
532
|
+
const level = this.options.logLevel?.toLowerCase();
|
|
533
|
+
if (level === "debug" || level === "all") {
|
|
534
|
+
process.stderr.write(`[copilot-sdk] ${message}
|
|
535
|
+
`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Environment variable that overrides the transport when the caller does not set
|
|
540
|
+
* {@link CopilotClientOptions.connection}. Accepts `"inprocess"` or `"stdio"`
|
|
541
|
+
* (case-insensitive); unset selects the in-process transport. Any other value
|
|
542
|
+
* is an error.
|
|
543
|
+
*/
|
|
544
|
+
static DEFAULT_CONNECTION_ENV_VAR = "COPILOT_SDK_DEFAULT_CONNECTION";
|
|
545
|
+
/**
|
|
546
|
+
* Resolves the default {@link RuntimeConnection} for the no-connection case,
|
|
547
|
+
* honoring {@link CopilotClient.DEFAULT_CONNECTION_ENV_VAR}.
|
|
548
|
+
*/
|
|
549
|
+
static resolveDefaultConnection() {
|
|
550
|
+
const value = process.env[CopilotClient.DEFAULT_CONNECTION_ENV_VAR];
|
|
551
|
+
if (value?.toLowerCase() === "stdio") {
|
|
552
|
+
return { kind: "stdio" };
|
|
553
|
+
}
|
|
554
|
+
if (!value || value.toLowerCase() === "inprocess") {
|
|
555
|
+
return { kind: "inprocess" };
|
|
556
|
+
}
|
|
557
|
+
throw new Error(
|
|
558
|
+
`Invalid ${CopilotClient.DEFAULT_CONNECTION_ENV_VAR} value '${value}'. Expected 'inprocess', 'stdio', or unset.`
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Creates a new CopilotClient instance.
|
|
563
|
+
*
|
|
564
|
+
* @param options - Configuration options for the client
|
|
565
|
+
*
|
|
566
|
+
* @example
|
|
567
|
+
* ```typescript
|
|
568
|
+
* // Default: loads the native runtime in this process
|
|
569
|
+
* const client = new CopilotClient({ mode: "coding-agent" });
|
|
570
|
+
*
|
|
571
|
+
* // Connect to an existing runtime
|
|
572
|
+
* const client = new CopilotClient({
|
|
573
|
+
* mode: "coding-agent",
|
|
574
|
+
* connection: RuntimeConnection.forUri("localhost:3000"),
|
|
575
|
+
* });
|
|
576
|
+
*
|
|
577
|
+
* // Spawn the runtime over TCP on a chosen port
|
|
578
|
+
* const client = new CopilotClient({
|
|
579
|
+
* mode: "coding-agent",
|
|
580
|
+
* connection: RuntimeConnection.forTcp({ port: 9001 }),
|
|
581
|
+
* });
|
|
582
|
+
*
|
|
583
|
+
* // Use a custom runtime binary
|
|
584
|
+
* const client = new CopilotClient({
|
|
585
|
+
* mode: "coding-agent",
|
|
586
|
+
* connection: RuntimeConnection.forStdio({ path: "/usr/local/bin/copilot" }),
|
|
587
|
+
* logLevel: "debug",
|
|
588
|
+
* });
|
|
589
|
+
* ```
|
|
590
|
+
*/
|
|
591
|
+
constructor(options) {
|
|
592
|
+
if (options?.mode !== "coding-agent" && options?.mode !== "empty") {
|
|
593
|
+
throw new Error("mode is required and must be 'coding-agent' or 'empty'");
|
|
594
|
+
}
|
|
595
|
+
const conn = options._internalConnection ?? options.connection ?? CopilotClient.resolveDefaultConnection();
|
|
596
|
+
if ((conn.kind === "uri" || conn.kind === "parent-process") && options.internalTestOptions !== void 0) {
|
|
597
|
+
throw new Error("internalTestOptions requires a runtime owned by this client");
|
|
598
|
+
}
|
|
599
|
+
if (conn.kind === "uri" && (options.gitHubToken !== void 0 || options.useLoggedInUser !== void 0)) {
|
|
600
|
+
throw new Error(
|
|
601
|
+
"gitHubToken and useLoggedInUser cannot be used with RuntimeConnection.forUri (external server manages its own auth)"
|
|
602
|
+
);
|
|
603
|
+
}
|
|
604
|
+
if (conn.kind === "inprocess" && options.env !== void 0) {
|
|
605
|
+
throw new Error(
|
|
606
|
+
"env is not supported with RuntimeConnection.forInProcess(): environment variables belong to the shared host process. Use typed client/session options or a child-process transport."
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
if (conn.kind === "inprocess" && options.workingDirectory !== void 0) {
|
|
610
|
+
throw new Error(
|
|
611
|
+
"workingDirectory is not supported with RuntimeConnection.forInProcess(): the in-process transport hosts the runtime in this process, so honoring it would require mutating the shared process-global cwd. Set SessionConfig.workingDirectory instead."
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
if ((conn.kind === "stdio" || conn.kind === "tcp") && conn.env !== void 0 && options.env !== void 0) {
|
|
615
|
+
throw new Error(
|
|
616
|
+
"Set environment variables via either the client-level env option or the connection's env (RuntimeConnection.forStdio/forTcp), not both. Prefer the connection-level env for child-process transports."
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
if (conn.kind === "tcp" && conn.connectionToken !== void 0) {
|
|
620
|
+
if (typeof conn.connectionToken !== "string" || conn.connectionToken.length === 0) {
|
|
621
|
+
throw new Error("connectionToken must be a non-empty string");
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
this.connectionConfig = conn;
|
|
625
|
+
if (options.sessionFs) {
|
|
626
|
+
this.validateSessionFsConfig(options.sessionFs);
|
|
627
|
+
}
|
|
628
|
+
if (options.builtinPluginDirectories) {
|
|
629
|
+
for (const path of options.builtinPluginDirectories) {
|
|
630
|
+
if (!isAbsolute(path)) {
|
|
631
|
+
throw new Error(
|
|
632
|
+
`builtinPluginDirectories must contain only absolute paths: ${path}`
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
this.builtinPluginDirectories = [...options.builtinPluginDirectories];
|
|
637
|
+
}
|
|
638
|
+
if (conn.kind === "uri") {
|
|
639
|
+
const { host, port } = this.parseCliUrl(conn.url);
|
|
640
|
+
this.actualHost = host;
|
|
641
|
+
this.runtimePort = port;
|
|
642
|
+
this.isExternalServer = true;
|
|
643
|
+
} else if (conn.kind === "parent-process") {
|
|
644
|
+
this.isExternalServer = true;
|
|
645
|
+
}
|
|
646
|
+
if (conn.kind === "tcp") {
|
|
647
|
+
this.effectiveConnectionToken = conn.connectionToken ?? randomUUID();
|
|
648
|
+
} else if (conn.kind === "uri") {
|
|
649
|
+
this.effectiveConnectionToken = conn.connectionToken;
|
|
650
|
+
}
|
|
651
|
+
this.onListModels = options.onListModels;
|
|
652
|
+
this.onGetTraceContext = options.onGetTraceContext;
|
|
653
|
+
this.sessionFsConfig = options.sessionFs ?? null;
|
|
654
|
+
this.requestHandler = options.requestHandler ?? null;
|
|
655
|
+
this.extensionLaunchProvider = options.extensionLaunchProvider;
|
|
656
|
+
this.network = options.network ? snapshotNetworkConfig(options.network) : void 0;
|
|
657
|
+
this.installationConfirmationHandler = options.installationConfirmationHandler;
|
|
658
|
+
this.onGitHubTelemetry = options.onGitHubTelemetry;
|
|
659
|
+
this.setupClientGlobalHandlers();
|
|
660
|
+
const connEnv = conn.kind === "stdio" || conn.kind === "tcp" ? conn.env : void 0;
|
|
661
|
+
const effectiveEnv = connEnv ?? options.env ?? process.env;
|
|
662
|
+
this.resolvedEnv = effectiveEnv;
|
|
663
|
+
if (conn.kind === "stdio" || conn.kind === "tcp") {
|
|
664
|
+
const explicitCliPath = conn.path ?? effectiveEnv.COPILOT_CLI_PATH;
|
|
665
|
+
if (explicitCliPath) {
|
|
666
|
+
this.resolvedCliPath = explicitCliPath;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
const connArgs = conn.kind === "stdio" || conn.kind === "tcp" ? conn.args ?? [] : [];
|
|
670
|
+
this.connectionExtraArgs = [...connArgs];
|
|
671
|
+
this.options = {
|
|
672
|
+
internalTestOptions: options.internalTestOptions,
|
|
673
|
+
entra: options.entra ? { ...options.entra, tokenProvider: options.entra.tokenProvider } : void 0,
|
|
674
|
+
workingDirectory: options.workingDirectory ?? process.cwd(),
|
|
675
|
+
logLevel: options.logLevel,
|
|
676
|
+
gitHubToken: options.gitHubToken,
|
|
677
|
+
// Default useLoggedInUser to false when gitHubToken is provided, otherwise true.
|
|
678
|
+
useLoggedInUser: options.useLoggedInUser ?? (options.gitHubToken ? false : true),
|
|
679
|
+
telemetry: options.telemetry,
|
|
680
|
+
baseDirectory: options.baseDirectory,
|
|
681
|
+
sessionIdleTimeoutSeconds: options.sessionIdleTimeoutSeconds ?? 0,
|
|
682
|
+
mode: options.mode,
|
|
683
|
+
clientInfo: options.clientInfo
|
|
684
|
+
};
|
|
685
|
+
if (this.options.mode === "empty") {
|
|
686
|
+
const hasPersistence = this.options.baseDirectory !== void 0 || this.sessionFsConfig !== null || // External runtimes manage their own persistence layer; the SDK
|
|
687
|
+
// can't enforce it from here.
|
|
688
|
+
conn.kind === "uri" || conn.kind === "parent-process";
|
|
689
|
+
if (!hasPersistence) {
|
|
690
|
+
throw new Error(
|
|
691
|
+
"CopilotClient was created with mode: 'empty' but neither 'baseDirectory' nor 'sessionFs' was set. Empty mode requires an explicit per-session persistence location; pick one."
|
|
692
|
+
);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
connectionExtraArgs = [];
|
|
697
|
+
/**
|
|
698
|
+
* Parse CLI URL into host and port
|
|
699
|
+
* Supports raw TCP addresses: "host:port", "[ipv6]:port", "http://host:port", or just "port"
|
|
700
|
+
*/
|
|
701
|
+
parseCliUrl(url) {
|
|
702
|
+
if (/^https:\/\//i.test(url)) {
|
|
703
|
+
throw new Error(
|
|
704
|
+
"HTTPS runtime connections are not supported: this transport uses plaintext TCP, not TLS"
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
const cleanUrl = url.replace(/^http:\/\//, "");
|
|
708
|
+
if (/^\d+$/.test(cleanUrl)) {
|
|
709
|
+
return { host: "localhost", port: parseInt(cleanUrl, 10) };
|
|
710
|
+
}
|
|
711
|
+
const ipv6Match = cleanUrl.match(/^\[([^\]]+)\]:(\d+)$/);
|
|
712
|
+
if (ipv6Match) {
|
|
713
|
+
const host2 = ipv6Match[1];
|
|
714
|
+
if (!isIPv6(host2)) {
|
|
715
|
+
throw new Error(`Invalid cliUrl format: ${url}`);
|
|
716
|
+
}
|
|
717
|
+
const port2 = parseInt(ipv6Match[2], 10);
|
|
718
|
+
if (isNaN(port2) || port2 <= 0 || port2 > 65535) {
|
|
719
|
+
throw new Error(`Invalid port in cliUrl: ${url}`);
|
|
720
|
+
}
|
|
721
|
+
return { host: host2, port: port2 };
|
|
722
|
+
}
|
|
723
|
+
const parts = cleanUrl.split(":");
|
|
724
|
+
if (parts.length !== 2) {
|
|
725
|
+
throw new Error(
|
|
726
|
+
`Invalid cliUrl format: ${url}. Expected "host:port", "[ipv6]:port", "http://host:port", or "port"`
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
const host = parts[0] || "localhost";
|
|
730
|
+
const port = parseInt(parts[1], 10);
|
|
731
|
+
if (isNaN(port) || port <= 0 || port > 65535) {
|
|
732
|
+
throw new Error(`Invalid port in cliUrl: ${url}`);
|
|
733
|
+
}
|
|
734
|
+
return { host, port };
|
|
735
|
+
}
|
|
736
|
+
validateSessionFsConfig(config) {
|
|
737
|
+
if (!config.initialCwd) {
|
|
738
|
+
throw new Error("sessionFs.initialCwd is required");
|
|
739
|
+
}
|
|
740
|
+
if (!config.sessionStatePath) {
|
|
741
|
+
throw new Error("sessionFs.sessionStatePath is required");
|
|
742
|
+
}
|
|
743
|
+
if (config.conventions !== "windows" && config.conventions !== "posix") {
|
|
744
|
+
throw new Error("sessionFs.conventions must be either 'windows' or 'posix'");
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
setupSessionFs(session, config) {
|
|
748
|
+
if (!this.sessionFsConfig) {
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
if (!config.createSessionFsProvider) {
|
|
752
|
+
throw new Error(
|
|
753
|
+
"createSessionFsProvider is required in session config when sessionFs is enabled in client options."
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
const provider = config.createSessionFsProvider(session);
|
|
757
|
+
if (this.sessionFsConfig.capabilities?.sqlite && !provider.sqlite) {
|
|
758
|
+
throw new Error(
|
|
759
|
+
"SessionFsConfig declares capabilities.sqlite but the provider does not implement sqlite."
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
if (this.sessionFsConfig.capabilities?.binary && (!provider.readFileBytes || !provider.writeFileBytes)) {
|
|
763
|
+
throw new Error(
|
|
764
|
+
"SessionFsConfig declares capabilities.binary but the provider does not implement readFileBytes and writeFileBytes."
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
if (this.sessionFsConfig.capabilities?.readFileRange && !provider.readFileRange) {
|
|
768
|
+
throw new Error(
|
|
769
|
+
"SessionFsConfig declares capabilities.readFileRange but the provider does not implement readFileRange."
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
session.clientSessionApis.sessionFs = createSessionFsAdapter(provider);
|
|
773
|
+
}
|
|
774
|
+
setupClientGlobalHandlers() {
|
|
775
|
+
const handlers = {};
|
|
776
|
+
handlers.host = {
|
|
777
|
+
exited: async (exit) => {
|
|
778
|
+
this.handleHostExit(exit);
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
handlers.extensionLaunchProvider = this.extensionLaunchProvider;
|
|
782
|
+
if (this.requestHandler) {
|
|
783
|
+
this.requestAdapter = createCopilotRequestAdapter(this.requestHandler, () => {
|
|
784
|
+
if (!this.connection) {
|
|
785
|
+
return void 0;
|
|
786
|
+
}
|
|
787
|
+
this._rpc ??= createServerRpc(this.connection);
|
|
788
|
+
return this._rpc;
|
|
789
|
+
});
|
|
790
|
+
handlers.llmInference = this.requestAdapter;
|
|
791
|
+
}
|
|
792
|
+
if (this.onGitHubTelemetry) {
|
|
793
|
+
const onGitHubTelemetry = this.onGitHubTelemetry;
|
|
794
|
+
handlers.gitHubTelemetry = {
|
|
795
|
+
event: async (notification) => {
|
|
796
|
+
try {
|
|
797
|
+
await onGitHubTelemetry(notification);
|
|
798
|
+
} catch {
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
handlers.gitHubToken = {
|
|
804
|
+
getToken: (params) => this.acquireGitHubToken(params)
|
|
805
|
+
};
|
|
806
|
+
handlers.uiThread = {
|
|
807
|
+
run: async ({ actionId }) => {
|
|
808
|
+
const connection = this.connectionConfig;
|
|
809
|
+
const host = this.ffiHost;
|
|
810
|
+
if (connection.kind !== "inprocess" || !connection.runOnUiThread || !host) {
|
|
811
|
+
throw new Error("No in-process runOnUiThread handler is configured.");
|
|
812
|
+
}
|
|
813
|
+
await connection.runOnUiThread(() => host.runUiAction(actionId));
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
this.clientGlobalHandlers = handlers;
|
|
817
|
+
}
|
|
818
|
+
async acquireGitHubToken(params) {
|
|
819
|
+
const registration = this.githubTokenProviders.get(params.registrationId);
|
|
820
|
+
if (!registration) {
|
|
821
|
+
throw new Error(
|
|
822
|
+
`No GitHub token provider registered for registration ID "${params.registrationId}"`
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
return await registration.provider({
|
|
826
|
+
host: params.host,
|
|
827
|
+
sessionId: params.sessionId ?? registration.sessionId,
|
|
828
|
+
reason: params.reason
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
registerGitHubTokenProvider(provider, sessionId) {
|
|
832
|
+
if (!provider) {
|
|
833
|
+
return void 0;
|
|
834
|
+
}
|
|
835
|
+
const registrationId = randomUUID();
|
|
836
|
+
this.githubTokenProviders.set(registrationId, { provider, sessionId, committed: false });
|
|
837
|
+
return registrationId;
|
|
838
|
+
}
|
|
839
|
+
assignGitHubTokenProvider(registrationId, sessionId) {
|
|
840
|
+
if (!registrationId) {
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
const registration = this.githubTokenProviders.get(registrationId);
|
|
844
|
+
if (registration) {
|
|
845
|
+
registration.sessionId = sessionId;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
commitGitHubTokenProvider(sessionId, registrationId) {
|
|
849
|
+
for (const [candidateId, registration2] of this.githubTokenProviders) {
|
|
850
|
+
if (registration2.sessionId === sessionId && registration2.committed) {
|
|
851
|
+
this.githubTokenProviders.delete(candidateId);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
const registration = registrationId ? this.githubTokenProviders.get(registrationId) : void 0;
|
|
855
|
+
if (registration) {
|
|
856
|
+
registration.sessionId = sessionId;
|
|
857
|
+
registration.committed = true;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Starts the runtime host and establishes a connection.
|
|
862
|
+
*
|
|
863
|
+
* An explicit {@link RuntimeConnection.forUri} only establishes the connection.
|
|
864
|
+
* Otherwise, starts an in-process host or the explicitly selected subprocess.
|
|
865
|
+
* If its subprocess survives a lost connection, it is terminated before restarting.
|
|
866
|
+
*
|
|
867
|
+
* This method is called automatically the first time you create or resume a session.
|
|
868
|
+
*
|
|
869
|
+
* @returns A promise that resolves when the connection is established
|
|
870
|
+
* @throws Error if the server fails to start or the connection fails
|
|
871
|
+
*
|
|
872
|
+
* @example
|
|
873
|
+
* ```typescript
|
|
874
|
+
* const client = new CopilotClient({ mode: "coding-agent" });
|
|
875
|
+
* await client.start();
|
|
876
|
+
* // Now ready to create sessions
|
|
877
|
+
* ```
|
|
878
|
+
*/
|
|
879
|
+
async start() {
|
|
880
|
+
if (this.forceStopPromise || this.stopPromise && !this.forceStopping) {
|
|
881
|
+
throw new Error("Client disconnected during session initialization");
|
|
882
|
+
}
|
|
883
|
+
const startup = this.startPromise;
|
|
884
|
+
if (startup && startup === this.shutdownCanceledStartup) {
|
|
885
|
+
const generation = this.sessionInitializationGeneration;
|
|
886
|
+
await Promise.allSettled([startup, this.stopPromise]);
|
|
887
|
+
if (generation !== this.sessionInitializationGeneration) {
|
|
888
|
+
throw new Error("Client disconnected during session initialization");
|
|
889
|
+
}
|
|
890
|
+
return this.start();
|
|
891
|
+
}
|
|
892
|
+
if (startup && !this.stopPromise) {
|
|
893
|
+
return startup;
|
|
894
|
+
}
|
|
895
|
+
const retireClosedConnection = this.retireClosedConnection;
|
|
896
|
+
if (this.state === "connected" && this.connectionClosed && !this.stopPromise && retireClosedConnection) {
|
|
897
|
+
const retirement = retireClosedConnection();
|
|
898
|
+
const generation = this.sessionInitializationGeneration;
|
|
899
|
+
await retirement;
|
|
900
|
+
if (generation !== this.sessionInitializationGeneration) {
|
|
901
|
+
throw new Error("Client disconnected during session initialization");
|
|
902
|
+
}
|
|
903
|
+
return this.start();
|
|
904
|
+
}
|
|
905
|
+
if (this.stopPromise || this.connection && this.sessionInitializationLifetime.signal.aborted) {
|
|
906
|
+
throw new Error("Client disconnected during session initialization");
|
|
907
|
+
}
|
|
908
|
+
if (this.state === "connected") {
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
this.startPromise = this.doStart();
|
|
912
|
+
try {
|
|
913
|
+
await this.startPromise;
|
|
914
|
+
} finally {
|
|
915
|
+
this.startPromise = null;
|
|
916
|
+
this.shutdownCanceledStartup = null;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
async doStart() {
|
|
920
|
+
this.sessionInitializationLifetime = new AbortController();
|
|
921
|
+
const signal = this.sessionInitializationLifetime.signal;
|
|
922
|
+
this.forceStopping = false;
|
|
923
|
+
this.connectionEpoch++;
|
|
924
|
+
this.connectionClosed = false;
|
|
925
|
+
this.processTransportError = null;
|
|
926
|
+
this.state = "connecting";
|
|
927
|
+
try {
|
|
928
|
+
if (this.cliProcess) {
|
|
929
|
+
await this.killCliProcess();
|
|
930
|
+
signal.throwIfAborted();
|
|
931
|
+
}
|
|
932
|
+
if (this.connectionConfig.kind === "inprocess") {
|
|
933
|
+
await this.startInProcessFfi();
|
|
934
|
+
} else if (!this.isExternalServer) {
|
|
935
|
+
await this.startCLIServer();
|
|
936
|
+
}
|
|
937
|
+
signal.throwIfAborted();
|
|
938
|
+
await this.connectToServer();
|
|
939
|
+
signal.throwIfAborted();
|
|
940
|
+
await this.verifyProtocolVersion();
|
|
941
|
+
if (this.network?.resolveProxy || this.network?.authenticateNegotiate || this.network?.authenticateBasic) {
|
|
942
|
+
const { scope, resolveProxy, authenticateNegotiate, authenticateBasic } = this.network;
|
|
943
|
+
await this.rpc.network.setProvider({
|
|
944
|
+
...scope ? { scope } : {},
|
|
945
|
+
...resolveProxy ? { resolveProxy: {} } : {},
|
|
946
|
+
...authenticateNegotiate ? { authenticateNegotiate: {} } : {},
|
|
947
|
+
...authenticateBasic ? { authenticateBasic: {} } : {}
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
if (this.extensionLaunchProvider) {
|
|
951
|
+
await this.rpc.registerExtensionLaunchProvider();
|
|
952
|
+
}
|
|
953
|
+
if (this.builtinPluginDirectories.length > 0) {
|
|
954
|
+
await this.connection.sendRequest("plugins.builtin.set", {
|
|
955
|
+
paths: this.builtinPluginDirectories
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
if (this.sessionFsConfig) {
|
|
959
|
+
await this.connection.sendRequest("sessionFs.setProvider", {
|
|
960
|
+
initialCwd: this.sessionFsConfig.initialCwd,
|
|
961
|
+
sessionStatePath: this.sessionFsConfig.sessionStatePath,
|
|
962
|
+
conventions: this.sessionFsConfig.conventions,
|
|
963
|
+
capabilities: this.sessionFsConfig.capabilities
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
if (this.requestHandler) {
|
|
967
|
+
await this.connection.sendRequest("llmInference.setProvider", {});
|
|
968
|
+
}
|
|
969
|
+
if (this.connectionClosed) {
|
|
970
|
+
throw new Error("CLI server connection closed during startup");
|
|
971
|
+
}
|
|
972
|
+
signal.throwIfAborted();
|
|
973
|
+
this.state = "connected";
|
|
974
|
+
} catch (error) {
|
|
975
|
+
const startupError = this.processTransportError ?? error;
|
|
976
|
+
if (!signal.aborted) {
|
|
977
|
+
this.invalidateSessionInitializations();
|
|
978
|
+
}
|
|
979
|
+
await this.doForceStop();
|
|
980
|
+
this.state = "error";
|
|
981
|
+
throw startupError;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Stops the CLI server and closes all active sessions.
|
|
986
|
+
*
|
|
987
|
+
* This method performs graceful cleanup:
|
|
988
|
+
* 1. Closes all active sessions, suspending unfinished work for resume;
|
|
989
|
+
* detach requests share one shutdown timeout
|
|
990
|
+
* 2. Requests runtime shutdown for SDK-owned CLI processes
|
|
991
|
+
* 3. Closes the JSON-RPC connection
|
|
992
|
+
* 4. Signals EOF to an owned stdio process and waits for host cleanup, then
|
|
993
|
+
* terminates the process if it does not exit within the shutdown timeout
|
|
994
|
+
*
|
|
995
|
+
* Note: session data on disk is preserved, so sessions can be resumed later.
|
|
996
|
+
* To permanently remove session data before stopping, call
|
|
997
|
+
* {@link deleteSession} for each session first.
|
|
998
|
+
*
|
|
999
|
+
* @returns A promise that resolves with an array of errors encountered during cleanup.
|
|
1000
|
+
* An empty array indicates all cleanup succeeded.
|
|
1001
|
+
*
|
|
1002
|
+
* @example
|
|
1003
|
+
* ```typescript
|
|
1004
|
+
* const errors = await client.stop();
|
|
1005
|
+
* if (errors.length > 0) {
|
|
1006
|
+
* console.error("Cleanup errors:", errors);
|
|
1007
|
+
* }
|
|
1008
|
+
* ```
|
|
1009
|
+
*/
|
|
1010
|
+
async stop() {
|
|
1011
|
+
if (this.stopPromise) {
|
|
1012
|
+
return this.stopPromise;
|
|
1013
|
+
}
|
|
1014
|
+
if (!this.sessionInitializationLifetime.signal.aborted) {
|
|
1015
|
+
this.shutdownCanceledStartup = this.startPromise;
|
|
1016
|
+
}
|
|
1017
|
+
this.invalidateSessionInitializations();
|
|
1018
|
+
this.stopPromise = this.doStop(this.startPromise);
|
|
1019
|
+
try {
|
|
1020
|
+
return await this.stopPromise;
|
|
1021
|
+
} finally {
|
|
1022
|
+
this.stopPromise = null;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
async doStop(startup) {
|
|
1026
|
+
const errors = [];
|
|
1027
|
+
const activeSessions = [...this.sessions.values()];
|
|
1028
|
+
let sessionCleanupDeadlineTimer;
|
|
1029
|
+
const sessionCleanupDeadline = new Promise((resolve2) => {
|
|
1030
|
+
sessionCleanupDeadlineTimer = setTimeout(
|
|
1031
|
+
() => resolve2("timeout"),
|
|
1032
|
+
RUNTIME_SHUTDOWN_TIMEOUT_MS
|
|
1033
|
+
);
|
|
1034
|
+
});
|
|
1035
|
+
for (const session of activeSessions) {
|
|
1036
|
+
const sessionId = session.sessionId;
|
|
1037
|
+
let lastError = null;
|
|
1038
|
+
let attempts = 0;
|
|
1039
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
1040
|
+
if (this.connectionClosed) {
|
|
1041
|
+
lastError = null;
|
|
1042
|
+
break;
|
|
1043
|
+
}
|
|
1044
|
+
attempts = attempt;
|
|
1045
|
+
try {
|
|
1046
|
+
const outcome = await Promise.race([
|
|
1047
|
+
session.disconnect().then(() => "disconnected"),
|
|
1048
|
+
sessionCleanupDeadline
|
|
1049
|
+
]);
|
|
1050
|
+
if (outcome === "timeout") {
|
|
1051
|
+
lastError = new Error(
|
|
1052
|
+
`session.detach did not complete within the ${RUNTIME_SHUTDOWN_TIMEOUT_MS}ms shutdown timeout`
|
|
1053
|
+
);
|
|
1054
|
+
break;
|
|
1055
|
+
}
|
|
1056
|
+
lastError = null;
|
|
1057
|
+
break;
|
|
1058
|
+
} catch (error) {
|
|
1059
|
+
if (this.connectionClosed) {
|
|
1060
|
+
lastError = null;
|
|
1061
|
+
break;
|
|
1062
|
+
}
|
|
1063
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
1064
|
+
if (attempt < 3) {
|
|
1065
|
+
const delay = 100 * Math.pow(2, attempt - 1);
|
|
1066
|
+
await new Promise((resolve2) => setTimeout(resolve2, delay));
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
if (lastError) {
|
|
1071
|
+
errors.push(
|
|
1072
|
+
new Error(
|
|
1073
|
+
`Failed to disconnect session ${sessionId} after ${attempts} ${attempts === 1 ? "attempt" : "attempts"}: ${lastError.message}`
|
|
1074
|
+
)
|
|
1075
|
+
);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
clearTimeout(sessionCleanupDeadlineTimer);
|
|
1079
|
+
for (const session of /* @__PURE__ */ new Set([...activeSessions, ...this.sessions.values()])) {
|
|
1080
|
+
session._markDisconnected();
|
|
1081
|
+
}
|
|
1082
|
+
this.sessions.clear();
|
|
1083
|
+
this.abortPendingShellAuthenticationRequests();
|
|
1084
|
+
this.githubTokenProviders.clear();
|
|
1085
|
+
this.requestAdapter?.cancelPending();
|
|
1086
|
+
this.abortPendingMemoryStores();
|
|
1087
|
+
if (this.connection && !this.connectionClosed && (this.cliProcess || this.ffiHost) && !this.isExternalServer) {
|
|
1088
|
+
const runtimeShutdownStart = Date.now();
|
|
1089
|
+
const shutdownPromise = this.rpc.runtime.shutdown();
|
|
1090
|
+
void shutdownPromise.catch(() => void 0);
|
|
1091
|
+
try {
|
|
1092
|
+
await withTimeout(
|
|
1093
|
+
shutdownPromise,
|
|
1094
|
+
RUNTIME_SHUTDOWN_TIMEOUT_MS,
|
|
1095
|
+
`runtime.shutdown timed out after ${RUNTIME_SHUTDOWN_TIMEOUT_MS}ms`
|
|
1096
|
+
);
|
|
1097
|
+
this.logDebugTiming(
|
|
1098
|
+
"CopilotClient.stop runtime shutdown complete",
|
|
1099
|
+
runtimeShutdownStart
|
|
1100
|
+
);
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
this.logDebugTiming(
|
|
1103
|
+
"CopilotClient.stop runtime shutdown failed",
|
|
1104
|
+
runtimeShutdownStart
|
|
1105
|
+
);
|
|
1106
|
+
errors.push(
|
|
1107
|
+
new Error(
|
|
1108
|
+
`Failed to gracefully shut down runtime: ${error instanceof Error ? error.message : String(error)}`
|
|
1109
|
+
)
|
|
1110
|
+
);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
if (this.messageWriter) {
|
|
1114
|
+
this.messageWriter.suppressWriteErrors = true;
|
|
1115
|
+
}
|
|
1116
|
+
if (this.connection) {
|
|
1117
|
+
try {
|
|
1118
|
+
this.connection.dispose();
|
|
1119
|
+
} catch (error) {
|
|
1120
|
+
errors.push(
|
|
1121
|
+
new Error(
|
|
1122
|
+
`Failed to dispose connection: ${error instanceof Error ? error.message : String(error)}`
|
|
1123
|
+
)
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
this.connection = null;
|
|
1127
|
+
this.messageWriter = null;
|
|
1128
|
+
this._rpc = null;
|
|
1129
|
+
this._internalRpc = null;
|
|
1130
|
+
}
|
|
1131
|
+
this.modelsCache = { models: null, lock: Promise.resolve() };
|
|
1132
|
+
if (this.socket) {
|
|
1133
|
+
const socket = this.socket;
|
|
1134
|
+
this.socket = null;
|
|
1135
|
+
try {
|
|
1136
|
+
if (!socket.destroyed) {
|
|
1137
|
+
let timeout;
|
|
1138
|
+
try {
|
|
1139
|
+
await new Promise((resolve2) => {
|
|
1140
|
+
socket.once("close", () => resolve2());
|
|
1141
|
+
if (this.connectionClosed) {
|
|
1142
|
+
socket.destroy();
|
|
1143
|
+
} else {
|
|
1144
|
+
timeout = setTimeout(
|
|
1145
|
+
() => socket.destroy(),
|
|
1146
|
+
RUNTIME_SHUTDOWN_TIMEOUT_MS
|
|
1147
|
+
);
|
|
1148
|
+
socket.end();
|
|
1149
|
+
}
|
|
1150
|
+
});
|
|
1151
|
+
} finally {
|
|
1152
|
+
if (timeout !== void 0) clearTimeout(timeout);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
errors.push(
|
|
1157
|
+
new Error(
|
|
1158
|
+
`Failed to close socket: ${error instanceof Error ? error.message : String(error)}`
|
|
1159
|
+
)
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
if (this.cliProcess && !this.isExternalServer) {
|
|
1164
|
+
const child = this.cliProcess;
|
|
1165
|
+
if (this.connectionConfig.kind === "stdio" && child.stdin && child.exitCode == null && child.signalCode == null) {
|
|
1166
|
+
const gracefulExitStart = Date.now();
|
|
1167
|
+
try {
|
|
1168
|
+
child.stdin.end();
|
|
1169
|
+
const exited = await waitForChildExit(child, RUNTIME_SHUTDOWN_TIMEOUT_MS);
|
|
1170
|
+
this.logDebugTiming(
|
|
1171
|
+
exited ? "CopilotClient.stop graceful stdio exit complete" : "CopilotClient.stop graceful stdio exit timed out; terminating child",
|
|
1172
|
+
gracefulExitStart
|
|
1173
|
+
);
|
|
1174
|
+
} catch (error) {
|
|
1175
|
+
errors.push(
|
|
1176
|
+
new Error(
|
|
1177
|
+
`Failed to close CLI stdin: ${error instanceof Error ? error.message : String(error)}`
|
|
1178
|
+
)
|
|
1179
|
+
);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
try {
|
|
1183
|
+
if (child.exitCode == null && child.signalCode == null) {
|
|
1184
|
+
child.kill();
|
|
1185
|
+
if (!await waitForChildExit(child, RUNTIME_SHUTDOWN_TIMEOUT_MS)) {
|
|
1186
|
+
errors.push(
|
|
1187
|
+
new Error(
|
|
1188
|
+
`Timed out waiting for CLI process to exit after kill: ${RUNTIME_SHUTDOWN_TIMEOUT_MS}ms`
|
|
1189
|
+
)
|
|
1190
|
+
);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
errors.push(
|
|
1195
|
+
new Error(
|
|
1196
|
+
`Failed to kill CLI process: ${error instanceof Error ? error.message : String(error)}`
|
|
1197
|
+
)
|
|
1198
|
+
);
|
|
1199
|
+
} finally {
|
|
1200
|
+
if (this.cliProcess === child) {
|
|
1201
|
+
this.cliProcess = null;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
if (this.ffiHost) {
|
|
1206
|
+
const host = this.ffiHost;
|
|
1207
|
+
this.ffiHost = null;
|
|
1208
|
+
try {
|
|
1209
|
+
await host.dispose();
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
errors.push(
|
|
1212
|
+
new Error(
|
|
1213
|
+
`Failed to dispose in-process runtime host: ${error instanceof Error ? error.message : String(error)}`
|
|
1214
|
+
)
|
|
1215
|
+
);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
if (this.cliStartTimeout) {
|
|
1219
|
+
clearTimeout(this.cliStartTimeout);
|
|
1220
|
+
this.cliStartTimeout = null;
|
|
1221
|
+
}
|
|
1222
|
+
if (startup) {
|
|
1223
|
+
await Promise.allSettled([startup]);
|
|
1224
|
+
}
|
|
1225
|
+
this.state = "disconnected";
|
|
1226
|
+
this.runtimePort = null;
|
|
1227
|
+
this.stderrBuffer = "";
|
|
1228
|
+
this.processExitPromise = null;
|
|
1229
|
+
this.disconnectHosts();
|
|
1230
|
+
return errors;
|
|
1231
|
+
}
|
|
1232
|
+
/**
|
|
1233
|
+
* Alias for {@link stop} that lets `CopilotClient` participate in `await using`
|
|
1234
|
+
* blocks for automatic cleanup.
|
|
1235
|
+
*
|
|
1236
|
+
* @example
|
|
1237
|
+
* ```typescript
|
|
1238
|
+
* await using client = new CopilotClient({ mode: "coding-agent" });
|
|
1239
|
+
* const session = await client.createSession({ onPermissionRequest: approveAll });
|
|
1240
|
+
* await session.sendAndWait("Hello");
|
|
1241
|
+
* // client.stop() is called automatically when the block exits.
|
|
1242
|
+
* ```
|
|
1243
|
+
*/
|
|
1244
|
+
async [Symbol.asyncDispose]() {
|
|
1245
|
+
await this.stop();
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Forcefully stops the CLI server without graceful cleanup.
|
|
1249
|
+
*
|
|
1250
|
+
* Use this when {@link stop} fails or takes too long. This method:
|
|
1251
|
+
* - Clears all sessions immediately without destroying them
|
|
1252
|
+
* - Force closes the connection
|
|
1253
|
+
* - Sends SIGKILL to the CLI process (if spawned by this client)
|
|
1254
|
+
* - Waits for the spawned CLI process to exit
|
|
1255
|
+
*
|
|
1256
|
+
* @returns Resolves after disconnection and spawned-process exit; later starts
|
|
1257
|
+
* wait for pending startup cleanup.
|
|
1258
|
+
* @throws If the spawned CLI process cannot be terminated
|
|
1259
|
+
*
|
|
1260
|
+
* @example
|
|
1261
|
+
* ```typescript
|
|
1262
|
+
* // If normal stop hangs, force stop
|
|
1263
|
+
* const stopPromise = client.stop();
|
|
1264
|
+
* const timeout = new Promise((_, reject) =>
|
|
1265
|
+
* setTimeout(() => reject(new Error("Timeout")), 5000)
|
|
1266
|
+
* );
|
|
1267
|
+
*
|
|
1268
|
+
* try {
|
|
1269
|
+
* await Promise.race([stopPromise, timeout]);
|
|
1270
|
+
* } catch {
|
|
1271
|
+
* await client.forceStop();
|
|
1272
|
+
* }
|
|
1273
|
+
* ```
|
|
1274
|
+
*/
|
|
1275
|
+
async forceStop() {
|
|
1276
|
+
if (this.forceStopPromise) {
|
|
1277
|
+
return this.forceStopPromise;
|
|
1278
|
+
}
|
|
1279
|
+
if (!this.sessionInitializationLifetime.signal.aborted) {
|
|
1280
|
+
this.shutdownCanceledStartup = this.startPromise;
|
|
1281
|
+
}
|
|
1282
|
+
this.invalidateSessionInitializations();
|
|
1283
|
+
this.forceStopPromise = this.doForceStop();
|
|
1284
|
+
try {
|
|
1285
|
+
await this.forceStopPromise;
|
|
1286
|
+
} finally {
|
|
1287
|
+
this.forceStopPromise = null;
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
async doForceStop() {
|
|
1291
|
+
this.forceStopping = true;
|
|
1292
|
+
this.disconnectHosts();
|
|
1293
|
+
for (const session of this.sessions.values()) {
|
|
1294
|
+
session._markDisconnected();
|
|
1295
|
+
}
|
|
1296
|
+
this.sessions.clear();
|
|
1297
|
+
this.abortPendingShellAuthenticationRequests();
|
|
1298
|
+
this.githubTokenProviders.clear();
|
|
1299
|
+
this.requestAdapter?.cancelPending();
|
|
1300
|
+
this.abortPendingMemoryStores();
|
|
1301
|
+
if (this.messageWriter) {
|
|
1302
|
+
this.messageWriter.suppressWriteErrors = true;
|
|
1303
|
+
}
|
|
1304
|
+
if (this.connection) {
|
|
1305
|
+
try {
|
|
1306
|
+
this.connection.dispose();
|
|
1307
|
+
} catch {
|
|
1308
|
+
}
|
|
1309
|
+
this.connection = null;
|
|
1310
|
+
this.messageWriter = null;
|
|
1311
|
+
this._rpc = null;
|
|
1312
|
+
this._internalRpc = null;
|
|
1313
|
+
}
|
|
1314
|
+
this.modelsCache = { models: null, lock: Promise.resolve() };
|
|
1315
|
+
if (this.socket) {
|
|
1316
|
+
try {
|
|
1317
|
+
this.socket.destroy();
|
|
1318
|
+
} catch {
|
|
1319
|
+
}
|
|
1320
|
+
this.socket = null;
|
|
1321
|
+
}
|
|
1322
|
+
if (this.ffiHost) {
|
|
1323
|
+
const host = this.ffiHost;
|
|
1324
|
+
this.ffiHost = null;
|
|
1325
|
+
try {
|
|
1326
|
+
await host.dispose();
|
|
1327
|
+
} catch {
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
if (this.cliStartTimeout) {
|
|
1331
|
+
clearTimeout(this.cliStartTimeout);
|
|
1332
|
+
this.cliStartTimeout = null;
|
|
1333
|
+
}
|
|
1334
|
+
this.state = "disconnected";
|
|
1335
|
+
this.runtimePort = null;
|
|
1336
|
+
this.stderrBuffer = "";
|
|
1337
|
+
this.processExitPromise = null;
|
|
1338
|
+
await this.killCliProcess();
|
|
1339
|
+
}
|
|
1340
|
+
/** Sends SIGKILL to the spawned CLI process, if it is still running, and waits for it to exit. */
|
|
1341
|
+
async killCliProcess() {
|
|
1342
|
+
if (!this.cliProcess || this.isExternalServer) {
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
const child = this.cliProcess;
|
|
1346
|
+
if (child.exitCode == null && child.signalCode == null) {
|
|
1347
|
+
child.kill("SIGKILL");
|
|
1348
|
+
if (!await waitForChildExit(child, RUNTIME_SHUTDOWN_TIMEOUT_MS)) {
|
|
1349
|
+
throw new Error(
|
|
1350
|
+
`Timed out waiting for CLI process to exit after SIGKILL: ${RUNTIME_SHUTDOWN_TIMEOUT_MS}ms`
|
|
1351
|
+
);
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
if (this.cliProcess === child) {
|
|
1355
|
+
this.cliProcess = null;
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Creates a new conversation session with the Copilot CLI.
|
|
1360
|
+
*
|
|
1361
|
+
* Sessions maintain conversation state, handle events, and manage tool execution.
|
|
1362
|
+
* If the client is not connected, this method automatically starts the connection.
|
|
1363
|
+
*
|
|
1364
|
+
* @param config - Optional configuration for the session
|
|
1365
|
+
* @returns A promise that resolves with the created session
|
|
1366
|
+
* @throws Error if the client fails to start
|
|
1367
|
+
*
|
|
1368
|
+
* @example
|
|
1369
|
+
* ```typescript
|
|
1370
|
+
* // Basic session
|
|
1371
|
+
* const session = await client.createSession({ onPermissionRequest: approveAll });
|
|
1372
|
+
*
|
|
1373
|
+
* // Session with model and tools
|
|
1374
|
+
* const session = await client.createSession({
|
|
1375
|
+
* onPermissionRequest: approveAll,
|
|
1376
|
+
* model: "gpt-5.4",
|
|
1377
|
+
* tools: [{
|
|
1378
|
+
* name: "get_weather",
|
|
1379
|
+
* description: "Get weather for a location",
|
|
1380
|
+
* parameters: { type: "object", properties: { location: { type: "string" } } },
|
|
1381
|
+
* handler: async (args) => ({ temperature: 72 })
|
|
1382
|
+
* }]
|
|
1383
|
+
* });
|
|
1384
|
+
* ```
|
|
1385
|
+
*/
|
|
1386
|
+
/**
|
|
1387
|
+
* Normalizes session-level tool filter options. Converts {@link ToolSet}
|
|
1388
|
+
* instances to plain string arrays, rejects misuse (bare `"*"`) and the
|
|
1389
|
+
* missing-availableTools case in `mode = "empty"`.
|
|
1390
|
+
*
|
|
1391
|
+
* @internal
|
|
1392
|
+
*/
|
|
1393
|
+
resolveToolFilterOptions(config) {
|
|
1394
|
+
const availableTools = toolFilterListToArray(config.availableTools);
|
|
1395
|
+
const excludedTools = toolFilterListToArray(config.excludedTools);
|
|
1396
|
+
validateToolFilterList("availableTools", availableTools);
|
|
1397
|
+
validateToolFilterList("excludedTools", excludedTools);
|
|
1398
|
+
if (this.options.mode === "empty") {
|
|
1399
|
+
if (availableTools === void 0) {
|
|
1400
|
+
throw new Error(
|
|
1401
|
+
"CopilotClient is in mode: 'empty' but the session config did not specify 'availableTools'. Empty mode requires every session to explicitly opt into the tools it wants \u2014 e.g. `new ToolSet().addBuiltIn(BuiltInTools.Isolated)`."
|
|
1402
|
+
);
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
return { availableTools, excludedTools };
|
|
1406
|
+
}
|
|
1407
|
+
/** Mode-specific defaults spread under the caller's config (app values win). */
|
|
1408
|
+
configDefaultsForMode() {
|
|
1409
|
+
if (this.options.mode === "empty") {
|
|
1410
|
+
return {
|
|
1411
|
+
enableSessionTelemetry: false,
|
|
1412
|
+
mcpOAuthTokenStorage: "in-memory",
|
|
1413
|
+
skipEmbeddingRetrieval: true,
|
|
1414
|
+
embeddingCacheStorage: "in-memory",
|
|
1415
|
+
enableOnDemandInstructionDiscovery: false,
|
|
1416
|
+
enableFileHooks: false,
|
|
1417
|
+
enableHostGitOperations: false,
|
|
1418
|
+
enableSessionStore: false,
|
|
1419
|
+
enableSkills: false,
|
|
1420
|
+
memory: { enabled: false },
|
|
1421
|
+
customAgentsLocalOnly: true
|
|
1422
|
+
};
|
|
1423
|
+
}
|
|
1424
|
+
return {};
|
|
1425
|
+
}
|
|
1426
|
+
/** Mode-specific default for enableExperimentalMode. */
|
|
1427
|
+
experimentalModeForMode(supplied) {
|
|
1428
|
+
return this.options.mode === "empty" ? supplied ?? false : supplied;
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* Returns the systemMessage config to use, adjusted for the current mode.
|
|
1432
|
+
* In empty mode we ensure the environment_context section is removed
|
|
1433
|
+
* unless the app has already taken control of it. `append` (and
|
|
1434
|
+
* unspecified) mode is promoted to `customize` so we can also strip
|
|
1435
|
+
* environment_context; the caller's `content` is preserved verbatim
|
|
1436
|
+
* because the runtime appends it as additional instructions in both
|
|
1437
|
+
* customize and append modes.
|
|
1438
|
+
*/
|
|
1439
|
+
getSystemMessageConfigForMode(supplied) {
|
|
1440
|
+
if (this.options.mode !== "empty") return supplied;
|
|
1441
|
+
if (!supplied) {
|
|
1442
|
+
return {
|
|
1443
|
+
mode: "customize",
|
|
1444
|
+
sections: { environment_context: { action: "remove" } }
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
switch (supplied.mode) {
|
|
1448
|
+
case "replace":
|
|
1449
|
+
return supplied;
|
|
1450
|
+
case "customize":
|
|
1451
|
+
if (supplied.sections?.environment_context) return supplied;
|
|
1452
|
+
return {
|
|
1453
|
+
...supplied,
|
|
1454
|
+
sections: {
|
|
1455
|
+
...supplied.sections,
|
|
1456
|
+
environment_context: { action: "remove" }
|
|
1457
|
+
}
|
|
1458
|
+
};
|
|
1459
|
+
case "append":
|
|
1460
|
+
case void 0:
|
|
1461
|
+
return {
|
|
1462
|
+
mode: "customize",
|
|
1463
|
+
content: supplied.content,
|
|
1464
|
+
sections: { environment_context: { action: "remove" } }
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* Mode-specific options applied via session.options.update after create/resume.
|
|
1470
|
+
*
|
|
1471
|
+
* In empty mode, defaults the four overridable feature flags to safe values
|
|
1472
|
+
* (caller values from `config` win). `installedPlugins=[]` is unconditional
|
|
1473
|
+
* in empty mode. `includedBuiltinSkills` defaults to `[]`, but callers can
|
|
1474
|
+
* explicitly allow selected runtime-bundled skills.
|
|
1475
|
+
*/
|
|
1476
|
+
async updateSessionOptionsForMode(session, config) {
|
|
1477
|
+
const patch = {};
|
|
1478
|
+
if (this.options.mode === "empty") {
|
|
1479
|
+
patch.skipCustomInstructions = config.skipCustomInstructions ?? true;
|
|
1480
|
+
patch.customAgentsLocalOnly = config.customAgentsLocalOnly ?? true;
|
|
1481
|
+
patch.coauthorEnabled = config.coauthorEnabled ?? false;
|
|
1482
|
+
patch.manageScheduleEnabled = config.manageScheduleEnabled ?? false;
|
|
1483
|
+
patch.installedPlugins = [];
|
|
1484
|
+
patch.includedBuiltinSkills = config.includedBuiltinSkills ?? [];
|
|
1485
|
+
} else {
|
|
1486
|
+
if (config.skipCustomInstructions !== void 0)
|
|
1487
|
+
patch.skipCustomInstructions = config.skipCustomInstructions;
|
|
1488
|
+
if (config.customAgentsLocalOnly !== void 0)
|
|
1489
|
+
patch.customAgentsLocalOnly = config.customAgentsLocalOnly;
|
|
1490
|
+
if (config.coauthorEnabled !== void 0)
|
|
1491
|
+
patch.coauthorEnabled = config.coauthorEnabled;
|
|
1492
|
+
if (config.manageScheduleEnabled !== void 0)
|
|
1493
|
+
patch.manageScheduleEnabled = config.manageScheduleEnabled;
|
|
1494
|
+
if (config.includedBuiltinSkills !== void 0)
|
|
1495
|
+
patch.includedBuiltinSkills = config.includedBuiltinSkills;
|
|
1496
|
+
}
|
|
1497
|
+
if (Object.keys(patch).length === 0) {
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
try {
|
|
1501
|
+
await session.rpc.options.update(patch);
|
|
1502
|
+
} catch (e) {
|
|
1503
|
+
try {
|
|
1504
|
+
await session.disconnect();
|
|
1505
|
+
} catch {
|
|
1506
|
+
}
|
|
1507
|
+
throw e;
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
async createSession(config) {
|
|
1511
|
+
if (config.autoModeRecovery && typeof config.onAutoModeSwitchRequest !== "function") {
|
|
1512
|
+
throw new Error("autoModeRecovery requires onAutoModeSwitchRequest");
|
|
1513
|
+
}
|
|
1514
|
+
if (config.gitHubToken !== void 0 && config.gitHubTokenProvider !== void 0) {
|
|
1515
|
+
throw new Error("gitHubToken and gitHubTokenProvider are mutually exclusive");
|
|
1516
|
+
}
|
|
1517
|
+
if (config.cloud != null && config.skillProvider) {
|
|
1518
|
+
throw new Error("Skill providers are not supported for cloud sessions.");
|
|
1519
|
+
}
|
|
1520
|
+
const storeMemory = requestedMemoryStore(config.memory);
|
|
1521
|
+
if (config.cloud != null && storeMemory) {
|
|
1522
|
+
throw new Error("Memory stores are not supported for cloud sessions.");
|
|
1523
|
+
}
|
|
1524
|
+
const signal = await this.getSessionInitializationSignal();
|
|
1525
|
+
const sessionId = config.sessionId ?? (config.cloud != null ? void 0 : randomUUID());
|
|
1526
|
+
if (sessionId === void 0) {
|
|
1527
|
+
return this.createSessionInternal(config, signal);
|
|
1528
|
+
}
|
|
1529
|
+
const release = await this.acquireSessionInitialization(sessionId, signal);
|
|
1530
|
+
try {
|
|
1531
|
+
signal.throwIfAborted();
|
|
1532
|
+
return await this.createSessionInternal({ ...config, sessionId }, signal);
|
|
1533
|
+
} finally {
|
|
1534
|
+
release();
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
invalidateSessionInitializations() {
|
|
1538
|
+
this.sessionInitializationGeneration++;
|
|
1539
|
+
this.sessionInitializationLifetime.abort(
|
|
1540
|
+
new Error("Client disconnected during session initialization")
|
|
1541
|
+
);
|
|
1542
|
+
}
|
|
1543
|
+
async getSessionInitializationSignal() {
|
|
1544
|
+
const generation = this.sessionInitializationGeneration;
|
|
1545
|
+
const starting = !this.connection || this.startPromise ? this.start() : void 0;
|
|
1546
|
+
await starting;
|
|
1547
|
+
if (generation !== this.sessionInitializationGeneration) {
|
|
1548
|
+
throw new Error("Client disconnected during session initialization");
|
|
1549
|
+
}
|
|
1550
|
+
const signal = this.sessionInitializationLifetime.signal;
|
|
1551
|
+
signal.throwIfAborted();
|
|
1552
|
+
return signal;
|
|
1553
|
+
}
|
|
1554
|
+
async runInitializationCallback(sessionId, callback) {
|
|
1555
|
+
const context = sessionId === void 0 ? void 0 : { sessionId, active: true };
|
|
1556
|
+
try {
|
|
1557
|
+
return await this.sessionInitializationContext.run(context, callback);
|
|
1558
|
+
} finally {
|
|
1559
|
+
if (context) context.active = false;
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
async acquireSessionInitialization(sessionId, signal) {
|
|
1563
|
+
signal.throwIfAborted();
|
|
1564
|
+
const predecessors = [...this.sessionInitializations].filter(([id]) => sessionIdsOverlap(id, sessionId)).map(([, pending]) => pending);
|
|
1565
|
+
const previous = predecessors.length ? Promise.all(predecessors).then(() => {
|
|
1566
|
+
}) : void 0;
|
|
1567
|
+
const context = this.sessionInitializationContext.getStore();
|
|
1568
|
+
if (previous && context?.active && sessionIdsOverlap(context.sessionId, sessionId)) {
|
|
1569
|
+
throw new Error(
|
|
1570
|
+
`Cannot re-enter session initialization for ${sessionId} from its callback`
|
|
1571
|
+
);
|
|
1572
|
+
}
|
|
1573
|
+
let finish;
|
|
1574
|
+
const current = new Promise((resolve2) => {
|
|
1575
|
+
finish = resolve2;
|
|
1576
|
+
});
|
|
1577
|
+
const tail = previous ? previous.then(() => current) : current;
|
|
1578
|
+
this.sessionInitializations.set(sessionId, tail);
|
|
1579
|
+
void tail.then(() => {
|
|
1580
|
+
if (this.sessionInitializations.get(sessionId) === tail) {
|
|
1581
|
+
this.sessionInitializations.delete(sessionId);
|
|
1582
|
+
}
|
|
1583
|
+
});
|
|
1584
|
+
try {
|
|
1585
|
+
if (previous) {
|
|
1586
|
+
let cancel;
|
|
1587
|
+
try {
|
|
1588
|
+
await new Promise((resolve2, reject) => {
|
|
1589
|
+
cancel = () => reject(signal.reason);
|
|
1590
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
1591
|
+
void previous.then(resolve2);
|
|
1592
|
+
});
|
|
1593
|
+
} finally {
|
|
1594
|
+
signal.removeEventListener("abort", cancel);
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
signal.throwIfAborted();
|
|
1598
|
+
const cleanupError = this.connection ? [...this.failedAutoModeRecoveryCleanups.get(this.connection) ?? []].find(
|
|
1599
|
+
([id]) => sessionIdsOverlap(id, sessionId)
|
|
1600
|
+
)?.[1] : void 0;
|
|
1601
|
+
if (cleanupError) {
|
|
1602
|
+
throw new Error(
|
|
1603
|
+
`Cannot initialize session ${sessionId} after failed Auto recovery cleanup; stop and restart the client before retrying`,
|
|
1604
|
+
{ cause: cleanupError }
|
|
1605
|
+
);
|
|
1606
|
+
}
|
|
1607
|
+
return finish;
|
|
1608
|
+
} catch (error) {
|
|
1609
|
+
finish();
|
|
1610
|
+
throw error;
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
async createSessionInternal(config, signal) {
|
|
1614
|
+
signal.throwIfAborted();
|
|
1615
|
+
const connection = this.connection;
|
|
1616
|
+
const storeMemory = requestedMemoryStore(config.memory);
|
|
1617
|
+
const modeDefaults = this.configDefaultsForMode();
|
|
1618
|
+
config = { ...modeDefaults, ...config };
|
|
1619
|
+
config.customAgentsLocalOnly ??= modeDefaults.customAgentsLocalOnly;
|
|
1620
|
+
config.systemMessage = this.getSystemMessageConfigForMode(config.systemMessage);
|
|
1621
|
+
const callerSessionId = config.sessionId;
|
|
1622
|
+
const useServerGeneratedId = config.cloud != null && callerSessionId == null;
|
|
1623
|
+
const localSessionId = useServerGeneratedId ? void 0 : callerSessionId ?? randomUUID();
|
|
1624
|
+
const toolFilterOptions = this.resolveToolFilterOptions(config);
|
|
1625
|
+
const gitHubTokenProviderRegistrationId = this.registerGitHubTokenProvider(
|
|
1626
|
+
config.gitHubTokenProvider,
|
|
1627
|
+
localSessionId
|
|
1628
|
+
);
|
|
1629
|
+
const {
|
|
1630
|
+
wireProvider: bearerWireProvider,
|
|
1631
|
+
wireProviders: bearerWireProviders,
|
|
1632
|
+
callbacks: bearerTokenCallbacks
|
|
1633
|
+
} = extractBearerTokenProviders(config.provider, config.providers);
|
|
1634
|
+
const { wirePayload: wireSystemMessage, transformCallbacks } = extractTransformCallbacks(
|
|
1635
|
+
config.systemMessage
|
|
1636
|
+
);
|
|
1637
|
+
let replacedSession;
|
|
1638
|
+
const initializeSession = (sessionId) => {
|
|
1639
|
+
const s = new CopilotSession(sessionId, connection, void 0, this.onGetTraceContext, {
|
|
1640
|
+
mcpAuthHandler: config.onMcpAuthRequest,
|
|
1641
|
+
managedSettingsEnabled: config.enableManagedSettings === true || config.managedSettings !== void 0,
|
|
1642
|
+
onDisconnected: gitHubTokenProviderRegistrationId === void 0 ? void 0 : () => this.githubTokenProviders.delete(gitHubTokenProviderRegistrationId)
|
|
1643
|
+
});
|
|
1644
|
+
s.registerTools(config.tools);
|
|
1645
|
+
s.registerCanvases(config.canvases);
|
|
1646
|
+
s.registerCommands(config.commands);
|
|
1647
|
+
if (bearerTokenCallbacks.size > 0) {
|
|
1648
|
+
s.registerBearerTokenProviders(bearerTokenCallbacks);
|
|
1649
|
+
}
|
|
1650
|
+
s.registerPermissionHandler(config.onPermissionRequest);
|
|
1651
|
+
if (config.onUserInputRequest) {
|
|
1652
|
+
s.registerUserInputHandler(config.onUserInputRequest);
|
|
1653
|
+
}
|
|
1654
|
+
if (config.onShellAuthenticationRequest) {
|
|
1655
|
+
s.registerShellAuthenticationHandler(config.onShellAuthenticationRequest);
|
|
1656
|
+
}
|
|
1657
|
+
if (config.onElicitationRequest) {
|
|
1658
|
+
s.registerElicitationHandler(config.onElicitationRequest);
|
|
1659
|
+
}
|
|
1660
|
+
if (config.onExitPlanModeRequest) {
|
|
1661
|
+
s.registerExitPlanModeHandler(config.onExitPlanModeRequest);
|
|
1662
|
+
}
|
|
1663
|
+
if (config.onAutoModeSwitchRequest) {
|
|
1664
|
+
s.registerAutoModeSwitchHandler(config.onAutoModeSwitchRequest);
|
|
1665
|
+
}
|
|
1666
|
+
if (config.hooks) {
|
|
1667
|
+
s.registerHooks(config.hooks);
|
|
1668
|
+
}
|
|
1669
|
+
if (config.skillProvider) {
|
|
1670
|
+
s.registerSkillProvider(config.skillProvider);
|
|
1671
|
+
}
|
|
1672
|
+
s._registerMemoryStore(storeMemory);
|
|
1673
|
+
if (transformCallbacks) {
|
|
1674
|
+
s.registerTransformCallbacks(transformCallbacks);
|
|
1675
|
+
}
|
|
1676
|
+
if (config.onEvent) {
|
|
1677
|
+
s.on(config.onEvent);
|
|
1678
|
+
}
|
|
1679
|
+
this.setupSessionFs(s, config);
|
|
1680
|
+
signal.throwIfAborted();
|
|
1681
|
+
replacedSession = this.sessions.get(sessionId);
|
|
1682
|
+
this.sessions.set(sessionId, s);
|
|
1683
|
+
return s;
|
|
1684
|
+
};
|
|
1685
|
+
let session;
|
|
1686
|
+
let registeredId;
|
|
1687
|
+
let uninitializedCloudSessionId;
|
|
1688
|
+
let releaseCloudInitialization;
|
|
1689
|
+
if (localSessionId !== void 0) {
|
|
1690
|
+
try {
|
|
1691
|
+
session = initializeSession(localSessionId);
|
|
1692
|
+
registeredId = localSessionId;
|
|
1693
|
+
} catch (error) {
|
|
1694
|
+
if (gitHubTokenProviderRegistrationId !== void 0) {
|
|
1695
|
+
this.githubTokenProviders.delete(gitHubTokenProviderRegistrationId);
|
|
1696
|
+
}
|
|
1697
|
+
throw error;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
try {
|
|
1701
|
+
const traceContext = await this.runInitializationCallback(
|
|
1702
|
+
localSessionId,
|
|
1703
|
+
() => getTraceContext(this.onGetTraceContext)
|
|
1704
|
+
);
|
|
1705
|
+
signal.throwIfAborted();
|
|
1706
|
+
const response = await connection.sendRequest("session.create", {
|
|
1707
|
+
...traceContext,
|
|
1708
|
+
model: config.model,
|
|
1709
|
+
allowedModels: config.allowedModels,
|
|
1710
|
+
sessionId: localSessionId,
|
|
1711
|
+
name: config.name,
|
|
1712
|
+
clientName: config.clientName,
|
|
1713
|
+
reasoningEffort: config.reasoningEffort,
|
|
1714
|
+
allowMultipleToolCalls: config.allowMultipleToolCalls,
|
|
1715
|
+
reasoningSummary: config.reasoningSummary,
|
|
1716
|
+
isExperimentalMode: this.experimentalModeForMode(config.enableExperimentalMode),
|
|
1717
|
+
contextTier: config.contextTier,
|
|
1718
|
+
tools: config.tools?.map((tool) => ({
|
|
1719
|
+
name: tool.name,
|
|
1720
|
+
title: tool.title,
|
|
1721
|
+
description: tool.description,
|
|
1722
|
+
parameters: toJsonSchema(tool.parameters),
|
|
1723
|
+
overridesBuiltInTool: tool.overridesBuiltInTool,
|
|
1724
|
+
skipPermission: tool.skipPermission,
|
|
1725
|
+
hasHandler: !!tool.handler,
|
|
1726
|
+
defer: tool.defer,
|
|
1727
|
+
metadata: tool.metadata,
|
|
1728
|
+
isTerminal: tool.isTerminal,
|
|
1729
|
+
idempotent: tool.idempotent,
|
|
1730
|
+
namespace: tool.namespace
|
|
1731
|
+
})),
|
|
1732
|
+
toolSearch: config.toolSearch,
|
|
1733
|
+
imageGeneration: config.imageGeneration,
|
|
1734
|
+
canvases: config.canvases?.map((canvas) => canvas.declaration),
|
|
1735
|
+
requestCanvasRenderer: config.requestCanvasRenderer,
|
|
1736
|
+
requestExtensions: config.requestExtensions,
|
|
1737
|
+
extensionSdkPath: config.extensionSdkPath,
|
|
1738
|
+
extensionInfo: config.extensionInfo,
|
|
1739
|
+
canvasProvider: config.canvasProvider,
|
|
1740
|
+
commands: config.commands?.map((cmd) => ({
|
|
1741
|
+
name: cmd.name,
|
|
1742
|
+
description: cmd.description ?? ""
|
|
1743
|
+
})),
|
|
1744
|
+
systemMessage: wireSystemMessage,
|
|
1745
|
+
availableTools: toolFilterOptions.availableTools,
|
|
1746
|
+
excludedTools: toolFilterOptions.excludedTools,
|
|
1747
|
+
excludedBuiltinAgents: config.excludedBuiltinAgents,
|
|
1748
|
+
includedBuiltinAgents: config.includedBuiltinAgents,
|
|
1749
|
+
provider: bearerWireProvider,
|
|
1750
|
+
capi: config.capi,
|
|
1751
|
+
providers: bearerWireProviders,
|
|
1752
|
+
models: config.models,
|
|
1753
|
+
enableSessionTelemetry: config.enableSessionTelemetry,
|
|
1754
|
+
enableCitations: config.enableCitations,
|
|
1755
|
+
enableFileChangeTracking: config.enableFileChangeTracking,
|
|
1756
|
+
sessionLimits: config.sessionLimits,
|
|
1757
|
+
autopilot: config.autopilot,
|
|
1758
|
+
modelCapabilities: config.modelCapabilities,
|
|
1759
|
+
largeOutput: toWireLargeOutput(config.largeOutput),
|
|
1760
|
+
requestPermission: !!config.onPermissionRequest,
|
|
1761
|
+
requestUserInput: !!config.onUserInputRequest,
|
|
1762
|
+
requestElicitation: !!config.onElicitationRequest,
|
|
1763
|
+
...config.onShellAuthenticationRequest ? { requestShellAuthentication: true } : {},
|
|
1764
|
+
askUserVariant: config.askUserVariant,
|
|
1765
|
+
...config.enableMcpApps ? { requestMcpApps: true } : {},
|
|
1766
|
+
...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
|
|
1767
|
+
requestExitPlanMode: !!config.onExitPlanModeRequest,
|
|
1768
|
+
requestAutoModeSwitch: !!config.onAutoModeSwitchRequest,
|
|
1769
|
+
...config.autoModeRecovery ? { requestAutoModeRecovery: true } : {},
|
|
1770
|
+
hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),
|
|
1771
|
+
workingDirectory: config.workingDirectory,
|
|
1772
|
+
trustWorkingDirectory: config.trustWorkingDirectory,
|
|
1773
|
+
additionalDirectories: config.additionalDirectories,
|
|
1774
|
+
streaming: config.streaming,
|
|
1775
|
+
includeSubAgentStreamingEvents: config.includeSubAgentStreamingEvents ?? true,
|
|
1776
|
+
...this.onGitHubTelemetry != null ? { enableGitHubTelemetryForwarding: true } : {},
|
|
1777
|
+
mcpServers: toWireMcpServers(config.mcpServers),
|
|
1778
|
+
...config.diagnostics !== void 0 ? { diagnostics: config.diagnostics } : {},
|
|
1779
|
+
...config.lifecycleDiagnostics !== void 0 ? { lifecycleDiagnostics: config.lifecycleDiagnostics } : {},
|
|
1780
|
+
mcpOAuthTokenStorage: config.mcpOAuthTokenStorage,
|
|
1781
|
+
authClientIdMetadataUrl: config.authClientIdMetadataUrl,
|
|
1782
|
+
envValueMode: "direct",
|
|
1783
|
+
customAgents: toWireCustomAgents(config.customAgents),
|
|
1784
|
+
customAgentsLocalOnly: config.customAgentsLocalOnly,
|
|
1785
|
+
defaultAgent: config.defaultAgent,
|
|
1786
|
+
agent: config.agent,
|
|
1787
|
+
configDir: config.configDirectory,
|
|
1788
|
+
enableConfigDiscovery: config.enableConfigDiscovery,
|
|
1789
|
+
refreshCustomInstructions: config.refreshCustomInstructions,
|
|
1790
|
+
skipEmbeddingRetrieval: config.skipEmbeddingRetrieval,
|
|
1791
|
+
embeddingCacheStorage: config.embeddingCacheStorage,
|
|
1792
|
+
organizationCustomInstructions: config.organizationCustomInstructions,
|
|
1793
|
+
enableOnDemandInstructionDiscovery: config.enableOnDemandInstructionDiscovery,
|
|
1794
|
+
enableFileHooks: config.enableFileHooks,
|
|
1795
|
+
enableHostGitOperations: config.enableHostGitOperations,
|
|
1796
|
+
enableSessionStore: config.enableSessionStore,
|
|
1797
|
+
enableSkills: config.enableSkills,
|
|
1798
|
+
skillDirectories: config.skillDirectories,
|
|
1799
|
+
...config.skillProvider ? { hasSkillProvider: true } : {},
|
|
1800
|
+
...storeMemory ? { hasMemoryStore: true } : {},
|
|
1801
|
+
agentDirectories: config.agentDirectories,
|
|
1802
|
+
hookDirectories: config.hookDirectories,
|
|
1803
|
+
pluginDirectories: config.pluginDirectories,
|
|
1804
|
+
instructionDirectories: config.instructionDirectories,
|
|
1805
|
+
disabledSkills: config.disabledSkills,
|
|
1806
|
+
disabledMcpServers: config.disabledMcpServers,
|
|
1807
|
+
sandboxConfig: config.sandboxConfig,
|
|
1808
|
+
infiniteSessions: config.infiniteSessions,
|
|
1809
|
+
memory: toWireMemoryConfiguration(config.memory),
|
|
1810
|
+
gitHubToken: config.gitHubToken,
|
|
1811
|
+
gitHubTokenProviderRegistrationId,
|
|
1812
|
+
cloud: config.cloud,
|
|
1813
|
+
featureFlags: config.featureFlags,
|
|
1814
|
+
expAssignments: config.expAssignments,
|
|
1815
|
+
enableManagedSettings: config.enableManagedSettings,
|
|
1816
|
+
excludedManagedSettings: config.excludedManagedSettings,
|
|
1817
|
+
enforceManagedModelDefaults: config.enforceManagedModelDefaults,
|
|
1818
|
+
interactiveUser: config.interactiveUser,
|
|
1819
|
+
permissionMode: config.permissionMode,
|
|
1820
|
+
managedSettings: config.managedSettings
|
|
1821
|
+
});
|
|
1822
|
+
const {
|
|
1823
|
+
sessionId: returnedSessionId,
|
|
1824
|
+
workspacePath,
|
|
1825
|
+
capabilities,
|
|
1826
|
+
permissionModeResult
|
|
1827
|
+
} = response;
|
|
1828
|
+
if (!returnedSessionId) {
|
|
1829
|
+
throw new Error("session.create response did not include a sessionId");
|
|
1830
|
+
}
|
|
1831
|
+
if (localSessionId !== void 0 && localSessionId !== returnedSessionId) {
|
|
1832
|
+
throw new Error(
|
|
1833
|
+
`session.create returned sessionId ${returnedSessionId} but the caller requested ${localSessionId}`
|
|
1834
|
+
);
|
|
1835
|
+
}
|
|
1836
|
+
if (session === void 0) {
|
|
1837
|
+
uninitializedCloudSessionId = returnedSessionId;
|
|
1838
|
+
}
|
|
1839
|
+
signal.throwIfAborted();
|
|
1840
|
+
if (session === void 0) {
|
|
1841
|
+
releaseCloudInitialization = await this.acquireSessionInitialization(
|
|
1842
|
+
returnedSessionId,
|
|
1843
|
+
signal
|
|
1844
|
+
);
|
|
1845
|
+
signal.throwIfAborted();
|
|
1846
|
+
session = initializeSession(returnedSessionId);
|
|
1847
|
+
registeredId = returnedSessionId;
|
|
1848
|
+
}
|
|
1849
|
+
this.assignGitHubTokenProvider(gitHubTokenProviderRegistrationId, returnedSessionId);
|
|
1850
|
+
session.setCapabilities(capabilities);
|
|
1851
|
+
if (config.autoModeRecovery) {
|
|
1852
|
+
await this.requireAutoModeRecovery(session, connection);
|
|
1853
|
+
}
|
|
1854
|
+
if (config.onMcpAuthRequest) {
|
|
1855
|
+
await connection.sendRequest("session.eventLog.registerInterest", {
|
|
1856
|
+
sessionId: returnedSessionId,
|
|
1857
|
+
eventType: "mcp.oauth_required"
|
|
1858
|
+
});
|
|
1859
|
+
}
|
|
1860
|
+
session["_workspacePath"] = workspacePath;
|
|
1861
|
+
session.setPermissionModeResult(permissionModeResult);
|
|
1862
|
+
await this.updateSessionOptionsForMode(session, config);
|
|
1863
|
+
signal.throwIfAborted();
|
|
1864
|
+
uninitializedCloudSessionId = void 0;
|
|
1865
|
+
this.commitGitHubTokenProvider(returnedSessionId, gitHubTokenProviderRegistrationId);
|
|
1866
|
+
} catch (e) {
|
|
1867
|
+
session?._markDisconnected();
|
|
1868
|
+
if (registeredId !== void 0 && session !== void 0) {
|
|
1869
|
+
const current = this.sessions.get(registeredId);
|
|
1870
|
+
if (current === session) {
|
|
1871
|
+
if (replacedSession && !replacedSession._isDisconnected()) {
|
|
1872
|
+
this.sessions.set(registeredId, replacedSession);
|
|
1873
|
+
} else {
|
|
1874
|
+
this.sessions.delete(registeredId);
|
|
1875
|
+
}
|
|
1876
|
+
} else if (current === void 0) {
|
|
1877
|
+
replacedSession?._markDisconnected();
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
if (gitHubTokenProviderRegistrationId !== void 0) {
|
|
1881
|
+
this.githubTokenProviders.delete(gitHubTokenProviderRegistrationId);
|
|
1882
|
+
}
|
|
1883
|
+
if (uninitializedCloudSessionId !== void 0) {
|
|
1884
|
+
try {
|
|
1885
|
+
await withTimeout(
|
|
1886
|
+
this.requestSessionDeletion(connection, uninitializedCloudSessionId),
|
|
1887
|
+
CLOUD_SESSION_CLEANUP_TIMEOUT_MS,
|
|
1888
|
+
`session.delete timed out after ${CLOUD_SESSION_CLEANUP_TIMEOUT_MS}ms`
|
|
1889
|
+
);
|
|
1890
|
+
} catch (cleanupError) {
|
|
1891
|
+
const failure = new AggregateError(
|
|
1892
|
+
[e, cleanupError],
|
|
1893
|
+
`Failed to initialize and delete cloud session ${uninitializedCloudSessionId}`
|
|
1894
|
+
);
|
|
1895
|
+
if (config.autoModeRecovery) {
|
|
1896
|
+
this.recordFailedAutoModeRecoveryCleanup(
|
|
1897
|
+
connection,
|
|
1898
|
+
uninitializedCloudSessionId,
|
|
1899
|
+
failure
|
|
1900
|
+
);
|
|
1901
|
+
}
|
|
1902
|
+
throw failure;
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
throw e;
|
|
1906
|
+
} finally {
|
|
1907
|
+
releaseCloudInitialization?.();
|
|
1908
|
+
}
|
|
1909
|
+
if (session._isDisconnected()) {
|
|
1910
|
+
this.forgetSession(session);
|
|
1911
|
+
} else {
|
|
1912
|
+
session._setReleaseFromClient(this.forgetSession.bind(this, session));
|
|
1913
|
+
}
|
|
1914
|
+
for (const entry of this.hostHandoffs.values()) {
|
|
1915
|
+
if (entry.requestedSessionId === session.sessionId) {
|
|
1916
|
+
entry.configs.set(session, config);
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
return session;
|
|
1920
|
+
}
|
|
1921
|
+
/**
|
|
1922
|
+
* Resumes an existing conversation session by its ID.
|
|
1923
|
+
*
|
|
1924
|
+
* This allows you to continue a previous conversation, maintaining all
|
|
1925
|
+
* conversation history. The session must have been previously created
|
|
1926
|
+
* and not deleted.
|
|
1927
|
+
*
|
|
1928
|
+
* @param sessionId - The ID of the session to resume
|
|
1929
|
+
* @param config - Optional configuration for the resumed session
|
|
1930
|
+
* @returns A promise that resolves with the resumed session
|
|
1931
|
+
* @throws Error if the session does not exist or the client is not connected
|
|
1932
|
+
*
|
|
1933
|
+
* @example
|
|
1934
|
+
* ```typescript
|
|
1935
|
+
* // Resume a previous session
|
|
1936
|
+
* const session = await client.resumeSession("session-123", { onPermissionRequest: approveAll });
|
|
1937
|
+
*
|
|
1938
|
+
* // Resume with new tools
|
|
1939
|
+
* const session = await client.resumeSession("session-123", {
|
|
1940
|
+
* onPermissionRequest: approveAll,
|
|
1941
|
+
* tools: [myNewTool]
|
|
1942
|
+
* });
|
|
1943
|
+
* ```
|
|
1944
|
+
*/
|
|
1945
|
+
async resumeSession(sessionId, config) {
|
|
1946
|
+
return this.resumeSessionInternal(sessionId, config);
|
|
1947
|
+
}
|
|
1948
|
+
/** @internal */
|
|
1949
|
+
async resumeSessionForExtension(sessionId, config, contributions = {}, extensionOptions) {
|
|
1950
|
+
const session = await this.resumeSessionInternal(
|
|
1951
|
+
sessionId,
|
|
1952
|
+
config,
|
|
1953
|
+
contributions,
|
|
1954
|
+
extensionOptions
|
|
1955
|
+
);
|
|
1956
|
+
if (process.env.COPILOT_EXTENSION_INITIALIZATION === "module") {
|
|
1957
|
+
const connection = this.connection;
|
|
1958
|
+
Object.defineProperty(globalThis, /* @__PURE__ */ Symbol.for("copilot.extension.initialized"), {
|
|
1959
|
+
configurable: true,
|
|
1960
|
+
value: () => connection.sendNotification("extension.initialized")
|
|
1961
|
+
});
|
|
1962
|
+
}
|
|
1963
|
+
return session;
|
|
1964
|
+
}
|
|
1965
|
+
async resumeSessionInternal(sessionId, config, contributions = {}, extensionOptions) {
|
|
1966
|
+
if (config.autoModeRecovery && typeof config.onAutoModeSwitchRequest !== "function") {
|
|
1967
|
+
throw new Error("autoModeRecovery requires onAutoModeSwitchRequest");
|
|
1968
|
+
}
|
|
1969
|
+
if (config.gitHubToken !== void 0 && config.gitHubTokenProvider !== void 0) {
|
|
1970
|
+
throw new Error("gitHubToken and gitHubTokenProvider are mutually exclusive");
|
|
1971
|
+
}
|
|
1972
|
+
requestedMemoryStore(config.memory);
|
|
1973
|
+
const signal = await this.getSessionInitializationSignal();
|
|
1974
|
+
const release = await this.acquireSessionInitialization(sessionId, signal);
|
|
1975
|
+
try {
|
|
1976
|
+
signal.throwIfAborted();
|
|
1977
|
+
return await this.resumeSessionWithInitialization(
|
|
1978
|
+
sessionId,
|
|
1979
|
+
config,
|
|
1980
|
+
contributions,
|
|
1981
|
+
signal,
|
|
1982
|
+
extensionOptions
|
|
1983
|
+
);
|
|
1984
|
+
} finally {
|
|
1985
|
+
release();
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
async resumeSessionWithInitialization(sessionId, config, contributions, signal, extensionOptions) {
|
|
1989
|
+
const { workflows } = contributions;
|
|
1990
|
+
const storeMemory = requestedMemoryStore(config.memory);
|
|
1991
|
+
signal.throwIfAborted();
|
|
1992
|
+
const connection = this.connection;
|
|
1993
|
+
const resolveAliases = config.autoModeRecovery === true && !this.sessionFsConfig;
|
|
1994
|
+
if (resolveAliases && isAbbreviatedUuidPrefix(sessionId)) {
|
|
1995
|
+
const resolved = await connection.sendRequest(
|
|
1996
|
+
"sessions.findByPrefix",
|
|
1997
|
+
{ prefix: sessionId, configDir: config.configDirectory }
|
|
1998
|
+
);
|
|
1999
|
+
const canonicalId = resolved?.sessionId;
|
|
2000
|
+
if (typeof canonicalId !== "string" || canonicalId.length === 0) {
|
|
2001
|
+
throw new Error(`No unique session matches prefix ${sessionId}`);
|
|
2002
|
+
}
|
|
2003
|
+
if (!canonicalId.toLowerCase().startsWith(sessionId.toLowerCase())) {
|
|
2004
|
+
throw new Error(`Runtime returned an unrelated session ID for prefix ${sessionId}`);
|
|
2005
|
+
}
|
|
2006
|
+
sessionId = canonicalId;
|
|
2007
|
+
signal.throwIfAborted();
|
|
2008
|
+
}
|
|
2009
|
+
const session = new CopilotSession(
|
|
2010
|
+
sessionId,
|
|
2011
|
+
connection,
|
|
2012
|
+
void 0,
|
|
2013
|
+
this.onGetTraceContext,
|
|
2014
|
+
{
|
|
2015
|
+
mcpAuthHandler: config.onMcpAuthRequest,
|
|
2016
|
+
managedSettingsEnabled: config.enableManagedSettings === true || config.managedSettings !== void 0
|
|
2017
|
+
}
|
|
2018
|
+
);
|
|
2019
|
+
session.registerTools(config.tools);
|
|
2020
|
+
session.registerCanvases(config.canvases);
|
|
2021
|
+
session.registerCommands(config.commands);
|
|
2022
|
+
session.registerWorkflows(workflows);
|
|
2023
|
+
const {
|
|
2024
|
+
wireProvider: bearerWireProvider,
|
|
2025
|
+
wireProviders: bearerWireProviders,
|
|
2026
|
+
callbacks: bearerTokenCallbacks
|
|
2027
|
+
} = extractBearerTokenProviders(config.provider, config.providers);
|
|
2028
|
+
if (bearerTokenCallbacks.size > 0) {
|
|
2029
|
+
session.registerBearerTokenProviders(bearerTokenCallbacks);
|
|
2030
|
+
}
|
|
2031
|
+
session.registerPermissionHandler(config.onPermissionRequest);
|
|
2032
|
+
if (config.onUserInputRequest) {
|
|
2033
|
+
session.registerUserInputHandler(config.onUserInputRequest);
|
|
2034
|
+
}
|
|
2035
|
+
if (config.onShellAuthenticationRequest) {
|
|
2036
|
+
session.registerShellAuthenticationHandler(config.onShellAuthenticationRequest);
|
|
2037
|
+
}
|
|
2038
|
+
if (config.onElicitationRequest) {
|
|
2039
|
+
session.registerElicitationHandler(config.onElicitationRequest);
|
|
2040
|
+
}
|
|
2041
|
+
if (config.onExitPlanModeRequest) {
|
|
2042
|
+
session.registerExitPlanModeHandler(config.onExitPlanModeRequest);
|
|
2043
|
+
}
|
|
2044
|
+
if (config.onAutoModeSwitchRequest) {
|
|
2045
|
+
session.registerAutoModeSwitchHandler(config.onAutoModeSwitchRequest);
|
|
2046
|
+
}
|
|
2047
|
+
if (config.hooks) {
|
|
2048
|
+
session.registerHooks(config.hooks);
|
|
2049
|
+
}
|
|
2050
|
+
if (config.skillProvider) {
|
|
2051
|
+
session.registerSkillProvider(config.skillProvider);
|
|
2052
|
+
}
|
|
2053
|
+
session._registerMemoryStore(storeMemory);
|
|
2054
|
+
const modeDefaults = this.configDefaultsForMode();
|
|
2055
|
+
config = { ...modeDefaults, ...config };
|
|
2056
|
+
config.customAgentsLocalOnly ??= modeDefaults.customAgentsLocalOnly;
|
|
2057
|
+
config.systemMessage = this.getSystemMessageConfigForMode(config.systemMessage);
|
|
2058
|
+
const { wirePayload: wireSystemMessage, transformCallbacks } = extractTransformCallbacks(
|
|
2059
|
+
config.systemMessage
|
|
2060
|
+
);
|
|
2061
|
+
if (transformCallbacks) {
|
|
2062
|
+
session.registerTransformCallbacks(transformCallbacks);
|
|
2063
|
+
}
|
|
2064
|
+
if (config.onEvent) {
|
|
2065
|
+
session.on(config.onEvent);
|
|
2066
|
+
}
|
|
2067
|
+
const toolFilterOptions = this.resolveToolFilterOptions(config);
|
|
2068
|
+
this.setupSessionFs(session, config);
|
|
2069
|
+
signal.throwIfAborted();
|
|
2070
|
+
const requestedSessionId = sessionId;
|
|
2071
|
+
let replacedRequestedSession;
|
|
2072
|
+
let replacedSession;
|
|
2073
|
+
let releaseCanonicalInitialization;
|
|
2074
|
+
let keepResumedSessionOnRecoveryRejection = false;
|
|
2075
|
+
const gitHubTokenProviderRegistrationId = this.registerGitHubTokenProvider(
|
|
2076
|
+
config.gitHubTokenProvider,
|
|
2077
|
+
sessionId
|
|
2078
|
+
);
|
|
2079
|
+
if (gitHubTokenProviderRegistrationId !== void 0) {
|
|
2080
|
+
session._setOnDisconnected(
|
|
2081
|
+
() => this.githubTokenProviders.delete(gitHubTokenProviderRegistrationId)
|
|
2082
|
+
);
|
|
2083
|
+
}
|
|
2084
|
+
try {
|
|
2085
|
+
const traceContext = await this.runInitializationCallback(
|
|
2086
|
+
sessionId,
|
|
2087
|
+
() => getTraceContext(this.onGetTraceContext)
|
|
2088
|
+
);
|
|
2089
|
+
signal.throwIfAborted();
|
|
2090
|
+
replacedRequestedSession = this.sessions.get(sessionId);
|
|
2091
|
+
replacedSession = replacedRequestedSession;
|
|
2092
|
+
this.sessions.set(sessionId, session);
|
|
2093
|
+
this.pendingSessionResumes.set(requestedSessionId, {
|
|
2094
|
+
session,
|
|
2095
|
+
connection,
|
|
2096
|
+
gitHubTokenProviderRegistrationId,
|
|
2097
|
+
resolveAliases
|
|
2098
|
+
});
|
|
2099
|
+
const response = await connection.sendRequest("session.resume", {
|
|
2100
|
+
allowedModels: config.allowedModels,
|
|
2101
|
+
...traceContext,
|
|
2102
|
+
sessionId,
|
|
2103
|
+
allowTranscriptRecovery: config.allowTranscriptRecovery,
|
|
2104
|
+
clientName: config.clientName,
|
|
2105
|
+
model: config.model,
|
|
2106
|
+
reasoningEffort: config.reasoningEffort,
|
|
2107
|
+
allowMultipleToolCalls: config.allowMultipleToolCalls,
|
|
2108
|
+
reasoningSummary: config.reasoningSummary,
|
|
2109
|
+
isExperimentalMode: this.experimentalModeForMode(config.enableExperimentalMode),
|
|
2110
|
+
contextTier: config.contextTier,
|
|
2111
|
+
systemMessage: wireSystemMessage,
|
|
2112
|
+
availableTools: toolFilterOptions.availableTools,
|
|
2113
|
+
excludedTools: toolFilterOptions.excludedTools,
|
|
2114
|
+
enableSessionTelemetry: config.enableSessionTelemetry,
|
|
2115
|
+
excludedBuiltinAgents: config.excludedBuiltinAgents,
|
|
2116
|
+
includedBuiltinAgents: config.includedBuiltinAgents,
|
|
2117
|
+
enableCitations: config.enableCitations,
|
|
2118
|
+
enableFileChangeTracking: config.enableFileChangeTracking,
|
|
2119
|
+
sessionLimits: config.sessionLimits,
|
|
2120
|
+
autopilot: config.autopilot,
|
|
2121
|
+
tools: config.tools?.map((tool) => ({
|
|
2122
|
+
name: tool.name,
|
|
2123
|
+
title: tool.title,
|
|
2124
|
+
description: tool.description,
|
|
2125
|
+
parameters: toJsonSchema(tool.parameters),
|
|
2126
|
+
overridesBuiltInTool: tool.overridesBuiltInTool,
|
|
2127
|
+
skipPermission: tool.skipPermission,
|
|
2128
|
+
hasHandler: !!tool.handler,
|
|
2129
|
+
defer: tool.defer,
|
|
2130
|
+
metadata: tool.metadata,
|
|
2131
|
+
isTerminal: tool.isTerminal,
|
|
2132
|
+
idempotent: tool.idempotent,
|
|
2133
|
+
namespace: tool.namespace
|
|
2134
|
+
})),
|
|
2135
|
+
toolSearch: config.toolSearch,
|
|
2136
|
+
imageGeneration: config.imageGeneration,
|
|
2137
|
+
canvases: config.canvases?.map((canvas) => canvas.declaration),
|
|
2138
|
+
workflows: workflows?.map(getWorkflowRegistration),
|
|
2139
|
+
requestCanvasRenderer: config.requestCanvasRenderer,
|
|
2140
|
+
requestExtensions: config.requestExtensions,
|
|
2141
|
+
extensionSdkPath: config.extensionSdkPath,
|
|
2142
|
+
extensionInfo: config.extensionInfo,
|
|
2143
|
+
canvasProvider: config.canvasProvider,
|
|
2144
|
+
commands: config.commands?.map((cmd) => ({
|
|
2145
|
+
name: cmd.name,
|
|
2146
|
+
description: cmd.description ?? ""
|
|
2147
|
+
})),
|
|
2148
|
+
provider: bearerWireProvider,
|
|
2149
|
+
capi: config.capi,
|
|
2150
|
+
providers: bearerWireProviders,
|
|
2151
|
+
models: config.models,
|
|
2152
|
+
modelCapabilities: config.modelCapabilities,
|
|
2153
|
+
largeOutput: toWireLargeOutput(config.largeOutput),
|
|
2154
|
+
requestPermission: config.onPermissionRequest !== defaultJoinSessionPermissionHandler,
|
|
2155
|
+
requestUserInput: !!config.onUserInputRequest,
|
|
2156
|
+
requestElicitation: !!config.onElicitationRequest,
|
|
2157
|
+
...config.onShellAuthenticationRequest ? { requestShellAuthentication: true } : {},
|
|
2158
|
+
askUserVariant: config.askUserVariant,
|
|
2159
|
+
...config.enableMcpApps ? { requestMcpApps: true } : {},
|
|
2160
|
+
...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
|
|
2161
|
+
requestExitPlanMode: !!config.onExitPlanModeRequest,
|
|
2162
|
+
requestAutoModeSwitch: !!config.onAutoModeSwitchRequest,
|
|
2163
|
+
...config.autoModeRecovery ? { requestAutoModeRecovery: true } : {},
|
|
2164
|
+
hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),
|
|
2165
|
+
workingDirectory: config.workingDirectory,
|
|
2166
|
+
additionalDirectories: config.additionalDirectories,
|
|
2167
|
+
configDir: config.configDirectory,
|
|
2168
|
+
enableConfigDiscovery: config.enableConfigDiscovery,
|
|
2169
|
+
skipEmbeddingRetrieval: config.skipEmbeddingRetrieval,
|
|
2170
|
+
embeddingCacheStorage: config.embeddingCacheStorage,
|
|
2171
|
+
organizationCustomInstructions: config.organizationCustomInstructions,
|
|
2172
|
+
enableOnDemandInstructionDiscovery: config.enableOnDemandInstructionDiscovery,
|
|
2173
|
+
enableFileHooks: config.enableFileHooks,
|
|
2174
|
+
enableHostGitOperations: config.enableHostGitOperations,
|
|
2175
|
+
enableSessionStore: config.enableSessionStore,
|
|
2176
|
+
enableSkills: config.enableSkills,
|
|
2177
|
+
streaming: config.streaming,
|
|
2178
|
+
includeSubAgentStreamingEvents: config.includeSubAgentStreamingEvents ?? true,
|
|
2179
|
+
...this.onGitHubTelemetry != null ? { enableGitHubTelemetryForwarding: true } : {},
|
|
2180
|
+
mcpServers: toWireMcpServers(config.mcpServers),
|
|
2181
|
+
...config.diagnostics !== void 0 ? { diagnostics: config.diagnostics } : {},
|
|
2182
|
+
...config.lifecycleDiagnostics !== void 0 ? { lifecycleDiagnostics: config.lifecycleDiagnostics } : {},
|
|
2183
|
+
mcpOAuthTokenStorage: config.mcpOAuthTokenStorage,
|
|
2184
|
+
authClientIdMetadataUrl: config.authClientIdMetadataUrl,
|
|
2185
|
+
envValueMode: "direct",
|
|
2186
|
+
customAgents: toWireCustomAgents(config.customAgents),
|
|
2187
|
+
customAgentsLocalOnly: config.customAgentsLocalOnly,
|
|
2188
|
+
defaultAgent: config.defaultAgent,
|
|
2189
|
+
agent: config.agent,
|
|
2190
|
+
skillDirectories: config.skillDirectories,
|
|
2191
|
+
...config.skillProvider ? { hasSkillProvider: true } : {},
|
|
2192
|
+
...storeMemory ? { hasMemoryStore: true } : {},
|
|
2193
|
+
agentDirectories: config.agentDirectories,
|
|
2194
|
+
hookDirectories: config.hookDirectories,
|
|
2195
|
+
pluginDirectories: config.pluginDirectories,
|
|
2196
|
+
instructionDirectories: config.instructionDirectories,
|
|
2197
|
+
disabledSkills: config.disabledSkills,
|
|
2198
|
+
disabledMcpServers: config.disabledMcpServers,
|
|
2199
|
+
sandboxConfig: config.sandboxConfig,
|
|
2200
|
+
infiniteSessions: config.infiniteSessions,
|
|
2201
|
+
memory: toWireMemoryConfiguration(config.memory),
|
|
2202
|
+
disableResume: config.suppressResumeEvent,
|
|
2203
|
+
continuePendingWork: config.continuePendingWork,
|
|
2204
|
+
gitHubToken: config.gitHubToken,
|
|
2205
|
+
gitHubTokenProviderRegistrationId,
|
|
2206
|
+
openCanvases: config.openCanvases,
|
|
2207
|
+
featureFlags: config.featureFlags,
|
|
2208
|
+
expAssignments: config.expAssignments,
|
|
2209
|
+
enableManagedSettings: config.enableManagedSettings,
|
|
2210
|
+
excludedManagedSettings: config.excludedManagedSettings,
|
|
2211
|
+
enforceManagedModelDefaults: config.enforceManagedModelDefaults,
|
|
2212
|
+
interactiveUser: config.interactiveUser,
|
|
2213
|
+
permissionMode: config.permissionMode,
|
|
2214
|
+
managedSettings: config.managedSettings,
|
|
2215
|
+
...extensionOptions?.requestedEnvironmentVariables ? {
|
|
2216
|
+
requestedEnvironmentVariables: extensionOptions.requestedEnvironmentVariables
|
|
2217
|
+
} : {}
|
|
2218
|
+
});
|
|
2219
|
+
const { sessionId: returnedSessionId } = response;
|
|
2220
|
+
if (returnedSessionId && returnedSessionId !== sessionId) {
|
|
2221
|
+
if (!sessionIdsOverlap(requestedSessionId, returnedSessionId)) {
|
|
2222
|
+
releaseCanonicalInitialization = await this.acquireSessionInitialization(
|
|
2223
|
+
returnedSessionId,
|
|
2224
|
+
signal
|
|
2225
|
+
);
|
|
2226
|
+
}
|
|
2227
|
+
replacedSession = this.sessions.get(returnedSessionId);
|
|
2228
|
+
if (this.sessions.get(requestedSessionId) === session) {
|
|
2229
|
+
if (replacedRequestedSession) {
|
|
2230
|
+
this.sessions.set(requestedSessionId, replacedRequestedSession);
|
|
2231
|
+
} else {
|
|
2232
|
+
this.sessions.delete(requestedSessionId);
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
session._setSessionId(returnedSessionId);
|
|
2236
|
+
sessionId = returnedSessionId;
|
|
2237
|
+
this.sessions.set(sessionId, session);
|
|
2238
|
+
this.assignGitHubTokenProvider(gitHubTokenProviderRegistrationId, sessionId);
|
|
2239
|
+
}
|
|
2240
|
+
signal.throwIfAborted();
|
|
2241
|
+
if (extensionOptions?.requestedEnvironmentVariables) {
|
|
2242
|
+
const requested = new Set(extensionOptions.requestedEnvironmentVariables);
|
|
2243
|
+
const { grantedEnvironmentVariables } = response;
|
|
2244
|
+
for (const [name, value] of Object.entries(grantedEnvironmentVariables ?? {})) {
|
|
2245
|
+
if (requested.has(name)) {
|
|
2246
|
+
process.env[name] = value;
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
const {
|
|
2251
|
+
workspacePath,
|
|
2252
|
+
capabilities,
|
|
2253
|
+
openCanvases,
|
|
2254
|
+
transcriptRecovery,
|
|
2255
|
+
permissionModeResult
|
|
2256
|
+
} = response;
|
|
2257
|
+
session["_workspacePath"] = workspacePath;
|
|
2258
|
+
session.setCapabilities(capabilities);
|
|
2259
|
+
if (config.autoModeRecovery) {
|
|
2260
|
+
keepResumedSessionOnRecoveryRejection = replacedSession !== void 0 && session.capabilities.ui?.autoModeRecovery !== true;
|
|
2261
|
+
await this.requireAutoModeRecovery(
|
|
2262
|
+
session,
|
|
2263
|
+
connection,
|
|
2264
|
+
replacedSession === void 0
|
|
2265
|
+
);
|
|
2266
|
+
}
|
|
2267
|
+
session.setOpenCanvases(openCanvases ?? []);
|
|
2268
|
+
session.setTranscriptRecovery(transcriptRecovery);
|
|
2269
|
+
session.setPermissionModeResult(permissionModeResult);
|
|
2270
|
+
if (config.onMcpAuthRequest) {
|
|
2271
|
+
await connection.sendRequest("session.eventLog.registerInterest", {
|
|
2272
|
+
sessionId,
|
|
2273
|
+
eventType: "mcp.oauth_required"
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
await this.updateSessionOptionsForMode(session, config);
|
|
2277
|
+
signal.throwIfAborted();
|
|
2278
|
+
this.commitGitHubTokenProvider(sessionId, gitHubTokenProviderRegistrationId);
|
|
2279
|
+
} catch (e) {
|
|
2280
|
+
if (!keepResumedSessionOnRecoveryRejection) {
|
|
2281
|
+
session._markDisconnected();
|
|
2282
|
+
}
|
|
2283
|
+
const current = this.sessions.get(sessionId);
|
|
2284
|
+
if (current === session) {
|
|
2285
|
+
if (replacedSession && !replacedSession._isDisconnected() && !keepResumedSessionOnRecoveryRejection) {
|
|
2286
|
+
this.sessions.set(sessionId, replacedSession);
|
|
2287
|
+
} else if (!keepResumedSessionOnRecoveryRejection) {
|
|
2288
|
+
this.sessions.delete(sessionId);
|
|
2289
|
+
}
|
|
2290
|
+
} else if (current === void 0) {
|
|
2291
|
+
replacedSession?._markDisconnected();
|
|
2292
|
+
}
|
|
2293
|
+
if (gitHubTokenProviderRegistrationId !== void 0) {
|
|
2294
|
+
if (keepResumedSessionOnRecoveryRejection) {
|
|
2295
|
+
this.commitGitHubTokenProvider(sessionId, gitHubTokenProviderRegistrationId);
|
|
2296
|
+
} else {
|
|
2297
|
+
this.githubTokenProviders.delete(gitHubTokenProviderRegistrationId);
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
throw e;
|
|
2301
|
+
} finally {
|
|
2302
|
+
if (this.pendingSessionResumes.get(requestedSessionId)?.session === session) {
|
|
2303
|
+
this.pendingSessionResumes.delete(requestedSessionId);
|
|
2304
|
+
}
|
|
2305
|
+
releaseCanonicalInitialization?.();
|
|
2306
|
+
}
|
|
2307
|
+
if (session._isDisconnected()) {
|
|
2308
|
+
this.forgetSession(session);
|
|
2309
|
+
} else {
|
|
2310
|
+
session._setReleaseFromClient(this.forgetSession.bind(this, session));
|
|
2311
|
+
}
|
|
2312
|
+
for (const entry of this.hostHandoffs.values()) {
|
|
2313
|
+
if (entry.requestedSessionId === session.sessionId) {
|
|
2314
|
+
entry.configs.set(session, { ...config, sessionId });
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
return session;
|
|
2318
|
+
}
|
|
2319
|
+
async requireAutoModeRecovery(session, connection, detachOnFailure = true) {
|
|
2320
|
+
if (session.capabilities.ui?.autoModeRecovery === true) {
|
|
2321
|
+
return;
|
|
2322
|
+
}
|
|
2323
|
+
const error = new Error("The runtime does not support autoModeRecovery");
|
|
2324
|
+
if (!detachOnFailure) {
|
|
2325
|
+
throw error;
|
|
2326
|
+
}
|
|
2327
|
+
const cancellation = new CancellationTokenSource();
|
|
2328
|
+
try {
|
|
2329
|
+
const response = await withTimeout(
|
|
2330
|
+
connection.sendRequest(
|
|
2331
|
+
"session.detach",
|
|
2332
|
+
{ sessionId: session.sessionId },
|
|
2333
|
+
cancellation.token
|
|
2334
|
+
),
|
|
2335
|
+
AUTO_MODE_RECOVERY_CLEANUP_TIMEOUT_MS,
|
|
2336
|
+
`session.detach timed out after ${AUTO_MODE_RECOVERY_CLEANUP_TIMEOUT_MS}ms`
|
|
2337
|
+
);
|
|
2338
|
+
if (!response.success) {
|
|
2339
|
+
throw new Error(`Failed to detach session: ${response.error || "Unknown error"}`);
|
|
2340
|
+
}
|
|
2341
|
+
} catch (cleanupError) {
|
|
2342
|
+
const failure = new AggregateError([error, cleanupError], error.message);
|
|
2343
|
+
this.recordFailedAutoModeRecoveryCleanup(connection, session.sessionId, failure);
|
|
2344
|
+
throw failure;
|
|
2345
|
+
} finally {
|
|
2346
|
+
cancellation.cancel();
|
|
2347
|
+
cancellation.dispose();
|
|
2348
|
+
session._markDisconnected();
|
|
2349
|
+
}
|
|
2350
|
+
throw error;
|
|
2351
|
+
}
|
|
2352
|
+
recordFailedAutoModeRecoveryCleanup(connection, sessionId, failure) {
|
|
2353
|
+
let failed = this.failedAutoModeRecoveryCleanups.get(connection);
|
|
2354
|
+
if (!failed) {
|
|
2355
|
+
failed = /* @__PURE__ */ new Map();
|
|
2356
|
+
this.failedAutoModeRecoveryCleanups.set(connection, failed);
|
|
2357
|
+
}
|
|
2358
|
+
failed.set(sessionId, failure);
|
|
2359
|
+
}
|
|
2360
|
+
/**
|
|
2361
|
+
* Start a complete AHP listener hosted in-process by this runtime.
|
|
2362
|
+
*
|
|
2363
|
+
* This connection owns the host. Disposing it or disconnecting the client
|
|
2364
|
+
* stops the listener without deleting sessions. The host uses a separate
|
|
2365
|
+
* SDK connection to the same runtime, not another runtime process.
|
|
2366
|
+
* Only one AHP host may own a compute-scoped catalog in an effective Copilot home
|
|
2367
|
+
* at a time. Other SDK clients and sessions remain usable in that home.
|
|
2368
|
+
* Select localServer, githubEnvironment, or both. An empty localServer
|
|
2369
|
+
* selects 127.0.0.1 on an available port. `onExit` runs at most once; owner disconnection cannot
|
|
2370
|
+
* acknowledge listener cleanup over the disconnected transport.
|
|
2371
|
+
*
|
|
2372
|
+
* @experimental
|
|
2373
|
+
*/
|
|
2374
|
+
async startAhpHost(options) {
|
|
2375
|
+
const authentication = options?.authentication;
|
|
2376
|
+
if (!authentication || !["github", "none", "custom"].includes(authentication.mode)) {
|
|
2377
|
+
throw new Error("An explicit authentication mode is required");
|
|
2378
|
+
}
|
|
2379
|
+
if (authentication.mode === "custom" && (typeof authentication.requireIdentity !== "string" || !authentication.requireIdentity.trim() || typeof authentication.authenticate !== "function")) {
|
|
2380
|
+
throw new Error(
|
|
2381
|
+
"Custom authentication requires a nonempty requireIdentity and authenticate callback"
|
|
2382
|
+
);
|
|
2383
|
+
}
|
|
2384
|
+
if (authentication.mode !== "github" && options.githubEnvironment) {
|
|
2385
|
+
throw new Error("githubEnvironment requires github authentication");
|
|
2386
|
+
}
|
|
2387
|
+
if (!options?.localServer && !options?.githubEnvironment) {
|
|
2388
|
+
throw new Error("At least one of localServer or githubEnvironment is required");
|
|
2389
|
+
}
|
|
2390
|
+
if (this.state !== "connected") {
|
|
2391
|
+
await this.start();
|
|
2392
|
+
}
|
|
2393
|
+
const rpc = this.rpc;
|
|
2394
|
+
const hostId = randomUUID();
|
|
2395
|
+
if (authentication.mode === "custom") {
|
|
2396
|
+
this.hostAuthenticators.set(hostId, { ...authentication });
|
|
2397
|
+
}
|
|
2398
|
+
const {
|
|
2399
|
+
computeId,
|
|
2400
|
+
workspace,
|
|
2401
|
+
allowCreatingNewSessions,
|
|
2402
|
+
localServer,
|
|
2403
|
+
githubEnvironment,
|
|
2404
|
+
onExit,
|
|
2405
|
+
createSession,
|
|
2406
|
+
resumeSession,
|
|
2407
|
+
onSessionReleased
|
|
2408
|
+
} = options;
|
|
2409
|
+
if (createSession || resumeSession) {
|
|
2410
|
+
this.hostSessionFactories.set(hostId, {
|
|
2411
|
+
createSession,
|
|
2412
|
+
resumeSession,
|
|
2413
|
+
onSessionReleased,
|
|
2414
|
+
policy: {
|
|
2415
|
+
mode: authentication.mode,
|
|
2416
|
+
requireIdentity: authentication.mode === "custom" ? authentication.requireIdentity : void 0
|
|
2417
|
+
}
|
|
2418
|
+
});
|
|
2419
|
+
}
|
|
2420
|
+
if (onExit) {
|
|
2421
|
+
this.hostExitCallbacks.set(hostId, onExit);
|
|
2422
|
+
}
|
|
2423
|
+
try {
|
|
2424
|
+
const info = await rpc.host.start({
|
|
2425
|
+
hostId,
|
|
2426
|
+
authentication: authentication.mode === "custom" ? { mode: "custom", requireIdentity: authentication.requireIdentity } : { mode: authentication.mode },
|
|
2427
|
+
computeId,
|
|
2428
|
+
workspace,
|
|
2429
|
+
localServer,
|
|
2430
|
+
githubEnvironment,
|
|
2431
|
+
sessionFactory: createSession ? true : void 0,
|
|
2432
|
+
resumeFactory: resumeSession ? true : void 0,
|
|
2433
|
+
allowCreatingNewSessions
|
|
2434
|
+
});
|
|
2435
|
+
return new AhpHost(
|
|
2436
|
+
info,
|
|
2437
|
+
async () => {
|
|
2438
|
+
await rpc.host.dispose({ hostId });
|
|
2439
|
+
},
|
|
2440
|
+
(sessionId) => rpc.host.publishSession({ hostId, sessionId }),
|
|
2441
|
+
() => rpc.host.listSessions({ hostId }),
|
|
2442
|
+
(sessionId) => rpc.host.unpublishSession({ hostId, sessionId }),
|
|
2443
|
+
async (allowed) => {
|
|
2444
|
+
await rpc.host.setSessionCreationPolicy({
|
|
2445
|
+
hostId,
|
|
2446
|
+
allowCreatingNewSessions: allowed
|
|
2447
|
+
});
|
|
2448
|
+
}
|
|
2449
|
+
);
|
|
2450
|
+
} catch (error) {
|
|
2451
|
+
this.hostExitCallbacks.delete(hostId);
|
|
2452
|
+
this.releaseHostSessions(hostId);
|
|
2453
|
+
throw error;
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
handleHostExit(exit) {
|
|
2457
|
+
this.releaseHostSessions(exit.hostId);
|
|
2458
|
+
const onExit = this.hostExitCallbacks.get(exit.hostId);
|
|
2459
|
+
if (onExit) {
|
|
2460
|
+
this.hostExitCallbacks.delete(exit.hostId);
|
|
2461
|
+
const reportError = (error) => {
|
|
2462
|
+
console.error("AHP host exit callback failed", { hostId: exit.hostId, error });
|
|
2463
|
+
};
|
|
2464
|
+
try {
|
|
2465
|
+
void Promise.resolve(onExit(exit)).catch(reportError);
|
|
2466
|
+
} catch (error) {
|
|
2467
|
+
reportError(error);
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
abortPendingMemoryStores() {
|
|
2472
|
+
for (const controller of this.pendingMemoryStores) {
|
|
2473
|
+
controller.abort();
|
|
2474
|
+
}
|
|
2475
|
+
this.pendingMemoryStores.clear();
|
|
2476
|
+
}
|
|
2477
|
+
disconnectHosts() {
|
|
2478
|
+
for (const hostId of /* @__PURE__ */ new Set([
|
|
2479
|
+
...this.hostExitCallbacks.keys(),
|
|
2480
|
+
...this.hostSessionFactories.keys(),
|
|
2481
|
+
...this.hostAuthenticators.keys()
|
|
2482
|
+
])) {
|
|
2483
|
+
this.handleHostExit({
|
|
2484
|
+
hostId,
|
|
2485
|
+
reason: "ownerDisconnected",
|
|
2486
|
+
error: "Owner connection closed; runtime cleanup cannot be acknowledged on this connection."
|
|
2487
|
+
});
|
|
2488
|
+
}
|
|
2489
|
+
}
|
|
2490
|
+
releaseHostSessions(hostId) {
|
|
2491
|
+
this.hostAuthenticators.delete(hostId);
|
|
2492
|
+
for (const [requestId, entry] of this.hostAuthentications) {
|
|
2493
|
+
if (entry.hostId === hostId) {
|
|
2494
|
+
this.hostAuthentications.delete(requestId);
|
|
2495
|
+
entry.controller.abort();
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
this.hostSessionFactories.delete(hostId);
|
|
2499
|
+
for (const [handoffId, entry] of this.hostHandoffs) {
|
|
2500
|
+
if (entry.hostId === hostId) this.releaseHostSession(handoffId);
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
releaseHostSession(handoffId) {
|
|
2504
|
+
const entry = this.hostHandoffs.get(handoffId);
|
|
2505
|
+
if (!entry) return;
|
|
2506
|
+
this.hostHandoffs.delete(handoffId);
|
|
2507
|
+
entry.released = true;
|
|
2508
|
+
entry.configs.clear();
|
|
2509
|
+
entry.controller.abort();
|
|
2510
|
+
if (entry.session) this.notifyHostSessionReleased(entry);
|
|
2511
|
+
}
|
|
2512
|
+
notifyHostSessionReleased(entry) {
|
|
2513
|
+
const { session, onReleased } = entry;
|
|
2514
|
+
entry.session = void 0;
|
|
2515
|
+
if (session && onReleased) {
|
|
2516
|
+
try {
|
|
2517
|
+
void Promise.resolve(onReleased(session)).catch(() => {
|
|
2518
|
+
console.error("AHP session release callback failed");
|
|
2519
|
+
});
|
|
2520
|
+
} catch {
|
|
2521
|
+
console.error("AHP session release callback failed");
|
|
2522
|
+
}
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
async createHostSession(params) {
|
|
2526
|
+
const authentication = params.authentication;
|
|
2527
|
+
if (!authentication) {
|
|
2528
|
+
throw new Error("AHP session handoff authentication is required");
|
|
2529
|
+
}
|
|
2530
|
+
const options = this.hostSessionFactories.get(params.hostId);
|
|
2531
|
+
if (!(params.resume ? options?.resumeSession : options?.createSession) || this.hostHandoffs.has(params.handoffId)) {
|
|
2532
|
+
throw new Error("AHP session factory is unavailable or handoff already exists");
|
|
2533
|
+
}
|
|
2534
|
+
const policy = options.policy;
|
|
2535
|
+
const identity = authentication.identity;
|
|
2536
|
+
if (authentication.mode !== policy.mode || (authentication.mode === "none" ? identity !== void 0 : typeof identity !== "string" || !identity.trim()) || policy.mode === "custom" && identity !== policy.requireIdentity) {
|
|
2537
|
+
throw new Error("AHP trusted authentication does not match host policy");
|
|
2538
|
+
}
|
|
2539
|
+
const entry = {
|
|
2540
|
+
hostId: params.hostId,
|
|
2541
|
+
requestedSessionId: params.config.sessionId,
|
|
2542
|
+
controller: new AbortController(),
|
|
2543
|
+
configs: /* @__PURE__ */ new Map(),
|
|
2544
|
+
released: false,
|
|
2545
|
+
onReleased: options.onSessionReleased
|
|
2546
|
+
};
|
|
2547
|
+
this.hostHandoffs.set(params.handoffId, entry);
|
|
2548
|
+
const { configDir, ...config } = params.config;
|
|
2549
|
+
if (configDir !== void 0) config.configDirectory = configDir;
|
|
2550
|
+
const expected = structuredClone(config);
|
|
2551
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
2552
|
+
entry.controller.signal.addEventListener(
|
|
2553
|
+
"abort",
|
|
2554
|
+
() => {
|
|
2555
|
+
reject(new Error("AHP session handoff ended"));
|
|
2556
|
+
},
|
|
2557
|
+
{ once: true }
|
|
2558
|
+
);
|
|
2559
|
+
});
|
|
2560
|
+
const materialized = Promise.resolve().then(() => {
|
|
2561
|
+
if (params.resume) {
|
|
2562
|
+
const { sessionId, ...resumeConfig } = config;
|
|
2563
|
+
if (!sessionId) throw new Error("AHP resume requires sessionId");
|
|
2564
|
+
return options.resumeSession({
|
|
2565
|
+
authentication,
|
|
2566
|
+
sessionId,
|
|
2567
|
+
config: resumeConfig,
|
|
2568
|
+
signal: entry.controller.signal
|
|
2569
|
+
});
|
|
2570
|
+
}
|
|
2571
|
+
return options.createSession({
|
|
2572
|
+
authentication,
|
|
2573
|
+
config,
|
|
2574
|
+
signal: entry.controller.signal
|
|
2575
|
+
});
|
|
2576
|
+
}).then((session) => {
|
|
2577
|
+
entry.session = session;
|
|
2578
|
+
const actual = entry.configs.get(session);
|
|
2579
|
+
entry.configs.clear();
|
|
2580
|
+
if (entry.released) {
|
|
2581
|
+
this.notifyHostSessionReleased(entry);
|
|
2582
|
+
throw new Error("AHP session handoff ended");
|
|
2583
|
+
}
|
|
2584
|
+
if (this.sessions.get(session.sessionId) !== session || session.sessionId !== expected.sessionId) {
|
|
2585
|
+
throw new Error(
|
|
2586
|
+
"AHP callback must return the requested session from this client"
|
|
2587
|
+
);
|
|
2588
|
+
}
|
|
2589
|
+
const contains = (value, required) => {
|
|
2590
|
+
if (required && typeof required === "object" && !Array.isArray(required)) {
|
|
2591
|
+
return !!value && typeof value === "object" && Object.entries(required).every(
|
|
2592
|
+
([key, child]) => contains(value[key], child)
|
|
2593
|
+
);
|
|
2594
|
+
}
|
|
2595
|
+
return JSON.stringify(value) === JSON.stringify(required);
|
|
2596
|
+
};
|
|
2597
|
+
if ((!params.resume || actual !== void 0) && !contains(actual, expected)) {
|
|
2598
|
+
throw new Error(
|
|
2599
|
+
"AHP callback must preserve the supplied session configuration"
|
|
2600
|
+
);
|
|
2601
|
+
}
|
|
2602
|
+
return { sessionId: session.sessionId };
|
|
2603
|
+
});
|
|
2604
|
+
try {
|
|
2605
|
+
return await Promise.race([materialized, cancelled]);
|
|
2606
|
+
} catch (error) {
|
|
2607
|
+
this.releaseHostSession(params.handoffId);
|
|
2608
|
+
throw error;
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
/**
|
|
2612
|
+
* Sends a ping request to the server to verify connectivity.
|
|
2613
|
+
*
|
|
2614
|
+
* @param message - Optional message to include in the ping
|
|
2615
|
+
* @returns A promise that resolves with the ping response containing the message and timestamp
|
|
2616
|
+
* @throws Error if the client is not connected, or if a {@link start} in progress when
|
|
2617
|
+
* this was called fails
|
|
2618
|
+
*
|
|
2619
|
+
* @example
|
|
2620
|
+
* ```typescript
|
|
2621
|
+
* const response = await client.ping("health check");
|
|
2622
|
+
* console.log(`Server responded at ${new Date(response.timestamp)}`);
|
|
2623
|
+
* ```
|
|
2624
|
+
*/
|
|
2625
|
+
async ping(message) {
|
|
2626
|
+
return sendPing(await this.getStartedConnection(), message);
|
|
2627
|
+
}
|
|
2628
|
+
/**
|
|
2629
|
+
* Get CLI status including version and protocol information
|
|
2630
|
+
*/
|
|
2631
|
+
async getStatus() {
|
|
2632
|
+
const connection = await this.getStartedConnection();
|
|
2633
|
+
const result = await connection.sendRequest("status.get", {});
|
|
2634
|
+
return result;
|
|
2635
|
+
}
|
|
2636
|
+
/**
|
|
2637
|
+
* Get current authentication status
|
|
2638
|
+
*/
|
|
2639
|
+
async getAuthStatus() {
|
|
2640
|
+
const connection = await this.getStartedConnection();
|
|
2641
|
+
const result = await connection.sendRequest("auth.getStatus", {});
|
|
2642
|
+
return result;
|
|
2643
|
+
}
|
|
2644
|
+
/**
|
|
2645
|
+
* Returns the connection for a request that must not start the client. A
|
|
2646
|
+
* {@link start} already in progress is awaited, so the request never precedes the
|
|
2647
|
+
* `connect` handshake or the provider registrations that follow it. A caller that
|
|
2648
|
+
* queues before it calls this passes the startup it observed first, because
|
|
2649
|
+
* `startPromise` is cleared once that startup settles.
|
|
2650
|
+
*/
|
|
2651
|
+
async getStartedConnection(startup = this.startPromise) {
|
|
2652
|
+
if (startup) {
|
|
2653
|
+
await startup;
|
|
2654
|
+
}
|
|
2655
|
+
let latest = this.startPromise;
|
|
2656
|
+
while (latest && latest !== startup) {
|
|
2657
|
+
startup = latest;
|
|
2658
|
+
await latest;
|
|
2659
|
+
latest = this.startPromise;
|
|
2660
|
+
}
|
|
2661
|
+
if (!this.connection) {
|
|
2662
|
+
throw new Error("Client not connected");
|
|
2663
|
+
}
|
|
2664
|
+
return this.connection;
|
|
2665
|
+
}
|
|
2666
|
+
/**
|
|
2667
|
+
* List available models with their metadata.
|
|
2668
|
+
*
|
|
2669
|
+
* If an `onListModels` handler was provided in the client options,
|
|
2670
|
+
* it is called instead of querying the CLI server.
|
|
2671
|
+
*
|
|
2672
|
+
* Results are cached after the first successful call to avoid rate limiting.
|
|
2673
|
+
* The cache is cleared when the client disconnects.
|
|
2674
|
+
*
|
|
2675
|
+
* @throws Error if not connected, or if a {@link start} in progress when this was
|
|
2676
|
+
* called fails (when no custom handler is set)
|
|
2677
|
+
*/
|
|
2678
|
+
async listModels() {
|
|
2679
|
+
const cache = this.modelsCache;
|
|
2680
|
+
const startup = this.startPromise;
|
|
2681
|
+
const previousLock = cache.lock;
|
|
2682
|
+
let resolveLock;
|
|
2683
|
+
cache.lock = new Promise((resolve2) => {
|
|
2684
|
+
resolveLock = resolve2;
|
|
2685
|
+
});
|
|
2686
|
+
await previousLock;
|
|
2687
|
+
try {
|
|
2688
|
+
if (cache.models !== null) {
|
|
2689
|
+
return [...cache.models];
|
|
2690
|
+
}
|
|
2691
|
+
let models;
|
|
2692
|
+
if (this.onListModels) {
|
|
2693
|
+
models = await this.onListModels();
|
|
2694
|
+
} else {
|
|
2695
|
+
const connection = await this.getStartedConnection(startup);
|
|
2696
|
+
const result = await connection.sendRequest("models.list", {});
|
|
2697
|
+
const response = result;
|
|
2698
|
+
models = response.models;
|
|
2699
|
+
for (const model of models) {
|
|
2700
|
+
const m = model;
|
|
2701
|
+
if (!m.capabilities) {
|
|
2702
|
+
m.capabilities = {
|
|
2703
|
+
supports: {},
|
|
2704
|
+
limits: { max_context_window_tokens: 0 }
|
|
2705
|
+
};
|
|
2706
|
+
} else {
|
|
2707
|
+
if (!m.capabilities.supports) m.capabilities.supports = {};
|
|
2708
|
+
if (!m.capabilities.limits) {
|
|
2709
|
+
m.capabilities.limits = { max_context_window_tokens: 0 };
|
|
2710
|
+
} else if (m.capabilities.limits.max_context_window_tokens === void 0) {
|
|
2711
|
+
m.capabilities.limits.max_context_window_tokens = 0;
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
cache.models = [...models];
|
|
2717
|
+
return [...models];
|
|
2718
|
+
} finally {
|
|
2719
|
+
resolveLock();
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
/**
|
|
2723
|
+
* Send the `connect` handshake (carrying the optional token) and verify the
|
|
2724
|
+
* server's protocol version. Falls back to `ping` against legacy servers
|
|
2725
|
+
* that don't implement `connect`.
|
|
2726
|
+
*/
|
|
2727
|
+
async verifyProtocolVersion() {
|
|
2728
|
+
const connection = this.connection;
|
|
2729
|
+
if (!connection) {
|
|
2730
|
+
throw new Error("Client not connected");
|
|
2731
|
+
}
|
|
2732
|
+
const maxVersion = getSdkProtocolVersion();
|
|
2733
|
+
const raceAgainstExit = (p) => this.processExitPromise ? Promise.race([p, this.processExitPromise]) : p;
|
|
2734
|
+
let serverVersion;
|
|
2735
|
+
try {
|
|
2736
|
+
const connectParams = {
|
|
2737
|
+
entra: this.options.entra && {
|
|
2738
|
+
clientId: this.options.entra.clientId,
|
|
2739
|
+
matsAppName: this.options.entra.matsAppName
|
|
2740
|
+
},
|
|
2741
|
+
entraTokenProvider: this.options.entra?.tokenProvider ? true : void 0,
|
|
2742
|
+
token: this.effectiveConnectionToken,
|
|
2743
|
+
supportedTaskKinds: ["agent", "client", "shell"]
|
|
2744
|
+
};
|
|
2745
|
+
if (this.onGitHubTelemetry != null) {
|
|
2746
|
+
connectParams.enableGitHubTelemetryForwarding = true;
|
|
2747
|
+
}
|
|
2748
|
+
const clientInfo = clientInfoToWire(this.options.clientInfo);
|
|
2749
|
+
if (clientInfo != null) {
|
|
2750
|
+
connectParams.clientInfo = clientInfo;
|
|
2751
|
+
}
|
|
2752
|
+
const result = await raceAgainstExit(this.internalRpc.connect(connectParams));
|
|
2753
|
+
if (this.options.entra?.tokenProvider && result.entraTokenProvider !== true) {
|
|
2754
|
+
throw new Error("This runtime does not support host-owned Entra token providers.");
|
|
2755
|
+
}
|
|
2756
|
+
serverVersion = result.protocolVersion;
|
|
2757
|
+
} catch (err) {
|
|
2758
|
+
if (err instanceof ResponseError && (err.code === ErrorCodes.MethodNotFound || err.message === "Unhandled method connect")) {
|
|
2759
|
+
if (this.options.entra) {
|
|
2760
|
+
throw new Error("This runtime does not support Entra client configuration.");
|
|
2761
|
+
}
|
|
2762
|
+
serverVersion = (await raceAgainstExit(sendPing(connection))).protocolVersion;
|
|
2763
|
+
} else {
|
|
2764
|
+
throw err;
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
if (serverVersion === void 0) {
|
|
2768
|
+
throw new Error(
|
|
2769
|
+
`SDK protocol version mismatch: SDK supports versions ${MIN_PROTOCOL_VERSION}-${maxVersion}, but server does not report a protocol version. Please update your server to ensure compatibility.`
|
|
2770
|
+
);
|
|
2771
|
+
}
|
|
2772
|
+
if (serverVersion < MIN_PROTOCOL_VERSION || serverVersion > maxVersion) {
|
|
2773
|
+
throw new Error(
|
|
2774
|
+
`SDK protocol version mismatch: SDK supports versions ${MIN_PROTOCOL_VERSION}-${maxVersion}, but server reports version ${serverVersion}. Please update your SDK or server to ensure compatibility.`
|
|
2775
|
+
);
|
|
2776
|
+
}
|
|
2777
|
+
this.negotiatedProtocolVersion = serverVersion;
|
|
2778
|
+
}
|
|
2779
|
+
/**
|
|
2780
|
+
* Gets the ID of the most recently updated session.
|
|
2781
|
+
*
|
|
2782
|
+
* This is useful for resuming the last conversation when the session ID
|
|
2783
|
+
* was not stored.
|
|
2784
|
+
*
|
|
2785
|
+
* @returns A promise that resolves with the session ID, or undefined if no sessions exist
|
|
2786
|
+
* @throws Error if the client is not connected
|
|
2787
|
+
*
|
|
2788
|
+
* @example
|
|
2789
|
+
* ```typescript
|
|
2790
|
+
* const lastId = await client.getLastSessionId();
|
|
2791
|
+
* if (lastId) {
|
|
2792
|
+
* const session = await client.resumeSession(lastId, { onPermissionRequest: approveAll });
|
|
2793
|
+
* }
|
|
2794
|
+
* ```
|
|
2795
|
+
*/
|
|
2796
|
+
async getLastSessionId() {
|
|
2797
|
+
if (!this.connection) {
|
|
2798
|
+
throw new Error("Client not connected");
|
|
2799
|
+
}
|
|
2800
|
+
const response = await this.connection.sendRequest("session.getLastId", {});
|
|
2801
|
+
return response.sessionId;
|
|
2802
|
+
}
|
|
2803
|
+
/**
|
|
2804
|
+
* Permanently deletes a session and all its data from disk, including
|
|
2805
|
+
* conversation history, planning state, and artifacts.
|
|
2806
|
+
*
|
|
2807
|
+
* Unlike {@link CopilotSession.disconnect}, which only releases in-memory
|
|
2808
|
+
* resources and preserves session data for later resumption, this method
|
|
2809
|
+
* is irreversible. The session cannot be resumed after deletion.
|
|
2810
|
+
*
|
|
2811
|
+
* @param sessionId - The ID of the session to delete
|
|
2812
|
+
* @returns A promise that resolves when the session is deleted
|
|
2813
|
+
* @throws Error if the session does not exist or deletion fails
|
|
2814
|
+
*
|
|
2815
|
+
* @example
|
|
2816
|
+
* ```typescript
|
|
2817
|
+
* await client.deleteSession("session-123");
|
|
2818
|
+
* ```
|
|
2819
|
+
*/
|
|
2820
|
+
async deleteSession(sessionId) {
|
|
2821
|
+
if (!this.connection) {
|
|
2822
|
+
throw new Error("Client not connected");
|
|
2823
|
+
}
|
|
2824
|
+
const signal = await this.getSessionInitializationSignal();
|
|
2825
|
+
const release = await this.acquireSessionInitialization(sessionId, signal);
|
|
2826
|
+
try {
|
|
2827
|
+
signal.throwIfAborted();
|
|
2828
|
+
const connection = this.connection;
|
|
2829
|
+
const session = this.sessions.get(sessionId);
|
|
2830
|
+
await this.requestSessionDeletion(connection, sessionId);
|
|
2831
|
+
signal.throwIfAborted();
|
|
2832
|
+
if (this.sessions.get(sessionId) === session) {
|
|
2833
|
+
this.sessions.delete(sessionId);
|
|
2834
|
+
session?._markDisconnected();
|
|
2835
|
+
}
|
|
2836
|
+
} finally {
|
|
2837
|
+
release();
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
async requestSessionDeletion(connection, sessionId) {
|
|
2841
|
+
const response = await connection.sendRequest(
|
|
2842
|
+
"session.delete",
|
|
2843
|
+
{
|
|
2844
|
+
sessionId
|
|
2845
|
+
}
|
|
2846
|
+
);
|
|
2847
|
+
const { success, error } = response;
|
|
2848
|
+
if (!success) {
|
|
2849
|
+
throw new Error(`Failed to delete session ${sessionId}: ${error || "Unknown error"}`);
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
/** Stops tracking a disconnected session unless a later create or resume replaced it. */
|
|
2853
|
+
forgetSession(session) {
|
|
2854
|
+
if (this.sessions.get(session.sessionId) === session) {
|
|
2855
|
+
this.sessions.delete(session.sessionId);
|
|
2856
|
+
}
|
|
2857
|
+
}
|
|
2858
|
+
/**
|
|
2859
|
+
* List all available sessions.
|
|
2860
|
+
*
|
|
2861
|
+
* @param filter - Optional filter to limit returned sessions by context fields
|
|
2862
|
+
*
|
|
2863
|
+
* @example
|
|
2864
|
+
* // List all sessions
|
|
2865
|
+
* const sessions = await client.listSessions();
|
|
2866
|
+
*
|
|
2867
|
+
* @example
|
|
2868
|
+
* // List sessions for a specific repository
|
|
2869
|
+
* const sessions = await client.listSessions({ repository: "owner/repo" });
|
|
2870
|
+
*/
|
|
2871
|
+
async listSessions(filter) {
|
|
2872
|
+
if (!this.connection) {
|
|
2873
|
+
throw new Error("Client not connected");
|
|
2874
|
+
}
|
|
2875
|
+
let wireFilter;
|
|
2876
|
+
if (filter) {
|
|
2877
|
+
const { workingDirectory, ...rest } = filter;
|
|
2878
|
+
wireFilter = { ...rest, cwd: workingDirectory };
|
|
2879
|
+
}
|
|
2880
|
+
const response = await this.connection.sendRequest("session.list", {
|
|
2881
|
+
filter: wireFilter
|
|
2882
|
+
});
|
|
2883
|
+
const { sessions } = response;
|
|
2884
|
+
return sessions.map(CopilotClient.toSessionMetadata);
|
|
2885
|
+
}
|
|
2886
|
+
/**
|
|
2887
|
+
* Gets metadata for a specific session by ID.
|
|
2888
|
+
*
|
|
2889
|
+
* This provides an efficient O(1) lookup of a single session's metadata
|
|
2890
|
+
* instead of listing all sessions. Returns undefined if the session is not found.
|
|
2891
|
+
*
|
|
2892
|
+
* @param sessionId - The ID of the session to look up
|
|
2893
|
+
* @returns A promise that resolves with the session metadata, or undefined if not found
|
|
2894
|
+
* @throws Error if the client is not connected
|
|
2895
|
+
*
|
|
2896
|
+
* @example
|
|
2897
|
+
* ```typescript
|
|
2898
|
+
* const metadata = await client.getSessionMetadata("session-123");
|
|
2899
|
+
* if (metadata) {
|
|
2900
|
+
* console.log(`Session started at: ${metadata.startTime}`);
|
|
2901
|
+
* }
|
|
2902
|
+
* ```
|
|
2903
|
+
*/
|
|
2904
|
+
async getSessionMetadata(sessionId) {
|
|
2905
|
+
if (!this.connection) {
|
|
2906
|
+
throw new Error("Client not connected");
|
|
2907
|
+
}
|
|
2908
|
+
const response = await this.connection.sendRequest("session.getMetadata", { sessionId });
|
|
2909
|
+
const { session } = response;
|
|
2910
|
+
if (!session) {
|
|
2911
|
+
return void 0;
|
|
2912
|
+
}
|
|
2913
|
+
return CopilotClient.toSessionMetadata(session);
|
|
2914
|
+
}
|
|
2915
|
+
static toSessionMetadata(raw) {
|
|
2916
|
+
const { context } = raw;
|
|
2917
|
+
return {
|
|
2918
|
+
sessionId: raw.sessionId,
|
|
2919
|
+
startTime: new Date(raw.startTime),
|
|
2920
|
+
modifiedTime: new Date(raw.modifiedTime),
|
|
2921
|
+
summary: raw.summary,
|
|
2922
|
+
isRemote: raw.isRemote,
|
|
2923
|
+
context: context ? {
|
|
2924
|
+
workingDirectory: context.cwd,
|
|
2925
|
+
gitRoot: context.gitRoot,
|
|
2926
|
+
repository: context.repository,
|
|
2927
|
+
branch: context.branch
|
|
2928
|
+
} : void 0,
|
|
2929
|
+
clientName: raw.clientName,
|
|
2930
|
+
lastClientName: raw.lastClientName
|
|
2931
|
+
};
|
|
2932
|
+
}
|
|
2933
|
+
/**
|
|
2934
|
+
* Gets the foreground session ID in TUI+server mode.
|
|
2935
|
+
*
|
|
2936
|
+
* This returns the ID of the session currently displayed in the TUI.
|
|
2937
|
+
* Only available when connecting to a server running in TUI+server mode (--ui-server).
|
|
2938
|
+
*
|
|
2939
|
+
* @returns A promise that resolves with the foreground session ID, or undefined if none
|
|
2940
|
+
* @throws Error if the client is not connected
|
|
2941
|
+
*
|
|
2942
|
+
* @example
|
|
2943
|
+
* ```typescript
|
|
2944
|
+
* const sessionId = await client.getForegroundSessionId();
|
|
2945
|
+
* if (sessionId) {
|
|
2946
|
+
* console.log(`TUI is displaying session: ${sessionId}`);
|
|
2947
|
+
* }
|
|
2948
|
+
* ```
|
|
2949
|
+
*/
|
|
2950
|
+
async getForegroundSessionId() {
|
|
2951
|
+
if (!this.connection) {
|
|
2952
|
+
throw new Error("Client not connected");
|
|
2953
|
+
}
|
|
2954
|
+
const response = await this.connection.sendRequest("session.getForeground", {});
|
|
2955
|
+
return response.sessionId;
|
|
2956
|
+
}
|
|
2957
|
+
/**
|
|
2958
|
+
* Sets the foreground session in TUI+server mode.
|
|
2959
|
+
*
|
|
2960
|
+
* This requests the TUI to switch to displaying the specified session.
|
|
2961
|
+
* Only available when connecting to a server running in TUI+server mode (--ui-server).
|
|
2962
|
+
*
|
|
2963
|
+
* @param sessionId - The ID of the session to display in the TUI
|
|
2964
|
+
* @returns A promise that resolves when the session is switched
|
|
2965
|
+
* @throws Error if the client is not connected or if the operation fails
|
|
2966
|
+
*
|
|
2967
|
+
* @example
|
|
2968
|
+
* ```typescript
|
|
2969
|
+
* // Switch the TUI to display a specific session
|
|
2970
|
+
* await client.setForegroundSessionId("session-123");
|
|
2971
|
+
* ```
|
|
2972
|
+
*/
|
|
2973
|
+
async setForegroundSessionId(sessionId) {
|
|
2974
|
+
if (!this.connection) {
|
|
2975
|
+
throw new Error("Client not connected");
|
|
2976
|
+
}
|
|
2977
|
+
const response = await this.connection.sendRequest("session.setForeground", { sessionId });
|
|
2978
|
+
const result = response;
|
|
2979
|
+
if (!result.success) {
|
|
2980
|
+
throw new Error(result.error || "Failed to set foreground session");
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
onLifecycle(eventTypeOrHandler, handler) {
|
|
2984
|
+
if (typeof eventTypeOrHandler === "string" && handler) {
|
|
2985
|
+
const eventType = eventTypeOrHandler;
|
|
2986
|
+
if (!this.typedLifecycleHandlers.has(eventType)) {
|
|
2987
|
+
this.typedLifecycleHandlers.set(eventType, /* @__PURE__ */ new Set());
|
|
2988
|
+
}
|
|
2989
|
+
const storedHandler = handler;
|
|
2990
|
+
this.typedLifecycleHandlers.get(eventType).add(storedHandler);
|
|
2991
|
+
return () => {
|
|
2992
|
+
const handlers = this.typedLifecycleHandlers.get(eventType);
|
|
2993
|
+
if (handlers) {
|
|
2994
|
+
handlers.delete(storedHandler);
|
|
2995
|
+
}
|
|
2996
|
+
};
|
|
2997
|
+
}
|
|
2998
|
+
const wildcardHandler = eventTypeOrHandler;
|
|
2999
|
+
this.sessionLifecycleHandlers.add(wildcardHandler);
|
|
3000
|
+
return () => {
|
|
3001
|
+
this.sessionLifecycleHandlers.delete(wildcardHandler);
|
|
3002
|
+
};
|
|
3003
|
+
}
|
|
3004
|
+
/**
|
|
3005
|
+
* Builds runtime configuration for child processes and the per-host FFI snapshot.
|
|
3006
|
+
* Typed auth, home, keychain, and telemetry options override the effective env.
|
|
3007
|
+
*/
|
|
3008
|
+
buildRuntimeEnv() {
|
|
3009
|
+
const env = process.platform === "win32" ? Object.fromEntries(
|
|
3010
|
+
Object.entries(this.resolvedEnv).map(([key, value]) => [
|
|
3011
|
+
key.toUpperCase(),
|
|
3012
|
+
value
|
|
3013
|
+
])
|
|
3014
|
+
) : { ...this.resolvedEnv };
|
|
3015
|
+
delete env.NODE_DEBUG;
|
|
3016
|
+
const test = this.options.internalTestOptions;
|
|
3017
|
+
if (test) {
|
|
3018
|
+
const overrides = {
|
|
3019
|
+
COPILOT_API_URL: test.copilotApiUrl,
|
|
3020
|
+
COPILOT_DEBUG_GITHUB_API_URL: test.githubApiUrl,
|
|
3021
|
+
HTTP_PROXY: test.proxyUrl,
|
|
3022
|
+
HTTPS_PROXY: test.proxyUrl,
|
|
3023
|
+
http_proxy: test.proxyUrl,
|
|
3024
|
+
https_proxy: test.proxyUrl,
|
|
3025
|
+
NO_PROXY: test.noProxy,
|
|
3026
|
+
no_proxy: test.noProxy,
|
|
3027
|
+
NODE_EXTRA_CA_CERTS: test.caCertificatePath,
|
|
3028
|
+
SSL_CERT_FILE: test.caCertificatePath,
|
|
3029
|
+
REQUESTS_CA_BUNDLE: test.caCertificatePath,
|
|
3030
|
+
CURL_CA_BUNDLE: test.caCertificatePath,
|
|
3031
|
+
GIT_SSL_CAINFO: test.caCertificatePath
|
|
3032
|
+
};
|
|
3033
|
+
for (const [key, value] of Object.entries(overrides)) {
|
|
3034
|
+
if (value !== void 0) {
|
|
3035
|
+
env[process.platform === "win32" ? key.toUpperCase() : key] = value;
|
|
3036
|
+
}
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
if (this.options.gitHubToken) {
|
|
3040
|
+
env.COPILOT_SDK_AUTH_TOKEN = this.options.gitHubToken;
|
|
3041
|
+
}
|
|
3042
|
+
if (this.effectiveConnectionToken) {
|
|
3043
|
+
env.COPILOT_CONNECTION_TOKEN = this.effectiveConnectionToken;
|
|
3044
|
+
}
|
|
3045
|
+
if (this.options.baseDirectory) {
|
|
3046
|
+
env.COPILOT_HOME = this.options.baseDirectory;
|
|
3047
|
+
if (this.connectionConfig.kind === "inprocess") {
|
|
3048
|
+
env.COPILOT_CACHE_HOME = join(this.options.baseDirectory, "cache");
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
if (this.options.mode === "empty") {
|
|
3052
|
+
env.COPILOT_DISABLE_KEYTAR = "1";
|
|
3053
|
+
}
|
|
3054
|
+
if (this.options.mode !== "empty") {
|
|
3055
|
+
env.COPILOT_RUNTIME_PROCESS_FILE_LOGGING = "1";
|
|
3056
|
+
}
|
|
3057
|
+
if (this.options.telemetry) {
|
|
3058
|
+
const t = this.options.telemetry;
|
|
3059
|
+
env.COPILOT_OTEL_ENABLED = "true";
|
|
3060
|
+
if (t.otlpEndpoint !== void 0) env.OTEL_EXPORTER_OTLP_ENDPOINT = t.otlpEndpoint;
|
|
3061
|
+
if (t.otlpProtocol !== void 0) env.OTEL_EXPORTER_OTLP_PROTOCOL = t.otlpProtocol;
|
|
3062
|
+
if (t.filePath !== void 0) env.COPILOT_OTEL_FILE_EXPORTER_PATH = t.filePath;
|
|
3063
|
+
if (t.exporterType !== void 0) env.COPILOT_OTEL_EXPORTER_TYPE = t.exporterType;
|
|
3064
|
+
if (t.sourceName !== void 0) env.COPILOT_OTEL_SOURCE_NAME = t.sourceName;
|
|
3065
|
+
if (t.captureContent !== void 0) {
|
|
3066
|
+
env.OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT = t.captureContent ? "SPAN_ONLY" : "NO_CONTENT";
|
|
3067
|
+
env.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT = String(t.captureContent);
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
return env;
|
|
3071
|
+
}
|
|
3072
|
+
/**
|
|
3073
|
+
* Start the CLI server process
|
|
3074
|
+
*/
|
|
3075
|
+
async startCLIServer() {
|
|
3076
|
+
this.resolvedCliPath ??= await getSpawnableBundledRuntimePath();
|
|
3077
|
+
return new Promise((resolve2, reject) => {
|
|
3078
|
+
this.stderrBuffer = "";
|
|
3079
|
+
const args = [...this.connectionExtraArgs, "--headless", "--no-auto-update"];
|
|
3080
|
+
if (this.options.logLevel) {
|
|
3081
|
+
args.push("--log-level", this.options.logLevel);
|
|
3082
|
+
}
|
|
3083
|
+
if (this.connectionConfig.kind === "stdio") {
|
|
3084
|
+
args.push("--stdio");
|
|
3085
|
+
} else if (this.connectionConfig.kind === "tcp") {
|
|
3086
|
+
const requestedPort = this.connectionConfig.port ?? 0;
|
|
3087
|
+
if (requestedPort > 0) {
|
|
3088
|
+
args.push("--port", requestedPort.toString());
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
if (this.options.gitHubToken) {
|
|
3092
|
+
args.push("--auth-token-env", "COPILOT_SDK_AUTH_TOKEN");
|
|
3093
|
+
}
|
|
3094
|
+
if (!this.options.useLoggedInUser) {
|
|
3095
|
+
args.push("--no-auto-login");
|
|
3096
|
+
}
|
|
3097
|
+
if (this.options.sessionIdleTimeoutSeconds !== void 0 && this.options.sessionIdleTimeoutSeconds > 0) {
|
|
3098
|
+
args.push(
|
|
3099
|
+
"--session-idle-timeout",
|
|
3100
|
+
this.options.sessionIdleTimeoutSeconds.toString()
|
|
3101
|
+
);
|
|
3102
|
+
}
|
|
3103
|
+
const envWithoutNodeDebug = this.buildRuntimeEnv();
|
|
3104
|
+
if (!this.resolvedCliPath) {
|
|
3105
|
+
throw new Error(
|
|
3106
|
+
"Path to Copilot CLI is required. Please supply it via `RuntimeConnection.forStdio({ path })` or `RuntimeConnection.forTcp({ path })`, set the COPILOT_CLI_PATH environment variable, or use `RuntimeConnection.forUri(...)` to connect to an already-running runtime."
|
|
3107
|
+
);
|
|
3108
|
+
}
|
|
3109
|
+
if (!existsSync(this.resolvedCliPath)) {
|
|
3110
|
+
throw new Error(
|
|
3111
|
+
`Copilot CLI not found at ${this.resolvedCliPath}. Set COPILOT_CLI_PATH to use a custom installation.`
|
|
3112
|
+
);
|
|
3113
|
+
}
|
|
3114
|
+
const workingDirectory = this.options.workingDirectory;
|
|
3115
|
+
let workingDirectoryProblem;
|
|
3116
|
+
try {
|
|
3117
|
+
workingDirectoryProblem = statSync(workingDirectory).isDirectory() ? void 0 : "does not exist or is not a directory";
|
|
3118
|
+
if (!workingDirectoryProblem) {
|
|
3119
|
+
accessSync(workingDirectory, constants.X_OK);
|
|
3120
|
+
}
|
|
3121
|
+
} catch (error) {
|
|
3122
|
+
const code = error.code;
|
|
3123
|
+
workingDirectoryProblem = code === "ENOENT" || code === "ENOTDIR" ? "does not exist or is not a directory" : `cannot be entered: ${error instanceof Error ? error.message : String(error)}`;
|
|
3124
|
+
}
|
|
3125
|
+
if (workingDirectoryProblem) {
|
|
3126
|
+
throw new Error(
|
|
3127
|
+
`Working directory ${workingDirectory} ${workingDirectoryProblem}.`
|
|
3128
|
+
);
|
|
3129
|
+
}
|
|
3130
|
+
const stdioConfig = this.connectionConfig.kind === "stdio" ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"];
|
|
3131
|
+
const isJsFile = this.resolvedCliPath.endsWith(".js");
|
|
3132
|
+
if (isJsFile) {
|
|
3133
|
+
this.cliProcess = spawn(getNodeExecPath(), [this.resolvedCliPath, ...args], {
|
|
3134
|
+
stdio: stdioConfig,
|
|
3135
|
+
cwd: this.options.workingDirectory,
|
|
3136
|
+
env: envWithoutNodeDebug,
|
|
3137
|
+
windowsHide: true
|
|
3138
|
+
});
|
|
3139
|
+
} else {
|
|
3140
|
+
this.cliProcess = spawn(this.resolvedCliPath, args, {
|
|
3141
|
+
stdio: stdioConfig,
|
|
3142
|
+
cwd: this.options.workingDirectory,
|
|
3143
|
+
env: envWithoutNodeDebug,
|
|
3144
|
+
windowsHide: true
|
|
3145
|
+
});
|
|
3146
|
+
}
|
|
3147
|
+
let stdout = "";
|
|
3148
|
+
let resolved = false;
|
|
3149
|
+
if (this.connectionConfig.kind === "stdio") {
|
|
3150
|
+
resolved = true;
|
|
3151
|
+
resolve2();
|
|
3152
|
+
} else {
|
|
3153
|
+
this.cliProcess.stdout?.on("data", (data) => {
|
|
3154
|
+
stdout += data.toString();
|
|
3155
|
+
const match = stdout.match(/listening on port (\d+)/i);
|
|
3156
|
+
if (match && !resolved) {
|
|
3157
|
+
this.runtimePort = parseInt(match[1], 10);
|
|
3158
|
+
resolved = true;
|
|
3159
|
+
resolve2();
|
|
3160
|
+
}
|
|
3161
|
+
});
|
|
3162
|
+
}
|
|
3163
|
+
this.cliProcess.stderr?.on("data", (data) => {
|
|
3164
|
+
this.stderrBuffer += data.toString();
|
|
3165
|
+
const lines = data.toString().split("\n");
|
|
3166
|
+
for (const line of lines) {
|
|
3167
|
+
if (line.trim()) {
|
|
3168
|
+
process.stderr.write(`[CLI subprocess] ${line}
|
|
3169
|
+
`);
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3172
|
+
});
|
|
3173
|
+
this.cliProcess.on("error", (error) => {
|
|
3174
|
+
if (!resolved) {
|
|
3175
|
+
resolved = true;
|
|
3176
|
+
const stderrOutput = this.stderrBuffer.trim();
|
|
3177
|
+
if (stderrOutput) {
|
|
3178
|
+
reject(
|
|
3179
|
+
new Error(
|
|
3180
|
+
`Failed to start CLI server: ${error.message}
|
|
3181
|
+
stderr: ${stderrOutput}`
|
|
3182
|
+
)
|
|
3183
|
+
);
|
|
3184
|
+
} else {
|
|
3185
|
+
reject(new Error(`Failed to start CLI server: ${error.message}`));
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
});
|
|
3189
|
+
this.processExitPromise = new Promise((_, rejectProcessExit) => {
|
|
3190
|
+
this.cliProcess.on("exit", (code) => {
|
|
3191
|
+
if (this.messageWriter) {
|
|
3192
|
+
this.messageWriter.suppressWriteErrors = true;
|
|
3193
|
+
}
|
|
3194
|
+
const stderrOutput = this.stderrBuffer.trim();
|
|
3195
|
+
if (stderrOutput) {
|
|
3196
|
+
rejectProcessExit(
|
|
3197
|
+
new Error(
|
|
3198
|
+
`CLI server exited with code ${code}
|
|
3199
|
+
stderr: ${stderrOutput}`
|
|
3200
|
+
)
|
|
3201
|
+
);
|
|
3202
|
+
} else {
|
|
3203
|
+
rejectProcessExit(
|
|
3204
|
+
new Error(`CLI server exited unexpectedly with code ${code}`)
|
|
3205
|
+
);
|
|
3206
|
+
}
|
|
3207
|
+
});
|
|
3208
|
+
});
|
|
3209
|
+
this.processExitPromise.catch(() => {
|
|
3210
|
+
});
|
|
3211
|
+
this.cliProcess.on("close", (code) => {
|
|
3212
|
+
if (!resolved) {
|
|
3213
|
+
resolved = true;
|
|
3214
|
+
const stderrOutput = this.stderrBuffer.trim();
|
|
3215
|
+
if (stderrOutput) {
|
|
3216
|
+
reject(
|
|
3217
|
+
new Error(
|
|
3218
|
+
`CLI server exited with code ${code}
|
|
3219
|
+
stderr: ${stderrOutput}`
|
|
3220
|
+
)
|
|
3221
|
+
);
|
|
3222
|
+
} else {
|
|
3223
|
+
reject(new Error(`CLI server exited with code ${code}`));
|
|
3224
|
+
}
|
|
3225
|
+
}
|
|
3226
|
+
});
|
|
3227
|
+
this.cliStartTimeout = setTimeout(() => {
|
|
3228
|
+
if (!resolved) {
|
|
3229
|
+
resolved = true;
|
|
3230
|
+
reject(
|
|
3231
|
+
new Error(
|
|
3232
|
+
`Timeout waiting for CLI server to start
|
|
3233
|
+
stdout: ${stdout.trim().slice(-8192) || "(empty)"}
|
|
3234
|
+
stderr: ${this.stderrBuffer.trim().slice(-8192) || "(empty)"}`
|
|
3235
|
+
)
|
|
3236
|
+
);
|
|
3237
|
+
}
|
|
3238
|
+
}, 3e4);
|
|
3239
|
+
});
|
|
3240
|
+
}
|
|
3241
|
+
/**
|
|
3242
|
+
* Connect to the CLI server (via socket or stdio)
|
|
3243
|
+
*/
|
|
3244
|
+
async connectToServer() {
|
|
3245
|
+
switch (this.connectionConfig.kind) {
|
|
3246
|
+
case "parent-process":
|
|
3247
|
+
return this.connectToParentProcessViaStdio();
|
|
3248
|
+
case "stdio":
|
|
3249
|
+
return this.connectToChildProcessViaStdio();
|
|
3250
|
+
case "inprocess":
|
|
3251
|
+
return this.connectViaFfi();
|
|
3252
|
+
case "tcp":
|
|
3253
|
+
return this.connectViaTcp();
|
|
3254
|
+
case "uri": {
|
|
3255
|
+
const { host, port } = this.parseCliUrl(this.connectionConfig.url);
|
|
3256
|
+
this.actualHost = host;
|
|
3257
|
+
this.runtimePort = port;
|
|
3258
|
+
return this.connectViaTcp();
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
}
|
|
3262
|
+
/** Starts the in-process FFI runtime with SDK-managed typed options. */
|
|
3263
|
+
async startInProcessFfi() {
|
|
3264
|
+
const explicitEntrypoint = this.resolvedEnv.COPILOT_CLI_PATH;
|
|
3265
|
+
const cliLoginSyncIntegrationId = this.resolvedEnv.GITHUB_COPILOT_INTEGRATION_ID?.trim() || void 0;
|
|
3266
|
+
let runtimeLibrary;
|
|
3267
|
+
if (explicitEntrypoint) {
|
|
3268
|
+
const entrypointDirectory = dirname(resolve(explicitEntrypoint));
|
|
3269
|
+
const adjacentRuntime = join(entrypointDirectory, "runtime.node");
|
|
3270
|
+
runtimeLibrary = existsSync(adjacentRuntime) ? adjacentRuntime : join(
|
|
3271
|
+
entrypointDirectory,
|
|
3272
|
+
"prebuilds",
|
|
3273
|
+
CopilotClient.getNapiPrebuildsFolder(explicitEntrypoint),
|
|
3274
|
+
"runtime.node"
|
|
3275
|
+
);
|
|
3276
|
+
} else {
|
|
3277
|
+
const bundledRuntimePath = await getBundledRuntimePath();
|
|
3278
|
+
runtimeLibrary = join(dirname(bundledRuntimePath), "runtime.node");
|
|
3279
|
+
}
|
|
3280
|
+
const { FfiRuntimeHost } = await import("./ffiRuntimeHost.js");
|
|
3281
|
+
const environment = this.buildRuntimeEnv();
|
|
3282
|
+
const args = [];
|
|
3283
|
+
if (this.options.logLevel) {
|
|
3284
|
+
args.push("--log-level", this.options.logLevel);
|
|
3285
|
+
}
|
|
3286
|
+
if (this.options.gitHubToken) {
|
|
3287
|
+
args.push("--auth-token-env", "COPILOT_SDK_AUTH_TOKEN");
|
|
3288
|
+
}
|
|
3289
|
+
if (!this.options.useLoggedInUser) {
|
|
3290
|
+
args.push("--no-auto-login");
|
|
3291
|
+
}
|
|
3292
|
+
if (this.options.sessionIdleTimeoutSeconds > 0) {
|
|
3293
|
+
args.push("--session-idle-timeout", this.options.sessionIdleTimeoutSeconds.toString());
|
|
3294
|
+
}
|
|
3295
|
+
if (cliLoginSyncIntegrationId) {
|
|
3296
|
+
args.push(`--cli-login-sync-integration-id=${cliLoginSyncIntegrationId}`);
|
|
3297
|
+
}
|
|
3298
|
+
const host = FfiRuntimeHost.create(runtimeLibrary, explicitEntrypoint, environment, args);
|
|
3299
|
+
this.ffiHost = host;
|
|
3300
|
+
await host.start();
|
|
3301
|
+
}
|
|
3302
|
+
/**
|
|
3303
|
+
* Connect to the in-process FFI runtime host over its receive/send streams,
|
|
3304
|
+
* reusing the same `vscode-jsonrpc` framing as the stdio transport.
|
|
3305
|
+
*/
|
|
3306
|
+
async connectViaFfi() {
|
|
3307
|
+
if (!this.ffiHost) {
|
|
3308
|
+
throw new Error("In-process FFI runtime host not started");
|
|
3309
|
+
}
|
|
3310
|
+
const codec = createLocalModelJsonCodec();
|
|
3311
|
+
this.messageWriter = new TeardownResilientStreamMessageWriter(
|
|
3312
|
+
this.ffiHost.sendStream,
|
|
3313
|
+
codec
|
|
3314
|
+
);
|
|
3315
|
+
this.connection = createMessageConnection(
|
|
3316
|
+
new StreamMessageReader(this.ffiHost.receiveStream, {
|
|
3317
|
+
contentTypeDecoder: {
|
|
3318
|
+
name: "application/json",
|
|
3319
|
+
decode: (buffer, options) => codec.decode(Buffer.from(buffer).toString(options.charset))
|
|
3320
|
+
}
|
|
3321
|
+
}),
|
|
3322
|
+
this.messageWriter,
|
|
3323
|
+
this.sessionInitializationContext
|
|
3324
|
+
);
|
|
3325
|
+
this.attachConnectionHandlers();
|
|
3326
|
+
this.connection.listen();
|
|
3327
|
+
this.ffiHost.configureUiThread(
|
|
3328
|
+
this.connectionConfig.kind === "inprocess" && this.connectionConfig.runOnUiThread !== void 0
|
|
3329
|
+
);
|
|
3330
|
+
}
|
|
3331
|
+
static getNapiPrebuildsFolder(entrypoint) {
|
|
3332
|
+
const arch = process.arch;
|
|
3333
|
+
if (arch !== "x64" && arch !== "arm64") {
|
|
3334
|
+
throw new Error(`Unsupported architecture '${arch}' for in-process FFI hosting.`);
|
|
3335
|
+
}
|
|
3336
|
+
let platform = process.platform;
|
|
3337
|
+
if (platform === "linux" && CopilotClient.isMusl(entrypoint)) {
|
|
3338
|
+
platform = "linuxmusl";
|
|
3339
|
+
}
|
|
3340
|
+
return `${platform}-${arch}`;
|
|
3341
|
+
}
|
|
3342
|
+
static isMusl(entrypoint) {
|
|
3343
|
+
if (entrypoint.includes(`copilot-linuxmusl-${process.arch}`)) {
|
|
3344
|
+
return true;
|
|
3345
|
+
}
|
|
3346
|
+
if (entrypoint.includes(`copilot-linux-${process.arch}`)) {
|
|
3347
|
+
return false;
|
|
3348
|
+
}
|
|
3349
|
+
const report = process.report?.getReport();
|
|
3350
|
+
const header = report && "header" in report ? report.header : void 0;
|
|
3351
|
+
return header !== void 0 && header.glibcVersionRuntime === void 0;
|
|
3352
|
+
}
|
|
3353
|
+
/**
|
|
3354
|
+
* Connect to child via stdio pipes
|
|
3355
|
+
*/
|
|
3356
|
+
async connectToChildProcessViaStdio() {
|
|
3357
|
+
if (!this.cliProcess) {
|
|
3358
|
+
throw new Error("CLI process not started");
|
|
3359
|
+
}
|
|
3360
|
+
this.cliProcess.stdin?.on("error", (err) => {
|
|
3361
|
+
if (this.forceStopping) {
|
|
3362
|
+
return;
|
|
3363
|
+
}
|
|
3364
|
+
this.state = "error";
|
|
3365
|
+
const reason = err instanceof Error ? err.stack ?? err.message : String(err);
|
|
3366
|
+
const stderrOutput = this.stderrBuffer.trim();
|
|
3367
|
+
this.processTransportError = new Error(
|
|
3368
|
+
`CLI server connection failed: ${reason}${stderrOutput ? `
|
|
3369
|
+
stderr: ${stderrOutput}` : ""}`
|
|
3370
|
+
);
|
|
3371
|
+
this.logDebug(`stdin pipe error: ${reason}`);
|
|
3372
|
+
if (this.messageWriter) {
|
|
3373
|
+
this.messageWriter.suppressWriteErrors = true;
|
|
3374
|
+
}
|
|
3375
|
+
try {
|
|
3376
|
+
this.connection?.dispose();
|
|
3377
|
+
} catch {
|
|
3378
|
+
}
|
|
3379
|
+
});
|
|
3380
|
+
const codec = createLocalModelJsonCodec();
|
|
3381
|
+
this.messageWriter = new TeardownResilientStreamMessageWriter(
|
|
3382
|
+
this.cliProcess.stdin,
|
|
3383
|
+
codec
|
|
3384
|
+
);
|
|
3385
|
+
this.connection = createMessageConnection(
|
|
3386
|
+
new StreamMessageReader(this.cliProcess.stdout, {
|
|
3387
|
+
contentTypeDecoder: {
|
|
3388
|
+
name: "application/json",
|
|
3389
|
+
decode: (buffer, options) => codec.decode(Buffer.from(buffer).toString(options.charset))
|
|
3390
|
+
}
|
|
3391
|
+
}),
|
|
3392
|
+
this.messageWriter,
|
|
3393
|
+
this.sessionInitializationContext
|
|
3394
|
+
);
|
|
3395
|
+
this.attachConnectionHandlers();
|
|
3396
|
+
this.connection.listen();
|
|
3397
|
+
}
|
|
3398
|
+
/**
|
|
3399
|
+
* Connect to parent via stdio pipes
|
|
3400
|
+
*/
|
|
3401
|
+
async connectToParentProcessViaStdio() {
|
|
3402
|
+
if (this.cliProcess) {
|
|
3403
|
+
throw new Error("CLI child process was unexpectedly started in parent process mode");
|
|
3404
|
+
}
|
|
3405
|
+
const codec = createLocalModelJsonCodec();
|
|
3406
|
+
this.messageWriter = new TeardownResilientStreamMessageWriter(process.stdout, codec);
|
|
3407
|
+
this.connection = createMessageConnection(
|
|
3408
|
+
new StreamMessageReader(process.stdin, {
|
|
3409
|
+
contentTypeDecoder: {
|
|
3410
|
+
name: "application/json",
|
|
3411
|
+
decode: (buffer, options) => codec.decode(Buffer.from(buffer).toString(options.charset))
|
|
3412
|
+
}
|
|
3413
|
+
}),
|
|
3414
|
+
this.messageWriter,
|
|
3415
|
+
this.sessionInitializationContext
|
|
3416
|
+
);
|
|
3417
|
+
this.attachConnectionHandlers();
|
|
3418
|
+
this.connection.listen();
|
|
3419
|
+
}
|
|
3420
|
+
/**
|
|
3421
|
+
* Connect to the CLI server via TCP socket
|
|
3422
|
+
*/
|
|
3423
|
+
async connectViaTcp() {
|
|
3424
|
+
if (!this.runtimePort) {
|
|
3425
|
+
throw new Error("Server port not available");
|
|
3426
|
+
}
|
|
3427
|
+
const signal = this.sessionInitializationLifetime.signal;
|
|
3428
|
+
signal.throwIfAborted();
|
|
3429
|
+
return new Promise((resolve2, reject) => {
|
|
3430
|
+
const socket = new Socket();
|
|
3431
|
+
this.socket = socket;
|
|
3432
|
+
const settle = () => {
|
|
3433
|
+
clearTimeout(connectionTimeout);
|
|
3434
|
+
signal.removeEventListener("abort", cancel);
|
|
3435
|
+
};
|
|
3436
|
+
const cancel = () => {
|
|
3437
|
+
settle();
|
|
3438
|
+
socket.destroy();
|
|
3439
|
+
reject(signal.reason);
|
|
3440
|
+
};
|
|
3441
|
+
const connectionTimeout = setTimeout(() => {
|
|
3442
|
+
settle();
|
|
3443
|
+
socket.destroy();
|
|
3444
|
+
reject(new Error("Timeout connecting to CLI server"));
|
|
3445
|
+
}, 1e4);
|
|
3446
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
3447
|
+
socket.connect(this.runtimePort, this.actualHost, () => {
|
|
3448
|
+
settle();
|
|
3449
|
+
const codec = createLocalModelJsonCodec();
|
|
3450
|
+
this.messageWriter = new TeardownResilientStreamMessageWriter(socket, codec);
|
|
3451
|
+
this.connection = createMessageConnection(
|
|
3452
|
+
new StreamMessageReader(socket, {
|
|
3453
|
+
contentTypeDecoder: {
|
|
3454
|
+
name: "application/json",
|
|
3455
|
+
decode: (buffer, options) => codec.decode(Buffer.from(buffer).toString(options.charset))
|
|
3456
|
+
}
|
|
3457
|
+
}),
|
|
3458
|
+
this.messageWriter,
|
|
3459
|
+
this.sessionInitializationContext
|
|
3460
|
+
);
|
|
3461
|
+
this.attachConnectionHandlers();
|
|
3462
|
+
this.connection.listen();
|
|
3463
|
+
resolve2();
|
|
3464
|
+
});
|
|
3465
|
+
socket.on("error", (error) => {
|
|
3466
|
+
settle();
|
|
3467
|
+
reject(new Error(`Failed to connect to CLI server: ${error.message}`));
|
|
3468
|
+
});
|
|
3469
|
+
});
|
|
3470
|
+
}
|
|
3471
|
+
attachConnectionHandlers() {
|
|
3472
|
+
if (!this.connection) {
|
|
3473
|
+
return;
|
|
3474
|
+
}
|
|
3475
|
+
this.connection.onNotification("session.event", (notification) => {
|
|
3476
|
+
this.handleSessionEventNotification(notification);
|
|
3477
|
+
});
|
|
3478
|
+
this.connection.onNotification("session.lifecycle", (notification) => {
|
|
3479
|
+
this.handleSessionLifecycleNotification(notification);
|
|
3480
|
+
});
|
|
3481
|
+
this.connection.onRequest(
|
|
3482
|
+
"userInput.request",
|
|
3483
|
+
async (params) => await this.handleUserInputRequest(params)
|
|
3484
|
+
);
|
|
3485
|
+
this.connection.onRequest(
|
|
3486
|
+
"shellAuthentication.request",
|
|
3487
|
+
async (params) => await this.handleShellAuthenticationRequest(params)
|
|
3488
|
+
);
|
|
3489
|
+
this.connection.onRequest(
|
|
3490
|
+
"shellAuthentication.cancel",
|
|
3491
|
+
async (params) => {
|
|
3492
|
+
this.cancelShellAuthenticationRequest(params);
|
|
3493
|
+
return {};
|
|
3494
|
+
}
|
|
3495
|
+
);
|
|
3496
|
+
this.connection.onRequest(
|
|
3497
|
+
"exitPlanMode.request",
|
|
3498
|
+
async (params) => await this.handleExitPlanModeRequest(params)
|
|
3499
|
+
);
|
|
3500
|
+
this.connection.onRequest(
|
|
3501
|
+
"autoModeSwitch.request",
|
|
3502
|
+
async (params) => await this.handleAutoModeSwitchRequest(params)
|
|
3503
|
+
);
|
|
3504
|
+
this.connection.onRequest(
|
|
3505
|
+
"systemMessage.transform",
|
|
3506
|
+
async (params) => await this.handleSystemMessageTransform(params)
|
|
3507
|
+
);
|
|
3508
|
+
registerClientSessionApiHandlers(this.connection, (sessionId) => {
|
|
3509
|
+
const session = this.resolveSessionCallback(sessionId);
|
|
3510
|
+
if (!session) throw new Error(`No session found for sessionId: ${sessionId}`);
|
|
3511
|
+
return session.clientSessionApis;
|
|
3512
|
+
});
|
|
3513
|
+
registerClientGlobalApiHandlers(this.connection, this.clientGlobalHandlers);
|
|
3514
|
+
if (this.options.entra?.tokenProvider) {
|
|
3515
|
+
registerEntraTokenProvider(this.connection, this.options.entra.tokenProvider);
|
|
3516
|
+
}
|
|
3517
|
+
if (this.installationConfirmationHandler) {
|
|
3518
|
+
const confirmation = createInstallationConfirmationAdapter(
|
|
3519
|
+
this.connection,
|
|
3520
|
+
this.installationConfirmationHandler
|
|
3521
|
+
);
|
|
3522
|
+
this.connection.onRequest(
|
|
3523
|
+
"installations.confirm",
|
|
3524
|
+
(params, token) => confirmation.confirm(params, token)
|
|
3525
|
+
);
|
|
3526
|
+
}
|
|
3527
|
+
const resolveProxy = this.network?.resolveProxy;
|
|
3528
|
+
if (resolveProxy) {
|
|
3529
|
+
const connection2 = this.connection;
|
|
3530
|
+
this.connection.onRequest(
|
|
3531
|
+
"network.resolveProxy",
|
|
3532
|
+
(params, token) => resolveClientProxy(connection2, resolveProxy, params, token)
|
|
3533
|
+
);
|
|
3534
|
+
}
|
|
3535
|
+
const authenticateNegotiate = this.network?.authenticateNegotiate;
|
|
3536
|
+
if (authenticateNegotiate) {
|
|
3537
|
+
const connection2 = this.connection;
|
|
3538
|
+
this.connection.onRequest(
|
|
3539
|
+
"network.authenticateNegotiate",
|
|
3540
|
+
(params, token) => authenticateClientNegotiate(connection2, authenticateNegotiate, params, token)
|
|
3541
|
+
);
|
|
3542
|
+
}
|
|
3543
|
+
const authenticateBasic = this.network?.authenticateBasic;
|
|
3544
|
+
if (authenticateBasic) {
|
|
3545
|
+
const connection2 = this.connection;
|
|
3546
|
+
this.connection.onRequest(
|
|
3547
|
+
"network.authenticateBasic",
|
|
3548
|
+
(params, token) => authenticateClientBasic(connection2, authenticateBasic, params, token)
|
|
3549
|
+
);
|
|
3550
|
+
}
|
|
3551
|
+
this.connection.onRequest(
|
|
3552
|
+
"host.materializeSession",
|
|
3553
|
+
(params) => this.createHostSession(params)
|
|
3554
|
+
);
|
|
3555
|
+
this.connection.onRequest(
|
|
3556
|
+
"host.validateAuthentication",
|
|
3557
|
+
async (params) => {
|
|
3558
|
+
const authenticator = this.hostAuthenticators.get(params.hostId);
|
|
3559
|
+
if (!authenticator || this.hostAuthentications.has(params.requestId)) {
|
|
3560
|
+
throw new Error("AHP authenticator is unavailable or request already exists");
|
|
3561
|
+
}
|
|
3562
|
+
const entry = { hostId: params.hostId, controller: new AbortController() };
|
|
3563
|
+
this.hostAuthentications.set(params.requestId, entry);
|
|
3564
|
+
const signal = entry.controller.signal;
|
|
3565
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
3566
|
+
signal.addEventListener(
|
|
3567
|
+
"abort",
|
|
3568
|
+
() => reject(new Error("AHP authentication ended")),
|
|
3569
|
+
{ once: true }
|
|
3570
|
+
);
|
|
3571
|
+
});
|
|
3572
|
+
try {
|
|
3573
|
+
const result = await Promise.race([
|
|
3574
|
+
Promise.resolve().then(
|
|
3575
|
+
() => authenticator.authenticate({ token: params.token, signal })
|
|
3576
|
+
),
|
|
3577
|
+
cancelled
|
|
3578
|
+
]);
|
|
3579
|
+
if (signal.aborted || this.hostAuthenticators.get(params.hostId) !== authenticator) {
|
|
3580
|
+
throw new Error("AHP authentication ended");
|
|
3581
|
+
}
|
|
3582
|
+
return result;
|
|
3583
|
+
} finally {
|
|
3584
|
+
if (this.hostAuthentications.get(params.requestId) === entry) {
|
|
3585
|
+
this.hostAuthentications.delete(params.requestId);
|
|
3586
|
+
}
|
|
3587
|
+
entry.controller.abort();
|
|
3588
|
+
}
|
|
3589
|
+
}
|
|
3590
|
+
);
|
|
3591
|
+
this.connection.onNotification(
|
|
3592
|
+
"host.authenticationCancelled",
|
|
3593
|
+
(params) => {
|
|
3594
|
+
const entry = this.hostAuthentications.get(params.requestId);
|
|
3595
|
+
if (entry?.hostId === params.hostId) entry.controller.abort();
|
|
3596
|
+
}
|
|
3597
|
+
);
|
|
3598
|
+
this.connection.onNotification(
|
|
3599
|
+
"host.sessionReleased",
|
|
3600
|
+
(params) => {
|
|
3601
|
+
if (this.hostHandoffs.get(params.handoffId)?.hostId === params.hostId) {
|
|
3602
|
+
this.releaseHostSession(params.handoffId);
|
|
3603
|
+
}
|
|
3604
|
+
}
|
|
3605
|
+
);
|
|
3606
|
+
this.connection.onRequest(
|
|
3607
|
+
"hooks.invoke",
|
|
3608
|
+
async (params) => {
|
|
3609
|
+
return await this.handleHooksInvoke(params);
|
|
3610
|
+
}
|
|
3611
|
+
);
|
|
3612
|
+
this.connection.onRequest(
|
|
3613
|
+
"skillProvider.list",
|
|
3614
|
+
async (params, token) => await this.resolveSkillProviderSession(params)._handleSkillProviderList(token)
|
|
3615
|
+
);
|
|
3616
|
+
this.connection.onRequest(
|
|
3617
|
+
"sessionManagement.create",
|
|
3618
|
+
async (params, token) => {
|
|
3619
|
+
const session = this.resolveSessionCallback(params.sessionId);
|
|
3620
|
+
if (!session) throw new Error("Session creation owner is unavailable");
|
|
3621
|
+
return await session._handleSessionManagementCreate(params, token);
|
|
3622
|
+
}
|
|
3623
|
+
);
|
|
3624
|
+
this.connection.onRequest(
|
|
3625
|
+
"memoryStore.store",
|
|
3626
|
+
async (params, token) => {
|
|
3627
|
+
const session = this.sessions.get(params?.sessionId);
|
|
3628
|
+
if (!session) throw new Error("Memory store owner is unavailable");
|
|
3629
|
+
const controller = new AbortController();
|
|
3630
|
+
this.pendingMemoryStores.add(controller);
|
|
3631
|
+
const subscription = token.onCancellationRequested(() => controller.abort());
|
|
3632
|
+
if (token.isCancellationRequested) controller.abort();
|
|
3633
|
+
try {
|
|
3634
|
+
await session._handleMemoryStore(params, controller.signal);
|
|
3635
|
+
} finally {
|
|
3636
|
+
this.pendingMemoryStores.delete(controller);
|
|
3637
|
+
subscription.dispose();
|
|
3638
|
+
}
|
|
3639
|
+
return null;
|
|
3640
|
+
}
|
|
3641
|
+
);
|
|
3642
|
+
this.connection.onRequest(
|
|
3643
|
+
"skillProvider.read",
|
|
3644
|
+
async (params, token) => {
|
|
3645
|
+
const session = this.resolveSkillProviderSession(params);
|
|
3646
|
+
if (typeof params.name !== "string") {
|
|
3647
|
+
throw new Error("Invalid skillProvider.read payload");
|
|
3648
|
+
}
|
|
3649
|
+
return await session._handleSkillProviderRead(params.name, token);
|
|
3650
|
+
}
|
|
3651
|
+
);
|
|
3652
|
+
const connection = this.connection;
|
|
3653
|
+
const messageWriter = this.messageWriter;
|
|
3654
|
+
const cliProcess = this.isExternalServer ? null : this.cliProcess;
|
|
3655
|
+
const connectionEpoch = this.connectionEpoch;
|
|
3656
|
+
const isCurrentConnection = () => connectionEpoch === this.connectionEpoch && this.connection === connection && (cliProcess === null || this.cliProcess === cliProcess);
|
|
3657
|
+
let disconnected;
|
|
3658
|
+
let exitFallback;
|
|
3659
|
+
const markDisconnected = () => {
|
|
3660
|
+
if (!isCurrentConnection()) {
|
|
3661
|
+
connection.dispose();
|
|
3662
|
+
return;
|
|
3663
|
+
}
|
|
3664
|
+
this.connectionClosed = true;
|
|
3665
|
+
this.state = "disconnected";
|
|
3666
|
+
this.disconnectHosts();
|
|
3667
|
+
for (const session of this.sessions.values()) {
|
|
3668
|
+
session._markDisconnected();
|
|
3669
|
+
}
|
|
3670
|
+
this.sessions.clear();
|
|
3671
|
+
this.abortPendingShellAuthenticationRequests();
|
|
3672
|
+
this.githubTokenProviders.clear();
|
|
3673
|
+
this.requestAdapter?.cancelPending();
|
|
3674
|
+
this.abortPendingMemoryStores();
|
|
3675
|
+
connection.dispose();
|
|
3676
|
+
this.socket?.destroy();
|
|
3677
|
+
this.connection = null;
|
|
3678
|
+
this.messageWriter = null;
|
|
3679
|
+
this._rpc = null;
|
|
3680
|
+
this._internalRpc = null;
|
|
3681
|
+
this.modelsCache = { models: null, lock: Promise.resolve() };
|
|
3682
|
+
};
|
|
3683
|
+
const disconnectAfterDrain = () => {
|
|
3684
|
+
if (exitFallback !== void 0) {
|
|
3685
|
+
clearTimeout(exitFallback);
|
|
3686
|
+
exitFallback = void 0;
|
|
3687
|
+
}
|
|
3688
|
+
if (!isCurrentConnection()) {
|
|
3689
|
+
connection.dispose();
|
|
3690
|
+
return Promise.resolve();
|
|
3691
|
+
}
|
|
3692
|
+
if (disconnected) return disconnected;
|
|
3693
|
+
this.invalidateSessionInitializations();
|
|
3694
|
+
this.connectionClosed = true;
|
|
3695
|
+
if (messageWriter) messageWriter.suppressWriteErrors = true;
|
|
3696
|
+
disconnected = connection.drain().then(markDisconnected);
|
|
3697
|
+
return disconnected;
|
|
3698
|
+
};
|
|
3699
|
+
this.retireClosedConnection = disconnectAfterDrain;
|
|
3700
|
+
this.connection.onClose(disconnectAfterDrain);
|
|
3701
|
+
if (cliProcess) {
|
|
3702
|
+
cliProcess.once("exit", () => {
|
|
3703
|
+
if (!isCurrentConnection()) {
|
|
3704
|
+
connection.dispose();
|
|
3705
|
+
return;
|
|
3706
|
+
}
|
|
3707
|
+
if (disconnected) return;
|
|
3708
|
+
if (this.socket) {
|
|
3709
|
+
disconnectAfterDrain();
|
|
3710
|
+
return;
|
|
3711
|
+
}
|
|
3712
|
+
this.connectionClosed = true;
|
|
3713
|
+
if (messageWriter) messageWriter.suppressWriteErrors = true;
|
|
3714
|
+
exitFallback = setTimeout(disconnectAfterDrain, RUNTIME_SHUTDOWN_TIMEOUT_MS);
|
|
3715
|
+
exitFallback.unref?.();
|
|
3716
|
+
});
|
|
3717
|
+
}
|
|
3718
|
+
this.connection.onError(([error]) => {
|
|
3719
|
+
if (messageEncodeErrors.has(error)) {
|
|
3720
|
+
return;
|
|
3721
|
+
}
|
|
3722
|
+
if (connectionEpoch === this.connectionEpoch && this.connection === connection) {
|
|
3723
|
+
this.state = "disconnected";
|
|
3724
|
+
}
|
|
3725
|
+
});
|
|
3726
|
+
}
|
|
3727
|
+
resolveSessionCallback(sessionId) {
|
|
3728
|
+
let selected;
|
|
3729
|
+
let selectedPrefixLength = -1;
|
|
3730
|
+
for (const [prefix, pending] of this.pendingSessionResumes) {
|
|
3731
|
+
if (pending.connection !== this.connection || !pending.resolveAliases && prefix !== sessionId || prefix.length <= selectedPrefixLength || !(sessionIdsOverlap(prefix, sessionId) && sessionId.length >= prefix.length))
|
|
3732
|
+
continue;
|
|
3733
|
+
const knownOwners = new Set(
|
|
3734
|
+
[...this.sessions.values()].filter(
|
|
3735
|
+
(owner) => owner !== pending.session && sessionIdsOverlap(prefix, owner.sessionId) && owner.sessionId.length >= prefix.length
|
|
3736
|
+
)
|
|
3737
|
+
);
|
|
3738
|
+
if (knownOwners.size > 1) continue;
|
|
3739
|
+
if (pending.session.sessionId !== sessionId) {
|
|
3740
|
+
pending.session._setSessionId(sessionId);
|
|
3741
|
+
}
|
|
3742
|
+
this.assignGitHubTokenProvider(pending.gitHubTokenProviderRegistrationId, sessionId);
|
|
3743
|
+
selected = pending.session;
|
|
3744
|
+
selectedPrefixLength = prefix.length;
|
|
3745
|
+
}
|
|
3746
|
+
return selected ?? this.sessions.get(sessionId);
|
|
3747
|
+
}
|
|
3748
|
+
handleSessionEventNotification(notification) {
|
|
3749
|
+
if (typeof notification !== "object" || !notification || !("sessionId" in notification) || typeof notification.sessionId !== "string" || !("event" in notification)) {
|
|
3750
|
+
return;
|
|
3751
|
+
}
|
|
3752
|
+
const session = this.resolveSessionCallback(
|
|
3753
|
+
notification.sessionId
|
|
3754
|
+
);
|
|
3755
|
+
const event = notification.event;
|
|
3756
|
+
if (session) {
|
|
3757
|
+
session._dispatchEvent(event);
|
|
3758
|
+
}
|
|
3759
|
+
}
|
|
3760
|
+
handleSessionLifecycleNotification(notification) {
|
|
3761
|
+
if (typeof notification !== "object" || !notification || !("type" in notification) || typeof notification.type !== "string" || !("sessionId" in notification) || typeof notification.sessionId !== "string") {
|
|
3762
|
+
return;
|
|
3763
|
+
}
|
|
3764
|
+
const raw = notification;
|
|
3765
|
+
let metadata;
|
|
3766
|
+
if (raw.metadata && raw.metadata.startTime && raw.metadata.modifiedTime) {
|
|
3767
|
+
metadata = {
|
|
3768
|
+
startTime: new Date(raw.metadata.startTime),
|
|
3769
|
+
modifiedTime: new Date(raw.metadata.modifiedTime),
|
|
3770
|
+
summary: raw.metadata.summary
|
|
3771
|
+
};
|
|
3772
|
+
}
|
|
3773
|
+
const event = {
|
|
3774
|
+
type: raw.type,
|
|
3775
|
+
sessionId: raw.sessionId,
|
|
3776
|
+
metadata
|
|
3777
|
+
};
|
|
3778
|
+
const typedHandlers = this.typedLifecycleHandlers.get(event.type);
|
|
3779
|
+
if (typedHandlers) {
|
|
3780
|
+
for (const handler of typedHandlers) {
|
|
3781
|
+
try {
|
|
3782
|
+
handler(event);
|
|
3783
|
+
} catch {
|
|
3784
|
+
}
|
|
3785
|
+
}
|
|
3786
|
+
}
|
|
3787
|
+
for (const handler of this.sessionLifecycleHandlers) {
|
|
3788
|
+
try {
|
|
3789
|
+
handler(event);
|
|
3790
|
+
} catch {
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
}
|
|
3794
|
+
async handleUserInputRequest(params) {
|
|
3795
|
+
if (!params || typeof params.sessionId !== "string" || typeof params.question !== "string") {
|
|
3796
|
+
throw new Error("Invalid user input request payload");
|
|
3797
|
+
}
|
|
3798
|
+
const session = this.resolveSessionCallback(params.sessionId);
|
|
3799
|
+
if (!session) {
|
|
3800
|
+
throw new Error(`Session not found: ${params.sessionId}`);
|
|
3801
|
+
}
|
|
3802
|
+
const result = await session._handleUserInputRequest({
|
|
3803
|
+
question: params.question,
|
|
3804
|
+
choices: params.choices,
|
|
3805
|
+
allowFreeform: params.allowFreeform,
|
|
3806
|
+
requestId: params.requestId
|
|
3807
|
+
});
|
|
3808
|
+
return result;
|
|
3809
|
+
}
|
|
3810
|
+
async handleShellAuthenticationRequest(params) {
|
|
3811
|
+
const inputKinds = ["secret", "text", "confirm"];
|
|
3812
|
+
if (!params || typeof params.sessionId !== "string" || typeof params.requestId !== "string" || typeof params.program !== "string" || typeof params.prompt !== "string" || !inputKinds.includes(params.inputKind)) {
|
|
3813
|
+
return { action: "cancel" };
|
|
3814
|
+
}
|
|
3815
|
+
const session = this.sessions.get(params.sessionId);
|
|
3816
|
+
let pending = this.pendingShellAuthenticationRequests.get(params.sessionId);
|
|
3817
|
+
if (!session || pending?.has(params.requestId)) {
|
|
3818
|
+
return { action: "cancel" };
|
|
3819
|
+
}
|
|
3820
|
+
if (!pending) {
|
|
3821
|
+
pending = /* @__PURE__ */ new Map();
|
|
3822
|
+
this.pendingShellAuthenticationRequests.set(params.sessionId, pending);
|
|
3823
|
+
}
|
|
3824
|
+
const controller = new AbortController();
|
|
3825
|
+
pending.set(params.requestId, controller);
|
|
3826
|
+
try {
|
|
3827
|
+
return await session._handleShellAuthenticationRequest(
|
|
3828
|
+
{
|
|
3829
|
+
requestId: params.requestId,
|
|
3830
|
+
program: params.program,
|
|
3831
|
+
prompt: params.prompt,
|
|
3832
|
+
inputKind: params.inputKind,
|
|
3833
|
+
command: typeof params.command === "string" ? params.command : "",
|
|
3834
|
+
cwd: typeof params.cwd === "string" ? params.cwd : ""
|
|
3835
|
+
},
|
|
3836
|
+
controller.signal
|
|
3837
|
+
);
|
|
3838
|
+
} finally {
|
|
3839
|
+
pending.delete(params.requestId);
|
|
3840
|
+
if (pending.size === 0 && this.pendingShellAuthenticationRequests.get(params.sessionId) === pending) {
|
|
3841
|
+
this.pendingShellAuthenticationRequests.delete(params.sessionId);
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
cancelShellAuthenticationRequest(params) {
|
|
3846
|
+
if (typeof params?.sessionId === "string" && typeof params.requestId === "string") {
|
|
3847
|
+
this.pendingShellAuthenticationRequests.get(params.sessionId)?.get(params.requestId)?.abort();
|
|
3848
|
+
}
|
|
3849
|
+
}
|
|
3850
|
+
/** Cancels every open secret prompt once the runtime can no longer use an answer. */
|
|
3851
|
+
abortPendingShellAuthenticationRequests() {
|
|
3852
|
+
for (const pending of this.pendingShellAuthenticationRequests.values()) {
|
|
3853
|
+
for (const controller of pending.values()) {
|
|
3854
|
+
controller.abort();
|
|
3855
|
+
}
|
|
3856
|
+
}
|
|
3857
|
+
this.pendingShellAuthenticationRequests.clear();
|
|
3858
|
+
}
|
|
3859
|
+
async handleExitPlanModeRequest(params) {
|
|
3860
|
+
if (!params || typeof params.sessionId !== "string" || typeof params.summary !== "string" || !Array.isArray(params.actions) || typeof params.recommendedAction !== "string") {
|
|
3861
|
+
throw new Error("Invalid exit plan mode request payload");
|
|
3862
|
+
}
|
|
3863
|
+
const session = this.resolveSessionCallback(params.sessionId);
|
|
3864
|
+
if (!session) {
|
|
3865
|
+
throw new Error(`Session not found: ${params.sessionId}`);
|
|
3866
|
+
}
|
|
3867
|
+
return await session._handleExitPlanModeRequest({
|
|
3868
|
+
summary: params.summary,
|
|
3869
|
+
planContent: params.planContent,
|
|
3870
|
+
actions: params.actions,
|
|
3871
|
+
recommendedAction: params.recommendedAction,
|
|
3872
|
+
requestId: params.requestId
|
|
3873
|
+
});
|
|
3874
|
+
}
|
|
3875
|
+
async handleAutoModeSwitchRequest(params) {
|
|
3876
|
+
if (!params || typeof params.sessionId !== "string") {
|
|
3877
|
+
throw new Error("Invalid auto mode switch request payload");
|
|
3878
|
+
}
|
|
3879
|
+
const session = this.resolveSessionCallback(params.sessionId);
|
|
3880
|
+
if (!session) {
|
|
3881
|
+
throw new Error(`Session not found: ${params.sessionId}`);
|
|
3882
|
+
}
|
|
3883
|
+
const response = await session._handleAutoModeSwitchRequest({
|
|
3884
|
+
errorCode: params.errorCode,
|
|
3885
|
+
retryAfterSeconds: params.retryAfterSeconds,
|
|
3886
|
+
...params.autoModeRecovery === void 0 ? {} : { autoModeRecovery: params.autoModeRecovery }
|
|
3887
|
+
});
|
|
3888
|
+
return { response };
|
|
3889
|
+
}
|
|
3890
|
+
resolveSkillProviderSession(params) {
|
|
3891
|
+
if (!params || typeof params.sessionId !== "string") {
|
|
3892
|
+
throw new Error("Invalid skillProvider payload");
|
|
3893
|
+
}
|
|
3894
|
+
const session = this.resolveSessionCallback(params.sessionId);
|
|
3895
|
+
if (!session) {
|
|
3896
|
+
throw new Error(`Session not found: ${params.sessionId}`);
|
|
3897
|
+
}
|
|
3898
|
+
return session;
|
|
3899
|
+
}
|
|
3900
|
+
async handleHooksInvoke(params) {
|
|
3901
|
+
if (!params || typeof params.sessionId !== "string" || typeof params.hookType !== "string") {
|
|
3902
|
+
throw new Error("Invalid hooks invoke payload");
|
|
3903
|
+
}
|
|
3904
|
+
const session = this.resolveSessionCallback(params.sessionId);
|
|
3905
|
+
if (!session) {
|
|
3906
|
+
throw new Error(`Session not found: ${params.sessionId}`);
|
|
3907
|
+
}
|
|
3908
|
+
const output = await session._handleHooksInvoke(params.hookType, params.input);
|
|
3909
|
+
return { output };
|
|
3910
|
+
}
|
|
3911
|
+
async handleSystemMessageTransform(params) {
|
|
3912
|
+
if (!params || typeof params.sessionId !== "string" || !params.sections || typeof params.sections !== "object") {
|
|
3913
|
+
throw new Error("Invalid systemMessage.transform payload");
|
|
3914
|
+
}
|
|
3915
|
+
const session = this.resolveSessionCallback(params.sessionId);
|
|
3916
|
+
if (!session) {
|
|
3917
|
+
throw new Error(`Session not found: ${params.sessionId}`);
|
|
3918
|
+
}
|
|
3919
|
+
return await session._handleSystemMessageTransform(params.sections);
|
|
3920
|
+
}
|
|
3921
|
+
}
|
|
3922
|
+
export {
|
|
3923
|
+
CopilotClient
|
|
3924
|
+
};
|