@github/copilot-sdk 1.0.9-preview.2 → 1.0.9-preview.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,7 +36,7 @@ import { CopilotClient, approveAll } from "@github/copilot-sdk";
36
36
  const client = new CopilotClient();
37
37
  await client.start();
38
38
 
39
- // Create a session (onPermissionRequest is optional; approveAll allows every tool)
39
+ // approveAll is only valid when managed settings are disabled.
40
40
  const session = await client.createSession({
41
41
  model: "gpt-5",
42
42
  onPermissionRequest: approveAll,
@@ -137,7 +137,7 @@ Create a new conversation session.
137
137
  - `infiniteSessions?: InfiniteSessionConfig` - Configure automatic context compaction (see below)
138
138
  - `enableSessionStore?: boolean` - Enables the cross-session store for search and retrieval across sessions. When unset in `"copilot-cli"` mode, the runtime default applies (enabled). In `"empty"` mode, defaults to disabled.
139
139
  - `provider?: ProviderConfig` - Custom API provider configuration (BYOK - Bring Your Own Key). See [Custom Providers](#custom-providers) section.
140
- - `onPermissionRequest?: PermissionHandler` - Optional handler called before each tool execution to approve or deny it. When omitted, permission requests are emitted as events and left pending for manual resolution. Use `approveAll` to allow everything, or provide a custom function for fine-grained control. See [Permission Handling](#permission-handling) section.
140
+ - `onPermissionRequest?: PermissionHandler` - Optional handler called before each tool execution to approve or deny it. When omitted, permission requests are emitted as events and left pending for manual resolution. `approveAll` approves requests when managed settings are disabled and throws when `enableManagedSettings` is true. Custom handlers can inspect `managedApprovalRequired` for human-facing confirmation logic. See [Permission Handling](#permission-handling) section.
141
141
  - `onUserInputRequest?: UserInputHandler` - Handler for user input requests from the agent. Enables the `ask_user` tool. See [User Input Requests](#user-input-requests) section.
142
142
  - `onElicitationRequest?: ElicitationHandler` - Handler for elicitation requests dispatched by the server. Enables this client to present form-based UI dialogs on behalf of the agent or other session participants. See [Elicitation Requests](#elicitation-requests) section.
143
143
  - `hooks?: SessionHooks` - Hook handlers for session lifecycle events. See [Session Hooks](#session-hooks) section.
@@ -862,7 +862,7 @@ An `onPermissionRequest` handler is optional when you create or resume a session
862
862
 
863
863
  ### Approve All (simplest)
864
864
 
865
- Use the built-in `approveAll` helper to allow every tool call without any checks:
865
+ Use the built-in `approveAll` helper when managed settings are disabled:
866
866
 
867
867
  ```typescript
868
868
  import { CopilotClient, approveAll } from "@github/copilot-sdk";
@@ -873,9 +873,11 @@ const session = await client.createSession({
873
873
  });
874
874
  ```
875
875
 
876
+ When `enableManagedSettings` is true for the session, `approveAll` throws. Use a custom handler for managed sessions; request-level `managedApprovalRequired` remains available for human-facing confirmation logic.
877
+
876
878
  ### Custom Permission Handler
877
879
 
878
- Provide your own function to inspect each request and apply custom logic:
880
+ Provide your own function to inspect each request and apply custom logic. Check `managedApprovalRequired` before any automatic approval:
879
881
 
880
882
  ```typescript
881
883
  import type { PermissionRequest, PermissionRequestResult } from "@github/copilot-sdk";
@@ -883,6 +885,11 @@ import type { PermissionRequest, PermissionRequestResult } from "@github/copilot
883
885
  const session = await client.createSession({
884
886
  model: "gpt-5",
885
887
  onPermissionRequest: (request: PermissionRequest, invocation): PermissionRequestResult => {
888
+ if ("managedApprovalRequired" in request && request.managedApprovalRequired === true) {
889
+ // Leave the request pending for the host's human-facing confirmation flow.
890
+ return { kind: "no-result" };
891
+ }
892
+
886
893
  // request.kind — what type of operation is being requested:
887
894
  // "shell" — executing a shell command
888
895
  // "write" — writing or editing a file
@@ -920,7 +927,7 @@ The handler must return one of the `PermissionDecision` shapes (or `{ kind: "no-
920
927
  | `"approve-permanently"` | Allow this request and persist the approval across sessions (currently used for URL domains) | `domain` (URL domain to approve) |
921
928
  | `"reject"` | Deny the request | `feedback?` (optional string surfaced to the agent) |
922
929
  | `"user-not-available"` | Deny the request because no user is available to confirm it | — |
923
- | `"no-result"` | Leave the request unanswered (only valid with protocol v1; rejected by protocol v2 servers) | — |
930
+ | `"no-result"` | Suppress this SDK client's response so another connected client can answer the pending request | — |
924
931
 
925
932
  ### Resuming Sessions
926
933
 
@@ -920,6 +920,10 @@ class CopilotClient {
920
920
  }
921
921
  return {};
922
922
  }
923
+ /** Mode-specific default for enableExperimentalMode. */
924
+ experimentalModeForMode(supplied) {
925
+ return this.options.mode === "empty" ? supplied ?? false : supplied;
926
+ }
923
927
  /**
924
928
  * Returns the systemMessage config to use, adjusted for the current mode.
925
929
  * In empty mode we ensure the environment_context section is removed
@@ -1021,7 +1025,10 @@ class CopilotClient {
1021
1025
  this.connection,
1022
1026
  void 0,
1023
1027
  this.onGetTraceContext,
1024
- { mcpAuthHandler: config.onMcpAuthRequest }
1028
+ {
1029
+ mcpAuthHandler: config.onMcpAuthRequest,
1030
+ managedSettingsEnabled: config.enableManagedSettings
1031
+ }
1025
1032
  );
1026
1033
  s.registerTools(config.tools);
1027
1034
  s.registerCanvases(config.canvases);
@@ -1070,6 +1077,7 @@ class CopilotClient {
1070
1077
  clientName: config.clientName,
1071
1078
  reasoningEffort: config.reasoningEffort,
1072
1079
  reasoningSummary: config.reasoningSummary,
1080
+ isExperimentalMode: this.experimentalModeForMode(config.enableExperimentalMode),
1073
1081
  contextTier: config.contextTier,
1074
1082
  tools: config.tools?.map((tool) => ({
1075
1083
  name: tool.name,
@@ -1109,10 +1117,12 @@ class CopilotClient {
1109
1117
  requestUserInput: !!config.onUserInputRequest,
1110
1118
  requestElicitation: !!config.onElicitationRequest,
1111
1119
  ...config.enableMcpApps ? { requestMcpApps: true } : {},
1120
+ ...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
1112
1121
  requestExitPlanMode: !!config.onExitPlanModeRequest,
1113
1122
  requestAutoModeSwitch: !!config.onAutoModeSwitchRequest,
1114
1123
  hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),
1115
1124
  workingDirectory: config.workingDirectory,
1125
+ additionalDirectories: config.additionalDirectories,
1116
1126
  streaming: config.streaming,
1117
1127
  includeSubAgentStreamingEvents: config.includeSubAgentStreamingEvents ?? true,
1118
1128
  ...this.onGitHubTelemetry != null ? { enableGitHubTelemetryForwarding: true } : {},
@@ -1219,7 +1229,10 @@ class CopilotClient {
1219
1229
  this.connection,
1220
1230
  void 0,
1221
1231
  this.onGetTraceContext,
1222
- { mcpAuthHandler: config.onMcpAuthRequest }
1232
+ {
1233
+ mcpAuthHandler: config.onMcpAuthRequest,
1234
+ managedSettingsEnabled: config.enableManagedSettings
1235
+ }
1223
1236
  );
1224
1237
  session.registerTools(config.tools);
1225
1238
  session.registerCanvases(config.canvases);
@@ -1273,6 +1286,7 @@ class CopilotClient {
1273
1286
  model: config.model,
1274
1287
  reasoningEffort: config.reasoningEffort,
1275
1288
  reasoningSummary: config.reasoningSummary,
1289
+ isExperimentalMode: this.experimentalModeForMode(config.enableExperimentalMode),
1276
1290
  contextTier: config.contextTier,
1277
1291
  systemMessage: wireSystemMessage,
1278
1292
  availableTools: toolFilterOptions.availableTools,
@@ -1313,10 +1327,12 @@ class CopilotClient {
1313
1327
  requestUserInput: !!config.onUserInputRequest,
1314
1328
  requestElicitation: !!config.onElicitationRequest,
1315
1329
  ...config.enableMcpApps ? { requestMcpApps: true } : {},
1330
+ ...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
1316
1331
  requestExitPlanMode: !!config.onExitPlanModeRequest,
1317
1332
  requestAutoModeSwitch: !!config.onAutoModeSwitchRequest,
1318
1333
  hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),
1319
1334
  workingDirectory: config.workingDirectory,
1335
+ additionalDirectories: config.additionalDirectories,
1320
1336
  configDir: config.configDirectory,
1321
1337
  enableConfigDiscovery: config.enableConfigDiscovery,
1322
1338
  skipEmbeddingRetrieval: config.skipEmbeddingRetrieval,
@@ -171,6 +171,27 @@ function createServerRpc(connection) {
171
171
  discover: async (params) => connection.sendRequest("mcp.discover", params)
172
172
  },
173
173
  /** @experimental */
174
+ extensions: {
175
+ /**
176
+ * Discovers user and enabled installed-plugin extensions from persisted Copilot home state, including enablement preferences. Launch-scoped additional plugins are not included.
177
+ *
178
+ * @returns Extensions discovered from persisted Copilot home state and their effective loading mode. Launch-scoped additional plugins are not included.
179
+ */
180
+ discover: async () => connection.sendRequest("extensions.discover", {}),
181
+ /**
182
+ * Persistently enables extension IDs for future sessions. Active sessions are unchanged; use session.extensions.enable to update them.
183
+ *
184
+ * @param params Source-qualified extension identifiers to persistently enable for future sessions.
185
+ */
186
+ enable: async (params) => connection.sendRequest("extensions.enable", params),
187
+ /**
188
+ * Persistently disables extension IDs for future sessions. Active sessions are unchanged; use session.extensions.disable to update them.
189
+ *
190
+ * @param params Source-qualified extension identifiers to persistently disable for future sessions.
191
+ */
192
+ disable: async (params) => connection.sendRequest("extensions.disable", params)
193
+ },
194
+ /** @experimental */
174
195
  plugins: {
175
196
  /**
176
197
  * Lists plugins installed in user/global state.
@@ -1165,6 +1186,12 @@ function createSessionRpc(connection, sessionId) {
1165
1186
  * @returns Agents available to the session.
1166
1187
  */
1167
1188
  list: async (params) => connection.sendRequest("session.agent.list", { sessionId, ...params }),
1189
+ /**
1190
+ * Sets an in-memory authored prompt override for an available agent. For built-in agents, this replaces only the static base prompt while preserving runtime-owned dynamic prompt composition and behavior. The special `general-purpose` agent is not overrideable. Overrides are not persisted; resumed and forked sessions start without them, so the host must re-apply them.
1191
+ *
1192
+ * @param params An in-memory authored prompt override for an available agent.
1193
+ */
1194
+ setPrompt: async (params) => connection.sendRequest("session.agent.setPrompt", { sessionId, ...params }),
1168
1195
  /**
1169
1196
  * Gets the currently selected custom agent for the session.
1170
1197
  *
@@ -1406,6 +1433,12 @@ function createSessionRpc(connection, sessionId) {
1406
1433
  * @returns Indicates whether the pending MCP OAuth response was accepted.
1407
1434
  */
1408
1435
  handlePendingRequest: async (params) => connection.sendRequest("session.mcp.oauth.handlePendingRequest", { sessionId, ...params }),
1436
+ /**
1437
+ * Notifies the session that MCP OAuth authentication succeeded and updated credentials were persisted, so cached tool definitions can be refreshed.
1438
+ *
1439
+ * @param params Identifies the MCP server whose persisted OAuth credentials were updated.
1440
+ */
1441
+ authenticationStateChanged: async (params) => connection.sendRequest("session.mcp.oauth.authenticationStateChanged", { sessionId, ...params }),
1409
1442
  /**
1410
1443
  * Starts OAuth authentication for a remote MCP server.
1411
1444
  *
@@ -2129,7 +2162,15 @@ function createSessionRpc(connection, sessionId) {
2129
2162
  *
2130
2163
  * @returns Markdown summary of the conversation context (empty when not available).
2131
2164
  */
2132
- summarizeForHandoff: async () => connection.sendRequest("session.history.summarizeForHandoff", { sessionId })
2165
+ summarizeForHandoff: async () => connection.sendRequest("session.history.summarizeForHandoff", { sessionId }),
2166
+ /**
2167
+ * Clears the session's conversation history, keeping only system and developer messages, and seeds the fresh context window with a first user message. Must be called from inside a tool handler: the clear has to drop the results of the tool calls its wipe orphans, and it rejects when no tool call is in flight.
2168
+ *
2169
+ * @param params Parameters for clearing the conversation and seeding the window that replaces it.
2170
+ *
2171
+ * @returns What a successful clear removed. A clear that could not be applied rejects instead of reporting a count.
2172
+ */
2173
+ clearContext: async (params) => connection.sendRequest("session.history.clearContext", { sessionId, ...params })
2133
2174
  },
2134
2175
  /** @experimental */
2135
2176
  queue: {
@@ -2207,7 +2248,7 @@ function createSessionRpc(connection, sessionId) {
2207
2248
  /** @experimental */
2208
2249
  eventLog: {
2209
2250
  /**
2210
- * Reads a batch of session events from a cursor, optionally waiting for new events.
2251
+ * Reads a batch of session events from a cursor, optionally waiting for new events. Supports tail-first reads via `direction: backward`.
2211
2252
  *
2212
2253
  * @param params Cursor, batch size, and optional long-poll/filter parameters for reading session events.
2213
2254
  *
@@ -224,6 +224,7 @@ class CopilotSession {
224
224
  this._workspacePath = _workspacePath;
225
225
  this.traceContextProvider = traceContextProvider;
226
226
  this.mcpAuthHandler = options?.mcpAuthHandler;
227
+ this.managedSettingsEnabled = options?.managedSettingsEnabled === true;
227
228
  }
228
229
  sessionId;
229
230
  connection;
@@ -246,6 +247,7 @@ class CopilotSession {
246
247
  transformCallbacks;
247
248
  _rpc = null;
248
249
  traceContextProvider;
250
+ managedSettingsEnabled;
249
251
  _capabilities = {};
250
252
  openCanvasInstances = [];
251
253
  disconnected = false;
@@ -272,7 +274,7 @@ class CopilotSession {
272
274
  limits: options?.limits
273
275
  }
274
276
  });
275
- return toPublicFactoryRunResult(envelope);
277
+ return this.settleFactoryRun(envelope);
276
278
  }),
277
279
  resume: (async (runId, options) => {
278
280
  let response;
@@ -290,7 +292,7 @@ class CopilotSession {
290
292
  }
291
293
  throw error;
292
294
  }
293
- return toPublicFactoryRunResult(response.run);
295
+ return this.settleFactoryRun(response.run);
294
296
  }),
295
297
  getRun: async (runId) => toPublicFactoryRunResult(await this.rpc.factory.getRun({ runId })),
296
298
  waitForRun: (runId, options) => this.waitForFactoryRun(runId, options?.signal),
@@ -299,6 +301,19 @@ class CopilotSession {
299
301
  getRunProgress: (runId, options = {}) => this.rpc.factory.getRunProgress({ runId, ...options }),
300
302
  cancel: async (runId) => toPublicFactoryRunResult(await this.rpc.factory.cancel({ runId }))
301
303
  };
304
+ /**
305
+ * Resolve a start/resume envelope into the terminal envelope callers expect.
306
+ *
307
+ * The CLI may answer `session.factory.run` and `session.factory.resume`
308
+ * before the run settles, so a non-terminal envelope is followed by a wait
309
+ * on the run's terminal state.
310
+ */
311
+ settleFactoryRun(envelope) {
312
+ if ((0, import_factory.isFactoryRunTerminal)(envelope.status)) {
313
+ return Promise.resolve(toPublicFactoryRunResult(envelope));
314
+ }
315
+ return this.waitForFactoryRun(envelope.runId);
316
+ }
302
317
  /**
303
318
  * Resolve when a factory run reaches a terminal status.
304
319
  *
@@ -704,7 +719,8 @@ class CopilotSession {
704
719
  async _executePermissionAndRespond(requestId, permissionRequest) {
705
720
  try {
706
721
  const result = await this.permissionHandler(permissionRequest, {
707
- sessionId: this.sessionId
722
+ sessionId: this.sessionId,
723
+ managedSettingsEnabled: this.managedSettingsEnabled
708
724
  });
709
725
  if (result.kind === "no-result") {
710
726
  return;
@@ -713,10 +729,15 @@ class CopilotSession {
713
729
  return;
714
730
  }
715
731
  await this.rpc.permissions.handlePendingPermissionRequest({ requestId, result });
716
- } catch (_error) {
732
+ } catch (error) {
717
733
  if (this.disconnected) {
718
734
  return;
719
735
  }
736
+ console.error("Permission handler or response delivery failed", {
737
+ sessionId: this.sessionId,
738
+ requestId,
739
+ error
740
+ });
720
741
  try {
721
742
  await this.rpc.permissions.handlePendingPermissionRequest({
722
743
  requestId,
package/dist/cjs/types.js CHANGED
@@ -141,7 +141,18 @@ const SYSTEM_MESSAGE_SECTIONS = {
141
141
  description: "End-of-prompt instructions: parallel tool calling, persistence, task completion"
142
142
  }
143
143
  };
144
- const approveAll = () => ({ kind: "approve-once" });
144
+ const approveAll = (request, invocation) => {
145
+ if (invocation.managedSettingsEnabled) {
146
+ throw new Error("approveAll cannot be used when managed settings are enabled");
147
+ }
148
+ if ("managedApprovalRequired" in request) {
149
+ const managedApprovalRequired = request.managedApprovalRequired;
150
+ if (managedApprovalRequired !== void 0 && managedApprovalRequired !== false) {
151
+ return { kind: "no-result" };
152
+ }
153
+ }
154
+ return { kind: "approve-once" };
155
+ };
145
156
  const defaultJoinSessionPermissionHandler = () => ({
146
157
  kind: "no-result"
147
158
  });
package/dist/client.d.ts CHANGED
@@ -180,6 +180,8 @@ export declare class CopilotClient {
180
180
  forceStop(): Promise<void>;
181
181
  /** Mode-specific defaults spread under the caller's config (app values win). */
182
182
  private configDefaultsForMode;
183
+ /** Mode-specific default for enableExperimentalMode. */
184
+ private experimentalModeForMode;
183
185
  /**
184
186
  * Returns the systemMessage config to use, adjusted for the current mode.
185
187
  * In empty mode we ensure the environment_context section is removed
package/dist/client.js CHANGED
@@ -897,6 +897,10 @@ class CopilotClient {
897
897
  }
898
898
  return {};
899
899
  }
900
+ /** Mode-specific default for enableExperimentalMode. */
901
+ experimentalModeForMode(supplied) {
902
+ return this.options.mode === "empty" ? supplied ?? false : supplied;
903
+ }
900
904
  /**
901
905
  * Returns the systemMessage config to use, adjusted for the current mode.
902
906
  * In empty mode we ensure the environment_context section is removed
@@ -998,7 +1002,10 @@ class CopilotClient {
998
1002
  this.connection,
999
1003
  void 0,
1000
1004
  this.onGetTraceContext,
1001
- { mcpAuthHandler: config.onMcpAuthRequest }
1005
+ {
1006
+ mcpAuthHandler: config.onMcpAuthRequest,
1007
+ managedSettingsEnabled: config.enableManagedSettings
1008
+ }
1002
1009
  );
1003
1010
  s.registerTools(config.tools);
1004
1011
  s.registerCanvases(config.canvases);
@@ -1047,6 +1054,7 @@ class CopilotClient {
1047
1054
  clientName: config.clientName,
1048
1055
  reasoningEffort: config.reasoningEffort,
1049
1056
  reasoningSummary: config.reasoningSummary,
1057
+ isExperimentalMode: this.experimentalModeForMode(config.enableExperimentalMode),
1050
1058
  contextTier: config.contextTier,
1051
1059
  tools: config.tools?.map((tool) => ({
1052
1060
  name: tool.name,
@@ -1086,10 +1094,12 @@ class CopilotClient {
1086
1094
  requestUserInput: !!config.onUserInputRequest,
1087
1095
  requestElicitation: !!config.onElicitationRequest,
1088
1096
  ...config.enableMcpApps ? { requestMcpApps: true } : {},
1097
+ ...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
1089
1098
  requestExitPlanMode: !!config.onExitPlanModeRequest,
1090
1099
  requestAutoModeSwitch: !!config.onAutoModeSwitchRequest,
1091
1100
  hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),
1092
1101
  workingDirectory: config.workingDirectory,
1102
+ additionalDirectories: config.additionalDirectories,
1093
1103
  streaming: config.streaming,
1094
1104
  includeSubAgentStreamingEvents: config.includeSubAgentStreamingEvents ?? true,
1095
1105
  ...this.onGitHubTelemetry != null ? { enableGitHubTelemetryForwarding: true } : {},
@@ -1196,7 +1206,10 @@ class CopilotClient {
1196
1206
  this.connection,
1197
1207
  void 0,
1198
1208
  this.onGetTraceContext,
1199
- { mcpAuthHandler: config.onMcpAuthRequest }
1209
+ {
1210
+ mcpAuthHandler: config.onMcpAuthRequest,
1211
+ managedSettingsEnabled: config.enableManagedSettings
1212
+ }
1200
1213
  );
1201
1214
  session.registerTools(config.tools);
1202
1215
  session.registerCanvases(config.canvases);
@@ -1250,6 +1263,7 @@ class CopilotClient {
1250
1263
  model: config.model,
1251
1264
  reasoningEffort: config.reasoningEffort,
1252
1265
  reasoningSummary: config.reasoningSummary,
1266
+ isExperimentalMode: this.experimentalModeForMode(config.enableExperimentalMode),
1253
1267
  contextTier: config.contextTier,
1254
1268
  systemMessage: wireSystemMessage,
1255
1269
  availableTools: toolFilterOptions.availableTools,
@@ -1290,10 +1304,12 @@ class CopilotClient {
1290
1304
  requestUserInput: !!config.onUserInputRequest,
1291
1305
  requestElicitation: !!config.onElicitationRequest,
1292
1306
  ...config.enableMcpApps ? { requestMcpApps: true } : {},
1307
+ ...config.githubMcpToolConfig != null ? { githubMcpToolConfig: config.githubMcpToolConfig } : {},
1293
1308
  requestExitPlanMode: !!config.onExitPlanModeRequest,
1294
1309
  requestAutoModeSwitch: !!config.onAutoModeSwitchRequest,
1295
1310
  hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),
1296
1311
  workingDirectory: config.workingDirectory,
1312
+ additionalDirectories: config.additionalDirectories,
1297
1313
  configDir: config.configDirectory,
1298
1314
  enableConfigDiscovery: config.enableConfigDiscovery,
1299
1315
  skipEmbeddingRetrieval: config.skipEmbeddingRetrieval,