@microsoft/copilot-sdk 1.0.29-unstable.42916223485.gfff36db → 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 (48) hide show
  1. package/README.md +80 -62
  2. package/dist/canvas.d.ts +4 -0
  3. package/dist/canvas.js +1 -0
  4. package/dist/cjs/canvas.js +1 -0
  5. package/dist/cjs/cliVersion.js +1 -1
  6. package/dist/cjs/client.js +294 -107
  7. package/dist/cjs/copilotRequestHandler.js +24 -1
  8. package/dist/cjs/extension.js +4 -1
  9. package/dist/cjs/generated/rpc.js +295 -16
  10. package/dist/cjs/index.js +12 -2
  11. package/dist/cjs/localModelJson.js +103 -0
  12. package/dist/cjs/providerConfiguration.js +39 -0
  13. package/dist/cjs/rpcCancellation.js +49 -0
  14. package/dist/cjs/session.js +155 -10
  15. package/dist/cjs/taskAnalyticsJson.js +47 -0
  16. package/dist/cjs/types.js +14 -3
  17. package/dist/cjs/workflow.js +145 -1
  18. package/dist/cliVersion.d.ts +1 -1
  19. package/dist/cliVersion.js +1 -1
  20. package/dist/client.d.ts +33 -14
  21. package/dist/client.js +294 -107
  22. package/dist/copilotRequestHandler.js +24 -1
  23. package/dist/extension.d.ts +12 -2
  24. package/dist/extension.js +4 -1
  25. package/dist/generated/lifecycle-diagnostics.d.ts +48 -40
  26. package/dist/generated/rpc.d.ts +3668 -500
  27. package/dist/generated/rpc.js +295 -16
  28. package/dist/generated/session-events.d.ts +358 -115
  29. package/dist/index.d.ts +9 -5
  30. package/dist/index.js +14 -2
  31. package/dist/localModelJson.d.ts +1 -0
  32. package/dist/localModelJson.js +69 -0
  33. package/dist/providerConfiguration.d.ts +3 -0
  34. package/dist/providerConfiguration.js +15 -0
  35. package/dist/rpcCancellation.d.ts +3 -0
  36. package/dist/rpcCancellation.js +25 -0
  37. package/dist/session.d.ts +64 -5
  38. package/dist/session.js +156 -10
  39. package/dist/taskAnalyticsJson.d.ts +8 -0
  40. package/dist/taskAnalyticsJson.js +12 -0
  41. package/dist/types.d.ts +223 -43
  42. package/dist/types.js +13 -3
  43. package/dist/workflow.d.ts +60 -14
  44. package/dist/workflow.js +143 -1
  45. package/docs/agent-author.md +11 -11
  46. package/docs/extensions.md +41 -2
  47. package/docs/workflows.md +52 -17
  48. package/package.json +16 -15
@@ -44,6 +44,7 @@ var import_sdkProtocolVersion = require("./sdkProtocolVersion.js");
44
44
  var import_session = require("./session.js");
45
45
  var import_host = require("./host.js");
46
46
  var import_runtimeArtifacts = require("./runtimeArtifacts.js");
47
+ var import_localModelJson = require("./localModelJson.js");
47
48
  var import_cliVersion = require("./cliVersion.js");
48
49
  var import_sessionFsProvider = require("./sessionFsProvider.js");
49
50
  var import_copilotRequestHandler = require("./copilotRequestHandler.js");
@@ -53,6 +54,7 @@ var import_telemetry = require("./telemetry.js");
53
54
  var import_schema = require("./schema.js");
54
55
  var import_toolSet = require("./toolSet.js");
55
56
  var import_types = require("./types.js");
57
+ var import_workflow = require("./workflow.js");
56
58
  const MIN_PROTOCOL_VERSION = 3;
57
59
  const RUNTIME_SHUTDOWN_TIMEOUT_MS = 1e4;
58
60
  const CLOUD_SESSION_CLEANUP_TIMEOUT_MS = 1e4;
@@ -71,18 +73,20 @@ function isUuidSessionId(sessionId) {
71
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);
72
74
  }
73
75
  const messageEncodeErrors = /* @__PURE__ */ new WeakSet();
74
- const jsonMessageEncoder = {
75
- name: "application/json",
76
- encode: (msg, options) => {
77
- try {
78
- return Promise.resolve(Buffer.from(JSON.stringify(msg), options.charset));
79
- } catch (thrown) {
80
- const error = thrown instanceof Error ? thrown : new Error(String(thrown));
81
- messageEncodeErrors.add(error);
82
- return Promise.reject(error);
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
+ }
83
87
  }
84
- }
85
- };
88
+ };
89
+ }
86
90
  function createMessageConnection(reader, writer, sessionInitializationContext) {
87
91
  let dispatch;
88
92
  let finishDrain;
@@ -235,11 +239,12 @@ async function runCancellableCallback(connection, label, token, invoke) {
235
239
  }
236
240
  }
237
241
  function snapshotNetworkConfig(network) {
238
- const { scope, resolveProxy, authenticateNegotiate } = network;
242
+ const { scope, resolveProxy, authenticateNegotiate, authenticateBasic } = network;
239
243
  return {
240
244
  scope,
241
245
  resolveProxy: resolveProxy && ((request, signal) => resolveProxy.call(network, request, signal)),
242
- authenticateNegotiate: authenticateNegotiate && ((request, signal) => authenticateNegotiate.call(network, request, signal))
246
+ authenticateNegotiate: authenticateNegotiate && ((request, signal) => authenticateNegotiate.call(network, request, signal)),
247
+ authenticateBasic: authenticateBasic && ((request, signal) => authenticateBasic.call(network, request, signal))
243
248
  };
244
249
  }
245
250
  async function resolveClientProxy(connection, callback, request, token) {
@@ -262,6 +267,15 @@ async function authenticateClientNegotiate(connection, callback, request, token)
262
267
  )
263
268
  };
264
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
+ }
265
279
  const DEFAULT_PROVIDER_NAME = "default";
266
280
  function extractBearerTokenProviders(provider, providers) {
267
281
  const callbacks = /* @__PURE__ */ new Map();
@@ -320,6 +334,9 @@ function toWireCustomAgents(agents) {
320
334
  return { ...rest, mcpServers: toWireMcpServers(mcpServers) };
321
335
  });
322
336
  }
337
+ async function sendPing(connection, message) {
338
+ return await connection.sendRequest("ping", { message });
339
+ }
323
340
  function clientInfoToWire(info) {
324
341
  if (info == null) return void 0;
325
342
  const wire = {};
@@ -395,8 +412,8 @@ async function getSpawnableBundledRuntimePath() {
395
412
  }
396
413
  class TeardownResilientStreamMessageWriter extends import_node.StreamMessageWriter {
397
414
  suppressWriteErrors = false;
398
- constructor(writable) {
399
- super(writable, { contentTypeEncoder: jsonMessageEncoder });
415
+ constructor(writable, codec) {
416
+ super(writable, { contentTypeEncoder: jsonMessageEncoder(codec) });
400
417
  }
401
418
  async write(msg) {
402
419
  try {
@@ -417,17 +434,24 @@ class CopilotClient {
417
434
  pendingMemoryStores = /* @__PURE__ */ new Set();
418
435
  messageWriter = null;
419
436
  connectionClosed = false;
437
+ // Disconnects the current connection without waiting for its reader to reach EOF.
438
+ retireClosedConnection = null;
420
439
  connectionEpoch = 0;
421
440
  socket = null;
422
441
  runtimePort = null;
423
442
  actualHost = "localhost";
424
443
  state = "disconnected";
425
- /** Shared in-flight start; concurrent callers await it instead of spawning another CLI. */
444
+ /** Shared in-flight start; concurrent callers await the same runtime startup. */
426
445
  startPromise = null;
427
446
  shutdownCanceledStartup = null;
428
447
  stopPromise = null;
429
448
  forceStopPromise = null;
430
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();
431
455
  pendingSessionResumes = /* @__PURE__ */ new Map();
432
456
  sessionInitializations = /* @__PURE__ */ new Map();
433
457
  failedAutoModeRecoveryCleanups = /* @__PURE__ */ new WeakMap();
@@ -530,7 +554,7 @@ class CopilotClient {
530
554
  /**
531
555
  * Environment variable that overrides the transport when the caller does not set
532
556
  * {@link CopilotClientOptions.connection}. Accepts `"inprocess"` or `"stdio"`
533
- * (case-insensitive); unset preserves the default stdio transport. Any other value
557
+ * (case-insensitive); unset selects the in-process transport. Any other value
534
558
  * is an error.
535
559
  */
536
560
  static DEFAULT_CONNECTION_ENV_VAR = "COPILOT_SDK_DEFAULT_CONNECTION";
@@ -540,10 +564,10 @@ class CopilotClient {
540
564
  */
541
565
  static resolveDefaultConnection() {
542
566
  const value = process.env[CopilotClient.DEFAULT_CONNECTION_ENV_VAR];
543
- if (!value || value.toLowerCase() === "stdio") {
567
+ if (value?.toLowerCase() === "stdio") {
544
568
  return { kind: "stdio" };
545
569
  }
546
- if (value.toLowerCase() === "inprocess") {
570
+ if (!value || value.toLowerCase() === "inprocess") {
547
571
  return { kind: "inprocess" };
548
572
  }
549
573
  throw new Error(
@@ -557,7 +581,7 @@ class CopilotClient {
557
581
  *
558
582
  * @example
559
583
  * ```typescript
560
- * // Default: spawns the bundled runtime over stdio
584
+ * // Default: loads the native runtime in this process
561
585
  * const client = new CopilotClient({ mode: "coding-agent" });
562
586
  *
563
587
  * // Connect to an existing runtime
@@ -603,11 +627,6 @@ class CopilotClient {
603
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."
604
628
  );
605
629
  }
606
- if (conn.kind === "inprocess" && options.telemetry !== void 0) {
607
- throw new Error(
608
- "telemetry is not supported with RuntimeConnection.forInProcess(): telemetry configuration is lowered to environment variables read by native runtime code running in the shared host process, so per-client telemetry cannot be honored in-process. Configure telemetry via the host process environment, or use a child-process transport."
609
- );
610
- }
611
630
  if ((conn.kind === "stdio" || conn.kind === "tcp") && conn.env !== void 0 && options.env !== void 0) {
612
631
  throw new Error(
613
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."
@@ -855,10 +874,11 @@ class CopilotClient {
855
874
  }
856
875
  }
857
876
  /**
858
- * Starts the CLI server and establishes a connection.
877
+ * Starts the runtime host and establishes a connection.
859
878
  *
860
- * If connecting to an external server (via cliUrl), only establishes the connection.
861
- * Otherwise, spawns the CLI server process and then connects.
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.
862
882
  *
863
883
  * This method is called automatically the first time you create or resume a session.
864
884
  *
@@ -888,6 +908,16 @@ class CopilotClient {
888
908
  if (startup && !this.stopPromise) {
889
909
  return startup;
890
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
+ }
891
921
  if (this.stopPromise || this.connection && this.sessionInitializationLifetime.signal.aborted) {
892
922
  throw new Error("Client disconnected during session initialization");
893
923
  }
@@ -911,6 +941,10 @@ class CopilotClient {
911
941
  this.processTransportError = null;
912
942
  this.state = "connecting";
913
943
  try {
944
+ if (this.cliProcess) {
945
+ await this.killCliProcess();
946
+ signal.throwIfAborted();
947
+ }
914
948
  if (this.connectionConfig.kind === "inprocess") {
915
949
  await this.startInProcessFfi();
916
950
  } else if (!this.isExternalServer) {
@@ -920,12 +954,13 @@ class CopilotClient {
920
954
  await this.connectToServer();
921
955
  signal.throwIfAborted();
922
956
  await this.verifyProtocolVersion();
923
- if (this.network?.resolveProxy || this.network?.authenticateNegotiate) {
924
- const { scope, resolveProxy, authenticateNegotiate } = this.network;
957
+ if (this.network?.resolveProxy || this.network?.authenticateNegotiate || this.network?.authenticateBasic) {
958
+ const { scope, resolveProxy, authenticateNegotiate, authenticateBasic } = this.network;
925
959
  await this.rpc.network.setProvider({
926
960
  ...scope ? { scope } : {},
927
961
  ...resolveProxy ? { resolveProxy: {} } : {},
928
- ...authenticateNegotiate ? { authenticateNegotiate: {} } : {}
962
+ ...authenticateNegotiate ? { authenticateNegotiate: {} } : {},
963
+ ...authenticateBasic ? { authenticateBasic: {} } : {}
929
964
  });
930
965
  }
931
966
  if (this.extensionLaunchProvider) {
@@ -966,17 +1001,13 @@ class CopilotClient {
966
1001
  * Stops the CLI server and closes all active sessions.
967
1002
  *
968
1003
  * This method performs graceful cleanup:
969
- * 1. Closes all active sessions (releases in-memory resources); detach
970
- * requests share one shutdown timeout
1004
+ * 1. Closes all active sessions, suspending unfinished work for resume;
1005
+ * detach requests share one shutdown timeout
971
1006
  * 2. Requests runtime shutdown for SDK-owned CLI processes
972
1007
  * 3. Closes the JSON-RPC connection
973
1008
  * 4. Signals EOF to an owned stdio process and waits for host cleanup, then
974
1009
  * terminates the process if it does not exit within the shutdown timeout
975
1010
  *
976
- * In-process connections first abort active turns without a timeout. That
977
- * step is outside the detach deadline, so in-process stop() can still wait
978
- * indefinitely if the runtime stops answering abort requests.
979
- *
980
1011
  * Note: session data on disk is preserved, so sessions can be resumed later.
981
1012
  * To permanently remove session data before stopping, call
982
1013
  * {@link deleteSession} for each session first.
@@ -1010,12 +1041,12 @@ class CopilotClient {
1010
1041
  async doStop(startup) {
1011
1042
  const errors = [];
1012
1043
  const activeSessions = [...this.sessions.values()];
1013
- if (this.connectionConfig.kind === "inprocess") {
1014
- await Promise.allSettled(activeSessions.map((session) => session.abort()));
1015
- }
1016
- let detachDeadlineTimer;
1017
- const detachDeadline = new Promise((resolve2) => {
1018
- detachDeadlineTimer = setTimeout(() => resolve2("timeout"), RUNTIME_SHUTDOWN_TIMEOUT_MS);
1044
+ let sessionCleanupDeadlineTimer;
1045
+ const sessionCleanupDeadline = new Promise((resolve2) => {
1046
+ sessionCleanupDeadlineTimer = setTimeout(
1047
+ () => resolve2("timeout"),
1048
+ RUNTIME_SHUTDOWN_TIMEOUT_MS
1049
+ );
1019
1050
  });
1020
1051
  for (const session of activeSessions) {
1021
1052
  const sessionId = session.sessionId;
@@ -1030,7 +1061,7 @@ class CopilotClient {
1030
1061
  try {
1031
1062
  const outcome = await Promise.race([
1032
1063
  session.disconnect().then(() => "disconnected"),
1033
- detachDeadline
1064
+ sessionCleanupDeadline
1034
1065
  ]);
1035
1066
  if (outcome === "timeout") {
1036
1067
  lastError = new Error(
@@ -1060,11 +1091,12 @@ class CopilotClient {
1060
1091
  );
1061
1092
  }
1062
1093
  }
1063
- clearTimeout(detachDeadlineTimer);
1094
+ clearTimeout(sessionCleanupDeadlineTimer);
1064
1095
  for (const session of /* @__PURE__ */ new Set([...activeSessions, ...this.sessions.values()])) {
1065
1096
  session._markDisconnected();
1066
1097
  }
1067
1098
  this.sessions.clear();
1099
+ this.abortPendingShellAuthenticationRequests();
1068
1100
  this.githubTokenProviders.clear();
1069
1101
  this.requestAdapter?.cancelPending();
1070
1102
  this.abortPendingMemoryStores();
@@ -1278,6 +1310,7 @@ class CopilotClient {
1278
1310
  session._markDisconnected();
1279
1311
  }
1280
1312
  this.sessions.clear();
1313
+ this.abortPendingShellAuthenticationRequests();
1281
1314
  this.githubTokenProviders.clear();
1282
1315
  this.requestAdapter?.cancelPending();
1283
1316
  this.abortPendingMemoryStores();
@@ -1318,20 +1351,25 @@ class CopilotClient {
1318
1351
  this.runtimePort = null;
1319
1352
  this.stderrBuffer = "";
1320
1353
  this.processExitPromise = null;
1321
- if (this.cliProcess && !this.isExternalServer) {
1322
- const child = this.cliProcess;
1323
- if (child.exitCode == null && child.signalCode == null) {
1324
- child.kill("SIGKILL");
1325
- if (!await waitForChildExit(child, RUNTIME_SHUTDOWN_TIMEOUT_MS)) {
1326
- throw new Error(
1327
- `Timed out waiting for CLI process to exit after SIGKILL: ${RUNTIME_SHUTDOWN_TIMEOUT_MS}ms`
1328
- );
1329
- }
1330
- }
1331
- if (this.cliProcess === child) {
1332
- this.cliProcess = 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
+ );
1333
1368
  }
1334
1369
  }
1370
+ if (this.cliProcess === child) {
1371
+ this.cliProcess = null;
1372
+ }
1335
1373
  }
1336
1374
  /**
1337
1375
  * Creates a new conversation session with the Copilot CLI.
@@ -1366,12 +1404,6 @@ class CopilotClient {
1366
1404
  * instances to plain string arrays, rejects misuse (bare `"*"`) and the
1367
1405
  * missing-availableTools case in `mode = "empty"`.
1368
1406
  *
1369
- * The SDK always sends `toolFilterPrecedence: "excluded"` so callers can
1370
- * compose include + exclude lists naturally (e.g. "everything matching X
1371
- * except Y") regardless of mode. Allowlist-precedence is intentionally not
1372
- * exposed — it's available on the runtime side as a CLI-only concession to
1373
- * legacy behavior, but SDK consumers always get the composable semantics.
1374
- *
1375
1407
  * @internal
1376
1408
  */
1377
1409
  resolveToolFilterOptions(config) {
@@ -1386,7 +1418,7 @@ class CopilotClient {
1386
1418
  );
1387
1419
  }
1388
1420
  }
1389
- return { availableTools, excludedTools, toolFilterPrecedence: "excluded" };
1421
+ return { availableTools, excludedTools };
1390
1422
  }
1391
1423
  /** Mode-specific defaults spread under the caller's config (app values win). */
1392
1424
  configDefaultsForMode() {
@@ -1635,6 +1667,9 @@ class CopilotClient {
1635
1667
  if (config.onUserInputRequest) {
1636
1668
  s.registerUserInputHandler(config.onUserInputRequest);
1637
1669
  }
1670
+ if (config.onShellAuthenticationRequest) {
1671
+ s.registerShellAuthenticationHandler(config.onShellAuthenticationRequest);
1672
+ }
1638
1673
  if (config.onElicitationRequest) {
1639
1674
  s.registerElicitationHandler(config.onElicitationRequest);
1640
1675
  }
@@ -1698,6 +1733,7 @@ class CopilotClient {
1698
1733
  contextTier: config.contextTier,
1699
1734
  tools: config.tools?.map((tool) => ({
1700
1735
  name: tool.name,
1736
+ title: tool.title,
1701
1737
  description: tool.description,
1702
1738
  parameters: (0, import_schema.toJsonSchema)(tool.parameters),
1703
1739
  overridesBuiltInTool: tool.overridesBuiltInTool,
@@ -1706,6 +1742,7 @@ class CopilotClient {
1706
1742
  defer: tool.defer,
1707
1743
  metadata: tool.metadata,
1708
1744
  isTerminal: tool.isTerminal,
1745
+ idempotent: tool.idempotent,
1709
1746
  namespace: tool.namespace
1710
1747
  })),
1711
1748
  toolSearch: config.toolSearch,
@@ -1723,8 +1760,8 @@ class CopilotClient {
1723
1760
  systemMessage: wireSystemMessage,
1724
1761
  availableTools: toolFilterOptions.availableTools,
1725
1762
  excludedTools: toolFilterOptions.excludedTools,
1726
- toolFilterPrecedence: toolFilterOptions.toolFilterPrecedence,
1727
1763
  excludedBuiltinAgents: config.excludedBuiltinAgents,
1764
+ includedBuiltinAgents: config.includedBuiltinAgents,
1728
1765
  provider: bearerWireProvider,
1729
1766
  capi: config.capi,
1730
1767
  providers: bearerWireProviders,
@@ -1739,6 +1776,7 @@ class CopilotClient {
1739
1776
  requestPermission: !!config.onPermissionRequest,
1740
1777
  requestUserInput: !!config.onUserInputRequest,
1741
1778
  requestElicitation: !!config.onElicitationRequest,
1779
+ ...config.onShellAuthenticationRequest ? { requestShellAuthentication: true } : {},
1742
1780
  askUserVariant: config.askUserVariant,
1743
1781
  ...config.enableMcpApps ? { requestMcpApps: true } : {},
1744
1782
  ...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
@@ -1925,7 +1963,20 @@ class CopilotClient {
1925
1963
  }
1926
1964
  /** @internal */
1927
1965
  async resumeSessionForExtension(sessionId, config, contributions = {}, extensionOptions) {
1928
- return this.resumeSessionInternal(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;
1929
1980
  }
1930
1981
  async resumeSessionInternal(sessionId, config, contributions = {}, extensionOptions) {
1931
1982
  if (config.autoModeRecovery && typeof config.onAutoModeSwitchRequest !== "function") {
@@ -1997,6 +2048,9 @@ class CopilotClient {
1997
2048
  if (config.onUserInputRequest) {
1998
2049
  session.registerUserInputHandler(config.onUserInputRequest);
1999
2050
  }
2051
+ if (config.onShellAuthenticationRequest) {
2052
+ session.registerShellAuthenticationHandler(config.onShellAuthenticationRequest);
2053
+ }
2000
2054
  if (config.onElicitationRequest) {
2001
2055
  session.registerElicitationHandler(config.onElicitationRequest);
2002
2056
  }
@@ -2073,15 +2127,16 @@ class CopilotClient {
2073
2127
  systemMessage: wireSystemMessage,
2074
2128
  availableTools: toolFilterOptions.availableTools,
2075
2129
  excludedTools: toolFilterOptions.excludedTools,
2076
- toolFilterPrecedence: toolFilterOptions.toolFilterPrecedence,
2077
2130
  enableSessionTelemetry: config.enableSessionTelemetry,
2078
2131
  excludedBuiltinAgents: config.excludedBuiltinAgents,
2132
+ includedBuiltinAgents: config.includedBuiltinAgents,
2079
2133
  enableCitations: config.enableCitations,
2080
2134
  enableFileChangeTracking: config.enableFileChangeTracking,
2081
2135
  sessionLimits: config.sessionLimits,
2082
2136
  autopilot: config.autopilot,
2083
2137
  tools: config.tools?.map((tool) => ({
2084
2138
  name: tool.name,
2139
+ title: tool.title,
2085
2140
  description: tool.description,
2086
2141
  parameters: (0, import_schema.toJsonSchema)(tool.parameters),
2087
2142
  overridesBuiltInTool: tool.overridesBuiltInTool,
@@ -2090,12 +2145,13 @@ class CopilotClient {
2090
2145
  defer: tool.defer,
2091
2146
  metadata: tool.metadata,
2092
2147
  isTerminal: tool.isTerminal,
2148
+ idempotent: tool.idempotent,
2093
2149
  namespace: tool.namespace
2094
2150
  })),
2095
2151
  toolSearch: config.toolSearch,
2096
2152
  imageGeneration: config.imageGeneration,
2097
2153
  canvases: config.canvases?.map((canvas) => canvas.declaration),
2098
- workflows: workflows?.map((workflow) => workflow.meta),
2154
+ workflows: workflows?.map(import_workflow.getWorkflowRegistration),
2099
2155
  requestCanvasRenderer: config.requestCanvasRenderer,
2100
2156
  requestExtensions: config.requestExtensions,
2101
2157
  extensionSdkPath: config.extensionSdkPath,
@@ -2114,6 +2170,7 @@ class CopilotClient {
2114
2170
  requestPermission: config.onPermissionRequest !== import_types.defaultJoinSessionPermissionHandler,
2115
2171
  requestUserInput: !!config.onUserInputRequest,
2116
2172
  requestElicitation: !!config.onElicitationRequest,
2173
+ ...config.onShellAuthenticationRequest ? { requestShellAuthentication: true } : {},
2117
2174
  askUserVariant: config.askUserVariant,
2118
2175
  ...config.enableMcpApps ? { requestMcpApps: true } : {},
2119
2176
  ...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
@@ -2572,7 +2629,8 @@ class CopilotClient {
2572
2629
  *
2573
2630
  * @param message - Optional message to include in the ping
2574
2631
  * @returns A promise that resolves with the ping response containing the message and timestamp
2575
- * @throws Error if the client is not connected
2632
+ * @throws Error if the client is not connected, or if a {@link start} in progress when
2633
+ * this was called fails
2576
2634
  *
2577
2635
  * @example
2578
2636
  * ```typescript
@@ -2581,31 +2639,45 @@ class CopilotClient {
2581
2639
  * ```
2582
2640
  */
2583
2641
  async ping(message) {
2584
- if (!this.connection) {
2585
- throw new Error("Client not connected");
2586
- }
2587
- const result = await this.connection.sendRequest("ping", { message });
2588
- return result;
2642
+ return sendPing(await this.getStartedConnection(), message);
2589
2643
  }
2590
2644
  /**
2591
2645
  * Get CLI status including version and protocol information
2592
2646
  */
2593
2647
  async getStatus() {
2594
- if (!this.connection) {
2595
- throw new Error("Client not connected");
2596
- }
2597
- const result = await this.connection.sendRequest("status.get", {});
2648
+ const connection = await this.getStartedConnection();
2649
+ const result = await connection.sendRequest("status.get", {});
2598
2650
  return result;
2599
2651
  }
2600
2652
  /**
2601
2653
  * Get current authentication status
2602
2654
  */
2603
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
+ }
2604
2677
  if (!this.connection) {
2605
2678
  throw new Error("Client not connected");
2606
2679
  }
2607
- const result = await this.connection.sendRequest("auth.getStatus", {});
2608
- return result;
2680
+ return this.connection;
2609
2681
  }
2610
2682
  /**
2611
2683
  * List available models with their metadata.
@@ -2616,10 +2688,12 @@ class CopilotClient {
2616
2688
  * Results are cached after the first successful call to avoid rate limiting.
2617
2689
  * The cache is cleared when the client disconnects.
2618
2690
  *
2619
- * @throws Error if not connected (when no custom handler is set)
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)
2620
2693
  */
2621
2694
  async listModels() {
2622
2695
  const cache = this.modelsCache;
2696
+ const startup = this.startPromise;
2623
2697
  const previousLock = cache.lock;
2624
2698
  let resolveLock;
2625
2699
  cache.lock = new Promise((resolve2) => {
@@ -2634,10 +2708,8 @@ class CopilotClient {
2634
2708
  if (this.onListModels) {
2635
2709
  models = await this.onListModels();
2636
2710
  } else {
2637
- if (!this.connection) {
2638
- throw new Error("Client not connected");
2639
- }
2640
- const result = await this.connection.sendRequest("models.list", {});
2711
+ const connection = await this.getStartedConnection(startup);
2712
+ const result = await connection.sendRequest("models.list", {});
2641
2713
  const response = result;
2642
2714
  models = response.models;
2643
2715
  for (const model of models) {
@@ -2669,7 +2741,8 @@ class CopilotClient {
2669
2741
  * that don't implement `connect`.
2670
2742
  */
2671
2743
  async verifyProtocolVersion() {
2672
- if (!this.connection) {
2744
+ const connection = this.connection;
2745
+ if (!connection) {
2673
2746
  throw new Error("Client not connected");
2674
2747
  }
2675
2748
  const maxVersion = (0, import_sdkProtocolVersion.getSdkProtocolVersion)();
@@ -2702,7 +2775,7 @@ class CopilotClient {
2702
2775
  if (this.options.entra) {
2703
2776
  throw new Error("This runtime does not support Entra client configuration.");
2704
2777
  }
2705
- serverVersion = (await raceAgainstExit(this.ping())).protocolVersion;
2778
+ serverVersion = (await raceAgainstExit(sendPing(connection))).protocolVersion;
2706
2779
  } else {
2707
2780
  throw err;
2708
2781
  }
@@ -3250,9 +3323,18 @@ stderr: ${this.stderrBuffer.trim().slice(-8192) || "(empty)"}`
3250
3323
  if (!this.ffiHost) {
3251
3324
  throw new Error("In-process FFI runtime host not started");
3252
3325
  }
3253
- this.messageWriter = new TeardownResilientStreamMessageWriter(this.ffiHost.sendStream);
3326
+ const codec = (0, import_localModelJson.createLocalModelJsonCodec)();
3327
+ this.messageWriter = new TeardownResilientStreamMessageWriter(
3328
+ this.ffiHost.sendStream,
3329
+ codec
3330
+ );
3254
3331
  this.connection = createMessageConnection(
3255
- new import_node.StreamMessageReader(this.ffiHost.receiveStream),
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
+ }),
3256
3338
  this.messageWriter,
3257
3339
  this.sessionInitializationContext
3258
3340
  );
@@ -3311,9 +3393,18 @@ stderr: ${stderrOutput}` : ""}`
3311
3393
  } catch {
3312
3394
  }
3313
3395
  });
3314
- this.messageWriter = new TeardownResilientStreamMessageWriter(this.cliProcess.stdin);
3396
+ const codec = (0, import_localModelJson.createLocalModelJsonCodec)();
3397
+ this.messageWriter = new TeardownResilientStreamMessageWriter(
3398
+ this.cliProcess.stdin,
3399
+ codec
3400
+ );
3315
3401
  this.connection = createMessageConnection(
3316
- new import_node.StreamMessageReader(this.cliProcess.stdout),
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
+ }),
3317
3408
  this.messageWriter,
3318
3409
  this.sessionInitializationContext
3319
3410
  );
@@ -3327,9 +3418,15 @@ stderr: ${stderrOutput}` : ""}`
3327
3418
  if (this.cliProcess) {
3328
3419
  throw new Error("CLI child process was unexpectedly started in parent process mode");
3329
3420
  }
3330
- this.messageWriter = new TeardownResilientStreamMessageWriter(process.stdout);
3421
+ const codec = (0, import_localModelJson.createLocalModelJsonCodec)();
3422
+ this.messageWriter = new TeardownResilientStreamMessageWriter(process.stdout, codec);
3331
3423
  this.connection = createMessageConnection(
3332
- new import_node.StreamMessageReader(process.stdin),
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
+ }),
3333
3430
  this.messageWriter,
3334
3431
  this.sessionInitializationContext
3335
3432
  );
@@ -3343,17 +3440,37 @@ stderr: ${stderrOutput}` : ""}`
3343
3440
  if (!this.runtimePort) {
3344
3441
  throw new Error("Server port not available");
3345
3442
  }
3443
+ const signal = this.sessionInitializationLifetime.signal;
3444
+ signal.throwIfAborted();
3346
3445
  return new Promise((resolve2, reject) => {
3347
- this.socket = new import_node_net.Socket();
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
+ };
3348
3457
  const connectionTimeout = setTimeout(() => {
3349
- this.socket?.destroy();
3458
+ settle();
3459
+ socket.destroy();
3350
3460
  reject(new Error("Timeout connecting to CLI server"));
3351
3461
  }, 1e4);
3352
- this.socket.connect(this.runtimePort, this.actualHost, () => {
3353
- clearTimeout(connectionTimeout);
3354
- this.messageWriter = new TeardownResilientStreamMessageWriter(this.socket);
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);
3355
3467
  this.connection = createMessageConnection(
3356
- new import_node.StreamMessageReader(this.socket),
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
+ }),
3357
3474
  this.messageWriter,
3358
3475
  this.sessionInitializationContext
3359
3476
  );
@@ -3361,8 +3478,8 @@ stderr: ${stderrOutput}` : ""}`
3361
3478
  this.connection.listen();
3362
3479
  resolve2();
3363
3480
  });
3364
- this.socket.on("error", (error) => {
3365
- clearTimeout(connectionTimeout);
3481
+ socket.on("error", (error) => {
3482
+ settle();
3366
3483
  reject(new Error(`Failed to connect to CLI server: ${error.message}`));
3367
3484
  });
3368
3485
  });
@@ -3381,6 +3498,17 @@ stderr: ${stderrOutput}` : ""}`
3381
3498
  "userInput.request",
3382
3499
  async (params) => await this.handleUserInputRequest(params)
3383
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
+ );
3384
3512
  this.connection.onRequest(
3385
3513
  "exitPlanMode.request",
3386
3514
  async (params) => await this.handleExitPlanModeRequest(params)
@@ -3428,6 +3556,14 @@ stderr: ${stderrOutput}` : ""}`
3428
3556
  (params, token) => authenticateClientNegotiate(connection2, authenticateNegotiate, params, token)
3429
3557
  );
3430
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
+ }
3431
3567
  this.connection.onRequest(
3432
3568
  "host.materializeSession",
3433
3569
  (params) => this.createHostSession(params)
@@ -3534,7 +3670,7 @@ stderr: ${stderrOutput}` : ""}`
3534
3670
  const cliProcess = this.isExternalServer ? null : this.cliProcess;
3535
3671
  const connectionEpoch = this.connectionEpoch;
3536
3672
  const isCurrentConnection = () => connectionEpoch === this.connectionEpoch && this.connection === connection && (cliProcess === null || this.cliProcess === cliProcess);
3537
- let disconnecting = false;
3673
+ let disconnected;
3538
3674
  let exitFallback;
3539
3675
  const markDisconnected = () => {
3540
3676
  if (!isCurrentConnection()) {
@@ -3548,6 +3684,7 @@ stderr: ${stderrOutput}` : ""}`
3548
3684
  session._markDisconnected();
3549
3685
  }
3550
3686
  this.sessions.clear();
3687
+ this.abortPendingShellAuthenticationRequests();
3551
3688
  this.githubTokenProviders.clear();
3552
3689
  this.requestAdapter?.cancelPending();
3553
3690
  this.abortPendingMemoryStores();
@@ -3566,15 +3703,16 @@ stderr: ${stderrOutput}` : ""}`
3566
3703
  }
3567
3704
  if (!isCurrentConnection()) {
3568
3705
  connection.dispose();
3569
- return;
3706
+ return Promise.resolve();
3570
3707
  }
3571
- if (disconnecting) return;
3572
- disconnecting = true;
3708
+ if (disconnected) return disconnected;
3573
3709
  this.invalidateSessionInitializations();
3574
3710
  this.connectionClosed = true;
3575
3711
  if (messageWriter) messageWriter.suppressWriteErrors = true;
3576
- void connection.drain().then(markDisconnected);
3712
+ disconnected = connection.drain().then(markDisconnected);
3713
+ return disconnected;
3577
3714
  };
3715
+ this.retireClosedConnection = disconnectAfterDrain;
3578
3716
  this.connection.onClose(disconnectAfterDrain);
3579
3717
  if (cliProcess) {
3580
3718
  cliProcess.once("exit", () => {
@@ -3582,7 +3720,7 @@ stderr: ${stderrOutput}` : ""}`
3582
3720
  connection.dispose();
3583
3721
  return;
3584
3722
  }
3585
- if (disconnecting) return;
3723
+ if (disconnected) return;
3586
3724
  if (this.socket) {
3587
3725
  disconnectAfterDrain();
3588
3726
  return;
@@ -3685,6 +3823,55 @@ stderr: ${stderrOutput}` : ""}`
3685
3823
  });
3686
3824
  return result;
3687
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
+ }
3688
3875
  async handleExitPlanModeRequest(params) {
3689
3876
  if (!params || typeof params.sessionId !== "string" || typeof params.summary !== "string" || !Array.isArray(params.actions) || typeof params.recommendedAction !== "string") {
3690
3877
  throw new Error("Invalid exit plan mode request payload");