@microsoft/copilot-sdk 2.0.0-preview.0 → 2.0.0-preview.1

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.
@@ -55,10 +55,66 @@ var import_schema = require("./schema.js");
55
55
  var import_toolSet = require("./toolSet.js");
56
56
  var import_types = require("./types.js");
57
57
  var import_workflow = require("./workflow.js");
58
- const MIN_PROTOCOL_VERSION = 3;
58
+ const MIN_PROTOCOL_VERSION = 4;
59
59
  const RUNTIME_SHUTDOWN_TIMEOUT_MS = 1e4;
60
60
  const CLOUD_SESSION_CLEANUP_TIMEOUT_MS = 1e4;
61
61
  const AUTO_MODE_RECOVERY_CLEANUP_TIMEOUT_MS = 1e4;
62
+ function groupHostSessionSettings(settings) {
63
+ const paths = {
64
+ enableExperimentalMode: ["experiments", "enableExperimentalMode"],
65
+ infiniteSessions: ["state", "infiniteSessions"],
66
+ additionalDirectories: ["filesystem", "additionalDirectories"],
67
+ streaming: ["events", "streaming"],
68
+ gitHubToken: ["github", "token"],
69
+ mcpOAuthTokenStorage: ["mcp", "oauthTokenStorage"],
70
+ featureFlags: ["experiments", "flags"],
71
+ enableManagedSettings: ["github", "fetchManagedSettings"],
72
+ excludedManagedSettings: ["policy", "excludedManagedSettings"],
73
+ enableSessionStore: ["state", "enableCrossSessionStore"],
74
+ availableTools: ["tools", "availableTools"],
75
+ excludedTools: ["tools", "excludedTools"],
76
+ allowedModels: ["policy", "allowedModels"],
77
+ skipCustomInstructions: ["instructions", "skipCustomInstructions"],
78
+ refreshCustomInstructions: ["instructions", "refreshCustomInstructions"],
79
+ customAgentsLocalOnly: ["agents", "localDiscoveryOnly"],
80
+ coauthorEnabled: ["git", "coauthorEnabled"],
81
+ manageScheduleEnabled: ["tools", "manageScheduleEnabled"],
82
+ memory: ["state", "memory"],
83
+ pluginDirectories: ["plugins", "directories"],
84
+ skillDirectories: ["skills", "directories"],
85
+ agentDirectories: ["agents", "directories"],
86
+ hookDirectories: ["hooks", "directories"],
87
+ instructionDirectories: ["instructions", "directories"],
88
+ enableMcpApps: ["mcp", "enableApps"],
89
+ reasoningEffort: ["inference", "reasoningEffort"],
90
+ allowMultipleToolCalls: ["inference", "allowMultipleToolCalls"],
91
+ contextTier: ["inference", "contextTier"],
92
+ providers: ["inference", "providers"],
93
+ models: ["inference", "models"],
94
+ defaultProvider: ["inference", "defaultProvider"],
95
+ capi: ["github", "capi"],
96
+ autopilot: ["execution", "autopilot"],
97
+ sessionLimits: ["execution", "limits"],
98
+ permissionMode: ["permissions", "mode"]
99
+ };
100
+ const root = {};
101
+ const groups = {};
102
+ for (const [name, value] of Object.entries(settings)) {
103
+ const path = Object.hasOwn(paths, name) ? paths[name] : void 0;
104
+ if (path) {
105
+ const [group, field] = path;
106
+ (groups[group] ??= {})[field] = value;
107
+ } else {
108
+ root[name === "configDir" ? "configDirectory" : name] = value;
109
+ }
110
+ }
111
+ for (const group of Object.keys(groups)) {
112
+ if (Object.hasOwn(root, group)) {
113
+ throw new Error("AHP host settings must not mix flat and grouped options");
114
+ }
115
+ }
116
+ return { ...root, ...groups };
117
+ }
62
118
  function sessionIdsOverlap(left, right) {
63
119
  if (left === right) return true;
64
120
  if (!isUuidSessionId(left) || !isUuidSessionId(right)) return false;
@@ -276,19 +332,9 @@ async function authenticateClientBasic(connection, callback, request, token) {
276
332
  );
277
333
  return credentials ? { username: credentials.username, password: credentials.password } : {};
278
334
  }
279
- const DEFAULT_PROVIDER_NAME = "default";
280
- function extractBearerTokenProviders(provider, providers) {
335
+ function extractBearerTokenProviders(providers) {
281
336
  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;
337
+ let wireProviders = providers && [...providers];
292
338
  if (providers?.some((p) => p.bearerTokenProvider)) {
293
339
  wireProviders = providers.map((p) => {
294
340
  if (!p.bearerTokenProvider) return p;
@@ -300,7 +346,7 @@ function extractBearerTokenProviders(provider, providers) {
300
346
  };
301
347
  });
302
348
  }
303
- return { wireProvider, wireProviders, callbacks };
349
+ return { wireProviders, callbacks };
304
350
  }
305
351
  function toWireMcpServers(mcpServers) {
306
352
  if (!mcpServers) return void 0;
@@ -359,7 +405,7 @@ function toolFilterListToArray(value) {
359
405
  if (value === void 0) {
360
406
  return void 0;
361
407
  }
362
- return value instanceof import_toolSet.ToolSet ? value.toArray() : value;
408
+ return value instanceof import_toolSet.ToolSet ? value.toArray() : [...value];
363
409
  }
364
410
  function validateToolFilterList(field, list) {
365
411
  if (!list) {
@@ -425,6 +471,43 @@ class TeardownResilientStreamMessageWriter extends import_node.StreamMessageWrit
425
471
  }
426
472
  }
427
473
  }
474
+ function physicalDirectory(directory) {
475
+ try {
476
+ return import_node_fs.realpathSync.native(directory);
477
+ } catch {
478
+ return walkPhysicalPath((0, import_node_path.resolve)(directory));
479
+ }
480
+ }
481
+ const MAX_SYMLINKS = 40;
482
+ function walkPhysicalPath(absolutePath) {
483
+ let resolved = "/";
484
+ const pending = absolutePath.split("/");
485
+ let links = 0;
486
+ while (pending.length > 0) {
487
+ const part = pending.shift();
488
+ if (part === "" || part === ".") {
489
+ continue;
490
+ }
491
+ if (part === "..") {
492
+ resolved = (0, import_node_path.dirname)(resolved);
493
+ continue;
494
+ }
495
+ const next = (0, import_node_path.join)(resolved, part);
496
+ if (!(0, import_node_fs.lstatSync)(next).isSymbolicLink()) {
497
+ resolved = next;
498
+ continue;
499
+ }
500
+ if (++links > MAX_SYMLINKS) {
501
+ throw new Error(`Too many levels of symbolic links in ${absolutePath}`);
502
+ }
503
+ const target = (0, import_node_fs.readlinkSync)(next);
504
+ if (target.startsWith("/")) {
505
+ resolved = "/";
506
+ }
507
+ pending.unshift(...target.split("/"));
508
+ }
509
+ return resolved;
510
+ }
428
511
  class CopilotClient {
429
512
  cliStartTimeout = null;
430
513
  cliProcess = null;
@@ -551,29 +634,6 @@ class CopilotClient {
551
634
  `);
552
635
  }
553
636
  }
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
637
  /**
578
638
  * Creates a new CopilotClient instance.
579
639
  *
@@ -587,20 +647,20 @@ class CopilotClient {
587
647
  * // Connect to an existing runtime
588
648
  * const client = new CopilotClient({
589
649
  * mode: "coding-agent",
590
- * connection: RuntimeConnection.forUri("localhost:3000"),
650
+ * runtime: RuntimeConnection.forTcp("localhost", 3000),
591
651
  * });
592
- *
652
+ * *
593
653
  * // Spawn the runtime over TCP on a chosen port
594
654
  * const client = new CopilotClient({
595
655
  * mode: "coding-agent",
596
- * connection: RuntimeConnection.forTcp({ port: 9001 }),
656
+ * runtime: RuntimeConnection.forSpawnedTcp({ port: 9001 }),
597
657
  * });
598
- *
658
+ * *
599
659
  * // Use a custom runtime binary
600
660
  * const client = new CopilotClient({
601
661
  * mode: "coding-agent",
602
- * connection: RuntimeConnection.forStdio({ path: "/usr/local/bin/copilot" }),
603
- * logLevel: "debug",
662
+ * runtime: RuntimeConnection.forSpawnedStdio({ path: "/usr/local/bin/copilot" }),
663
+ * observability: { logLevel: "debug" },
604
664
  * });
605
665
  * ```
606
666
  */
@@ -608,31 +668,39 @@ class CopilotClient {
608
668
  if (options?.mode !== "coding-agent" && options?.mode !== "empty") {
609
669
  throw new Error("mode is required and must be 'coding-agent' or 'empty'");
610
670
  }
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");
671
+ const conn = options._internalConnection ?? options.runtime ?? import_types.RuntimeConnection.forDefault();
672
+ if (conn.kind === "tcp" || conn.kind === "parent-process") {
673
+ const runtimeOnlyOptions = {
674
+ "runtime.baseDirectory": "baseDirectory" in conn ? conn.baseDirectory : void 0,
675
+ "github.token": options.github?.token,
676
+ "github.useLoggedInUser": options.github?.useLoggedInUser,
677
+ "observability.telemetry": options.observability?.telemetry,
678
+ "runtime.sessionIdleTimeoutSeconds": "sessionIdleTimeoutSeconds" in conn ? conn.sessionIdleTimeoutSeconds : void 0,
679
+ internalTestOptions: options.internalTestOptions
680
+ };
681
+ const unsupported = Object.entries(runtimeOnlyOptions).filter(([, value]) => value !== void 0).map(([name]) => name);
682
+ if (unsupported.length > 0) {
683
+ throw new Error(
684
+ `Cannot configure runtime startup options for an attached runtime: ${unsupported.join(", ")}`
685
+ );
686
+ }
614
687
  }
615
- if (conn.kind === "uri" && (options.gitHubToken !== void 0 || options.useLoggedInUser !== void 0)) {
688
+ if ("env" in options || "workingDirectory" in options) {
616
689
  throw new Error(
617
- "gitHubToken and useLoggedInUser cannot be used with RuntimeConnection.forUri (external server manages its own auth)"
690
+ "Configure env and workingDirectory on RuntimeConnection.forSpawnedStdio/forSpawnedTcp, not on CopilotClientOptions. Set session working directories on individual sessions."
618
691
  );
619
692
  }
620
- if (conn.kind === "inprocess" && options.env !== void 0) {
693
+ if (conn.kind === "inprocess" && "env" in conn && conn.env !== void 0) {
621
694
  throw new Error(
622
695
  "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
696
  );
624
697
  }
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) {
698
+ if (conn.kind === "inprocess" && "workingDirectory" in conn && conn.workingDirectory !== void 0) {
631
699
  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."
700
+ "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 CreateSessionOptions.workingDirectory instead."
633
701
  );
634
702
  }
635
- if (conn.kind === "tcp" && conn.connectionToken !== void 0) {
703
+ if (conn.kind === "spawned-tcp" && conn.connectionToken !== void 0) {
636
704
  if (typeof conn.connectionToken !== "string" || conn.connectionToken.length === 0) {
637
705
  throw new Error("connectionToken must be a non-empty string");
638
706
  }
@@ -641,67 +709,74 @@ class CopilotClient {
641
709
  if (options.sessionFs) {
642
710
  this.validateSessionFsConfig(options.sessionFs);
643
711
  }
644
- if (options.builtinPluginDirectories) {
645
- for (const path of options.builtinPluginDirectories) {
712
+ if (options.plugins?.builtinDirectories) {
713
+ for (const path of options.plugins?.builtinDirectories) {
646
714
  if (!(0, import_node_path.isAbsolute)(path)) {
647
715
  throw new Error(
648
716
  `builtinPluginDirectories must contain only absolute paths: ${path}`
649
717
  );
650
718
  }
651
719
  }
652
- this.builtinPluginDirectories = [...options.builtinPluginDirectories];
720
+ this.builtinPluginDirectories = [...options.plugins?.builtinDirectories];
653
721
  }
654
- if (conn.kind === "uri") {
655
- const { host, port } = this.parseCliUrl(conn.url);
656
- this.actualHost = host;
657
- this.runtimePort = port;
722
+ if (conn.kind === "tcp") {
723
+ if (typeof conn.host !== "string" || !conn.host || /[\s/\\?#@[\]]/.test(conn.host) || conn.host.includes(":") && !(0, import_node_net.isIPv6)(conn.host)) {
724
+ throw new Error(
725
+ "host must be a hostname or IP address without a scheme, port, or path"
726
+ );
727
+ }
728
+ if (!Number.isInteger(conn.port) || conn.port < 1 || conn.port > 65535) {
729
+ throw new Error("port must be an integer from 1 through 65535");
730
+ }
731
+ this.actualHost = conn.host;
732
+ this.runtimePort = conn.port;
658
733
  this.isExternalServer = true;
659
734
  } else if (conn.kind === "parent-process") {
660
735
  this.isExternalServer = true;
661
736
  }
662
- if (conn.kind === "tcp") {
737
+ if (conn.kind === "spawned-tcp") {
663
738
  this.effectiveConnectionToken = conn.connectionToken ?? (0, import_node_crypto.randomUUID)();
664
- } else if (conn.kind === "uri") {
739
+ } else if (conn.kind === "tcp") {
665
740
  this.effectiveConnectionToken = conn.connectionToken;
666
741
  }
667
- this.onListModels = options.onListModels;
668
- this.onGetTraceContext = options.onGetTraceContext;
742
+ this.onListModels = options.models?.onListModels;
743
+ this.onGetTraceContext = options.observability?.onGetTraceContext;
669
744
  this.sessionFsConfig = options.sessionFs ?? null;
670
- this.requestHandler = options.requestHandler ?? null;
671
- this.extensionLaunchProvider = options.extensionLaunchProvider;
745
+ this.requestHandler = options.models?.requestHandler ?? null;
746
+ this.extensionLaunchProvider = options.extensions?.launchProvider;
672
747
  this.network = options.network ? snapshotNetworkConfig(options.network) : void 0;
673
- this.installationConfirmationHandler = options.installationConfirmationHandler;
674
- this.onGitHubTelemetry = options.onGitHubTelemetry;
748
+ this.installationConfirmationHandler = options.installations?.confirmationHandler;
749
+ this.onGitHubTelemetry = options.github?.onTelemetry;
675
750
  this.setupClientGlobalHandlers();
676
- const connEnv = conn.kind === "stdio" || conn.kind === "tcp" ? conn.env : void 0;
677
- const effectiveEnv = connEnv ?? options.env ?? process.env;
751
+ const spawnedConnection = conn.kind === "spawned-stdio" || conn.kind === "spawned-tcp" ? conn : void 0;
752
+ const effectiveEnv = spawnedConnection?.env ?? process.env;
678
753
  this.resolvedEnv = effectiveEnv;
679
- if (conn.kind === "stdio" || conn.kind === "tcp") {
680
- const explicitCliPath = conn.path ?? effectiveEnv.COPILOT_CLI_PATH;
754
+ if (conn.kind === "spawned-stdio" || conn.kind === "spawned-tcp") {
755
+ const explicitCliPath = conn.path ?? CopilotClient.normalizeEnvironment(effectiveEnv).COPILOT_CLI_PATH;
681
756
  if (explicitCliPath) {
682
757
  this.resolvedCliPath = explicitCliPath;
683
758
  }
684
759
  }
685
- const connArgs = conn.kind === "stdio" || conn.kind === "tcp" ? conn.args ?? [] : [];
760
+ const connArgs = conn.kind === "spawned-stdio" || conn.kind === "spawned-tcp" ? conn.args ?? [] : [];
686
761
  this.connectionExtraArgs = [...connArgs];
687
762
  this.options = {
688
763
  internalTestOptions: options.internalTestOptions,
689
764
  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,
765
+ workingDirectory: spawnedConnection?.workingDirectory ?? process.cwd(),
766
+ logLevel: options.observability?.logLevel,
767
+ gitHubToken: options.github?.token,
693
768
  // 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,
769
+ useLoggedInUser: options.github?.useLoggedInUser ?? (options.github?.token ? false : true),
770
+ telemetry: options.observability?.telemetry,
771
+ baseDirectory: "baseDirectory" in conn ? conn.baseDirectory : void 0,
772
+ sessionIdleTimeoutSeconds: ("sessionIdleTimeoutSeconds" in conn ? conn.sessionIdleTimeoutSeconds : void 0) ?? 0,
698
773
  mode: options.mode,
699
774
  clientInfo: options.clientInfo
700
775
  };
701
776
  if (this.options.mode === "empty") {
702
777
  const hasPersistence = this.options.baseDirectory !== void 0 || this.sessionFsConfig !== null || // External runtimes manage their own persistence layer; the SDK
703
778
  // can't enforce it from here.
704
- conn.kind === "uri" || conn.kind === "parent-process";
779
+ conn.kind === "tcp" || conn.kind === "parent-process";
705
780
  if (!hasPersistence) {
706
781
  throw new Error(
707
782
  "CopilotClient was created with mode: 'empty' but neither 'baseDirectory' nor 'sessionFs' was set. Empty mode requires an explicit per-session persistence location; pick one."
@@ -710,45 +785,6 @@ class CopilotClient {
710
785
  }
711
786
  }
712
787
  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
788
  validateSessionFsConfig(config) {
753
789
  if (!config.initialCwd) {
754
790
  throw new Error("sessionFs.initialCwd is required");
@@ -764,12 +800,12 @@ class CopilotClient {
764
800
  if (!this.sessionFsConfig) {
765
801
  return;
766
802
  }
767
- if (!config.createSessionFsProvider) {
803
+ if (!config.state?.createSessionFsProvider) {
768
804
  throw new Error(
769
805
  "createSessionFsProvider is required in session config when sessionFs is enabled in client options."
770
806
  );
771
807
  }
772
- const provider = config.createSessionFsProvider(session);
808
+ const provider = config.state.createSessionFsProvider(session);
773
809
  if (this.sessionFsConfig.capabilities?.sqlite && !provider.sqlite) {
774
810
  throw new Error(
775
811
  "SessionFsConfig declares capabilities.sqlite but the provider does not implement sqlite."
@@ -876,7 +912,7 @@ class CopilotClient {
876
912
  /**
877
913
  * Starts the runtime host and establishes a connection.
878
914
  *
879
- * An explicit {@link RuntimeConnection.forUri} only establishes the connection.
915
+ * An explicit {@link RuntimeConnection.forTcp} only establishes the connection.
880
916
  * Otherwise, starts an in-process host or the explicitly selected subprocess.
881
917
  * If its subprocess survives a lost connection, it is terminated before restarting.
882
918
  *
@@ -1178,7 +1214,7 @@ class CopilotClient {
1178
1214
  }
1179
1215
  if (this.cliProcess && !this.isExternalServer) {
1180
1216
  const child = this.cliProcess;
1181
- if (this.connectionConfig.kind === "stdio" && child.stdin && child.exitCode == null && child.signalCode == null) {
1217
+ if (this.connectionConfig.kind === "spawned-stdio" && child.stdin && child.exitCode == null && child.signalCode == null) {
1182
1218
  const gracefulExitStart = Date.now();
1183
1219
  try {
1184
1220
  child.stdin.end();
@@ -1243,6 +1279,7 @@ class CopilotClient {
1243
1279
  this.stderrBuffer = "";
1244
1280
  this.processExitPromise = null;
1245
1281
  this.disconnectHosts();
1282
+ this.connectionClosed = false;
1246
1283
  return errors;
1247
1284
  }
1248
1285
  /**
@@ -1252,7 +1289,11 @@ class CopilotClient {
1252
1289
  * @example
1253
1290
  * ```typescript
1254
1291
  * await using client = new CopilotClient({ mode: "coding-agent" });
1255
- * const session = await client.createSession({ onPermissionRequest: approveAll });
1292
+ * const session = await client.createSession({
1293
+ * permissions: {
1294
+ * onRequest: approveAll,
1295
+ * },
1296
+ * });
1256
1297
  * await session.sendAndWait("Hello");
1257
1298
  * // client.stop() is called automatically when the block exits.
1258
1299
  * ```
@@ -1352,6 +1393,7 @@ class CopilotClient {
1352
1393
  this.stderrBuffer = "";
1353
1394
  this.processExitPromise = null;
1354
1395
  await this.killCliProcess();
1396
+ this.connectionClosed = false;
1355
1397
  }
1356
1398
  /** Sends SIGKILL to the spawned CLI process, if it is still running, and waits for it to exit. */
1357
1399
  async killCliProcess() {
@@ -1384,18 +1426,26 @@ class CopilotClient {
1384
1426
  * @example
1385
1427
  * ```typescript
1386
1428
  * // Basic session
1387
- * const session = await client.createSession({ onPermissionRequest: approveAll });
1388
- *
1429
+ * const session = await client.createSession({
1430
+ * permissions: {
1431
+ * onRequest: approveAll
1432
+ * }
1433
+ * });
1434
+ * *
1389
1435
  * // Session with model and tools
1390
1436
  * const session = await client.createSession({
1391
- * onPermissionRequest: approveAll,
1392
- * model: "gpt-5.4",
1393
- * tools: [{
1437
+ * permissions: {
1438
+ * onRequest: approveAll
1439
+ * },
1440
+ * model: "gpt-5.4",
1441
+ * tools: {
1442
+ * definitions: [{
1394
1443
  * name: "get_weather",
1395
1444
  * description: "Get weather for a location",
1396
1445
  * parameters: { type: "object", properties: { location: { type: "string" } } },
1397
1446
  * handler: async (args) => ({ temperature: 72 })
1398
1447
  * }]
1448
+ * }
1399
1449
  * });
1400
1450
  * ```
1401
1451
  */
@@ -1407,8 +1457,8 @@ class CopilotClient {
1407
1457
  * @internal
1408
1458
  */
1409
1459
  resolveToolFilterOptions(config) {
1410
- const availableTools = toolFilterListToArray(config.availableTools);
1411
- const excludedTools = toolFilterListToArray(config.excludedTools);
1460
+ const availableTools = toolFilterListToArray(config.tools?.availableTools);
1461
+ const excludedTools = toolFilterListToArray(config.tools?.excludedTools);
1412
1462
  validateToolFilterList("availableTools", availableTools);
1413
1463
  validateToolFilterList("excludedTools", excludedTools);
1414
1464
  if (this.options.mode === "empty") {
@@ -1424,21 +1474,79 @@ class CopilotClient {
1424
1474
  configDefaultsForMode() {
1425
1475
  if (this.options.mode === "empty") {
1426
1476
  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
1477
+ github: {
1478
+ telemetryEnabled: false
1479
+ },
1480
+ mcp: {
1481
+ oauthTokenStorage: "in-memory"
1482
+ },
1483
+ state: {
1484
+ skipEmbeddingRetrieval: true,
1485
+ embeddingCacheStorage: "in-memory",
1486
+ enableCrossSessionStore: false,
1487
+ memory: { enabled: false }
1488
+ },
1489
+ instructions: {
1490
+ onDemandDiscovery: false
1491
+ },
1492
+ hooks: {
1493
+ enableRepositoryHooks: false
1494
+ },
1495
+ git: {
1496
+ enableHostGitOperations: false
1497
+ },
1498
+ skills: {
1499
+ enabled: false
1500
+ },
1501
+ agents: {
1502
+ localDiscoveryOnly: true
1503
+ }
1438
1504
  };
1439
1505
  }
1440
1506
  return {};
1441
1507
  }
1508
+ applyModeDefaults(config) {
1509
+ const defaults = this.configDefaultsForMode();
1510
+ return {
1511
+ ...config,
1512
+ inference: { ...config.inference },
1513
+ filesystem: { ...config.filesystem },
1514
+ tools: { ...config.tools },
1515
+ interaction: { ...config.interaction },
1516
+ experiments: { ...config.experiments },
1517
+ permissions: { ...config.permissions },
1518
+ events: { ...config.events },
1519
+ plugins: { ...config.plugins },
1520
+ execution: { ...config.execution },
1521
+ policy: { ...config.policy },
1522
+ canvases: { ...config.canvases },
1523
+ extensions: { ...config.extensions },
1524
+ github: { ...defaults.github, ...config.github },
1525
+ mcp: { ...defaults.mcp, ...config.mcp },
1526
+ state: { ...defaults.state, ...config.state },
1527
+ instructions: { ...defaults.instructions, ...config.instructions },
1528
+ hooks: { ...defaults.hooks, ...config.hooks },
1529
+ git: { ...defaults.git, ...config.git },
1530
+ skills: { ...defaults.skills, ...config.skills },
1531
+ agents: {
1532
+ ...defaults.agents,
1533
+ ...config.agents,
1534
+ localDiscoveryOnly: config.agents?.localDiscoveryOnly ?? defaults.agents?.localDiscoveryOnly
1535
+ },
1536
+ systemMessage: this.getSystemMessageConfigForMode(config.systemMessage)
1537
+ };
1538
+ }
1539
+ validateSessionCredentials(config) {
1540
+ const { token, tokenProvider } = config.github ?? {};
1541
+ if (token !== void 0 && tokenProvider !== void 0) {
1542
+ throw new Error("github.token and github.tokenProvider are mutually exclusive");
1543
+ }
1544
+ if (config.inference && "provider" in config.inference) {
1545
+ throw new Error(
1546
+ "inference.provider is no longer supported; use inference.providers and inference.models"
1547
+ );
1548
+ }
1549
+ }
1442
1550
  /** Mode-specific default for enableExperimentalMode. */
1443
1551
  experimentalModeForMode(supplied) {
1444
1552
  return this.options.mode === "empty" ? supplied ?? false : supplied;
@@ -1485,30 +1593,36 @@ class CopilotClient {
1485
1593
  * Mode-specific options applied via session.options.update after create/resume.
1486
1594
  *
1487
1595
  * 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
1596
+ * (caller values from `config` win). `plugins.installed=[]` is unconditional
1597
+ * in empty mode. `skills.includedBuiltinSkills` defaults to `[]`, but callers can
1490
1598
  * explicitly allow selected runtime-bundled skills.
1491
1599
  */
1492
1600
  async updateSessionOptionsForMode(session, config) {
1493
1601
  const patch = {};
1494
1602
  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 ?? [];
1603
+ patch.instructions = {
1604
+ skipCustomInstructions: config.instructions?.skipCustomInstructions ?? true
1605
+ };
1606
+ patch.agents = { localDiscoveryOnly: config.agents?.localDiscoveryOnly ?? true };
1607
+ patch.git = { coauthorEnabled: config.git?.coauthorEnabled ?? false };
1608
+ patch.tools = { manageScheduleEnabled: config.tools?.manageScheduleEnabled ?? false };
1609
+ patch.plugins = { installed: [] };
1610
+ patch.skills = {
1611
+ includedBuiltinSkills: [...config.skills?.includedBuiltinSkills ?? []]
1612
+ };
1501
1613
  } 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;
1614
+ if (config.instructions?.skipCustomInstructions !== void 0)
1615
+ patch.instructions = {
1616
+ skipCustomInstructions: config.instructions.skipCustomInstructions
1617
+ };
1618
+ if (config.agents?.localDiscoveryOnly !== void 0)
1619
+ patch.agents = { localDiscoveryOnly: config.agents.localDiscoveryOnly };
1620
+ if (config.git?.coauthorEnabled !== void 0)
1621
+ patch.git = { coauthorEnabled: config.git.coauthorEnabled };
1622
+ if (config.tools?.manageScheduleEnabled !== void 0)
1623
+ patch.tools = { manageScheduleEnabled: config.tools.manageScheduleEnabled };
1624
+ if (config.skills?.includedBuiltinSkills !== void 0)
1625
+ patch.skills = { includedBuiltinSkills: [...config.skills.includedBuiltinSkills] };
1512
1626
  }
1513
1627
  if (Object.keys(patch).length === 0) {
1514
1628
  return;
@@ -1524,16 +1638,14 @@ class CopilotClient {
1524
1638
  }
1525
1639
  }
1526
1640
  async createSession(config) {
1527
- if (config.autoModeRecovery && typeof config.onAutoModeSwitchRequest !== "function") {
1641
+ if (config.interaction?.autoModeRecovery && typeof config.interaction?.onAutoModeSwitchRequest !== "function") {
1528
1642
  throw new Error("autoModeRecovery requires onAutoModeSwitchRequest");
1529
1643
  }
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) {
1644
+ this.validateSessionCredentials(config);
1645
+ if (config.cloud != null && config.skills?.provider) {
1534
1646
  throw new Error("Skill providers are not supported for cloud sessions.");
1535
1647
  }
1536
- const storeMemory = requestedMemoryStore(config.memory);
1648
+ const storeMemory = requestedMemoryStore(config.state?.memory);
1537
1649
  if (config.cloud != null && storeMemory) {
1538
1650
  throw new Error("Memory stores are not supported for cloud sessions.");
1539
1651
  }
@@ -1629,68 +1741,63 @@ class CopilotClient {
1629
1741
  async createSessionInternal(config, signal) {
1630
1742
  signal.throwIfAborted();
1631
1743
  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);
1744
+ const storeMemory = requestedMemoryStore(config.state?.memory);
1745
+ config = this.applyModeDefaults(config);
1637
1746
  const callerSessionId = config.sessionId;
1638
1747
  const useServerGeneratedId = config.cloud != null && callerSessionId == null;
1639
1748
  const localSessionId = useServerGeneratedId ? void 0 : callerSessionId ?? (0, import_node_crypto.randomUUID)();
1640
1749
  const toolFilterOptions = this.resolveToolFilterOptions(config);
1641
1750
  const gitHubTokenProviderRegistrationId = this.registerGitHubTokenProvider(
1642
- config.gitHubTokenProvider,
1751
+ config.github?.tokenProvider,
1643
1752
  localSessionId
1644
1753
  );
1645
- const {
1646
- wireProvider: bearerWireProvider,
1647
- wireProviders: bearerWireProviders,
1648
- callbacks: bearerTokenCallbacks
1649
- } = extractBearerTokenProviders(config.provider, config.providers);
1754
+ const { wireProviders: bearerWireProviders, callbacks: bearerTokenCallbacks } = extractBearerTokenProviders(config.inference?.providers);
1650
1755
  const { wirePayload: wireSystemMessage, transformCallbacks } = extractTransformCallbacks(
1651
1756
  config.systemMessage
1652
1757
  );
1653
1758
  let replacedSession;
1654
1759
  const initializeSession = (sessionId) => {
1655
1760
  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,
1761
+ mcpAuthHandler: config.mcp?.onAuthRequest,
1762
+ managedSettingsEnabled: config.github?.fetchManagedSettings === true || config.policy?.managedSettings !== void 0,
1658
1763
  onDisconnected: gitHubTokenProviderRegistrationId === void 0 ? void 0 : () => this.githubTokenProviders.delete(gitHubTokenProviderRegistrationId)
1659
1764
  });
1660
- s.registerTools(config.tools);
1661
- s.registerCanvases(config.canvases);
1662
- s.registerCommands(config.commands);
1765
+ s.registerTools(config.tools?.definitions);
1766
+ s.registerCanvases(config.canvases?.definitions);
1767
+ s.registerCommands(config.interaction?.commands);
1663
1768
  if (bearerTokenCallbacks.size > 0) {
1664
1769
  s.registerBearerTokenProviders(bearerTokenCallbacks);
1665
1770
  }
1666
- s.registerPermissionHandler(config.onPermissionRequest);
1667
- if (config.onUserInputRequest) {
1668
- s.registerUserInputHandler(config.onUserInputRequest);
1771
+ s.registerPermissionHandler(config.permissions?.onRequest);
1772
+ if (config.interaction?.onUserInputRequest) {
1773
+ s.registerUserInputHandler(config.interaction?.onUserInputRequest);
1669
1774
  }
1670
- if (config.onShellAuthenticationRequest) {
1671
- s.registerShellAuthenticationHandler(config.onShellAuthenticationRequest);
1775
+ if (config.interaction?.onShellAuthenticationRequest) {
1776
+ s.registerShellAuthenticationHandler(
1777
+ config.interaction?.onShellAuthenticationRequest
1778
+ );
1672
1779
  }
1673
- if (config.onElicitationRequest) {
1674
- s.registerElicitationHandler(config.onElicitationRequest);
1780
+ if (config.interaction?.onElicitationRequest) {
1781
+ s.registerElicitationHandler(config.interaction?.onElicitationRequest);
1675
1782
  }
1676
- if (config.onExitPlanModeRequest) {
1677
- s.registerExitPlanModeHandler(config.onExitPlanModeRequest);
1783
+ if (config.interaction?.onExitPlanModeRequest) {
1784
+ s.registerExitPlanModeHandler(config.interaction?.onExitPlanModeRequest);
1678
1785
  }
1679
- if (config.onAutoModeSwitchRequest) {
1680
- s.registerAutoModeSwitchHandler(config.onAutoModeSwitchRequest);
1786
+ if (config.interaction?.onAutoModeSwitchRequest) {
1787
+ s.registerAutoModeSwitchHandler(config.interaction?.onAutoModeSwitchRequest);
1681
1788
  }
1682
- if (config.hooks) {
1683
- s.registerHooks(config.hooks);
1789
+ if (config.hooks?.handlers) {
1790
+ s.registerHooks(config.hooks?.handlers);
1684
1791
  }
1685
- if (config.skillProvider) {
1686
- s.registerSkillProvider(config.skillProvider);
1792
+ if (config.skills?.provider) {
1793
+ s.registerSkillProvider(config.skills?.provider);
1687
1794
  }
1688
1795
  s._registerMemoryStore(storeMemory);
1689
1796
  if (transformCallbacks) {
1690
1797
  s.registerTransformCallbacks(transformCallbacks);
1691
1798
  }
1692
- if (config.onEvent) {
1693
- s.on(config.onEvent);
1799
+ if (config.events?.onEvent) {
1800
+ s.on(config.events?.onEvent);
1694
1801
  }
1695
1802
  this.setupSessionFs(s, config);
1696
1803
  signal.throwIfAborted();
@@ -1722,118 +1829,174 @@ class CopilotClient {
1722
1829
  const response = await connection.sendRequest("session.create", {
1723
1830
  ...traceContext,
1724
1831
  model: config.model,
1725
- allowedModels: config.allowedModels,
1832
+ policy: {
1833
+ allowedModels: config.policy?.allowedModels,
1834
+ excludedManagedSettings: config.policy?.excludedManagedSettings,
1835
+ enforceManagedModelDefaults: config.policy?.enforceManagedModelDefaults,
1836
+ managedSettings: config.policy?.managedSettings
1837
+ },
1726
1838
  sessionId: localSessionId,
1727
1839
  name: config.name,
1728
1840
  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
- })),
1841
+ inference: {
1842
+ reasoningEffort: config.inference?.reasoningEffort,
1843
+ allowMultipleToolCalls: config.inference?.allowMultipleToolCalls,
1844
+ reasoningSummary: config.inference?.reasoningSummary,
1845
+ contextTier: config.inference?.contextTier,
1846
+ defaultProvider: config.inference?.defaultProvider,
1847
+ providers: bearerWireProviders,
1848
+ models: config.inference?.models,
1849
+ enableCitations: config.inference?.enableCitations,
1850
+ capabilities: config.inference?.capabilities
1851
+ },
1852
+ experiments: {
1853
+ enableExperimentalMode: this.experimentalModeForMode(
1854
+ config.experiments?.enableExperimentalMode
1855
+ ),
1856
+ flags: config.experiments?.flags,
1857
+ assignments: config.experiments?.assignments
1858
+ },
1859
+ tools: {
1860
+ definitions: config.tools?.definitions?.map((tool) => ({
1861
+ name: tool.name,
1862
+ title: tool.title,
1863
+ description: tool.description,
1864
+ parameters: (0, import_schema.toJsonSchema)(tool.parameters),
1865
+ overridesBuiltInTool: tool.overridesBuiltInTool,
1866
+ skipPermission: tool.skipPermission,
1867
+ hasHandler: !!tool.handler,
1868
+ defer: tool.defer,
1869
+ metadata: tool.metadata,
1870
+ isTerminal: tool.isTerminal,
1871
+ idempotent: tool.idempotent,
1872
+ namespace: tool.namespace
1873
+ })),
1874
+ search: config.tools?.search,
1875
+ imageGeneration: config.tools?.imageGeneration,
1876
+ availableTools: toolFilterOptions.availableTools,
1877
+ excludedTools: toolFilterOptions.excludedTools,
1878
+ largeOutput: toWireLargeOutput(config.tools?.largeOutput)
1879
+ },
1880
+ canvases: {
1881
+ definitions: config.canvases?.definitions?.map((canvas) => canvas.declaration),
1882
+ requestRenderer: config.canvases?.requestRenderer,
1883
+ provider: config.canvases?.provider
1884
+ },
1885
+ extensions: {
1886
+ enabled: config.extensions?.enabled,
1887
+ sdkPath: config.extensions?.sdkPath,
1888
+ identity: config.extensions?.identity
1889
+ },
1890
+ interaction: {
1891
+ commands: config.interaction?.commands?.map((cmd) => ({
1892
+ name: cmd.name,
1893
+ description: cmd.description ?? ""
1894
+ })),
1895
+ requestUserInput: !!config.interaction?.onUserInputRequest,
1896
+ requestElicitation: !!config.interaction?.onElicitationRequest,
1897
+ askUserVariant: config.interaction?.askUserVariant,
1898
+ requestExitPlanMode: !!config.interaction?.onExitPlanModeRequest,
1899
+ requestAutoModeSwitch: !!config.interaction?.onAutoModeSwitchRequest,
1900
+ ...config.interaction?.onShellAuthenticationRequest ? {
1901
+ requestShellAuthentication: true
1902
+ } : {},
1903
+ ...config.interaction?.autoModeRecovery ? {
1904
+ requestAutoModeRecovery: true
1905
+ } : {}
1906
+ },
1760
1907
  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)),
1908
+ agents: {
1909
+ excludedBuiltinAgents: config.agents?.excludedBuiltinAgents,
1910
+ includedBuiltinAgents: config.agents?.includedBuiltinAgents,
1911
+ definitions: toWireCustomAgents(config.agents?.definitions),
1912
+ localDiscoveryOnly: config.agents?.localDiscoveryOnly,
1913
+ default: config.agents?.default,
1914
+ selected: config.agents?.selected,
1915
+ directories: config.agents?.directories
1916
+ },
1917
+ github: {
1918
+ capi: config.github?.capi,
1919
+ telemetryEnabled: config.github?.telemetryEnabled,
1920
+ token: config.github?.token,
1921
+ tokenProviderRegistrationId: gitHubTokenProviderRegistrationId,
1922
+ fetchManagedSettings: config.github?.fetchManagedSettings,
1923
+ interactiveUser: config.github?.interactiveUser,
1924
+ ...config.github?.mcp != null ? {
1925
+ mcp: config.github?.mcp
1926
+ } : {},
1927
+ ...this.onGitHubTelemetry != null ? {
1928
+ telemetryForwarding: true
1929
+ } : {}
1930
+ },
1931
+ filesystem: {
1932
+ trackFileChanges: config.filesystem?.trackFileChanges,
1933
+ trustWorkingDirectory: config.filesystem?.trustWorkingDirectory,
1934
+ additionalDirectories: config.filesystem?.additionalDirectories
1935
+ },
1936
+ execution: {
1937
+ limits: config.execution?.limits,
1938
+ autopilot: config.execution?.autopilot
1939
+ },
1940
+ permissions: {
1941
+ request: !!config.permissions?.onRequest,
1942
+ sandbox: config.permissions?.sandbox,
1943
+ mode: config.permissions?.mode
1944
+ },
1945
+ mcp: {
1946
+ ...config.mcp?.enableApps ? {
1947
+ enableApps: true
1948
+ } : {},
1949
+ servers: toWireMcpServers(config.mcp?.servers),
1950
+ oauthTokenStorage: config.mcp?.oauthTokenStorage,
1951
+ authClientIdMetadataUrl: config.mcp?.authClientIdMetadataUrl,
1952
+ envValueMode: "direct",
1953
+ disabledServers: config.mcp?.disabledServers
1954
+ },
1955
+ hooks: {
1956
+ hasHandlers: !!(config.hooks?.handlers && Object.values(config.hooks?.handlers).some(Boolean)),
1957
+ enableRepositoryHooks: config.hooks?.enableRepositoryHooks,
1958
+ directories: config.hooks?.directories
1959
+ },
1787
1960
  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),
1961
+ events: {
1962
+ streaming: config.events?.streaming,
1963
+ includeSubAgentStreamingEvents: config.events?.includeSubAgentStreamingEvents ?? true
1964
+ },
1794
1965
  ...config.diagnostics !== void 0 ? { diagnostics: config.diagnostics } : {},
1795
1966
  ...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,
1967
+ configDirectory: config.configDirectory,
1804
1968
  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
1969
+ instructions: {
1970
+ refreshCustomInstructions: config.instructions?.refreshCustomInstructions,
1971
+ organizationText: config.instructions?.organizationText,
1972
+ onDemandDiscovery: config.instructions?.onDemandDiscovery,
1973
+ directories: config.instructions?.directories
1974
+ },
1975
+ state: {
1976
+ skipEmbeddingRetrieval: config.state?.skipEmbeddingRetrieval,
1977
+ embeddingCacheStorage: config.state?.embeddingCacheStorage,
1978
+ enableCrossSessionStore: config.state?.enableCrossSessionStore,
1979
+ infiniteSessions: config.state?.infiniteSessions,
1980
+ memory: toWireMemoryConfiguration(config.state?.memory),
1981
+ ...storeMemory ? {
1982
+ hasMemoryStore: true
1983
+ } : {}
1984
+ },
1985
+ git: {
1986
+ enableHostGitOperations: config.git?.enableHostGitOperations
1987
+ },
1988
+ skills: {
1989
+ enabled: config.skills?.enabled,
1990
+ directories: config.skills?.directories,
1991
+ disabledSkills: config.skills?.disabledSkills,
1992
+ ...config.skills?.provider ? {
1993
+ hasProvider: true
1994
+ } : {}
1995
+ },
1996
+ plugins: {
1997
+ directories: config.plugins?.directories
1998
+ },
1999
+ cloud: config.cloud
1837
2000
  });
1838
2001
  const {
1839
2002
  sessionId: returnedSessionId,
@@ -1864,10 +2027,10 @@ class CopilotClient {
1864
2027
  }
1865
2028
  this.assignGitHubTokenProvider(gitHubTokenProviderRegistrationId, returnedSessionId);
1866
2029
  session.setCapabilities(capabilities);
1867
- if (config.autoModeRecovery) {
2030
+ if (config.interaction?.autoModeRecovery) {
1868
2031
  await this.requireAutoModeRecovery(session, connection);
1869
2032
  }
1870
- if (config.onMcpAuthRequest) {
2033
+ if (config.mcp?.onAuthRequest) {
1871
2034
  await connection.sendRequest("session.eventLog.registerInterest", {
1872
2035
  sessionId: returnedSessionId,
1873
2036
  eventType: "mcp.oauth_required"
@@ -1908,7 +2071,7 @@ class CopilotClient {
1908
2071
  [e, cleanupError],
1909
2072
  `Failed to initialize and delete cloud session ${uninitializedCloudSessionId}`
1910
2073
  );
1911
- if (config.autoModeRecovery) {
2074
+ if (config.interaction?.autoModeRecovery) {
1912
2075
  this.recordFailedAutoModeRecoveryCleanup(
1913
2076
  connection,
1914
2077
  uninitializedCloudSessionId,
@@ -1949,12 +2112,20 @@ class CopilotClient {
1949
2112
  * @example
1950
2113
  * ```typescript
1951
2114
  * // Resume a previous session
1952
- * const session = await client.resumeSession("session-123", { onPermissionRequest: approveAll });
1953
- *
2115
+ * const session = await client.resumeSession("session-123", {
2116
+ * permissions: {
2117
+ * onRequest: approveAll
2118
+ * }
2119
+ * });
2120
+ * *
1954
2121
  * // Resume with new tools
1955
2122
  * const session = await client.resumeSession("session-123", {
1956
- * onPermissionRequest: approveAll,
1957
- * tools: [myNewTool]
2123
+ * permissions: {
2124
+ * onRequest: approveAll
2125
+ * },
2126
+ * tools: {
2127
+ * definitions: [myNewTool]
2128
+ * }
1958
2129
  * });
1959
2130
  * ```
1960
2131
  */
@@ -1979,13 +2150,11 @@ class CopilotClient {
1979
2150
  return session;
1980
2151
  }
1981
2152
  async resumeSessionInternal(sessionId, config, contributions = {}, extensionOptions) {
1982
- if (config.autoModeRecovery && typeof config.onAutoModeSwitchRequest !== "function") {
2153
+ if (config.interaction?.autoModeRecovery && typeof config.interaction?.onAutoModeSwitchRequest !== "function") {
1983
2154
  throw new Error("autoModeRecovery requires onAutoModeSwitchRequest");
1984
2155
  }
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);
2156
+ this.validateSessionCredentials(config);
2157
+ requestedMemoryStore(config.state?.memory);
1989
2158
  const signal = await this.getSessionInitializationSignal();
1990
2159
  const release = await this.acquireSessionInitialization(sessionId, signal);
1991
2160
  try {
@@ -2003,10 +2172,10 @@ class CopilotClient {
2003
2172
  }
2004
2173
  async resumeSessionWithInitialization(sessionId, config, contributions, signal, extensionOptions) {
2005
2174
  const { workflows } = contributions;
2006
- const storeMemory = requestedMemoryStore(config.memory);
2175
+ const storeMemory = requestedMemoryStore(config.state?.memory);
2007
2176
  signal.throwIfAborted();
2008
2177
  const connection = this.connection;
2009
- const resolveAliases = config.autoModeRecovery === true && !this.sessionFsConfig;
2178
+ const resolveAliases = config.interaction?.autoModeRecovery === true && !this.sessionFsConfig;
2010
2179
  if (resolveAliases && isAbbreviatedUuidPrefix(sessionId)) {
2011
2180
  const resolved = await connection.sendRequest(
2012
2181
  "sessions.findByPrefix",
@@ -2028,57 +2197,52 @@ class CopilotClient {
2028
2197
  void 0,
2029
2198
  this.onGetTraceContext,
2030
2199
  {
2031
- mcpAuthHandler: config.onMcpAuthRequest,
2032
- managedSettingsEnabled: config.enableManagedSettings === true || config.managedSettings !== void 0
2200
+ mcpAuthHandler: config.mcp?.onAuthRequest,
2201
+ managedSettingsEnabled: config.github?.fetchManagedSettings === true || config.policy?.managedSettings !== void 0
2033
2202
  }
2034
2203
  );
2035
- session.registerTools(config.tools);
2036
- session.registerCanvases(config.canvases);
2037
- session.registerCommands(config.commands);
2204
+ session.registerTools(config.tools?.definitions);
2205
+ session.registerCanvases(config.canvases?.definitions);
2206
+ session.registerCommands(config.interaction?.commands);
2038
2207
  session.registerWorkflows(workflows);
2039
- const {
2040
- wireProvider: bearerWireProvider,
2041
- wireProviders: bearerWireProviders,
2042
- callbacks: bearerTokenCallbacks
2043
- } = extractBearerTokenProviders(config.provider, config.providers);
2208
+ const { wireProviders: bearerWireProviders, callbacks: bearerTokenCallbacks } = extractBearerTokenProviders(config.inference?.providers);
2044
2209
  if (bearerTokenCallbacks.size > 0) {
2045
2210
  session.registerBearerTokenProviders(bearerTokenCallbacks);
2046
2211
  }
2047
- session.registerPermissionHandler(config.onPermissionRequest);
2048
- if (config.onUserInputRequest) {
2049
- session.registerUserInputHandler(config.onUserInputRequest);
2212
+ session.registerPermissionHandler(config.permissions?.onRequest);
2213
+ if (config.interaction?.onUserInputRequest) {
2214
+ session.registerUserInputHandler(config.interaction?.onUserInputRequest);
2050
2215
  }
2051
- if (config.onShellAuthenticationRequest) {
2052
- session.registerShellAuthenticationHandler(config.onShellAuthenticationRequest);
2216
+ if (config.interaction?.onShellAuthenticationRequest) {
2217
+ session.registerShellAuthenticationHandler(
2218
+ config.interaction?.onShellAuthenticationRequest
2219
+ );
2053
2220
  }
2054
- if (config.onElicitationRequest) {
2055
- session.registerElicitationHandler(config.onElicitationRequest);
2221
+ if (config.interaction?.onElicitationRequest) {
2222
+ session.registerElicitationHandler(config.interaction?.onElicitationRequest);
2056
2223
  }
2057
- if (config.onExitPlanModeRequest) {
2058
- session.registerExitPlanModeHandler(config.onExitPlanModeRequest);
2224
+ if (config.interaction?.onExitPlanModeRequest) {
2225
+ session.registerExitPlanModeHandler(config.interaction?.onExitPlanModeRequest);
2059
2226
  }
2060
- if (config.onAutoModeSwitchRequest) {
2061
- session.registerAutoModeSwitchHandler(config.onAutoModeSwitchRequest);
2227
+ if (config.interaction?.onAutoModeSwitchRequest) {
2228
+ session.registerAutoModeSwitchHandler(config.interaction?.onAutoModeSwitchRequest);
2062
2229
  }
2063
- if (config.hooks) {
2064
- session.registerHooks(config.hooks);
2230
+ if (config.hooks?.handlers) {
2231
+ session.registerHooks(config.hooks?.handlers);
2065
2232
  }
2066
- if (config.skillProvider) {
2067
- session.registerSkillProvider(config.skillProvider);
2233
+ if (config.skills?.provider) {
2234
+ session.registerSkillProvider(config.skills?.provider);
2068
2235
  }
2069
2236
  session._registerMemoryStore(storeMemory);
2070
- const modeDefaults = this.configDefaultsForMode();
2071
- config = { ...modeDefaults, ...config };
2072
- config.customAgentsLocalOnly ??= modeDefaults.customAgentsLocalOnly;
2073
- config.systemMessage = this.getSystemMessageConfigForMode(config.systemMessage);
2237
+ config = this.applyModeDefaults(config);
2074
2238
  const { wirePayload: wireSystemMessage, transformCallbacks } = extractTransformCallbacks(
2075
2239
  config.systemMessage
2076
2240
  );
2077
2241
  if (transformCallbacks) {
2078
2242
  session.registerTransformCallbacks(transformCallbacks);
2079
2243
  }
2080
- if (config.onEvent) {
2081
- session.on(config.onEvent);
2244
+ if (config.events?.onEvent) {
2245
+ session.on(config.events?.onEvent);
2082
2246
  }
2083
2247
  const toolFilterOptions = this.resolveToolFilterOptions(config);
2084
2248
  this.setupSessionFs(session, config);
@@ -2089,7 +2253,7 @@ class CopilotClient {
2089
2253
  let releaseCanonicalInitialization;
2090
2254
  let keepResumedSessionOnRecoveryRejection = false;
2091
2255
  const gitHubTokenProviderRegistrationId = this.registerGitHubTokenProvider(
2092
- config.gitHubTokenProvider,
2256
+ config.github?.tokenProvider,
2093
2257
  sessionId
2094
2258
  );
2095
2259
  if (gitHubTokenProviderRegistrationId !== void 0) {
@@ -2113,121 +2277,177 @@ class CopilotClient {
2113
2277
  resolveAliases
2114
2278
  });
2115
2279
  const response = await connection.sendRequest("session.resume", {
2116
- allowedModels: config.allowedModels,
2280
+ policy: {
2281
+ allowedModels: config.policy?.allowedModels,
2282
+ excludedManagedSettings: config.policy?.excludedManagedSettings,
2283
+ enforceManagedModelDefaults: config.policy?.enforceManagedModelDefaults,
2284
+ managedSettings: config.policy?.managedSettings
2285
+ },
2117
2286
  ...traceContext,
2118
2287
  sessionId,
2119
2288
  allowTranscriptRecovery: config.allowTranscriptRecovery,
2120
2289
  clientName: config.clientName,
2121
2290
  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,
2291
+ inference: {
2292
+ reasoningEffort: config.inference?.reasoningEffort,
2293
+ allowMultipleToolCalls: config.inference?.allowMultipleToolCalls,
2294
+ reasoningSummary: config.inference?.reasoningSummary,
2295
+ contextTier: config.inference?.contextTier,
2296
+ enableCitations: config.inference?.enableCitations,
2297
+ defaultProvider: config.inference?.defaultProvider,
2298
+ providers: bearerWireProviders,
2299
+ models: config.inference?.models,
2300
+ capabilities: config.inference?.capabilities
2301
+ },
2302
+ experiments: {
2303
+ enableExperimentalMode: this.experimentalModeForMode(
2304
+ config.experiments?.enableExperimentalMode
2305
+ ),
2306
+ flags: config.experiments?.flags,
2307
+ assignments: config.experiments?.assignments
2308
+ },
2127
2309
  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),
2310
+ tools: {
2311
+ availableTools: toolFilterOptions.availableTools,
2312
+ excludedTools: toolFilterOptions.excludedTools,
2313
+ definitions: config.tools?.definitions?.map((tool) => ({
2314
+ name: tool.name,
2315
+ title: tool.title,
2316
+ description: tool.description,
2317
+ parameters: (0, import_schema.toJsonSchema)(tool.parameters),
2318
+ overridesBuiltInTool: tool.overridesBuiltInTool,
2319
+ skipPermission: tool.skipPermission,
2320
+ hasHandler: !!tool.handler,
2321
+ defer: tool.defer,
2322
+ metadata: tool.metadata,
2323
+ isTerminal: tool.isTerminal,
2324
+ idempotent: tool.idempotent,
2325
+ namespace: tool.namespace
2326
+ })),
2327
+ search: config.tools?.search,
2328
+ imageGeneration: config.tools?.imageGeneration,
2329
+ largeOutput: toWireLargeOutput(config.tools?.largeOutput)
2330
+ },
2331
+ github: {
2332
+ telemetryEnabled: config.github?.telemetryEnabled,
2333
+ capi: config.github?.capi,
2334
+ token: config.github?.token,
2335
+ tokenProviderRegistrationId: gitHubTokenProviderRegistrationId,
2336
+ fetchManagedSettings: config.github?.fetchManagedSettings,
2337
+ interactiveUser: config.github?.interactiveUser,
2338
+ ...config.github?.mcp != null ? {
2339
+ mcp: config.github?.mcp
2340
+ } : {},
2341
+ ...this.onGitHubTelemetry != null ? {
2342
+ telemetryForwarding: true
2343
+ } : {}
2344
+ },
2345
+ agents: {
2346
+ excludedBuiltinAgents: config.agents?.excludedBuiltinAgents,
2347
+ includedBuiltinAgents: config.agents?.includedBuiltinAgents,
2348
+ definitions: toWireCustomAgents(config.agents?.definitions),
2349
+ localDiscoveryOnly: config.agents?.localDiscoveryOnly,
2350
+ default: config.agents?.default,
2351
+ selected: config.agents?.selected,
2352
+ directories: config.agents?.directories
2353
+ },
2354
+ filesystem: {
2355
+ trackFileChanges: config.filesystem?.trackFileChanges,
2356
+ additionalDirectories: config.filesystem?.additionalDirectories
2357
+ },
2358
+ execution: {
2359
+ limits: config.execution?.limits,
2360
+ autopilot: config.execution?.autopilot
2361
+ },
2362
+ canvases: {
2363
+ definitions: config.canvases?.definitions?.map((canvas) => canvas.declaration),
2364
+ requestRenderer: config.canvases?.requestRenderer,
2365
+ provider: config.canvases?.provider,
2366
+ open: config.canvases?.open
2367
+ },
2154
2368
  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)),
2369
+ extensions: {
2370
+ enabled: config.extensions?.enabled,
2371
+ sdkPath: config.extensions?.sdkPath,
2372
+ identity: config.extensions?.identity
2373
+ },
2374
+ interaction: {
2375
+ commands: config.interaction?.commands?.map((cmd) => ({
2376
+ name: cmd.name,
2377
+ description: cmd.description ?? ""
2378
+ })),
2379
+ requestUserInput: !!config.interaction?.onUserInputRequest,
2380
+ requestElicitation: !!config.interaction?.onElicitationRequest,
2381
+ askUserVariant: config.interaction?.askUserVariant,
2382
+ requestExitPlanMode: !!config.interaction?.onExitPlanModeRequest,
2383
+ requestAutoModeSwitch: !!config.interaction?.onAutoModeSwitchRequest,
2384
+ ...config.interaction?.onShellAuthenticationRequest ? {
2385
+ requestShellAuthentication: true
2386
+ } : {},
2387
+ ...config.interaction?.autoModeRecovery ? {
2388
+ requestAutoModeRecovery: true
2389
+ } : {}
2390
+ },
2391
+ permissions: {
2392
+ request: config.permissions?.onRequest !== import_types.defaultJoinSessionPermissionHandler,
2393
+ sandbox: config.permissions?.sandbox,
2394
+ mode: config.permissions?.mode
2395
+ },
2396
+ mcp: {
2397
+ ...config.mcp?.enableApps ? {
2398
+ enableApps: true
2399
+ } : {},
2400
+ servers: toWireMcpServers(config.mcp?.servers),
2401
+ oauthTokenStorage: config.mcp?.oauthTokenStorage,
2402
+ authClientIdMetadataUrl: config.mcp?.authClientIdMetadataUrl,
2403
+ envValueMode: "direct",
2404
+ disabledServers: config.mcp?.disabledServers
2405
+ },
2406
+ hooks: {
2407
+ hasHandlers: !!(config.hooks?.handlers && Object.values(config.hooks?.handlers).some(Boolean)),
2408
+ enableRepositoryHooks: config.hooks?.enableRepositoryHooks,
2409
+ directories: config.hooks?.directories
2410
+ },
2181
2411
  workingDirectory: config.workingDirectory,
2182
- additionalDirectories: config.additionalDirectories,
2183
- configDir: config.configDirectory,
2412
+ configDirectory: config.configDirectory,
2184
2413
  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),
2414
+ state: {
2415
+ skipEmbeddingRetrieval: config.state?.skipEmbeddingRetrieval,
2416
+ embeddingCacheStorage: config.state?.embeddingCacheStorage,
2417
+ enableCrossSessionStore: config.state?.enableCrossSessionStore,
2418
+ infiniteSessions: config.state?.infiniteSessions,
2419
+ memory: toWireMemoryConfiguration(config.state?.memory),
2420
+ ...storeMemory ? {
2421
+ hasMemoryStore: true
2422
+ } : {}
2423
+ },
2424
+ instructions: {
2425
+ organizationText: config.instructions?.organizationText,
2426
+ onDemandDiscovery: config.instructions?.onDemandDiscovery,
2427
+ directories: config.instructions?.directories
2428
+ },
2429
+ git: {
2430
+ enableHostGitOperations: config.git?.enableHostGitOperations
2431
+ },
2432
+ skills: {
2433
+ enabled: config.skills?.enabled,
2434
+ directories: config.skills?.directories,
2435
+ disabledSkills: config.skills?.disabledSkills,
2436
+ ...config.skills?.provider ? {
2437
+ hasProvider: true
2438
+ } : {}
2439
+ },
2440
+ events: {
2441
+ streaming: config.events?.streaming,
2442
+ includeSubAgentStreamingEvents: config.events?.includeSubAgentStreamingEvents ?? true
2443
+ },
2197
2444
  ...config.diagnostics !== void 0 ? { diagnostics: config.diagnostics } : {},
2198
2445
  ...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,
2446
+ plugins: {
2447
+ directories: config.plugins?.directories
2448
+ },
2449
+ suppressResumeEvent: config.suppressResumeEvent,
2219
2450
  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
2451
  ...extensionOptions?.requestedEnvironmentVariables ? {
2232
2452
  requestedEnvironmentVariables: extensionOptions.requestedEnvironmentVariables
2233
2453
  } : {}
@@ -2272,7 +2492,7 @@ class CopilotClient {
2272
2492
  } = response;
2273
2493
  session["_workspacePath"] = workspacePath;
2274
2494
  session.setCapabilities(capabilities);
2275
- if (config.autoModeRecovery) {
2495
+ if (config.interaction?.autoModeRecovery) {
2276
2496
  keepResumedSessionOnRecoveryRejection = replacedSession !== void 0 && session.capabilities.ui?.autoModeRecovery !== true;
2277
2497
  await this.requireAutoModeRecovery(
2278
2498
  session,
@@ -2283,7 +2503,7 @@ class CopilotClient {
2283
2503
  session.setOpenCanvases(openCanvases ?? []);
2284
2504
  session.setTranscriptRecovery(transcriptRecovery);
2285
2505
  session.setPermissionModeResult(permissionModeResult);
2286
- if (config.onMcpAuthRequest) {
2506
+ if (config.mcp?.onAuthRequest) {
2287
2507
  await connection.sendRequest("session.eventLog.registerInterest", {
2288
2508
  sessionId,
2289
2509
  eventType: "mcp.oauth_required"
@@ -2403,9 +2623,7 @@ class CopilotClient {
2403
2623
  if (!options?.localServer && !options?.githubEnvironment) {
2404
2624
  throw new Error("At least one of localServer or githubEnvironment is required");
2405
2625
  }
2406
- if (this.state !== "connected") {
2407
- await this.start();
2408
- }
2626
+ await this.getStartedConnection();
2409
2627
  const rpc = this.rpc;
2410
2628
  const hostId = (0, import_node_crypto.randomUUID)();
2411
2629
  if (authentication.mode === "custom") {
@@ -2552,6 +2770,7 @@ class CopilotClient {
2552
2770
  if (authentication.mode !== policy.mode || (authentication.mode === "none" ? identity !== void 0 : typeof identity !== "string" || !identity.trim()) || policy.mode === "custom" && identity !== policy.requireIdentity) {
2553
2771
  throw new Error("AHP trusted authentication does not match host policy");
2554
2772
  }
2773
+ const config = groupHostSessionSettings(params.config);
2555
2774
  const entry = {
2556
2775
  hostId: params.hostId,
2557
2776
  requestedSessionId: params.config.sessionId,
@@ -2561,8 +2780,6 @@ class CopilotClient {
2561
2780
  onReleased: options.onSessionReleased
2562
2781
  };
2563
2782
  this.hostHandoffs.set(params.handoffId, entry);
2564
- const { configDir, ...config } = params.config;
2565
- if (configDir !== void 0) config.configDirectory = configDir;
2566
2783
  const expected = structuredClone(config);
2567
2784
  const cancelled = new Promise((_resolve, reject) => {
2568
2785
  entry.controller.signal.addEventListener(
@@ -2629,8 +2846,7 @@ class CopilotClient {
2629
2846
  *
2630
2847
  * @param message - Optional message to include in the ping
2631
2848
  * @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
2849
+ * @throws Error if startup fails, the connection is unavailable, or shutdown is in progress
2634
2850
  *
2635
2851
  * @example
2636
2852
  * ```typescript
@@ -2658,15 +2874,22 @@ class CopilotClient {
2658
2874
  return result;
2659
2875
  }
2660
2876
  /**
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.
2877
+ * Lazily starts the client or joins its current startup. Await the observed
2878
+ * attempt directly so its failure cannot turn into a retry within this request.
2666
2879
  */
2667
- async getStartedConnection(startup = this.startPromise) {
2668
- if (startup) {
2669
- await startup;
2880
+ async getStartedConnection() {
2881
+ let startup = this.startPromise;
2882
+ if (startup && startup === this.shutdownCanceledStartup) {
2883
+ await this.start();
2884
+ } else {
2885
+ this.assertNotStopping();
2886
+ if (startup) {
2887
+ await startup;
2888
+ } else if (this.connectionClosed) {
2889
+ throw new Error("Client not connected");
2890
+ } else if (!this.connection) {
2891
+ await this.start();
2892
+ }
2670
2893
  }
2671
2894
  let latest = this.startPromise;
2672
2895
  while (latest && latest !== startup) {
@@ -2674,11 +2897,18 @@ class CopilotClient {
2674
2897
  await latest;
2675
2898
  latest = this.startPromise;
2676
2899
  }
2900
+ this.assertNotStopping();
2901
+ this.sessionInitializationLifetime.signal.throwIfAborted();
2677
2902
  if (!this.connection) {
2678
2903
  throw new Error("Client not connected");
2679
2904
  }
2680
2905
  return this.connection;
2681
2906
  }
2907
+ assertNotStopping() {
2908
+ if (this.stopPromise || this.forceStopPromise) {
2909
+ throw new Error("Client disconnected during session initialization");
2910
+ }
2911
+ }
2682
2912
  /**
2683
2913
  * List available models with their metadata.
2684
2914
  *
@@ -2688,51 +2918,80 @@ class CopilotClient {
2688
2918
  * Results are cached after the first successful call to avoid rate limiting.
2689
2919
  * The cache is cleared when the client disconnects.
2690
2920
  *
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)
2921
+ * Starts the client if needed, unless a custom handler is set.
2922
+ *
2923
+ * @throws Error if startup fails, the connection is retired, or shutdown is in
2924
+ * progress (when no custom handler is set)
2693
2925
  */
2694
2926
  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];
2927
+ const connection = this.onListModels ? void 0 : await this.getStartedConnection();
2928
+ const connectionEpoch = this.connectionEpoch;
2929
+ const assertCurrentConnection = () => {
2930
+ if (connection) {
2931
+ this.assertNotStopping();
2932
+ if (connectionEpoch !== this.connectionEpoch || connection !== this.connection || this.sessionInitializationLifetime.signal.aborted) {
2933
+ throw new Error("Client disconnected while listing models");
2934
+ }
2706
2935
  }
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;
2936
+ };
2937
+ let startup = null;
2938
+ while (true) {
2939
+ assertCurrentConnection();
2940
+ if (startup) {
2941
+ await startup;
2942
+ startup = null;
2943
+ assertCurrentConnection();
2944
+ }
2945
+ const cache = this.modelsCache;
2946
+ const previousLock = cache.lock;
2947
+ let resolveLock;
2948
+ cache.lock = new Promise((resolve2) => {
2949
+ resolveLock = resolve2;
2950
+ });
2951
+ await previousLock;
2952
+ try {
2953
+ assertCurrentConnection();
2954
+ if (connection) {
2955
+ if (cache !== this.modelsCache) {
2956
+ throw new Error("Client disconnected while listing models");
2957
+ }
2958
+ if (this.startPromise) {
2959
+ startup = this.startPromise;
2960
+ continue;
2961
+ }
2962
+ }
2963
+ if (cache.models !== null) {
2964
+ return [...cache.models];
2965
+ }
2966
+ let models;
2967
+ if (this.onListModels) {
2968
+ models = await this.onListModels();
2969
+ } else {
2970
+ const result = await connection.sendRequest("models.list", {});
2971
+ const response = result;
2972
+ models = response.models;
2973
+ for (const model of models) {
2974
+ const m = model;
2975
+ if (!m.capabilities) {
2976
+ m.capabilities = {
2977
+ supports: {},
2978
+ limits: { max_context_window_tokens: 0 }
2979
+ };
2980
+ } else {
2981
+ if (!m.capabilities.supports) m.capabilities.supports = {};
2982
+ if (!m.capabilities.limits) {
2983
+ m.capabilities.limits = { max_context_window_tokens: 0 };
2984
+ } else if (m.capabilities.limits.max_context_window_tokens === void 0) {
2985
+ m.capabilities.limits.max_context_window_tokens = 0;
2986
+ }
2728
2987
  }
2729
2988
  }
2730
2989
  }
2990
+ cache.models = [...models];
2991
+ return [...models];
2992
+ } finally {
2993
+ resolveLock();
2731
2994
  }
2732
- cache.models = [...models];
2733
- return [...models];
2734
- } finally {
2735
- resolveLock();
2736
2995
  }
2737
2996
  }
2738
2997
  /**
@@ -2752,7 +3011,8 @@ class CopilotClient {
2752
3011
  const connectParams = {
2753
3012
  entra: this.options.entra && {
2754
3013
  clientId: this.options.entra.clientId,
2755
- matsAppName: this.options.entra.matsAppName
3014
+ matsAppName: this.options.entra.matsAppName,
3015
+ oneAuthApplicationId: this.options.entra.oneAuthApplicationId
2756
3016
  },
2757
3017
  entraTokenProvider: this.options.entra?.tokenProvider ? true : void 0,
2758
3018
  token: this.effectiveConnectionToken,
@@ -2805,15 +3065,17 @@ class CopilotClient {
2805
3065
  * ```typescript
2806
3066
  * const lastId = await client.getLastSessionId();
2807
3067
  * if (lastId) {
2808
- * const session = await client.resumeSession(lastId, { onPermissionRequest: approveAll });
3068
+ * const session = await client.resumeSession(lastId, {
3069
+ * permissions: {
3070
+ * onRequest: approveAll,
3071
+ * },
3072
+ * });
2809
3073
  * }
2810
3074
  * ```
2811
3075
  */
2812
3076
  async getLastSessionId() {
2813
- if (!this.connection) {
2814
- throw new Error("Client not connected");
2815
- }
2816
- const response = await this.connection.sendRequest("session.getLastId", {});
3077
+ const connection = await this.getStartedConnection();
3078
+ const response = await connection.sendRequest("session.getLastId", {});
2817
3079
  return response.sessionId;
2818
3080
  }
2819
3081
  /**
@@ -2834,9 +3096,7 @@ class CopilotClient {
2834
3096
  * ```
2835
3097
  */
2836
3098
  async deleteSession(sessionId) {
2837
- if (!this.connection) {
2838
- throw new Error("Client not connected");
2839
- }
3099
+ this.assertNotStopping();
2840
3100
  const signal = await this.getSessionInitializationSignal();
2841
3101
  const release = await this.acquireSessionInitialization(sessionId, signal);
2842
3102
  try {
@@ -2885,15 +3145,13 @@ class CopilotClient {
2885
3145
  * const sessions = await client.listSessions({ repository: "owner/repo" });
2886
3146
  */
2887
3147
  async listSessions(filter) {
2888
- if (!this.connection) {
2889
- throw new Error("Client not connected");
2890
- }
3148
+ const connection = await this.getStartedConnection();
2891
3149
  let wireFilter;
2892
3150
  if (filter) {
2893
3151
  const { workingDirectory, ...rest } = filter;
2894
3152
  wireFilter = { ...rest, cwd: workingDirectory };
2895
3153
  }
2896
- const response = await this.connection.sendRequest("session.list", {
3154
+ const response = await connection.sendRequest("session.list", {
2897
3155
  filter: wireFilter
2898
3156
  });
2899
3157
  const { sessions } = response;
@@ -2918,10 +3176,8 @@ class CopilotClient {
2918
3176
  * ```
2919
3177
  */
2920
3178
  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 });
3179
+ const connection = await this.getStartedConnection();
3180
+ const response = await connection.sendRequest("session.getMetadata", { sessionId });
2925
3181
  const { session } = response;
2926
3182
  if (!session) {
2927
3183
  return void 0;
@@ -2964,10 +3220,8 @@ class CopilotClient {
2964
3220
  * ```
2965
3221
  */
2966
3222
  async getForegroundSessionId() {
2967
- if (!this.connection) {
2968
- throw new Error("Client not connected");
2969
- }
2970
- const response = await this.connection.sendRequest("session.getForeground", {});
3223
+ const connection = await this.getStartedConnection();
3224
+ const response = await connection.sendRequest("session.getForeground", {});
2971
3225
  return response.sessionId;
2972
3226
  }
2973
3227
  /**
@@ -2987,10 +3241,8 @@ class CopilotClient {
2987
3241
  * ```
2988
3242
  */
2989
3243
  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 });
3244
+ const connection = await this.getStartedConnection();
3245
+ const response = await connection.sendRequest("session.setForeground", { sessionId });
2994
3246
  const result = response;
2995
3247
  if (!result.success) {
2996
3248
  throw new Error(result.error || "Failed to set foreground session");
@@ -3017,17 +3269,17 @@ class CopilotClient {
3017
3269
  this.sessionLifecycleHandlers.delete(wildcardHandler);
3018
3270
  };
3019
3271
  }
3272
+ static normalizeEnvironment(environment) {
3273
+ return process.platform === "win32" ? Object.fromEntries(
3274
+ Object.entries(environment).map(([key, value]) => [key.toUpperCase(), value])
3275
+ ) : { ...environment };
3276
+ }
3020
3277
  /**
3021
3278
  * Builds runtime configuration for child processes and the per-host FFI snapshot.
3022
3279
  * Typed auth, home, keychain, and telemetry options override the effective env.
3023
3280
  */
3024
3281
  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 };
3282
+ const env = CopilotClient.normalizeEnvironment(this.resolvedEnv);
3031
3283
  delete env.NODE_DEBUG;
3032
3284
  const test = this.options.internalTestOptions;
3033
3285
  if (test) {
@@ -3096,9 +3348,9 @@ class CopilotClient {
3096
3348
  if (this.options.logLevel) {
3097
3349
  args.push("--log-level", this.options.logLevel);
3098
3350
  }
3099
- if (this.connectionConfig.kind === "stdio") {
3351
+ if (this.connectionConfig.kind === "spawned-stdio") {
3100
3352
  args.push("--stdio");
3101
- } else if (this.connectionConfig.kind === "tcp") {
3353
+ } else if (this.connectionConfig.kind === "spawned-tcp") {
3102
3354
  const requestedPort = this.connectionConfig.port ?? 0;
3103
3355
  if (requestedPort > 0) {
3104
3356
  args.push("--port", requestedPort.toString());
@@ -3119,15 +3371,20 @@ class CopilotClient {
3119
3371
  const envWithoutNodeDebug = this.buildRuntimeEnv();
3120
3372
  if (!this.resolvedCliPath) {
3121
3373
  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."
3374
+ "Path to Copilot CLI is required. Please supply it via `RuntimeConnection.forSpawnedStdio({ path })` or `RuntimeConnection.forSpawnedTcp({ path })`, set the COPILOT_CLI_PATH environment variable, or use `RuntimeConnection.forTcp(...)` to connect to an already-running runtime."
3123
3375
  );
3124
3376
  }
3125
- if (!(0, import_node_fs.existsSync)(this.resolvedCliPath)) {
3377
+ const cliPath = this.resolvedCliPath;
3378
+ const workingDirectory = this.options.workingDirectory;
3379
+ const launchedCliPath = (0, import_node_path.isAbsolute)(cliPath) || (0, import_node_path.basename)(cliPath) === cliPath ? cliPath : cliPath.endsWith(".js") ? (0, import_node_path.join)(
3380
+ process.platform !== "win32" && (0, import_node_fs.existsSync)(workingDirectory) ? physicalDirectory(workingDirectory) : workingDirectory,
3381
+ cliPath
3382
+ ) : `${workingDirectory}${import_node_path.sep}${cliPath}`;
3383
+ if (!(0, import_node_fs.existsSync)(launchedCliPath)) {
3126
3384
  throw new Error(
3127
- `Copilot CLI not found at ${this.resolvedCliPath}. Set COPILOT_CLI_PATH to use a custom installation.`
3385
+ `Copilot CLI not found at ${launchedCliPath}. Set COPILOT_CLI_PATH to use a custom installation.`
3128
3386
  );
3129
3387
  }
3130
- const workingDirectory = this.options.workingDirectory;
3131
3388
  let workingDirectoryProblem;
3132
3389
  try {
3133
3390
  workingDirectoryProblem = (0, import_node_fs.statSync)(workingDirectory).isDirectory() ? void 0 : "does not exist or is not a directory";
@@ -3143,7 +3400,7 @@ class CopilotClient {
3143
3400
  `Working directory ${workingDirectory} ${workingDirectoryProblem}.`
3144
3401
  );
3145
3402
  }
3146
- const stdioConfig = this.connectionConfig.kind === "stdio" ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"];
3403
+ const stdioConfig = this.connectionConfig.kind === "spawned-stdio" ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"];
3147
3404
  const isJsFile = this.resolvedCliPath.endsWith(".js");
3148
3405
  if (isJsFile) {
3149
3406
  this.cliProcess = (0, import_node_child_process.spawn)(getNodeExecPath(), [this.resolvedCliPath, ...args], {
@@ -3162,7 +3419,7 @@ class CopilotClient {
3162
3419
  }
3163
3420
  let stdout = "";
3164
3421
  let resolved = false;
3165
- if (this.connectionConfig.kind === "stdio") {
3422
+ if (this.connectionConfig.kind === "spawned-stdio") {
3166
3423
  resolved = true;
3167
3424
  resolve2();
3168
3425
  } else {
@@ -3261,18 +3518,16 @@ stderr: ${this.stderrBuffer.trim().slice(-8192) || "(empty)"}`
3261
3518
  switch (this.connectionConfig.kind) {
3262
3519
  case "parent-process":
3263
3520
  return this.connectToParentProcessViaStdio();
3264
- case "stdio":
3521
+ case "spawned-stdio":
3265
3522
  return this.connectToChildProcessViaStdio();
3266
3523
  case "inprocess":
3267
3524
  return this.connectViaFfi();
3268
- case "tcp":
3525
+ case "spawned-tcp":
3269
3526
  return this.connectViaTcp();
3270
- case "uri": {
3271
- const { host, port } = this.parseCliUrl(this.connectionConfig.url);
3272
- this.actualHost = host;
3273
- this.runtimePort = port;
3527
+ case "tcp":
3528
+ this.actualHost = this.connectionConfig.host;
3529
+ this.runtimePort = this.connectionConfig.port;
3274
3530
  return this.connectViaTcp();
3275
- }
3276
3531
  }
3277
3532
  }
3278
3533
  /** Starts the in-process FFI runtime with SDK-managed typed options. */