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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -1,9 +1,17 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { spawn } from "node:child_process";
3
3
  import { randomUUID } from "node:crypto";
4
- import { accessSync, constants, existsSync, statSync } from "node:fs";
4
+ import {
5
+ accessSync,
6
+ constants,
7
+ existsSync,
8
+ lstatSync,
9
+ readlinkSync,
10
+ realpathSync,
11
+ statSync
12
+ } from "node:fs";
5
13
  import { isIPv6, Socket } from "node:net";
6
- import { dirname, isAbsolute, join, resolve, win32 } from "node:path";
14
+ import { basename, dirname, isAbsolute, join, resolve, sep, win32 } from "node:path";
7
15
  import {
8
16
  CancellationTokenSource,
9
17
  createMessageConnection as createRpcMessageConnection,
@@ -37,12 +45,68 @@ import { registerEntraTokenProvider } from "./entra.js";
37
45
  import { getTraceContext } from "./telemetry.js";
38
46
  import { toJsonSchema } from "./schema.js";
39
47
  import { ToolSet } from "./toolSet.js";
40
- import { defaultJoinSessionPermissionHandler } from "./types.js";
48
+ import { defaultJoinSessionPermissionHandler, RuntimeConnection } from "./types.js";
41
49
  import { getWorkflowRegistration } from "./workflow.js";
42
- const MIN_PROTOCOL_VERSION = 3;
50
+ const MIN_PROTOCOL_VERSION = 4;
43
51
  const RUNTIME_SHUTDOWN_TIMEOUT_MS = 1e4;
44
52
  const CLOUD_SESSION_CLEANUP_TIMEOUT_MS = 1e4;
45
53
  const AUTO_MODE_RECOVERY_CLEANUP_TIMEOUT_MS = 1e4;
54
+ function groupHostSessionSettings(settings) {
55
+ const paths = {
56
+ enableExperimentalMode: ["experiments", "enableExperimentalMode"],
57
+ infiniteSessions: ["state", "infiniteSessions"],
58
+ additionalDirectories: ["filesystem", "additionalDirectories"],
59
+ streaming: ["events", "streaming"],
60
+ gitHubToken: ["github", "token"],
61
+ mcpOAuthTokenStorage: ["mcp", "oauthTokenStorage"],
62
+ featureFlags: ["experiments", "flags"],
63
+ enableManagedSettings: ["github", "fetchManagedSettings"],
64
+ excludedManagedSettings: ["policy", "excludedManagedSettings"],
65
+ enableSessionStore: ["state", "enableCrossSessionStore"],
66
+ availableTools: ["tools", "availableTools"],
67
+ excludedTools: ["tools", "excludedTools"],
68
+ allowedModels: ["policy", "allowedModels"],
69
+ skipCustomInstructions: ["instructions", "skipCustomInstructions"],
70
+ refreshCustomInstructions: ["instructions", "refreshCustomInstructions"],
71
+ customAgentsLocalOnly: ["agents", "localDiscoveryOnly"],
72
+ coauthorEnabled: ["git", "coauthorEnabled"],
73
+ manageScheduleEnabled: ["tools", "manageScheduleEnabled"],
74
+ memory: ["state", "memory"],
75
+ pluginDirectories: ["plugins", "directories"],
76
+ skillDirectories: ["skills", "directories"],
77
+ agentDirectories: ["agents", "directories"],
78
+ hookDirectories: ["hooks", "directories"],
79
+ instructionDirectories: ["instructions", "directories"],
80
+ enableMcpApps: ["mcp", "enableApps"],
81
+ reasoningEffort: ["inference", "reasoningEffort"],
82
+ allowMultipleToolCalls: ["inference", "allowMultipleToolCalls"],
83
+ contextTier: ["inference", "contextTier"],
84
+ providers: ["inference", "providers"],
85
+ models: ["inference", "models"],
86
+ defaultProvider: ["inference", "defaultProvider"],
87
+ capi: ["github", "capi"],
88
+ autopilot: ["execution", "autopilot"],
89
+ sessionLimits: ["execution", "limits"],
90
+ permissionMode: ["permissions", "mode"]
91
+ };
92
+ const root = {};
93
+ const groups = {};
94
+ for (const [name, value] of Object.entries(settings)) {
95
+ const path = Object.hasOwn(paths, name) ? paths[name] : void 0;
96
+ if (path) {
97
+ const [group, field] = path;
98
+ (groups[group] ??= {})[field] = value;
99
+ } else {
100
+ root[name === "configDir" ? "configDirectory" : name] = value;
101
+ }
102
+ }
103
+ for (const group of Object.keys(groups)) {
104
+ if (Object.hasOwn(root, group)) {
105
+ throw new Error("AHP host settings must not mix flat and grouped options");
106
+ }
107
+ }
108
+ return { ...root, ...groups };
109
+ }
46
110
  function sessionIdsOverlap(left, right) {
47
111
  if (left === right) return true;
48
112
  if (!isUuidSessionId(left) || !isUuidSessionId(right)) return false;
@@ -260,19 +324,9 @@ async function authenticateClientBasic(connection, callback, request, token) {
260
324
  );
261
325
  return credentials ? { username: credentials.username, password: credentials.password } : {};
262
326
  }
263
- const DEFAULT_PROVIDER_NAME = "default";
264
- function extractBearerTokenProviders(provider, providers) {
327
+ function extractBearerTokenProviders(providers) {
265
328
  const callbacks = /* @__PURE__ */ new Map();
266
- let wireProvider = provider;
267
- if (provider?.bearerTokenProvider) {
268
- const { bearerTokenProvider, ...rest } = provider;
269
- callbacks.set(DEFAULT_PROVIDER_NAME, bearerTokenProvider);
270
- wireProvider = {
271
- ...rest,
272
- hasBearerTokenProvider: true
273
- };
274
- }
275
- let wireProviders = providers;
329
+ let wireProviders = providers && [...providers];
276
330
  if (providers?.some((p) => p.bearerTokenProvider)) {
277
331
  wireProviders = providers.map((p) => {
278
332
  if (!p.bearerTokenProvider) return p;
@@ -284,7 +338,7 @@ function extractBearerTokenProviders(provider, providers) {
284
338
  };
285
339
  });
286
340
  }
287
- return { wireProvider, wireProviders, callbacks };
341
+ return { wireProviders, callbacks };
288
342
  }
289
343
  function toWireMcpServers(mcpServers) {
290
344
  if (!mcpServers) return void 0;
@@ -343,7 +397,7 @@ function toolFilterListToArray(value) {
343
397
  if (value === void 0) {
344
398
  return void 0;
345
399
  }
346
- return value instanceof ToolSet ? value.toArray() : value;
400
+ return value instanceof ToolSet ? value.toArray() : [...value];
347
401
  }
348
402
  function validateToolFilterList(field, list) {
349
403
  if (!list) {
@@ -409,6 +463,43 @@ class TeardownResilientStreamMessageWriter extends StreamMessageWriter {
409
463
  }
410
464
  }
411
465
  }
466
+ function physicalDirectory(directory) {
467
+ try {
468
+ return realpathSync.native(directory);
469
+ } catch {
470
+ return walkPhysicalPath(resolve(directory));
471
+ }
472
+ }
473
+ const MAX_SYMLINKS = 40;
474
+ function walkPhysicalPath(absolutePath) {
475
+ let resolved = "/";
476
+ const pending = absolutePath.split("/");
477
+ let links = 0;
478
+ while (pending.length > 0) {
479
+ const part = pending.shift();
480
+ if (part === "" || part === ".") {
481
+ continue;
482
+ }
483
+ if (part === "..") {
484
+ resolved = dirname(resolved);
485
+ continue;
486
+ }
487
+ const next = join(resolved, part);
488
+ if (!lstatSync(next).isSymbolicLink()) {
489
+ resolved = next;
490
+ continue;
491
+ }
492
+ if (++links > MAX_SYMLINKS) {
493
+ throw new Error(`Too many levels of symbolic links in ${absolutePath}`);
494
+ }
495
+ const target = readlinkSync(next);
496
+ if (target.startsWith("/")) {
497
+ resolved = "/";
498
+ }
499
+ pending.unshift(...target.split("/"));
500
+ }
501
+ return resolved;
502
+ }
412
503
  class CopilotClient {
413
504
  cliStartTimeout = null;
414
505
  cliProcess = null;
@@ -535,29 +626,6 @@ class CopilotClient {
535
626
  `);
536
627
  }
537
628
  }
538
- /**
539
- * Environment variable that overrides the transport when the caller does not set
540
- * {@link CopilotClientOptions.connection}. Accepts `"inprocess"` or `"stdio"`
541
- * (case-insensitive); unset selects the in-process transport. Any other value
542
- * is an error.
543
- */
544
- static DEFAULT_CONNECTION_ENV_VAR = "COPILOT_SDK_DEFAULT_CONNECTION";
545
- /**
546
- * Resolves the default {@link RuntimeConnection} for the no-connection case,
547
- * honoring {@link CopilotClient.DEFAULT_CONNECTION_ENV_VAR}.
548
- */
549
- static resolveDefaultConnection() {
550
- const value = process.env[CopilotClient.DEFAULT_CONNECTION_ENV_VAR];
551
- if (value?.toLowerCase() === "stdio") {
552
- return { kind: "stdio" };
553
- }
554
- if (!value || value.toLowerCase() === "inprocess") {
555
- return { kind: "inprocess" };
556
- }
557
- throw new Error(
558
- `Invalid ${CopilotClient.DEFAULT_CONNECTION_ENV_VAR} value '${value}'. Expected 'inprocess', 'stdio', or unset.`
559
- );
560
- }
561
629
  /**
562
630
  * Creates a new CopilotClient instance.
563
631
  *
@@ -571,20 +639,20 @@ class CopilotClient {
571
639
  * // Connect to an existing runtime
572
640
  * const client = new CopilotClient({
573
641
  * mode: "coding-agent",
574
- * connection: RuntimeConnection.forUri("localhost:3000"),
642
+ * runtime: RuntimeConnection.forTcp("localhost", 3000),
575
643
  * });
576
- *
644
+ * *
577
645
  * // Spawn the runtime over TCP on a chosen port
578
646
  * const client = new CopilotClient({
579
647
  * mode: "coding-agent",
580
- * connection: RuntimeConnection.forTcp({ port: 9001 }),
648
+ * runtime: RuntimeConnection.forSpawnedTcp({ port: 9001 }),
581
649
  * });
582
- *
650
+ * *
583
651
  * // Use a custom runtime binary
584
652
  * const client = new CopilotClient({
585
653
  * mode: "coding-agent",
586
- * connection: RuntimeConnection.forStdio({ path: "/usr/local/bin/copilot" }),
587
- * logLevel: "debug",
654
+ * runtime: RuntimeConnection.forSpawnedStdio({ path: "/usr/local/bin/copilot" }),
655
+ * observability: { logLevel: "debug" },
588
656
  * });
589
657
  * ```
590
658
  */
@@ -592,31 +660,39 @@ class CopilotClient {
592
660
  if (options?.mode !== "coding-agent" && options?.mode !== "empty") {
593
661
  throw new Error("mode is required and must be 'coding-agent' or 'empty'");
594
662
  }
595
- const conn = options._internalConnection ?? options.connection ?? CopilotClient.resolveDefaultConnection();
596
- if ((conn.kind === "uri" || conn.kind === "parent-process") && options.internalTestOptions !== void 0) {
597
- throw new Error("internalTestOptions requires a runtime owned by this client");
663
+ const conn = options._internalConnection ?? options.runtime ?? RuntimeConnection.forDefault();
664
+ if (conn.kind === "tcp" || conn.kind === "parent-process") {
665
+ const runtimeOnlyOptions = {
666
+ "runtime.baseDirectory": "baseDirectory" in conn ? conn.baseDirectory : void 0,
667
+ "github.token": options.github?.token,
668
+ "github.useLoggedInUser": options.github?.useLoggedInUser,
669
+ "observability.telemetry": options.observability?.telemetry,
670
+ "runtime.sessionIdleTimeoutSeconds": "sessionIdleTimeoutSeconds" in conn ? conn.sessionIdleTimeoutSeconds : void 0,
671
+ internalTestOptions: options.internalTestOptions
672
+ };
673
+ const unsupported = Object.entries(runtimeOnlyOptions).filter(([, value]) => value !== void 0).map(([name]) => name);
674
+ if (unsupported.length > 0) {
675
+ throw new Error(
676
+ `Cannot configure runtime startup options for an attached runtime: ${unsupported.join(", ")}`
677
+ );
678
+ }
598
679
  }
599
- if (conn.kind === "uri" && (options.gitHubToken !== void 0 || options.useLoggedInUser !== void 0)) {
680
+ if ("env" in options || "workingDirectory" in options) {
600
681
  throw new Error(
601
- "gitHubToken and useLoggedInUser cannot be used with RuntimeConnection.forUri (external server manages its own auth)"
682
+ "Configure env and workingDirectory on RuntimeConnection.forSpawnedStdio/forSpawnedTcp, not on CopilotClientOptions. Set session working directories on individual sessions."
602
683
  );
603
684
  }
604
- if (conn.kind === "inprocess" && options.env !== void 0) {
685
+ if (conn.kind === "inprocess" && "env" in conn && conn.env !== void 0) {
605
686
  throw new Error(
606
687
  "env is not supported with RuntimeConnection.forInProcess(): environment variables belong to the shared host process. Use typed client/session options or a child-process transport."
607
688
  );
608
689
  }
609
- if (conn.kind === "inprocess" && options.workingDirectory !== void 0) {
610
- throw new Error(
611
- "workingDirectory is not supported with RuntimeConnection.forInProcess(): the in-process transport hosts the runtime in this process, so honoring it would require mutating the shared process-global cwd. Set SessionConfig.workingDirectory instead."
612
- );
613
- }
614
- if ((conn.kind === "stdio" || conn.kind === "tcp") && conn.env !== void 0 && options.env !== void 0) {
690
+ if (conn.kind === "inprocess" && "workingDirectory" in conn && conn.workingDirectory !== void 0) {
615
691
  throw new Error(
616
- "Set environment variables via either the client-level env option or the connection's env (RuntimeConnection.forStdio/forTcp), not both. Prefer the connection-level env for child-process transports."
692
+ "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."
617
693
  );
618
694
  }
619
- if (conn.kind === "tcp" && conn.connectionToken !== void 0) {
695
+ if (conn.kind === "spawned-tcp" && conn.connectionToken !== void 0) {
620
696
  if (typeof conn.connectionToken !== "string" || conn.connectionToken.length === 0) {
621
697
  throw new Error("connectionToken must be a non-empty string");
622
698
  }
@@ -625,67 +701,74 @@ class CopilotClient {
625
701
  if (options.sessionFs) {
626
702
  this.validateSessionFsConfig(options.sessionFs);
627
703
  }
628
- if (options.builtinPluginDirectories) {
629
- for (const path of options.builtinPluginDirectories) {
704
+ if (options.plugins?.builtinDirectories) {
705
+ for (const path of options.plugins?.builtinDirectories) {
630
706
  if (!isAbsolute(path)) {
631
707
  throw new Error(
632
708
  `builtinPluginDirectories must contain only absolute paths: ${path}`
633
709
  );
634
710
  }
635
711
  }
636
- this.builtinPluginDirectories = [...options.builtinPluginDirectories];
712
+ this.builtinPluginDirectories = [...options.plugins?.builtinDirectories];
637
713
  }
638
- if (conn.kind === "uri") {
639
- const { host, port } = this.parseCliUrl(conn.url);
640
- this.actualHost = host;
641
- this.runtimePort = port;
714
+ if (conn.kind === "tcp") {
715
+ if (typeof conn.host !== "string" || !conn.host || /[\s/\\?#@[\]]/.test(conn.host) || conn.host.includes(":") && !isIPv6(conn.host)) {
716
+ throw new Error(
717
+ "host must be a hostname or IP address without a scheme, port, or path"
718
+ );
719
+ }
720
+ if (!Number.isInteger(conn.port) || conn.port < 1 || conn.port > 65535) {
721
+ throw new Error("port must be an integer from 1 through 65535");
722
+ }
723
+ this.actualHost = conn.host;
724
+ this.runtimePort = conn.port;
642
725
  this.isExternalServer = true;
643
726
  } else if (conn.kind === "parent-process") {
644
727
  this.isExternalServer = true;
645
728
  }
646
- if (conn.kind === "tcp") {
729
+ if (conn.kind === "spawned-tcp") {
647
730
  this.effectiveConnectionToken = conn.connectionToken ?? randomUUID();
648
- } else if (conn.kind === "uri") {
731
+ } else if (conn.kind === "tcp") {
649
732
  this.effectiveConnectionToken = conn.connectionToken;
650
733
  }
651
- this.onListModels = options.onListModels;
652
- this.onGetTraceContext = options.onGetTraceContext;
734
+ this.onListModels = options.models?.onListModels;
735
+ this.onGetTraceContext = options.observability?.onGetTraceContext;
653
736
  this.sessionFsConfig = options.sessionFs ?? null;
654
- this.requestHandler = options.requestHandler ?? null;
655
- this.extensionLaunchProvider = options.extensionLaunchProvider;
737
+ this.requestHandler = options.models?.requestHandler ?? null;
738
+ this.extensionLaunchProvider = options.extensions?.launchProvider;
656
739
  this.network = options.network ? snapshotNetworkConfig(options.network) : void 0;
657
- this.installationConfirmationHandler = options.installationConfirmationHandler;
658
- this.onGitHubTelemetry = options.onGitHubTelemetry;
740
+ this.installationConfirmationHandler = options.installations?.confirmationHandler;
741
+ this.onGitHubTelemetry = options.github?.onTelemetry;
659
742
  this.setupClientGlobalHandlers();
660
- const connEnv = conn.kind === "stdio" || conn.kind === "tcp" ? conn.env : void 0;
661
- const effectiveEnv = connEnv ?? options.env ?? process.env;
743
+ const spawnedConnection = conn.kind === "spawned-stdio" || conn.kind === "spawned-tcp" ? conn : void 0;
744
+ const effectiveEnv = spawnedConnection?.env ?? process.env;
662
745
  this.resolvedEnv = effectiveEnv;
663
- if (conn.kind === "stdio" || conn.kind === "tcp") {
664
- const explicitCliPath = conn.path ?? effectiveEnv.COPILOT_CLI_PATH;
746
+ if (conn.kind === "spawned-stdio" || conn.kind === "spawned-tcp") {
747
+ const explicitCliPath = conn.path ?? CopilotClient.normalizeEnvironment(effectiveEnv).COPILOT_CLI_PATH;
665
748
  if (explicitCliPath) {
666
749
  this.resolvedCliPath = explicitCliPath;
667
750
  }
668
751
  }
669
- const connArgs = conn.kind === "stdio" || conn.kind === "tcp" ? conn.args ?? [] : [];
752
+ const connArgs = conn.kind === "spawned-stdio" || conn.kind === "spawned-tcp" ? conn.args ?? [] : [];
670
753
  this.connectionExtraArgs = [...connArgs];
671
754
  this.options = {
672
755
  internalTestOptions: options.internalTestOptions,
673
756
  entra: options.entra ? { ...options.entra, tokenProvider: options.entra.tokenProvider } : void 0,
674
- workingDirectory: options.workingDirectory ?? process.cwd(),
675
- logLevel: options.logLevel,
676
- gitHubToken: options.gitHubToken,
757
+ workingDirectory: spawnedConnection?.workingDirectory ?? process.cwd(),
758
+ logLevel: options.observability?.logLevel,
759
+ gitHubToken: options.github?.token,
677
760
  // Default useLoggedInUser to false when gitHubToken is provided, otherwise true.
678
- useLoggedInUser: options.useLoggedInUser ?? (options.gitHubToken ? false : true),
679
- telemetry: options.telemetry,
680
- baseDirectory: options.baseDirectory,
681
- sessionIdleTimeoutSeconds: options.sessionIdleTimeoutSeconds ?? 0,
761
+ useLoggedInUser: options.github?.useLoggedInUser ?? (options.github?.token ? false : true),
762
+ telemetry: options.observability?.telemetry,
763
+ baseDirectory: "baseDirectory" in conn ? conn.baseDirectory : void 0,
764
+ sessionIdleTimeoutSeconds: ("sessionIdleTimeoutSeconds" in conn ? conn.sessionIdleTimeoutSeconds : void 0) ?? 0,
682
765
  mode: options.mode,
683
766
  clientInfo: options.clientInfo
684
767
  };
685
768
  if (this.options.mode === "empty") {
686
769
  const hasPersistence = this.options.baseDirectory !== void 0 || this.sessionFsConfig !== null || // External runtimes manage their own persistence layer; the SDK
687
770
  // can't enforce it from here.
688
- conn.kind === "uri" || conn.kind === "parent-process";
771
+ conn.kind === "tcp" || conn.kind === "parent-process";
689
772
  if (!hasPersistence) {
690
773
  throw new Error(
691
774
  "CopilotClient was created with mode: 'empty' but neither 'baseDirectory' nor 'sessionFs' was set. Empty mode requires an explicit per-session persistence location; pick one."
@@ -694,45 +777,6 @@ class CopilotClient {
694
777
  }
695
778
  }
696
779
  connectionExtraArgs = [];
697
- /**
698
- * Parse CLI URL into host and port
699
- * Supports raw TCP addresses: "host:port", "[ipv6]:port", "http://host:port", or just "port"
700
- */
701
- parseCliUrl(url) {
702
- if (/^https:\/\//i.test(url)) {
703
- throw new Error(
704
- "HTTPS runtime connections are not supported: this transport uses plaintext TCP, not TLS"
705
- );
706
- }
707
- const cleanUrl = url.replace(/^http:\/\//, "");
708
- if (/^\d+$/.test(cleanUrl)) {
709
- return { host: "localhost", port: parseInt(cleanUrl, 10) };
710
- }
711
- const ipv6Match = cleanUrl.match(/^\[([^\]]+)\]:(\d+)$/);
712
- if (ipv6Match) {
713
- const host2 = ipv6Match[1];
714
- if (!isIPv6(host2)) {
715
- throw new Error(`Invalid cliUrl format: ${url}`);
716
- }
717
- const port2 = parseInt(ipv6Match[2], 10);
718
- if (isNaN(port2) || port2 <= 0 || port2 > 65535) {
719
- throw new Error(`Invalid port in cliUrl: ${url}`);
720
- }
721
- return { host: host2, port: port2 };
722
- }
723
- const parts = cleanUrl.split(":");
724
- if (parts.length !== 2) {
725
- throw new Error(
726
- `Invalid cliUrl format: ${url}. Expected "host:port", "[ipv6]:port", "http://host:port", or "port"`
727
- );
728
- }
729
- const host = parts[0] || "localhost";
730
- const port = parseInt(parts[1], 10);
731
- if (isNaN(port) || port <= 0 || port > 65535) {
732
- throw new Error(`Invalid port in cliUrl: ${url}`);
733
- }
734
- return { host, port };
735
- }
736
780
  validateSessionFsConfig(config) {
737
781
  if (!config.initialCwd) {
738
782
  throw new Error("sessionFs.initialCwd is required");
@@ -748,12 +792,12 @@ class CopilotClient {
748
792
  if (!this.sessionFsConfig) {
749
793
  return;
750
794
  }
751
- if (!config.createSessionFsProvider) {
795
+ if (!config.state?.createSessionFsProvider) {
752
796
  throw new Error(
753
797
  "createSessionFsProvider is required in session config when sessionFs is enabled in client options."
754
798
  );
755
799
  }
756
- const provider = config.createSessionFsProvider(session);
800
+ const provider = config.state.createSessionFsProvider(session);
757
801
  if (this.sessionFsConfig.capabilities?.sqlite && !provider.sqlite) {
758
802
  throw new Error(
759
803
  "SessionFsConfig declares capabilities.sqlite but the provider does not implement sqlite."
@@ -860,7 +904,7 @@ class CopilotClient {
860
904
  /**
861
905
  * Starts the runtime host and establishes a connection.
862
906
  *
863
- * An explicit {@link RuntimeConnection.forUri} only establishes the connection.
907
+ * An explicit {@link RuntimeConnection.forTcp} only establishes the connection.
864
908
  * Otherwise, starts an in-process host or the explicitly selected subprocess.
865
909
  * If its subprocess survives a lost connection, it is terminated before restarting.
866
910
  *
@@ -1162,7 +1206,7 @@ class CopilotClient {
1162
1206
  }
1163
1207
  if (this.cliProcess && !this.isExternalServer) {
1164
1208
  const child = this.cliProcess;
1165
- if (this.connectionConfig.kind === "stdio" && child.stdin && child.exitCode == null && child.signalCode == null) {
1209
+ if (this.connectionConfig.kind === "spawned-stdio" && child.stdin && child.exitCode == null && child.signalCode == null) {
1166
1210
  const gracefulExitStart = Date.now();
1167
1211
  try {
1168
1212
  child.stdin.end();
@@ -1227,6 +1271,7 @@ class CopilotClient {
1227
1271
  this.stderrBuffer = "";
1228
1272
  this.processExitPromise = null;
1229
1273
  this.disconnectHosts();
1274
+ this.connectionClosed = false;
1230
1275
  return errors;
1231
1276
  }
1232
1277
  /**
@@ -1236,7 +1281,11 @@ class CopilotClient {
1236
1281
  * @example
1237
1282
  * ```typescript
1238
1283
  * await using client = new CopilotClient({ mode: "coding-agent" });
1239
- * const session = await client.createSession({ onPermissionRequest: approveAll });
1284
+ * const session = await client.createSession({
1285
+ * permissions: {
1286
+ * onRequest: approveAll,
1287
+ * },
1288
+ * });
1240
1289
  * await session.sendAndWait("Hello");
1241
1290
  * // client.stop() is called automatically when the block exits.
1242
1291
  * ```
@@ -1336,6 +1385,7 @@ class CopilotClient {
1336
1385
  this.stderrBuffer = "";
1337
1386
  this.processExitPromise = null;
1338
1387
  await this.killCliProcess();
1388
+ this.connectionClosed = false;
1339
1389
  }
1340
1390
  /** Sends SIGKILL to the spawned CLI process, if it is still running, and waits for it to exit. */
1341
1391
  async killCliProcess() {
@@ -1368,18 +1418,26 @@ class CopilotClient {
1368
1418
  * @example
1369
1419
  * ```typescript
1370
1420
  * // Basic session
1371
- * const session = await client.createSession({ onPermissionRequest: approveAll });
1372
- *
1421
+ * const session = await client.createSession({
1422
+ * permissions: {
1423
+ * onRequest: approveAll
1424
+ * }
1425
+ * });
1426
+ * *
1373
1427
  * // Session with model and tools
1374
1428
  * const session = await client.createSession({
1375
- * onPermissionRequest: approveAll,
1376
- * model: "gpt-5.4",
1377
- * tools: [{
1429
+ * permissions: {
1430
+ * onRequest: approveAll
1431
+ * },
1432
+ * model: "gpt-5.4",
1433
+ * tools: {
1434
+ * definitions: [{
1378
1435
  * name: "get_weather",
1379
1436
  * description: "Get weather for a location",
1380
1437
  * parameters: { type: "object", properties: { location: { type: "string" } } },
1381
1438
  * handler: async (args) => ({ temperature: 72 })
1382
1439
  * }]
1440
+ * }
1383
1441
  * });
1384
1442
  * ```
1385
1443
  */
@@ -1391,8 +1449,8 @@ class CopilotClient {
1391
1449
  * @internal
1392
1450
  */
1393
1451
  resolveToolFilterOptions(config) {
1394
- const availableTools = toolFilterListToArray(config.availableTools);
1395
- const excludedTools = toolFilterListToArray(config.excludedTools);
1452
+ const availableTools = toolFilterListToArray(config.tools?.availableTools);
1453
+ const excludedTools = toolFilterListToArray(config.tools?.excludedTools);
1396
1454
  validateToolFilterList("availableTools", availableTools);
1397
1455
  validateToolFilterList("excludedTools", excludedTools);
1398
1456
  if (this.options.mode === "empty") {
@@ -1408,21 +1466,79 @@ class CopilotClient {
1408
1466
  configDefaultsForMode() {
1409
1467
  if (this.options.mode === "empty") {
1410
1468
  return {
1411
- enableSessionTelemetry: false,
1412
- mcpOAuthTokenStorage: "in-memory",
1413
- skipEmbeddingRetrieval: true,
1414
- embeddingCacheStorage: "in-memory",
1415
- enableOnDemandInstructionDiscovery: false,
1416
- enableFileHooks: false,
1417
- enableHostGitOperations: false,
1418
- enableSessionStore: false,
1419
- enableSkills: false,
1420
- memory: { enabled: false },
1421
- customAgentsLocalOnly: true
1469
+ github: {
1470
+ telemetryEnabled: false
1471
+ },
1472
+ mcp: {
1473
+ oauthTokenStorage: "in-memory"
1474
+ },
1475
+ state: {
1476
+ skipEmbeddingRetrieval: true,
1477
+ embeddingCacheStorage: "in-memory",
1478
+ enableCrossSessionStore: false,
1479
+ memory: { enabled: false }
1480
+ },
1481
+ instructions: {
1482
+ onDemandDiscovery: false
1483
+ },
1484
+ hooks: {
1485
+ enableRepositoryHooks: false
1486
+ },
1487
+ git: {
1488
+ enableHostGitOperations: false
1489
+ },
1490
+ skills: {
1491
+ enabled: false
1492
+ },
1493
+ agents: {
1494
+ localDiscoveryOnly: true
1495
+ }
1422
1496
  };
1423
1497
  }
1424
1498
  return {};
1425
1499
  }
1500
+ applyModeDefaults(config) {
1501
+ const defaults = this.configDefaultsForMode();
1502
+ return {
1503
+ ...config,
1504
+ inference: { ...config.inference },
1505
+ filesystem: { ...config.filesystem },
1506
+ tools: { ...config.tools },
1507
+ interaction: { ...config.interaction },
1508
+ experiments: { ...config.experiments },
1509
+ permissions: { ...config.permissions },
1510
+ events: { ...config.events },
1511
+ plugins: { ...config.plugins },
1512
+ execution: { ...config.execution },
1513
+ policy: { ...config.policy },
1514
+ canvases: { ...config.canvases },
1515
+ extensions: { ...config.extensions },
1516
+ github: { ...defaults.github, ...config.github },
1517
+ mcp: { ...defaults.mcp, ...config.mcp },
1518
+ state: { ...defaults.state, ...config.state },
1519
+ instructions: { ...defaults.instructions, ...config.instructions },
1520
+ hooks: { ...defaults.hooks, ...config.hooks },
1521
+ git: { ...defaults.git, ...config.git },
1522
+ skills: { ...defaults.skills, ...config.skills },
1523
+ agents: {
1524
+ ...defaults.agents,
1525
+ ...config.agents,
1526
+ localDiscoveryOnly: config.agents?.localDiscoveryOnly ?? defaults.agents?.localDiscoveryOnly
1527
+ },
1528
+ systemMessage: this.getSystemMessageConfigForMode(config.systemMessage)
1529
+ };
1530
+ }
1531
+ validateSessionCredentials(config) {
1532
+ const { token, tokenProvider } = config.github ?? {};
1533
+ if (token !== void 0 && tokenProvider !== void 0) {
1534
+ throw new Error("github.token and github.tokenProvider are mutually exclusive");
1535
+ }
1536
+ if (config.inference && "provider" in config.inference) {
1537
+ throw new Error(
1538
+ "inference.provider is no longer supported; use inference.providers and inference.models"
1539
+ );
1540
+ }
1541
+ }
1426
1542
  /** Mode-specific default for enableExperimentalMode. */
1427
1543
  experimentalModeForMode(supplied) {
1428
1544
  return this.options.mode === "empty" ? supplied ?? false : supplied;
@@ -1469,30 +1585,36 @@ class CopilotClient {
1469
1585
  * Mode-specific options applied via session.options.update after create/resume.
1470
1586
  *
1471
1587
  * In empty mode, defaults the four overridable feature flags to safe values
1472
- * (caller values from `config` win). `installedPlugins=[]` is unconditional
1473
- * in empty mode. `includedBuiltinSkills` defaults to `[]`, but callers can
1588
+ * (caller values from `config` win). `plugins.installed=[]` is unconditional
1589
+ * in empty mode. `skills.includedBuiltinSkills` defaults to `[]`, but callers can
1474
1590
  * explicitly allow selected runtime-bundled skills.
1475
1591
  */
1476
1592
  async updateSessionOptionsForMode(session, config) {
1477
1593
  const patch = {};
1478
1594
  if (this.options.mode === "empty") {
1479
- patch.skipCustomInstructions = config.skipCustomInstructions ?? true;
1480
- patch.customAgentsLocalOnly = config.customAgentsLocalOnly ?? true;
1481
- patch.coauthorEnabled = config.coauthorEnabled ?? false;
1482
- patch.manageScheduleEnabled = config.manageScheduleEnabled ?? false;
1483
- patch.installedPlugins = [];
1484
- patch.includedBuiltinSkills = config.includedBuiltinSkills ?? [];
1595
+ patch.instructions = {
1596
+ skipCustomInstructions: config.instructions?.skipCustomInstructions ?? true
1597
+ };
1598
+ patch.agents = { localDiscoveryOnly: config.agents?.localDiscoveryOnly ?? true };
1599
+ patch.git = { coauthorEnabled: config.git?.coauthorEnabled ?? false };
1600
+ patch.tools = { manageScheduleEnabled: config.tools?.manageScheduleEnabled ?? false };
1601
+ patch.plugins = { installed: [] };
1602
+ patch.skills = {
1603
+ includedBuiltinSkills: [...config.skills?.includedBuiltinSkills ?? []]
1604
+ };
1485
1605
  } else {
1486
- if (config.skipCustomInstructions !== void 0)
1487
- patch.skipCustomInstructions = config.skipCustomInstructions;
1488
- if (config.customAgentsLocalOnly !== void 0)
1489
- patch.customAgentsLocalOnly = config.customAgentsLocalOnly;
1490
- if (config.coauthorEnabled !== void 0)
1491
- patch.coauthorEnabled = config.coauthorEnabled;
1492
- if (config.manageScheduleEnabled !== void 0)
1493
- patch.manageScheduleEnabled = config.manageScheduleEnabled;
1494
- if (config.includedBuiltinSkills !== void 0)
1495
- patch.includedBuiltinSkills = config.includedBuiltinSkills;
1606
+ if (config.instructions?.skipCustomInstructions !== void 0)
1607
+ patch.instructions = {
1608
+ skipCustomInstructions: config.instructions.skipCustomInstructions
1609
+ };
1610
+ if (config.agents?.localDiscoveryOnly !== void 0)
1611
+ patch.agents = { localDiscoveryOnly: config.agents.localDiscoveryOnly };
1612
+ if (config.git?.coauthorEnabled !== void 0)
1613
+ patch.git = { coauthorEnabled: config.git.coauthorEnabled };
1614
+ if (config.tools?.manageScheduleEnabled !== void 0)
1615
+ patch.tools = { manageScheduleEnabled: config.tools.manageScheduleEnabled };
1616
+ if (config.skills?.includedBuiltinSkills !== void 0)
1617
+ patch.skills = { includedBuiltinSkills: [...config.skills.includedBuiltinSkills] };
1496
1618
  }
1497
1619
  if (Object.keys(patch).length === 0) {
1498
1620
  return;
@@ -1508,16 +1630,14 @@ class CopilotClient {
1508
1630
  }
1509
1631
  }
1510
1632
  async createSession(config) {
1511
- if (config.autoModeRecovery && typeof config.onAutoModeSwitchRequest !== "function") {
1633
+ if (config.interaction?.autoModeRecovery && typeof config.interaction?.onAutoModeSwitchRequest !== "function") {
1512
1634
  throw new Error("autoModeRecovery requires onAutoModeSwitchRequest");
1513
1635
  }
1514
- if (config.gitHubToken !== void 0 && config.gitHubTokenProvider !== void 0) {
1515
- throw new Error("gitHubToken and gitHubTokenProvider are mutually exclusive");
1516
- }
1517
- if (config.cloud != null && config.skillProvider) {
1636
+ this.validateSessionCredentials(config);
1637
+ if (config.cloud != null && config.skills?.provider) {
1518
1638
  throw new Error("Skill providers are not supported for cloud sessions.");
1519
1639
  }
1520
- const storeMemory = requestedMemoryStore(config.memory);
1640
+ const storeMemory = requestedMemoryStore(config.state?.memory);
1521
1641
  if (config.cloud != null && storeMemory) {
1522
1642
  throw new Error("Memory stores are not supported for cloud sessions.");
1523
1643
  }
@@ -1613,68 +1733,63 @@ class CopilotClient {
1613
1733
  async createSessionInternal(config, signal) {
1614
1734
  signal.throwIfAborted();
1615
1735
  const connection = this.connection;
1616
- const storeMemory = requestedMemoryStore(config.memory);
1617
- const modeDefaults = this.configDefaultsForMode();
1618
- config = { ...modeDefaults, ...config };
1619
- config.customAgentsLocalOnly ??= modeDefaults.customAgentsLocalOnly;
1620
- config.systemMessage = this.getSystemMessageConfigForMode(config.systemMessage);
1736
+ const storeMemory = requestedMemoryStore(config.state?.memory);
1737
+ config = this.applyModeDefaults(config);
1621
1738
  const callerSessionId = config.sessionId;
1622
1739
  const useServerGeneratedId = config.cloud != null && callerSessionId == null;
1623
1740
  const localSessionId = useServerGeneratedId ? void 0 : callerSessionId ?? randomUUID();
1624
1741
  const toolFilterOptions = this.resolveToolFilterOptions(config);
1625
1742
  const gitHubTokenProviderRegistrationId = this.registerGitHubTokenProvider(
1626
- config.gitHubTokenProvider,
1743
+ config.github?.tokenProvider,
1627
1744
  localSessionId
1628
1745
  );
1629
- const {
1630
- wireProvider: bearerWireProvider,
1631
- wireProviders: bearerWireProviders,
1632
- callbacks: bearerTokenCallbacks
1633
- } = extractBearerTokenProviders(config.provider, config.providers);
1746
+ const { wireProviders: bearerWireProviders, callbacks: bearerTokenCallbacks } = extractBearerTokenProviders(config.inference?.providers);
1634
1747
  const { wirePayload: wireSystemMessage, transformCallbacks } = extractTransformCallbacks(
1635
1748
  config.systemMessage
1636
1749
  );
1637
1750
  let replacedSession;
1638
1751
  const initializeSession = (sessionId) => {
1639
1752
  const s = new CopilotSession(sessionId, connection, void 0, this.onGetTraceContext, {
1640
- mcpAuthHandler: config.onMcpAuthRequest,
1641
- managedSettingsEnabled: config.enableManagedSettings === true || config.managedSettings !== void 0,
1753
+ mcpAuthHandler: config.mcp?.onAuthRequest,
1754
+ managedSettingsEnabled: config.github?.fetchManagedSettings === true || config.policy?.managedSettings !== void 0,
1642
1755
  onDisconnected: gitHubTokenProviderRegistrationId === void 0 ? void 0 : () => this.githubTokenProviders.delete(gitHubTokenProviderRegistrationId)
1643
1756
  });
1644
- s.registerTools(config.tools);
1645
- s.registerCanvases(config.canvases);
1646
- s.registerCommands(config.commands);
1757
+ s.registerTools(config.tools?.definitions);
1758
+ s.registerCanvases(config.canvases?.definitions);
1759
+ s.registerCommands(config.interaction?.commands);
1647
1760
  if (bearerTokenCallbacks.size > 0) {
1648
1761
  s.registerBearerTokenProviders(bearerTokenCallbacks);
1649
1762
  }
1650
- s.registerPermissionHandler(config.onPermissionRequest);
1651
- if (config.onUserInputRequest) {
1652
- s.registerUserInputHandler(config.onUserInputRequest);
1763
+ s.registerPermissionHandler(config.permissions?.onRequest);
1764
+ if (config.interaction?.onUserInputRequest) {
1765
+ s.registerUserInputHandler(config.interaction?.onUserInputRequest);
1653
1766
  }
1654
- if (config.onShellAuthenticationRequest) {
1655
- s.registerShellAuthenticationHandler(config.onShellAuthenticationRequest);
1767
+ if (config.interaction?.onShellAuthenticationRequest) {
1768
+ s.registerShellAuthenticationHandler(
1769
+ config.interaction?.onShellAuthenticationRequest
1770
+ );
1656
1771
  }
1657
- if (config.onElicitationRequest) {
1658
- s.registerElicitationHandler(config.onElicitationRequest);
1772
+ if (config.interaction?.onElicitationRequest) {
1773
+ s.registerElicitationHandler(config.interaction?.onElicitationRequest);
1659
1774
  }
1660
- if (config.onExitPlanModeRequest) {
1661
- s.registerExitPlanModeHandler(config.onExitPlanModeRequest);
1775
+ if (config.interaction?.onExitPlanModeRequest) {
1776
+ s.registerExitPlanModeHandler(config.interaction?.onExitPlanModeRequest);
1662
1777
  }
1663
- if (config.onAutoModeSwitchRequest) {
1664
- s.registerAutoModeSwitchHandler(config.onAutoModeSwitchRequest);
1778
+ if (config.interaction?.onAutoModeSwitchRequest) {
1779
+ s.registerAutoModeSwitchHandler(config.interaction?.onAutoModeSwitchRequest);
1665
1780
  }
1666
- if (config.hooks) {
1667
- s.registerHooks(config.hooks);
1781
+ if (config.hooks?.handlers) {
1782
+ s.registerHooks(config.hooks?.handlers);
1668
1783
  }
1669
- if (config.skillProvider) {
1670
- s.registerSkillProvider(config.skillProvider);
1784
+ if (config.skills?.provider) {
1785
+ s.registerSkillProvider(config.skills?.provider);
1671
1786
  }
1672
1787
  s._registerMemoryStore(storeMemory);
1673
1788
  if (transformCallbacks) {
1674
1789
  s.registerTransformCallbacks(transformCallbacks);
1675
1790
  }
1676
- if (config.onEvent) {
1677
- s.on(config.onEvent);
1791
+ if (config.events?.onEvent) {
1792
+ s.on(config.events?.onEvent);
1678
1793
  }
1679
1794
  this.setupSessionFs(s, config);
1680
1795
  signal.throwIfAborted();
@@ -1706,118 +1821,174 @@ class CopilotClient {
1706
1821
  const response = await connection.sendRequest("session.create", {
1707
1822
  ...traceContext,
1708
1823
  model: config.model,
1709
- allowedModels: config.allowedModels,
1824
+ policy: {
1825
+ allowedModels: config.policy?.allowedModels,
1826
+ excludedManagedSettings: config.policy?.excludedManagedSettings,
1827
+ enforceManagedModelDefaults: config.policy?.enforceManagedModelDefaults,
1828
+ managedSettings: config.policy?.managedSettings
1829
+ },
1710
1830
  sessionId: localSessionId,
1711
1831
  name: config.name,
1712
1832
  clientName: config.clientName,
1713
- reasoningEffort: config.reasoningEffort,
1714
- allowMultipleToolCalls: config.allowMultipleToolCalls,
1715
- reasoningSummary: config.reasoningSummary,
1716
- isExperimentalMode: this.experimentalModeForMode(config.enableExperimentalMode),
1717
- contextTier: config.contextTier,
1718
- tools: config.tools?.map((tool) => ({
1719
- name: tool.name,
1720
- title: tool.title,
1721
- description: tool.description,
1722
- parameters: toJsonSchema(tool.parameters),
1723
- overridesBuiltInTool: tool.overridesBuiltInTool,
1724
- skipPermission: tool.skipPermission,
1725
- hasHandler: !!tool.handler,
1726
- defer: tool.defer,
1727
- metadata: tool.metadata,
1728
- isTerminal: tool.isTerminal,
1729
- idempotent: tool.idempotent,
1730
- namespace: tool.namespace
1731
- })),
1732
- toolSearch: config.toolSearch,
1733
- imageGeneration: config.imageGeneration,
1734
- canvases: config.canvases?.map((canvas) => canvas.declaration),
1735
- requestCanvasRenderer: config.requestCanvasRenderer,
1736
- requestExtensions: config.requestExtensions,
1737
- extensionSdkPath: config.extensionSdkPath,
1738
- extensionInfo: config.extensionInfo,
1739
- canvasProvider: config.canvasProvider,
1740
- commands: config.commands?.map((cmd) => ({
1741
- name: cmd.name,
1742
- description: cmd.description ?? ""
1743
- })),
1833
+ inference: {
1834
+ reasoningEffort: config.inference?.reasoningEffort,
1835
+ allowMultipleToolCalls: config.inference?.allowMultipleToolCalls,
1836
+ reasoningSummary: config.inference?.reasoningSummary,
1837
+ contextTier: config.inference?.contextTier,
1838
+ defaultProvider: config.inference?.defaultProvider,
1839
+ providers: bearerWireProviders,
1840
+ models: config.inference?.models,
1841
+ enableCitations: config.inference?.enableCitations,
1842
+ capabilities: config.inference?.capabilities
1843
+ },
1844
+ experiments: {
1845
+ enableExperimentalMode: this.experimentalModeForMode(
1846
+ config.experiments?.enableExperimentalMode
1847
+ ),
1848
+ flags: config.experiments?.flags,
1849
+ assignments: config.experiments?.assignments
1850
+ },
1851
+ tools: {
1852
+ definitions: config.tools?.definitions?.map((tool) => ({
1853
+ name: tool.name,
1854
+ title: tool.title,
1855
+ description: tool.description,
1856
+ parameters: toJsonSchema(tool.parameters),
1857
+ overridesBuiltInTool: tool.overridesBuiltInTool,
1858
+ skipPermission: tool.skipPermission,
1859
+ hasHandler: !!tool.handler,
1860
+ defer: tool.defer,
1861
+ metadata: tool.metadata,
1862
+ isTerminal: tool.isTerminal,
1863
+ idempotent: tool.idempotent,
1864
+ namespace: tool.namespace
1865
+ })),
1866
+ search: config.tools?.search,
1867
+ imageGeneration: config.tools?.imageGeneration,
1868
+ availableTools: toolFilterOptions.availableTools,
1869
+ excludedTools: toolFilterOptions.excludedTools,
1870
+ largeOutput: toWireLargeOutput(config.tools?.largeOutput)
1871
+ },
1872
+ canvases: {
1873
+ definitions: config.canvases?.definitions?.map((canvas) => canvas.declaration),
1874
+ requestRenderer: config.canvases?.requestRenderer,
1875
+ provider: config.canvases?.provider
1876
+ },
1877
+ extensions: {
1878
+ enabled: config.extensions?.enabled,
1879
+ sdkPath: config.extensions?.sdkPath,
1880
+ identity: config.extensions?.identity
1881
+ },
1882
+ interaction: {
1883
+ commands: config.interaction?.commands?.map((cmd) => ({
1884
+ name: cmd.name,
1885
+ description: cmd.description ?? ""
1886
+ })),
1887
+ requestUserInput: !!config.interaction?.onUserInputRequest,
1888
+ requestElicitation: !!config.interaction?.onElicitationRequest,
1889
+ askUserVariant: config.interaction?.askUserVariant,
1890
+ requestExitPlanMode: !!config.interaction?.onExitPlanModeRequest,
1891
+ requestAutoModeSwitch: !!config.interaction?.onAutoModeSwitchRequest,
1892
+ ...config.interaction?.onShellAuthenticationRequest ? {
1893
+ requestShellAuthentication: true
1894
+ } : {},
1895
+ ...config.interaction?.autoModeRecovery ? {
1896
+ requestAutoModeRecovery: true
1897
+ } : {}
1898
+ },
1744
1899
  systemMessage: wireSystemMessage,
1745
- availableTools: toolFilterOptions.availableTools,
1746
- excludedTools: toolFilterOptions.excludedTools,
1747
- excludedBuiltinAgents: config.excludedBuiltinAgents,
1748
- includedBuiltinAgents: config.includedBuiltinAgents,
1749
- provider: bearerWireProvider,
1750
- capi: config.capi,
1751
- providers: bearerWireProviders,
1752
- models: config.models,
1753
- enableSessionTelemetry: config.enableSessionTelemetry,
1754
- enableCitations: config.enableCitations,
1755
- enableFileChangeTracking: config.enableFileChangeTracking,
1756
- sessionLimits: config.sessionLimits,
1757
- autopilot: config.autopilot,
1758
- modelCapabilities: config.modelCapabilities,
1759
- largeOutput: toWireLargeOutput(config.largeOutput),
1760
- requestPermission: !!config.onPermissionRequest,
1761
- requestUserInput: !!config.onUserInputRequest,
1762
- requestElicitation: !!config.onElicitationRequest,
1763
- ...config.onShellAuthenticationRequest ? { requestShellAuthentication: true } : {},
1764
- askUserVariant: config.askUserVariant,
1765
- ...config.enableMcpApps ? { requestMcpApps: true } : {},
1766
- ...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
1767
- requestExitPlanMode: !!config.onExitPlanModeRequest,
1768
- requestAutoModeSwitch: !!config.onAutoModeSwitchRequest,
1769
- ...config.autoModeRecovery ? { requestAutoModeRecovery: true } : {},
1770
- hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),
1900
+ agents: {
1901
+ excludedBuiltinAgents: config.agents?.excludedBuiltinAgents,
1902
+ includedBuiltinAgents: config.agents?.includedBuiltinAgents,
1903
+ definitions: toWireCustomAgents(config.agents?.definitions),
1904
+ localDiscoveryOnly: config.agents?.localDiscoveryOnly,
1905
+ default: config.agents?.default,
1906
+ selected: config.agents?.selected,
1907
+ directories: config.agents?.directories
1908
+ },
1909
+ github: {
1910
+ capi: config.github?.capi,
1911
+ telemetryEnabled: config.github?.telemetryEnabled,
1912
+ token: config.github?.token,
1913
+ tokenProviderRegistrationId: gitHubTokenProviderRegistrationId,
1914
+ fetchManagedSettings: config.github?.fetchManagedSettings,
1915
+ interactiveUser: config.github?.interactiveUser,
1916
+ ...config.github?.mcp != null ? {
1917
+ mcp: config.github?.mcp
1918
+ } : {},
1919
+ ...this.onGitHubTelemetry != null ? {
1920
+ telemetryForwarding: true
1921
+ } : {}
1922
+ },
1923
+ filesystem: {
1924
+ trackFileChanges: config.filesystem?.trackFileChanges,
1925
+ trustWorkingDirectory: config.filesystem?.trustWorkingDirectory,
1926
+ additionalDirectories: config.filesystem?.additionalDirectories
1927
+ },
1928
+ execution: {
1929
+ limits: config.execution?.limits,
1930
+ autopilot: config.execution?.autopilot
1931
+ },
1932
+ permissions: {
1933
+ request: !!config.permissions?.onRequest,
1934
+ sandbox: config.permissions?.sandbox,
1935
+ mode: config.permissions?.mode
1936
+ },
1937
+ mcp: {
1938
+ ...config.mcp?.enableApps ? {
1939
+ enableApps: true
1940
+ } : {},
1941
+ servers: toWireMcpServers(config.mcp?.servers),
1942
+ oauthTokenStorage: config.mcp?.oauthTokenStorage,
1943
+ authClientIdMetadataUrl: config.mcp?.authClientIdMetadataUrl,
1944
+ envValueMode: "direct",
1945
+ disabledServers: config.mcp?.disabledServers
1946
+ },
1947
+ hooks: {
1948
+ hasHandlers: !!(config.hooks?.handlers && Object.values(config.hooks?.handlers).some(Boolean)),
1949
+ enableRepositoryHooks: config.hooks?.enableRepositoryHooks,
1950
+ directories: config.hooks?.directories
1951
+ },
1771
1952
  workingDirectory: config.workingDirectory,
1772
- trustWorkingDirectory: config.trustWorkingDirectory,
1773
- additionalDirectories: config.additionalDirectories,
1774
- streaming: config.streaming,
1775
- includeSubAgentStreamingEvents: config.includeSubAgentStreamingEvents ?? true,
1776
- ...this.onGitHubTelemetry != null ? { enableGitHubTelemetryForwarding: true } : {},
1777
- mcpServers: toWireMcpServers(config.mcpServers),
1953
+ events: {
1954
+ streaming: config.events?.streaming,
1955
+ includeSubAgentStreamingEvents: config.events?.includeSubAgentStreamingEvents ?? true
1956
+ },
1778
1957
  ...config.diagnostics !== void 0 ? { diagnostics: config.diagnostics } : {},
1779
1958
  ...config.lifecycleDiagnostics !== void 0 ? { lifecycleDiagnostics: config.lifecycleDiagnostics } : {},
1780
- mcpOAuthTokenStorage: config.mcpOAuthTokenStorage,
1781
- authClientIdMetadataUrl: config.authClientIdMetadataUrl,
1782
- envValueMode: "direct",
1783
- customAgents: toWireCustomAgents(config.customAgents),
1784
- customAgentsLocalOnly: config.customAgentsLocalOnly,
1785
- defaultAgent: config.defaultAgent,
1786
- agent: config.agent,
1787
- configDir: config.configDirectory,
1959
+ configDirectory: config.configDirectory,
1788
1960
  enableConfigDiscovery: config.enableConfigDiscovery,
1789
- refreshCustomInstructions: config.refreshCustomInstructions,
1790
- skipEmbeddingRetrieval: config.skipEmbeddingRetrieval,
1791
- embeddingCacheStorage: config.embeddingCacheStorage,
1792
- organizationCustomInstructions: config.organizationCustomInstructions,
1793
- enableOnDemandInstructionDiscovery: config.enableOnDemandInstructionDiscovery,
1794
- enableFileHooks: config.enableFileHooks,
1795
- enableHostGitOperations: config.enableHostGitOperations,
1796
- enableSessionStore: config.enableSessionStore,
1797
- enableSkills: config.enableSkills,
1798
- skillDirectories: config.skillDirectories,
1799
- ...config.skillProvider ? { hasSkillProvider: true } : {},
1800
- ...storeMemory ? { hasMemoryStore: true } : {},
1801
- agentDirectories: config.agentDirectories,
1802
- hookDirectories: config.hookDirectories,
1803
- pluginDirectories: config.pluginDirectories,
1804
- instructionDirectories: config.instructionDirectories,
1805
- disabledSkills: config.disabledSkills,
1806
- disabledMcpServers: config.disabledMcpServers,
1807
- sandboxConfig: config.sandboxConfig,
1808
- infiniteSessions: config.infiniteSessions,
1809
- memory: toWireMemoryConfiguration(config.memory),
1810
- gitHubToken: config.gitHubToken,
1811
- gitHubTokenProviderRegistrationId,
1812
- cloud: config.cloud,
1813
- featureFlags: config.featureFlags,
1814
- expAssignments: config.expAssignments,
1815
- enableManagedSettings: config.enableManagedSettings,
1816
- excludedManagedSettings: config.excludedManagedSettings,
1817
- enforceManagedModelDefaults: config.enforceManagedModelDefaults,
1818
- interactiveUser: config.interactiveUser,
1819
- permissionMode: config.permissionMode,
1820
- managedSettings: config.managedSettings
1961
+ instructions: {
1962
+ refreshCustomInstructions: config.instructions?.refreshCustomInstructions,
1963
+ organizationText: config.instructions?.organizationText,
1964
+ onDemandDiscovery: config.instructions?.onDemandDiscovery,
1965
+ directories: config.instructions?.directories
1966
+ },
1967
+ state: {
1968
+ skipEmbeddingRetrieval: config.state?.skipEmbeddingRetrieval,
1969
+ embeddingCacheStorage: config.state?.embeddingCacheStorage,
1970
+ enableCrossSessionStore: config.state?.enableCrossSessionStore,
1971
+ infiniteSessions: config.state?.infiniteSessions,
1972
+ memory: toWireMemoryConfiguration(config.state?.memory),
1973
+ ...storeMemory ? {
1974
+ hasMemoryStore: true
1975
+ } : {}
1976
+ },
1977
+ git: {
1978
+ enableHostGitOperations: config.git?.enableHostGitOperations
1979
+ },
1980
+ skills: {
1981
+ enabled: config.skills?.enabled,
1982
+ directories: config.skills?.directories,
1983
+ disabledSkills: config.skills?.disabledSkills,
1984
+ ...config.skills?.provider ? {
1985
+ hasProvider: true
1986
+ } : {}
1987
+ },
1988
+ plugins: {
1989
+ directories: config.plugins?.directories
1990
+ },
1991
+ cloud: config.cloud
1821
1992
  });
1822
1993
  const {
1823
1994
  sessionId: returnedSessionId,
@@ -1848,10 +2019,10 @@ class CopilotClient {
1848
2019
  }
1849
2020
  this.assignGitHubTokenProvider(gitHubTokenProviderRegistrationId, returnedSessionId);
1850
2021
  session.setCapabilities(capabilities);
1851
- if (config.autoModeRecovery) {
2022
+ if (config.interaction?.autoModeRecovery) {
1852
2023
  await this.requireAutoModeRecovery(session, connection);
1853
2024
  }
1854
- if (config.onMcpAuthRequest) {
2025
+ if (config.mcp?.onAuthRequest) {
1855
2026
  await connection.sendRequest("session.eventLog.registerInterest", {
1856
2027
  sessionId: returnedSessionId,
1857
2028
  eventType: "mcp.oauth_required"
@@ -1892,7 +2063,7 @@ class CopilotClient {
1892
2063
  [e, cleanupError],
1893
2064
  `Failed to initialize and delete cloud session ${uninitializedCloudSessionId}`
1894
2065
  );
1895
- if (config.autoModeRecovery) {
2066
+ if (config.interaction?.autoModeRecovery) {
1896
2067
  this.recordFailedAutoModeRecoveryCleanup(
1897
2068
  connection,
1898
2069
  uninitializedCloudSessionId,
@@ -1933,12 +2104,20 @@ class CopilotClient {
1933
2104
  * @example
1934
2105
  * ```typescript
1935
2106
  * // Resume a previous session
1936
- * const session = await client.resumeSession("session-123", { onPermissionRequest: approveAll });
1937
- *
2107
+ * const session = await client.resumeSession("session-123", {
2108
+ * permissions: {
2109
+ * onRequest: approveAll
2110
+ * }
2111
+ * });
2112
+ * *
1938
2113
  * // Resume with new tools
1939
2114
  * const session = await client.resumeSession("session-123", {
1940
- * onPermissionRequest: approveAll,
1941
- * tools: [myNewTool]
2115
+ * permissions: {
2116
+ * onRequest: approveAll
2117
+ * },
2118
+ * tools: {
2119
+ * definitions: [myNewTool]
2120
+ * }
1942
2121
  * });
1943
2122
  * ```
1944
2123
  */
@@ -1963,13 +2142,11 @@ class CopilotClient {
1963
2142
  return session;
1964
2143
  }
1965
2144
  async resumeSessionInternal(sessionId, config, contributions = {}, extensionOptions) {
1966
- if (config.autoModeRecovery && typeof config.onAutoModeSwitchRequest !== "function") {
2145
+ if (config.interaction?.autoModeRecovery && typeof config.interaction?.onAutoModeSwitchRequest !== "function") {
1967
2146
  throw new Error("autoModeRecovery requires onAutoModeSwitchRequest");
1968
2147
  }
1969
- if (config.gitHubToken !== void 0 && config.gitHubTokenProvider !== void 0) {
1970
- throw new Error("gitHubToken and gitHubTokenProvider are mutually exclusive");
1971
- }
1972
- requestedMemoryStore(config.memory);
2148
+ this.validateSessionCredentials(config);
2149
+ requestedMemoryStore(config.state?.memory);
1973
2150
  const signal = await this.getSessionInitializationSignal();
1974
2151
  const release = await this.acquireSessionInitialization(sessionId, signal);
1975
2152
  try {
@@ -1987,10 +2164,10 @@ class CopilotClient {
1987
2164
  }
1988
2165
  async resumeSessionWithInitialization(sessionId, config, contributions, signal, extensionOptions) {
1989
2166
  const { workflows } = contributions;
1990
- const storeMemory = requestedMemoryStore(config.memory);
2167
+ const storeMemory = requestedMemoryStore(config.state?.memory);
1991
2168
  signal.throwIfAborted();
1992
2169
  const connection = this.connection;
1993
- const resolveAliases = config.autoModeRecovery === true && !this.sessionFsConfig;
2170
+ const resolveAliases = config.interaction?.autoModeRecovery === true && !this.sessionFsConfig;
1994
2171
  if (resolveAliases && isAbbreviatedUuidPrefix(sessionId)) {
1995
2172
  const resolved = await connection.sendRequest(
1996
2173
  "sessions.findByPrefix",
@@ -2012,57 +2189,52 @@ class CopilotClient {
2012
2189
  void 0,
2013
2190
  this.onGetTraceContext,
2014
2191
  {
2015
- mcpAuthHandler: config.onMcpAuthRequest,
2016
- managedSettingsEnabled: config.enableManagedSettings === true || config.managedSettings !== void 0
2192
+ mcpAuthHandler: config.mcp?.onAuthRequest,
2193
+ managedSettingsEnabled: config.github?.fetchManagedSettings === true || config.policy?.managedSettings !== void 0
2017
2194
  }
2018
2195
  );
2019
- session.registerTools(config.tools);
2020
- session.registerCanvases(config.canvases);
2021
- session.registerCommands(config.commands);
2196
+ session.registerTools(config.tools?.definitions);
2197
+ session.registerCanvases(config.canvases?.definitions);
2198
+ session.registerCommands(config.interaction?.commands);
2022
2199
  session.registerWorkflows(workflows);
2023
- const {
2024
- wireProvider: bearerWireProvider,
2025
- wireProviders: bearerWireProviders,
2026
- callbacks: bearerTokenCallbacks
2027
- } = extractBearerTokenProviders(config.provider, config.providers);
2200
+ const { wireProviders: bearerWireProviders, callbacks: bearerTokenCallbacks } = extractBearerTokenProviders(config.inference?.providers);
2028
2201
  if (bearerTokenCallbacks.size > 0) {
2029
2202
  session.registerBearerTokenProviders(bearerTokenCallbacks);
2030
2203
  }
2031
- session.registerPermissionHandler(config.onPermissionRequest);
2032
- if (config.onUserInputRequest) {
2033
- session.registerUserInputHandler(config.onUserInputRequest);
2204
+ session.registerPermissionHandler(config.permissions?.onRequest);
2205
+ if (config.interaction?.onUserInputRequest) {
2206
+ session.registerUserInputHandler(config.interaction?.onUserInputRequest);
2034
2207
  }
2035
- if (config.onShellAuthenticationRequest) {
2036
- session.registerShellAuthenticationHandler(config.onShellAuthenticationRequest);
2208
+ if (config.interaction?.onShellAuthenticationRequest) {
2209
+ session.registerShellAuthenticationHandler(
2210
+ config.interaction?.onShellAuthenticationRequest
2211
+ );
2037
2212
  }
2038
- if (config.onElicitationRequest) {
2039
- session.registerElicitationHandler(config.onElicitationRequest);
2213
+ if (config.interaction?.onElicitationRequest) {
2214
+ session.registerElicitationHandler(config.interaction?.onElicitationRequest);
2040
2215
  }
2041
- if (config.onExitPlanModeRequest) {
2042
- session.registerExitPlanModeHandler(config.onExitPlanModeRequest);
2216
+ if (config.interaction?.onExitPlanModeRequest) {
2217
+ session.registerExitPlanModeHandler(config.interaction?.onExitPlanModeRequest);
2043
2218
  }
2044
- if (config.onAutoModeSwitchRequest) {
2045
- session.registerAutoModeSwitchHandler(config.onAutoModeSwitchRequest);
2219
+ if (config.interaction?.onAutoModeSwitchRequest) {
2220
+ session.registerAutoModeSwitchHandler(config.interaction?.onAutoModeSwitchRequest);
2046
2221
  }
2047
- if (config.hooks) {
2048
- session.registerHooks(config.hooks);
2222
+ if (config.hooks?.handlers) {
2223
+ session.registerHooks(config.hooks?.handlers);
2049
2224
  }
2050
- if (config.skillProvider) {
2051
- session.registerSkillProvider(config.skillProvider);
2225
+ if (config.skills?.provider) {
2226
+ session.registerSkillProvider(config.skills?.provider);
2052
2227
  }
2053
2228
  session._registerMemoryStore(storeMemory);
2054
- const modeDefaults = this.configDefaultsForMode();
2055
- config = { ...modeDefaults, ...config };
2056
- config.customAgentsLocalOnly ??= modeDefaults.customAgentsLocalOnly;
2057
- config.systemMessage = this.getSystemMessageConfigForMode(config.systemMessage);
2229
+ config = this.applyModeDefaults(config);
2058
2230
  const { wirePayload: wireSystemMessage, transformCallbacks } = extractTransformCallbacks(
2059
2231
  config.systemMessage
2060
2232
  );
2061
2233
  if (transformCallbacks) {
2062
2234
  session.registerTransformCallbacks(transformCallbacks);
2063
2235
  }
2064
- if (config.onEvent) {
2065
- session.on(config.onEvent);
2236
+ if (config.events?.onEvent) {
2237
+ session.on(config.events?.onEvent);
2066
2238
  }
2067
2239
  const toolFilterOptions = this.resolveToolFilterOptions(config);
2068
2240
  this.setupSessionFs(session, config);
@@ -2073,7 +2245,7 @@ class CopilotClient {
2073
2245
  let releaseCanonicalInitialization;
2074
2246
  let keepResumedSessionOnRecoveryRejection = false;
2075
2247
  const gitHubTokenProviderRegistrationId = this.registerGitHubTokenProvider(
2076
- config.gitHubTokenProvider,
2248
+ config.github?.tokenProvider,
2077
2249
  sessionId
2078
2250
  );
2079
2251
  if (gitHubTokenProviderRegistrationId !== void 0) {
@@ -2097,121 +2269,177 @@ class CopilotClient {
2097
2269
  resolveAliases
2098
2270
  });
2099
2271
  const response = await connection.sendRequest("session.resume", {
2100
- allowedModels: config.allowedModels,
2272
+ policy: {
2273
+ allowedModels: config.policy?.allowedModels,
2274
+ excludedManagedSettings: config.policy?.excludedManagedSettings,
2275
+ enforceManagedModelDefaults: config.policy?.enforceManagedModelDefaults,
2276
+ managedSettings: config.policy?.managedSettings
2277
+ },
2101
2278
  ...traceContext,
2102
2279
  sessionId,
2103
2280
  allowTranscriptRecovery: config.allowTranscriptRecovery,
2104
2281
  clientName: config.clientName,
2105
2282
  model: config.model,
2106
- reasoningEffort: config.reasoningEffort,
2107
- allowMultipleToolCalls: config.allowMultipleToolCalls,
2108
- reasoningSummary: config.reasoningSummary,
2109
- isExperimentalMode: this.experimentalModeForMode(config.enableExperimentalMode),
2110
- contextTier: config.contextTier,
2283
+ inference: {
2284
+ reasoningEffort: config.inference?.reasoningEffort,
2285
+ allowMultipleToolCalls: config.inference?.allowMultipleToolCalls,
2286
+ reasoningSummary: config.inference?.reasoningSummary,
2287
+ contextTier: config.inference?.contextTier,
2288
+ enableCitations: config.inference?.enableCitations,
2289
+ defaultProvider: config.inference?.defaultProvider,
2290
+ providers: bearerWireProviders,
2291
+ models: config.inference?.models,
2292
+ capabilities: config.inference?.capabilities
2293
+ },
2294
+ experiments: {
2295
+ enableExperimentalMode: this.experimentalModeForMode(
2296
+ config.experiments?.enableExperimentalMode
2297
+ ),
2298
+ flags: config.experiments?.flags,
2299
+ assignments: config.experiments?.assignments
2300
+ },
2111
2301
  systemMessage: wireSystemMessage,
2112
- availableTools: toolFilterOptions.availableTools,
2113
- excludedTools: toolFilterOptions.excludedTools,
2114
- enableSessionTelemetry: config.enableSessionTelemetry,
2115
- excludedBuiltinAgents: config.excludedBuiltinAgents,
2116
- includedBuiltinAgents: config.includedBuiltinAgents,
2117
- enableCitations: config.enableCitations,
2118
- enableFileChangeTracking: config.enableFileChangeTracking,
2119
- sessionLimits: config.sessionLimits,
2120
- autopilot: config.autopilot,
2121
- tools: config.tools?.map((tool) => ({
2122
- name: tool.name,
2123
- title: tool.title,
2124
- description: tool.description,
2125
- parameters: toJsonSchema(tool.parameters),
2126
- overridesBuiltInTool: tool.overridesBuiltInTool,
2127
- skipPermission: tool.skipPermission,
2128
- hasHandler: !!tool.handler,
2129
- defer: tool.defer,
2130
- metadata: tool.metadata,
2131
- isTerminal: tool.isTerminal,
2132
- idempotent: tool.idempotent,
2133
- namespace: tool.namespace
2134
- })),
2135
- toolSearch: config.toolSearch,
2136
- imageGeneration: config.imageGeneration,
2137
- canvases: config.canvases?.map((canvas) => canvas.declaration),
2302
+ tools: {
2303
+ availableTools: toolFilterOptions.availableTools,
2304
+ excludedTools: toolFilterOptions.excludedTools,
2305
+ definitions: config.tools?.definitions?.map((tool) => ({
2306
+ name: tool.name,
2307
+ title: tool.title,
2308
+ description: tool.description,
2309
+ parameters: toJsonSchema(tool.parameters),
2310
+ overridesBuiltInTool: tool.overridesBuiltInTool,
2311
+ skipPermission: tool.skipPermission,
2312
+ hasHandler: !!tool.handler,
2313
+ defer: tool.defer,
2314
+ metadata: tool.metadata,
2315
+ isTerminal: tool.isTerminal,
2316
+ idempotent: tool.idempotent,
2317
+ namespace: tool.namespace
2318
+ })),
2319
+ search: config.tools?.search,
2320
+ imageGeneration: config.tools?.imageGeneration,
2321
+ largeOutput: toWireLargeOutput(config.tools?.largeOutput)
2322
+ },
2323
+ github: {
2324
+ telemetryEnabled: config.github?.telemetryEnabled,
2325
+ capi: config.github?.capi,
2326
+ token: config.github?.token,
2327
+ tokenProviderRegistrationId: gitHubTokenProviderRegistrationId,
2328
+ fetchManagedSettings: config.github?.fetchManagedSettings,
2329
+ interactiveUser: config.github?.interactiveUser,
2330
+ ...config.github?.mcp != null ? {
2331
+ mcp: config.github?.mcp
2332
+ } : {},
2333
+ ...this.onGitHubTelemetry != null ? {
2334
+ telemetryForwarding: true
2335
+ } : {}
2336
+ },
2337
+ agents: {
2338
+ excludedBuiltinAgents: config.agents?.excludedBuiltinAgents,
2339
+ includedBuiltinAgents: config.agents?.includedBuiltinAgents,
2340
+ definitions: toWireCustomAgents(config.agents?.definitions),
2341
+ localDiscoveryOnly: config.agents?.localDiscoveryOnly,
2342
+ default: config.agents?.default,
2343
+ selected: config.agents?.selected,
2344
+ directories: config.agents?.directories
2345
+ },
2346
+ filesystem: {
2347
+ trackFileChanges: config.filesystem?.trackFileChanges,
2348
+ additionalDirectories: config.filesystem?.additionalDirectories
2349
+ },
2350
+ execution: {
2351
+ limits: config.execution?.limits,
2352
+ autopilot: config.execution?.autopilot
2353
+ },
2354
+ canvases: {
2355
+ definitions: config.canvases?.definitions?.map((canvas) => canvas.declaration),
2356
+ requestRenderer: config.canvases?.requestRenderer,
2357
+ provider: config.canvases?.provider,
2358
+ open: config.canvases?.open
2359
+ },
2138
2360
  workflows: workflows?.map(getWorkflowRegistration),
2139
- requestCanvasRenderer: config.requestCanvasRenderer,
2140
- requestExtensions: config.requestExtensions,
2141
- extensionSdkPath: config.extensionSdkPath,
2142
- extensionInfo: config.extensionInfo,
2143
- canvasProvider: config.canvasProvider,
2144
- commands: config.commands?.map((cmd) => ({
2145
- name: cmd.name,
2146
- description: cmd.description ?? ""
2147
- })),
2148
- provider: bearerWireProvider,
2149
- capi: config.capi,
2150
- providers: bearerWireProviders,
2151
- models: config.models,
2152
- modelCapabilities: config.modelCapabilities,
2153
- largeOutput: toWireLargeOutput(config.largeOutput),
2154
- requestPermission: config.onPermissionRequest !== defaultJoinSessionPermissionHandler,
2155
- requestUserInput: !!config.onUserInputRequest,
2156
- requestElicitation: !!config.onElicitationRequest,
2157
- ...config.onShellAuthenticationRequest ? { requestShellAuthentication: true } : {},
2158
- askUserVariant: config.askUserVariant,
2159
- ...config.enableMcpApps ? { requestMcpApps: true } : {},
2160
- ...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
2161
- requestExitPlanMode: !!config.onExitPlanModeRequest,
2162
- requestAutoModeSwitch: !!config.onAutoModeSwitchRequest,
2163
- ...config.autoModeRecovery ? { requestAutoModeRecovery: true } : {},
2164
- hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),
2361
+ extensions: {
2362
+ enabled: config.extensions?.enabled,
2363
+ sdkPath: config.extensions?.sdkPath,
2364
+ identity: config.extensions?.identity
2365
+ },
2366
+ interaction: {
2367
+ commands: config.interaction?.commands?.map((cmd) => ({
2368
+ name: cmd.name,
2369
+ description: cmd.description ?? ""
2370
+ })),
2371
+ requestUserInput: !!config.interaction?.onUserInputRequest,
2372
+ requestElicitation: !!config.interaction?.onElicitationRequest,
2373
+ askUserVariant: config.interaction?.askUserVariant,
2374
+ requestExitPlanMode: !!config.interaction?.onExitPlanModeRequest,
2375
+ requestAutoModeSwitch: !!config.interaction?.onAutoModeSwitchRequest,
2376
+ ...config.interaction?.onShellAuthenticationRequest ? {
2377
+ requestShellAuthentication: true
2378
+ } : {},
2379
+ ...config.interaction?.autoModeRecovery ? {
2380
+ requestAutoModeRecovery: true
2381
+ } : {}
2382
+ },
2383
+ permissions: {
2384
+ request: config.permissions?.onRequest !== defaultJoinSessionPermissionHandler,
2385
+ sandbox: config.permissions?.sandbox,
2386
+ mode: config.permissions?.mode
2387
+ },
2388
+ mcp: {
2389
+ ...config.mcp?.enableApps ? {
2390
+ enableApps: true
2391
+ } : {},
2392
+ servers: toWireMcpServers(config.mcp?.servers),
2393
+ oauthTokenStorage: config.mcp?.oauthTokenStorage,
2394
+ authClientIdMetadataUrl: config.mcp?.authClientIdMetadataUrl,
2395
+ envValueMode: "direct",
2396
+ disabledServers: config.mcp?.disabledServers
2397
+ },
2398
+ hooks: {
2399
+ hasHandlers: !!(config.hooks?.handlers && Object.values(config.hooks?.handlers).some(Boolean)),
2400
+ enableRepositoryHooks: config.hooks?.enableRepositoryHooks,
2401
+ directories: config.hooks?.directories
2402
+ },
2165
2403
  workingDirectory: config.workingDirectory,
2166
- additionalDirectories: config.additionalDirectories,
2167
- configDir: config.configDirectory,
2404
+ configDirectory: config.configDirectory,
2168
2405
  enableConfigDiscovery: config.enableConfigDiscovery,
2169
- skipEmbeddingRetrieval: config.skipEmbeddingRetrieval,
2170
- embeddingCacheStorage: config.embeddingCacheStorage,
2171
- organizationCustomInstructions: config.organizationCustomInstructions,
2172
- enableOnDemandInstructionDiscovery: config.enableOnDemandInstructionDiscovery,
2173
- enableFileHooks: config.enableFileHooks,
2174
- enableHostGitOperations: config.enableHostGitOperations,
2175
- enableSessionStore: config.enableSessionStore,
2176
- enableSkills: config.enableSkills,
2177
- streaming: config.streaming,
2178
- includeSubAgentStreamingEvents: config.includeSubAgentStreamingEvents ?? true,
2179
- ...this.onGitHubTelemetry != null ? { enableGitHubTelemetryForwarding: true } : {},
2180
- mcpServers: toWireMcpServers(config.mcpServers),
2406
+ state: {
2407
+ skipEmbeddingRetrieval: config.state?.skipEmbeddingRetrieval,
2408
+ embeddingCacheStorage: config.state?.embeddingCacheStorage,
2409
+ enableCrossSessionStore: config.state?.enableCrossSessionStore,
2410
+ infiniteSessions: config.state?.infiniteSessions,
2411
+ memory: toWireMemoryConfiguration(config.state?.memory),
2412
+ ...storeMemory ? {
2413
+ hasMemoryStore: true
2414
+ } : {}
2415
+ },
2416
+ instructions: {
2417
+ organizationText: config.instructions?.organizationText,
2418
+ onDemandDiscovery: config.instructions?.onDemandDiscovery,
2419
+ directories: config.instructions?.directories
2420
+ },
2421
+ git: {
2422
+ enableHostGitOperations: config.git?.enableHostGitOperations
2423
+ },
2424
+ skills: {
2425
+ enabled: config.skills?.enabled,
2426
+ directories: config.skills?.directories,
2427
+ disabledSkills: config.skills?.disabledSkills,
2428
+ ...config.skills?.provider ? {
2429
+ hasProvider: true
2430
+ } : {}
2431
+ },
2432
+ events: {
2433
+ streaming: config.events?.streaming,
2434
+ includeSubAgentStreamingEvents: config.events?.includeSubAgentStreamingEvents ?? true
2435
+ },
2181
2436
  ...config.diagnostics !== void 0 ? { diagnostics: config.diagnostics } : {},
2182
2437
  ...config.lifecycleDiagnostics !== void 0 ? { lifecycleDiagnostics: config.lifecycleDiagnostics } : {},
2183
- mcpOAuthTokenStorage: config.mcpOAuthTokenStorage,
2184
- authClientIdMetadataUrl: config.authClientIdMetadataUrl,
2185
- envValueMode: "direct",
2186
- customAgents: toWireCustomAgents(config.customAgents),
2187
- customAgentsLocalOnly: config.customAgentsLocalOnly,
2188
- defaultAgent: config.defaultAgent,
2189
- agent: config.agent,
2190
- skillDirectories: config.skillDirectories,
2191
- ...config.skillProvider ? { hasSkillProvider: true } : {},
2192
- ...storeMemory ? { hasMemoryStore: true } : {},
2193
- agentDirectories: config.agentDirectories,
2194
- hookDirectories: config.hookDirectories,
2195
- pluginDirectories: config.pluginDirectories,
2196
- instructionDirectories: config.instructionDirectories,
2197
- disabledSkills: config.disabledSkills,
2198
- disabledMcpServers: config.disabledMcpServers,
2199
- sandboxConfig: config.sandboxConfig,
2200
- infiniteSessions: config.infiniteSessions,
2201
- memory: toWireMemoryConfiguration(config.memory),
2202
- disableResume: config.suppressResumeEvent,
2438
+ plugins: {
2439
+ directories: config.plugins?.directories
2440
+ },
2441
+ suppressResumeEvent: config.suppressResumeEvent,
2203
2442
  continuePendingWork: config.continuePendingWork,
2204
- gitHubToken: config.gitHubToken,
2205
- gitHubTokenProviderRegistrationId,
2206
- openCanvases: config.openCanvases,
2207
- featureFlags: config.featureFlags,
2208
- expAssignments: config.expAssignments,
2209
- enableManagedSettings: config.enableManagedSettings,
2210
- excludedManagedSettings: config.excludedManagedSettings,
2211
- enforceManagedModelDefaults: config.enforceManagedModelDefaults,
2212
- interactiveUser: config.interactiveUser,
2213
- permissionMode: config.permissionMode,
2214
- managedSettings: config.managedSettings,
2215
2443
  ...extensionOptions?.requestedEnvironmentVariables ? {
2216
2444
  requestedEnvironmentVariables: extensionOptions.requestedEnvironmentVariables
2217
2445
  } : {}
@@ -2256,7 +2484,7 @@ class CopilotClient {
2256
2484
  } = response;
2257
2485
  session["_workspacePath"] = workspacePath;
2258
2486
  session.setCapabilities(capabilities);
2259
- if (config.autoModeRecovery) {
2487
+ if (config.interaction?.autoModeRecovery) {
2260
2488
  keepResumedSessionOnRecoveryRejection = replacedSession !== void 0 && session.capabilities.ui?.autoModeRecovery !== true;
2261
2489
  await this.requireAutoModeRecovery(
2262
2490
  session,
@@ -2267,7 +2495,7 @@ class CopilotClient {
2267
2495
  session.setOpenCanvases(openCanvases ?? []);
2268
2496
  session.setTranscriptRecovery(transcriptRecovery);
2269
2497
  session.setPermissionModeResult(permissionModeResult);
2270
- if (config.onMcpAuthRequest) {
2498
+ if (config.mcp?.onAuthRequest) {
2271
2499
  await connection.sendRequest("session.eventLog.registerInterest", {
2272
2500
  sessionId,
2273
2501
  eventType: "mcp.oauth_required"
@@ -2387,9 +2615,7 @@ class CopilotClient {
2387
2615
  if (!options?.localServer && !options?.githubEnvironment) {
2388
2616
  throw new Error("At least one of localServer or githubEnvironment is required");
2389
2617
  }
2390
- if (this.state !== "connected") {
2391
- await this.start();
2392
- }
2618
+ await this.getStartedConnection();
2393
2619
  const rpc = this.rpc;
2394
2620
  const hostId = randomUUID();
2395
2621
  if (authentication.mode === "custom") {
@@ -2536,6 +2762,7 @@ class CopilotClient {
2536
2762
  if (authentication.mode !== policy.mode || (authentication.mode === "none" ? identity !== void 0 : typeof identity !== "string" || !identity.trim()) || policy.mode === "custom" && identity !== policy.requireIdentity) {
2537
2763
  throw new Error("AHP trusted authentication does not match host policy");
2538
2764
  }
2765
+ const config = groupHostSessionSettings(params.config);
2539
2766
  const entry = {
2540
2767
  hostId: params.hostId,
2541
2768
  requestedSessionId: params.config.sessionId,
@@ -2545,8 +2772,6 @@ class CopilotClient {
2545
2772
  onReleased: options.onSessionReleased
2546
2773
  };
2547
2774
  this.hostHandoffs.set(params.handoffId, entry);
2548
- const { configDir, ...config } = params.config;
2549
- if (configDir !== void 0) config.configDirectory = configDir;
2550
2775
  const expected = structuredClone(config);
2551
2776
  const cancelled = new Promise((_resolve, reject) => {
2552
2777
  entry.controller.signal.addEventListener(
@@ -2613,8 +2838,7 @@ class CopilotClient {
2613
2838
  *
2614
2839
  * @param message - Optional message to include in the ping
2615
2840
  * @returns A promise that resolves with the ping response containing the message and timestamp
2616
- * @throws Error if the client is not connected, or if a {@link start} in progress when
2617
- * this was called fails
2841
+ * @throws Error if startup fails, the connection is unavailable, or shutdown is in progress
2618
2842
  *
2619
2843
  * @example
2620
2844
  * ```typescript
@@ -2642,15 +2866,22 @@ class CopilotClient {
2642
2866
  return result;
2643
2867
  }
2644
2868
  /**
2645
- * Returns the connection for a request that must not start the client. A
2646
- * {@link start} already in progress is awaited, so the request never precedes the
2647
- * `connect` handshake or the provider registrations that follow it. A caller that
2648
- * queues before it calls this passes the startup it observed first, because
2649
- * `startPromise` is cleared once that startup settles.
2869
+ * Lazily starts the client or joins its current startup. Await the observed
2870
+ * attempt directly so its failure cannot turn into a retry within this request.
2650
2871
  */
2651
- async getStartedConnection(startup = this.startPromise) {
2652
- if (startup) {
2653
- await startup;
2872
+ async getStartedConnection() {
2873
+ let startup = this.startPromise;
2874
+ if (startup && startup === this.shutdownCanceledStartup) {
2875
+ await this.start();
2876
+ } else {
2877
+ this.assertNotStopping();
2878
+ if (startup) {
2879
+ await startup;
2880
+ } else if (this.connectionClosed) {
2881
+ throw new Error("Client not connected");
2882
+ } else if (!this.connection) {
2883
+ await this.start();
2884
+ }
2654
2885
  }
2655
2886
  let latest = this.startPromise;
2656
2887
  while (latest && latest !== startup) {
@@ -2658,11 +2889,18 @@ class CopilotClient {
2658
2889
  await latest;
2659
2890
  latest = this.startPromise;
2660
2891
  }
2892
+ this.assertNotStopping();
2893
+ this.sessionInitializationLifetime.signal.throwIfAborted();
2661
2894
  if (!this.connection) {
2662
2895
  throw new Error("Client not connected");
2663
2896
  }
2664
2897
  return this.connection;
2665
2898
  }
2899
+ assertNotStopping() {
2900
+ if (this.stopPromise || this.forceStopPromise) {
2901
+ throw new Error("Client disconnected during session initialization");
2902
+ }
2903
+ }
2666
2904
  /**
2667
2905
  * List available models with their metadata.
2668
2906
  *
@@ -2672,51 +2910,80 @@ class CopilotClient {
2672
2910
  * Results are cached after the first successful call to avoid rate limiting.
2673
2911
  * The cache is cleared when the client disconnects.
2674
2912
  *
2675
- * @throws Error if not connected, or if a {@link start} in progress when this was
2676
- * called fails (when no custom handler is set)
2913
+ * Starts the client if needed, unless a custom handler is set.
2914
+ *
2915
+ * @throws Error if startup fails, the connection is retired, or shutdown is in
2916
+ * progress (when no custom handler is set)
2677
2917
  */
2678
2918
  async listModels() {
2679
- const cache = this.modelsCache;
2680
- const startup = this.startPromise;
2681
- const previousLock = cache.lock;
2682
- let resolveLock;
2683
- cache.lock = new Promise((resolve2) => {
2684
- resolveLock = resolve2;
2685
- });
2686
- await previousLock;
2687
- try {
2688
- if (cache.models !== null) {
2689
- return [...cache.models];
2919
+ const connection = this.onListModels ? void 0 : await this.getStartedConnection();
2920
+ const connectionEpoch = this.connectionEpoch;
2921
+ const assertCurrentConnection = () => {
2922
+ if (connection) {
2923
+ this.assertNotStopping();
2924
+ if (connectionEpoch !== this.connectionEpoch || connection !== this.connection || this.sessionInitializationLifetime.signal.aborted) {
2925
+ throw new Error("Client disconnected while listing models");
2926
+ }
2690
2927
  }
2691
- let models;
2692
- if (this.onListModels) {
2693
- models = await this.onListModels();
2694
- } else {
2695
- const connection = await this.getStartedConnection(startup);
2696
- const result = await connection.sendRequest("models.list", {});
2697
- const response = result;
2698
- models = response.models;
2699
- for (const model of models) {
2700
- const m = model;
2701
- if (!m.capabilities) {
2702
- m.capabilities = {
2703
- supports: {},
2704
- limits: { max_context_window_tokens: 0 }
2705
- };
2706
- } else {
2707
- if (!m.capabilities.supports) m.capabilities.supports = {};
2708
- if (!m.capabilities.limits) {
2709
- m.capabilities.limits = { max_context_window_tokens: 0 };
2710
- } else if (m.capabilities.limits.max_context_window_tokens === void 0) {
2711
- m.capabilities.limits.max_context_window_tokens = 0;
2928
+ };
2929
+ let startup = null;
2930
+ while (true) {
2931
+ assertCurrentConnection();
2932
+ if (startup) {
2933
+ await startup;
2934
+ startup = null;
2935
+ assertCurrentConnection();
2936
+ }
2937
+ const cache = this.modelsCache;
2938
+ const previousLock = cache.lock;
2939
+ let resolveLock;
2940
+ cache.lock = new Promise((resolve2) => {
2941
+ resolveLock = resolve2;
2942
+ });
2943
+ await previousLock;
2944
+ try {
2945
+ assertCurrentConnection();
2946
+ if (connection) {
2947
+ if (cache !== this.modelsCache) {
2948
+ throw new Error("Client disconnected while listing models");
2949
+ }
2950
+ if (this.startPromise) {
2951
+ startup = this.startPromise;
2952
+ continue;
2953
+ }
2954
+ }
2955
+ if (cache.models !== null) {
2956
+ return [...cache.models];
2957
+ }
2958
+ let models;
2959
+ if (this.onListModels) {
2960
+ models = await this.onListModels();
2961
+ } else {
2962
+ const result = await connection.sendRequest("models.list", {});
2963
+ const response = result;
2964
+ models = response.models;
2965
+ for (const model of models) {
2966
+ const m = model;
2967
+ if (!m.capabilities) {
2968
+ m.capabilities = {
2969
+ supports: {},
2970
+ limits: { max_context_window_tokens: 0 }
2971
+ };
2972
+ } else {
2973
+ if (!m.capabilities.supports) m.capabilities.supports = {};
2974
+ if (!m.capabilities.limits) {
2975
+ m.capabilities.limits = { max_context_window_tokens: 0 };
2976
+ } else if (m.capabilities.limits.max_context_window_tokens === void 0) {
2977
+ m.capabilities.limits.max_context_window_tokens = 0;
2978
+ }
2712
2979
  }
2713
2980
  }
2714
2981
  }
2982
+ cache.models = [...models];
2983
+ return [...models];
2984
+ } finally {
2985
+ resolveLock();
2715
2986
  }
2716
- cache.models = [...models];
2717
- return [...models];
2718
- } finally {
2719
- resolveLock();
2720
2987
  }
2721
2988
  }
2722
2989
  /**
@@ -2736,7 +3003,8 @@ class CopilotClient {
2736
3003
  const connectParams = {
2737
3004
  entra: this.options.entra && {
2738
3005
  clientId: this.options.entra.clientId,
2739
- matsAppName: this.options.entra.matsAppName
3006
+ matsAppName: this.options.entra.matsAppName,
3007
+ oneAuthApplicationId: this.options.entra.oneAuthApplicationId
2740
3008
  },
2741
3009
  entraTokenProvider: this.options.entra?.tokenProvider ? true : void 0,
2742
3010
  token: this.effectiveConnectionToken,
@@ -2789,15 +3057,17 @@ class CopilotClient {
2789
3057
  * ```typescript
2790
3058
  * const lastId = await client.getLastSessionId();
2791
3059
  * if (lastId) {
2792
- * const session = await client.resumeSession(lastId, { onPermissionRequest: approveAll });
3060
+ * const session = await client.resumeSession(lastId, {
3061
+ * permissions: {
3062
+ * onRequest: approveAll,
3063
+ * },
3064
+ * });
2793
3065
  * }
2794
3066
  * ```
2795
3067
  */
2796
3068
  async getLastSessionId() {
2797
- if (!this.connection) {
2798
- throw new Error("Client not connected");
2799
- }
2800
- const response = await this.connection.sendRequest("session.getLastId", {});
3069
+ const connection = await this.getStartedConnection();
3070
+ const response = await connection.sendRequest("session.getLastId", {});
2801
3071
  return response.sessionId;
2802
3072
  }
2803
3073
  /**
@@ -2818,9 +3088,7 @@ class CopilotClient {
2818
3088
  * ```
2819
3089
  */
2820
3090
  async deleteSession(sessionId) {
2821
- if (!this.connection) {
2822
- throw new Error("Client not connected");
2823
- }
3091
+ this.assertNotStopping();
2824
3092
  const signal = await this.getSessionInitializationSignal();
2825
3093
  const release = await this.acquireSessionInitialization(sessionId, signal);
2826
3094
  try {
@@ -2869,15 +3137,13 @@ class CopilotClient {
2869
3137
  * const sessions = await client.listSessions({ repository: "owner/repo" });
2870
3138
  */
2871
3139
  async listSessions(filter) {
2872
- if (!this.connection) {
2873
- throw new Error("Client not connected");
2874
- }
3140
+ const connection = await this.getStartedConnection();
2875
3141
  let wireFilter;
2876
3142
  if (filter) {
2877
3143
  const { workingDirectory, ...rest } = filter;
2878
3144
  wireFilter = { ...rest, cwd: workingDirectory };
2879
3145
  }
2880
- const response = await this.connection.sendRequest("session.list", {
3146
+ const response = await connection.sendRequest("session.list", {
2881
3147
  filter: wireFilter
2882
3148
  });
2883
3149
  const { sessions } = response;
@@ -2902,10 +3168,8 @@ class CopilotClient {
2902
3168
  * ```
2903
3169
  */
2904
3170
  async getSessionMetadata(sessionId) {
2905
- if (!this.connection) {
2906
- throw new Error("Client not connected");
2907
- }
2908
- const response = await this.connection.sendRequest("session.getMetadata", { sessionId });
3171
+ const connection = await this.getStartedConnection();
3172
+ const response = await connection.sendRequest("session.getMetadata", { sessionId });
2909
3173
  const { session } = response;
2910
3174
  if (!session) {
2911
3175
  return void 0;
@@ -2948,10 +3212,8 @@ class CopilotClient {
2948
3212
  * ```
2949
3213
  */
2950
3214
  async getForegroundSessionId() {
2951
- if (!this.connection) {
2952
- throw new Error("Client not connected");
2953
- }
2954
- const response = await this.connection.sendRequest("session.getForeground", {});
3215
+ const connection = await this.getStartedConnection();
3216
+ const response = await connection.sendRequest("session.getForeground", {});
2955
3217
  return response.sessionId;
2956
3218
  }
2957
3219
  /**
@@ -2971,10 +3233,8 @@ class CopilotClient {
2971
3233
  * ```
2972
3234
  */
2973
3235
  async setForegroundSessionId(sessionId) {
2974
- if (!this.connection) {
2975
- throw new Error("Client not connected");
2976
- }
2977
- const response = await this.connection.sendRequest("session.setForeground", { sessionId });
3236
+ const connection = await this.getStartedConnection();
3237
+ const response = await connection.sendRequest("session.setForeground", { sessionId });
2978
3238
  const result = response;
2979
3239
  if (!result.success) {
2980
3240
  throw new Error(result.error || "Failed to set foreground session");
@@ -3001,17 +3261,17 @@ class CopilotClient {
3001
3261
  this.sessionLifecycleHandlers.delete(wildcardHandler);
3002
3262
  };
3003
3263
  }
3264
+ static normalizeEnvironment(environment) {
3265
+ return process.platform === "win32" ? Object.fromEntries(
3266
+ Object.entries(environment).map(([key, value]) => [key.toUpperCase(), value])
3267
+ ) : { ...environment };
3268
+ }
3004
3269
  /**
3005
3270
  * Builds runtime configuration for child processes and the per-host FFI snapshot.
3006
3271
  * Typed auth, home, keychain, and telemetry options override the effective env.
3007
3272
  */
3008
3273
  buildRuntimeEnv() {
3009
- const env = process.platform === "win32" ? Object.fromEntries(
3010
- Object.entries(this.resolvedEnv).map(([key, value]) => [
3011
- key.toUpperCase(),
3012
- value
3013
- ])
3014
- ) : { ...this.resolvedEnv };
3274
+ const env = CopilotClient.normalizeEnvironment(this.resolvedEnv);
3015
3275
  delete env.NODE_DEBUG;
3016
3276
  const test = this.options.internalTestOptions;
3017
3277
  if (test) {
@@ -3080,9 +3340,9 @@ class CopilotClient {
3080
3340
  if (this.options.logLevel) {
3081
3341
  args.push("--log-level", this.options.logLevel);
3082
3342
  }
3083
- if (this.connectionConfig.kind === "stdio") {
3343
+ if (this.connectionConfig.kind === "spawned-stdio") {
3084
3344
  args.push("--stdio");
3085
- } else if (this.connectionConfig.kind === "tcp") {
3345
+ } else if (this.connectionConfig.kind === "spawned-tcp") {
3086
3346
  const requestedPort = this.connectionConfig.port ?? 0;
3087
3347
  if (requestedPort > 0) {
3088
3348
  args.push("--port", requestedPort.toString());
@@ -3103,15 +3363,20 @@ class CopilotClient {
3103
3363
  const envWithoutNodeDebug = this.buildRuntimeEnv();
3104
3364
  if (!this.resolvedCliPath) {
3105
3365
  throw new Error(
3106
- "Path to Copilot CLI is required. Please supply it via `RuntimeConnection.forStdio({ path })` or `RuntimeConnection.forTcp({ path })`, set the COPILOT_CLI_PATH environment variable, or use `RuntimeConnection.forUri(...)` to connect to an already-running runtime."
3366
+ "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."
3107
3367
  );
3108
3368
  }
3109
- if (!existsSync(this.resolvedCliPath)) {
3369
+ const cliPath = this.resolvedCliPath;
3370
+ const workingDirectory = this.options.workingDirectory;
3371
+ const launchedCliPath = isAbsolute(cliPath) || basename(cliPath) === cliPath ? cliPath : cliPath.endsWith(".js") ? join(
3372
+ process.platform !== "win32" && existsSync(workingDirectory) ? physicalDirectory(workingDirectory) : workingDirectory,
3373
+ cliPath
3374
+ ) : `${workingDirectory}${sep}${cliPath}`;
3375
+ if (!existsSync(launchedCliPath)) {
3110
3376
  throw new Error(
3111
- `Copilot CLI not found at ${this.resolvedCliPath}. Set COPILOT_CLI_PATH to use a custom installation.`
3377
+ `Copilot CLI not found at ${launchedCliPath}. Set COPILOT_CLI_PATH to use a custom installation.`
3112
3378
  );
3113
3379
  }
3114
- const workingDirectory = this.options.workingDirectory;
3115
3380
  let workingDirectoryProblem;
3116
3381
  try {
3117
3382
  workingDirectoryProblem = statSync(workingDirectory).isDirectory() ? void 0 : "does not exist or is not a directory";
@@ -3127,7 +3392,7 @@ class CopilotClient {
3127
3392
  `Working directory ${workingDirectory} ${workingDirectoryProblem}.`
3128
3393
  );
3129
3394
  }
3130
- const stdioConfig = this.connectionConfig.kind === "stdio" ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"];
3395
+ const stdioConfig = this.connectionConfig.kind === "spawned-stdio" ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"];
3131
3396
  const isJsFile = this.resolvedCliPath.endsWith(".js");
3132
3397
  if (isJsFile) {
3133
3398
  this.cliProcess = spawn(getNodeExecPath(), [this.resolvedCliPath, ...args], {
@@ -3146,7 +3411,7 @@ class CopilotClient {
3146
3411
  }
3147
3412
  let stdout = "";
3148
3413
  let resolved = false;
3149
- if (this.connectionConfig.kind === "stdio") {
3414
+ if (this.connectionConfig.kind === "spawned-stdio") {
3150
3415
  resolved = true;
3151
3416
  resolve2();
3152
3417
  } else {
@@ -3245,18 +3510,16 @@ stderr: ${this.stderrBuffer.trim().slice(-8192) || "(empty)"}`
3245
3510
  switch (this.connectionConfig.kind) {
3246
3511
  case "parent-process":
3247
3512
  return this.connectToParentProcessViaStdio();
3248
- case "stdio":
3513
+ case "spawned-stdio":
3249
3514
  return this.connectToChildProcessViaStdio();
3250
3515
  case "inprocess":
3251
3516
  return this.connectViaFfi();
3252
- case "tcp":
3517
+ case "spawned-tcp":
3253
3518
  return this.connectViaTcp();
3254
- case "uri": {
3255
- const { host, port } = this.parseCliUrl(this.connectionConfig.url);
3256
- this.actualHost = host;
3257
- this.runtimePort = port;
3519
+ case "tcp":
3520
+ this.actualHost = this.connectionConfig.host;
3521
+ this.runtimePort = this.connectionConfig.port;
3258
3522
  return this.connectViaTcp();
3259
- }
3260
3523
  }
3261
3524
  }
3262
3525
  /** Starts the in-process FFI runtime with SDK-managed typed options. */