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